editor_all.js 763 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038
  1. (function(){UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  2. var baidu = window.baidu || {};
  3. window.baidu = baidu;
  4. window.UE = baidu.editor = {};
  5. UE.plugins = {};
  6. UE.commands = {};
  7. UE.instants = {};
  8. UE.I18N = {};
  9. UE.version = "1.2.5.0";
  10. var dom = UE.dom = {};
  11. /**
  12. * @file
  13. * @name UE.browser
  14. * @short Browser
  15. * @desc UEditor中采用的浏览器判断模块
  16. */
  17. var browser = UE.browser = function(){
  18. var agent = navigator.userAgent.toLowerCase(),
  19. opera = window.opera,
  20. browser = {
  21. /**
  22. * 检测浏览器是否为IE
  23. * @name ie
  24. * @grammar UE.browser.ie => true|false
  25. */
  26. ie : !!window.ActiveXObject,
  27. /**
  28. * 检测浏览器是否为Opera
  29. * @name opera
  30. * @grammar UE.browser.opera => true|false
  31. */
  32. opera : ( !!opera && opera.version ),
  33. /**
  34. * 检测浏览器是否为webkit内核
  35. * @name webkit
  36. * @grammar UE.browser.webkit => true|false
  37. */
  38. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  39. /**
  40. * 检测浏览器是否为mac系统下的浏览器
  41. * @name mac
  42. * @grammar UE.browser.mac => true|false
  43. */
  44. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  45. /**
  46. * 检测浏览器是否处于怪异模式
  47. * @name quirks
  48. * @grammar UE.browser.quirks => true|false
  49. */
  50. quirks : ( document.compatMode == 'BackCompat' )
  51. };
  52. /**
  53. * 检测浏览器是否处为gecko内核
  54. * @name gecko
  55. * @grammar UE.browser.gecko => true|false
  56. */
  57. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera );
  58. var version = 0;
  59. // Internet Explorer 6.0+
  60. if ( browser.ie ){
  61. version = parseFloat( agent.match( /msie (\d+)/ )[1] );
  62. /**
  63. * 检测浏览器是否为 IE9 模式
  64. * @name ie9Compat
  65. * @grammar UE.browser.ie9Compat => true|false
  66. */
  67. browser.ie9Compat = document.documentMode == 9;
  68. /**
  69. * 检测浏览器是否为 IE8 浏览器
  70. * @name ie8
  71. * @grammar UE.browser.ie8 => true|false
  72. */
  73. browser.ie8 = !!document.documentMode;
  74. /**
  75. * 检测浏览器是否为 IE8 模式
  76. * @name ie8Compat
  77. * @grammar UE.browser.ie8Compat => true|false
  78. */
  79. browser.ie8Compat = document.documentMode == 8;
  80. /**
  81. * 检测浏览器是否运行在 兼容IE7模式
  82. * @name ie7Compat
  83. * @grammar UE.browser.ie7Compat => true|false
  84. */
  85. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  86. || document.documentMode == 7 );
  87. /**
  88. * 检测浏览器是否IE6模式或怪异模式
  89. * @name ie6Compat
  90. * @grammar UE.browser.ie6Compat => true|false
  91. */
  92. browser.ie6Compat = ( version < 7 || browser.quirks );
  93. }
  94. // Gecko.
  95. if ( browser.gecko ){
  96. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  97. if ( geckoRelease )
  98. {
  99. geckoRelease = geckoRelease[1].split( '.' );
  100. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  101. }
  102. }
  103. /**
  104. * 检测浏览器是否为chrome
  105. * @name chrome
  106. * @grammar UE.browser.chrome => true|false
  107. */
  108. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  109. browser.chrome = + RegExp['\x241'];
  110. }
  111. /**
  112. * 检测浏览器是否为safari
  113. * @name safari
  114. * @grammar UE.browser.safari => true|false
  115. */
  116. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  117. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  118. }
  119. // Opera 9.50+
  120. if ( browser.opera )
  121. version = parseFloat( opera.version() );
  122. // WebKit 522+ (Safari 3+)
  123. if ( browser.webkit )
  124. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  125. /**
  126. * 浏览器版本判断
  127. * IE系列返回值为5,6,7,8,9,10等
  128. * gecko系列会返回10900,158900等.
  129. * webkit系列会返回其build号 (如 522等).
  130. * @name version
  131. * @grammar UE.browser.version => number
  132. * @example
  133. * if ( UE.browser.ie && UE.browser.version == 6 ){
  134. * alert( "Ouch!居然是万恶的IE6!" );
  135. * }
  136. */
  137. browser.version = version;
  138. /**
  139. * 是否是兼容模式的浏览器
  140. * @name isCompatible
  141. * @grammar UE.browser.isCompatible => true|false
  142. * @example
  143. * if ( UE.browser.isCompatible ){
  144. * alert( "你的浏览器相当不错哦!" );
  145. * }
  146. */
  147. browser.isCompatible =
  148. !browser.mobile && (
  149. ( browser.ie && version >= 6 ) ||
  150. ( browser.gecko && version >= 10801 ) ||
  151. ( browser.opera && version >= 9.5 ) ||
  152. ( browser.air && version >= 1 ) ||
  153. ( browser.webkit && version >= 522 ) ||
  154. false );
  155. return browser;
  156. }();
  157. //快捷方式
  158. var ie = browser.ie,
  159. webkit = browser.webkit,
  160. gecko = browser.gecko,
  161. opera = browser.opera;
  162. /**
  163. * @file
  164. * @name UE.Utils
  165. * @short Utils
  166. * @desc UEditor封装使用的静态工具函数
  167. * @import editor.js
  168. */
  169. var utils = UE.utils = {
  170. /**
  171. * 遍历数组,对象,nodeList
  172. * @name each
  173. * @grammar UE.utils.each(obj,iterator,[context])
  174. * @since 1.2.4+
  175. * @desc
  176. * * obj 要遍历的对象
  177. * * iterator 遍历的方法,方法的第一个是遍历的值,第二个是索引,第三个是obj
  178. * * context iterator的上下文
  179. * @example
  180. * UE.utils.each([1,2],function(v,i){
  181. * console.log(v)//值
  182. * console.log(i)//索引
  183. * })
  184. * UE.utils.each(document.getElementsByTagName('*'),function(n){
  185. * console.log(n.tagName)
  186. * })
  187. */
  188. each : function(obj, iterator, context) {
  189. if (obj == null) return;
  190. if (obj.length === +obj.length) {
  191. for (var i = 0, l = obj.length; i < l; i++) {
  192. if(iterator.call(context, obj[i], i, obj) === false)
  193. return false;
  194. }
  195. } else {
  196. for (var key in obj) {
  197. if (obj.hasOwnProperty(key)) {
  198. if(iterator.call(context, obj[key], key, obj) === false)
  199. return false;
  200. }
  201. }
  202. }
  203. },
  204. makeInstance:function (obj) {
  205. var noop = new Function();
  206. noop.prototype = obj;
  207. obj = new noop;
  208. noop.prototype = null;
  209. return obj;
  210. },
  211. /**
  212. * 将source对象中的属性扩展到target对象上
  213. * @name extend
  214. * @grammar UE.utils.extend(target,source) => Object //覆盖扩展
  215. * @grammar UE.utils.extend(target,source,true) ==> Object //保留扩展
  216. */
  217. extend:function (t, s, b) {
  218. if (s) {
  219. for (var k in s) {
  220. if (!b || !t.hasOwnProperty(k)) {
  221. t[k] = s[k];
  222. }
  223. }
  224. }
  225. return t;
  226. },
  227. /**
  228. * 模拟继承机制,subClass继承superClass
  229. * @name inherits
  230. * @grammar UE.utils.inherits(subClass,superClass) => subClass
  231. * @example
  232. * function SuperClass(){
  233. * this.name = "小李";
  234. * }
  235. * SuperClass.prototype = {
  236. * hello:function(str){
  237. * console.log(this.name + str);
  238. * }
  239. * }
  240. * function SubClass(){
  241. * this.name = "小张";
  242. * }
  243. * UE.utils.inherits(SubClass,SuperClass);
  244. * var sub = new SubClass();
  245. * sub.hello("早上好!"); ==> "小张早上好!"
  246. */
  247. inherits:function (subClass, superClass) {
  248. var oldP = subClass.prototype,
  249. newP = utils.makeInstance(superClass.prototype);
  250. utils.extend(newP, oldP, true);
  251. subClass.prototype = newP;
  252. return (newP.constructor = subClass);
  253. },
  254. /**
  255. * 用指定的context作为fn上下文,也就是this
  256. * @name bind
  257. * @grammar UE.utils.bind(fn,context) => fn
  258. */
  259. bind:function (fn, context) {
  260. return function () {
  261. return fn.apply(context, arguments);
  262. };
  263. },
  264. /**
  265. * 创建延迟delay执行的函数fn
  266. * @name defer
  267. * @grammar UE.utils.defer(fn,delay) =>fn //延迟delay毫秒执行fn,返回fn
  268. * @grammar UE.utils.defer(fn,delay,exclusion) =>fn //延迟delay毫秒执行fn,若exclusion为真,则互斥执行fn
  269. * @example
  270. * function test(){
  271. * console.log("延迟输出!");
  272. * }
  273. * //非互斥延迟执行
  274. * var testDefer = UE.utils.defer(test,1000);
  275. * testDefer(); => "延迟输出!";
  276. * testDefer(); => "延迟输出!";
  277. * //互斥延迟执行
  278. * var testDefer1 = UE.utils.defer(test,1000,true);
  279. * testDefer1(); => //本次不执行
  280. * testDefer1(); => "延迟输出!";
  281. */
  282. defer:function (fn, delay, exclusion) {
  283. var timerID;
  284. return function () {
  285. if (exclusion) {
  286. clearTimeout(timerID);
  287. }
  288. timerID = setTimeout(fn, delay);
  289. };
  290. },
  291. /**
  292. * 查找元素item在数组array中的索引, 若找不到返回-1
  293. * @name indexOf
  294. * @grammar UE.utils.indexOf(array,item) => index|-1 //默认从数组开头部开始搜索
  295. * @grammar UE.utils.indexOf(array,item,start) => index|-1 //start指定开始查找的位置
  296. */
  297. indexOf:function (array, item, start) {
  298. var index = -1;
  299. start = this.isNumber(start) ? start : 0;
  300. this.each(array,function(v,i){
  301. if(i >= start && v === item){
  302. index = i;
  303. return false;
  304. }
  305. });
  306. return index;
  307. },
  308. /**
  309. * 移除数组array中的元素item
  310. * @name removeItem
  311. * @grammar UE.utils.removeItem(array,item)
  312. */
  313. removeItem:function (array, item) {
  314. for (var i = 0, l = array.length; i < l; i++) {
  315. if (array[i] === item) {
  316. array.splice(i, 1);
  317. i--;
  318. }
  319. }
  320. },
  321. /**
  322. * 删除字符串str的首尾空格
  323. * @name trim
  324. * @grammar UE.utils.trim(str) => String
  325. */
  326. trim:function (str) {
  327. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  328. },
  329. /**
  330. * 将字符串list(以','分隔)或者数组list转成哈希对象
  331. * @name listToMap
  332. * @grammar UE.utils.listToMap(list) => Object //Object形如{test:1,br:1,textarea:1}
  333. */
  334. listToMap:function (list) {
  335. if (!list)return {};
  336. list = utils.isArray(list) ? list : list.split(',');
  337. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  338. obj[ci.toUpperCase()] = obj[ci] = 1;
  339. }
  340. return obj;
  341. },
  342. /**
  343. * 将str中的html符号转义,默认将转义''&<">''四个字符,可自定义reg来确定需要转义的字符
  344. * @name unhtml
  345. * @grammar UE.utils.unhtml(str); => String
  346. * @grammar UE.utils.unhtml(str,reg) => String
  347. * @example
  348. * var html = '<body>You say:"你好!Baidu & UEditor!"</body>';
  349. * UE.utils.unhtml(html); ==> &lt;body&gt;You say:&quot;你好!Baidu &amp; UEditor!&quot;&lt;/body&gt;
  350. * UE.utils.unhtml(html,/[<>]/g) ==> &lt;body&gt;You say:"你好!Baidu & UEditor!"&lt;/body&gt;
  351. */
  352. unhtml:function (str, reg) {
  353. return str ? str.replace(reg || /[&<">]/g, function (m) {
  354. return {
  355. '<':'&lt;',
  356. '&':'&amp;',
  357. '"':'&quot;',
  358. '>':'&gt;'
  359. }[m]
  360. }) : '';
  361. },
  362. /**
  363. * 将str中的转义字符还原成html字符
  364. * @name html
  365. * @grammar UE.utils.html(str) => String //详细参见<code><a href = '#unhtml'>unhtml</a></code>
  366. */
  367. html:function (str) {
  368. return str ? str.replace(/&((g|l|quo)t|amp);/g, function (m) {
  369. return {
  370. '&lt;':'<',
  371. '&amp;':'&',
  372. '&quot;':'"',
  373. '&gt;':'>'
  374. }[m]
  375. }) : '';
  376. },
  377. /**
  378. * 将css样式转换为驼峰的形式。如font-size => fontSize
  379. * @name cssStyleToDomStyle
  380. * @grammar UE.utils.cssStyleToDomStyle(cssName) => String
  381. */
  382. cssStyleToDomStyle:function () {
  383. var test = document.createElement('div').style,
  384. cache = {
  385. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  386. };
  387. return function (cssName) {
  388. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  389. return match.charAt(1).toUpperCase();
  390. }));
  391. };
  392. }(),
  393. /**
  394. * 动态加载文件到doc中,并依据obj来设置属性,加载成功后执行回调函数fn
  395. * @name loadFile
  396. * @grammar UE.utils.loadFile(doc,obj)
  397. * @grammar UE.utils.loadFile(doc,obj,fn)
  398. * @example
  399. * //指定加载到当前document中一个script文件,加载成功后执行function
  400. * utils.loadFile( document, {
  401. * src:"test.js",
  402. * tag:"script",
  403. * type:"text/javascript",
  404. * defer:"defer"
  405. * }, function () {
  406. * console.log('加载成功!')
  407. * });
  408. */
  409. loadFile:function () {
  410. var tmpList = [];
  411. function getItem(doc,obj){
  412. try{
  413. for(var i= 0,ci;ci=tmpList[i++];){
  414. if(ci.doc === doc && ci.url == (obj.src || obj.href)){
  415. return ci;
  416. }
  417. }
  418. }catch(e){
  419. return null;
  420. }
  421. }
  422. return function (doc, obj, fn) {
  423. var item = getItem(doc,obj);
  424. if (item) {
  425. if(item.ready){
  426. fn && fn();
  427. }else{
  428. item.funs.push(fn)
  429. }
  430. return;
  431. }
  432. tmpList.push({
  433. doc:doc,
  434. url:obj.src||obj.href,
  435. funs:[fn]
  436. });
  437. if (!doc.body) {
  438. var html = [];
  439. for(var p in obj){
  440. if(p == 'tag')continue;
  441. html.push(p + '="' + obj[p] + '"')
  442. }
  443. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></'+obj.tag+'>');
  444. return;
  445. }
  446. if (obj.id && doc.getElementById(obj.id)) {
  447. return;
  448. }
  449. var element = doc.createElement(obj.tag);
  450. delete obj.tag;
  451. for (var p in obj) {
  452. element.setAttribute(p, obj[p]);
  453. }
  454. element.onload = element.onreadystatechange = function () {
  455. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  456. item = getItem(doc,obj);
  457. if (item.funs.length > 0) {
  458. item.ready = 1;
  459. for (var fi; fi = item.funs.pop();) {
  460. fi();
  461. }
  462. }
  463. element.onload = element.onreadystatechange = null;
  464. }
  465. };
  466. element.onerror = function(){
  467. throw Error('The load '+(obj.href||obj.src)+' fails,check the url settings of file editor_config.js ')
  468. };
  469. doc.getElementsByTagName("head")[0].appendChild(element);
  470. }
  471. }(),
  472. /**
  473. * 判断obj对象是否为空
  474. * @name isEmptyObject
  475. * @grammar UE.utils.isEmptyObject(obj) => true|false
  476. * @example
  477. * UE.utils.isEmptyObject({}) ==>true
  478. * UE.utils.isEmptyObject([]) ==>true
  479. * UE.utils.isEmptyObject("") ==>true
  480. */
  481. isEmptyObject:function (obj) {
  482. if (obj == null) return true;
  483. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  484. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  485. return true;
  486. },
  487. /**
  488. * 统一将颜色值使用16进制形式表示
  489. * @name fixColor
  490. * @grammar UE.utils.fixColor(name,value) => value
  491. * @example
  492. * rgb(255,255,255) => "#ffffff"
  493. */
  494. fixColor:function (name, value) {
  495. if (/color/i.test(name) && /rgba?/.test(value)) {
  496. var array = value.split(",");
  497. if (array.length > 3)
  498. return "";
  499. value = "#";
  500. for (var i = 0, color; color = array[i++];) {
  501. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  502. value += color.length == 1 ? "0" + color : color;
  503. }
  504. value = value.toUpperCase();
  505. }
  506. return value;
  507. },
  508. /**
  509. * 只针对border,padding,margin做了处理,因为性能问题
  510. * @public
  511. * @function
  512. * @param {String} val style字符串
  513. */
  514. optCss:function (val) {
  515. var padding, margin, border;
  516. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  517. if (val.split(' ').length == 1) {
  518. switch (key) {
  519. case 'padding':
  520. !padding && (padding = {});
  521. padding[name] = val;
  522. return '';
  523. case 'margin':
  524. !margin && (margin = {});
  525. margin[name] = val;
  526. return '';
  527. case 'border':
  528. return val == 'initial' ? '' : str;
  529. }
  530. }
  531. return str;
  532. });
  533. function opt(obj, name) {
  534. if (!obj) {
  535. return '';
  536. }
  537. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  538. if (!t || !l || !b || !r) {
  539. for (var p in obj) {
  540. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  541. }
  542. } else {
  543. val += ';' + name + ':' +
  544. (t == b && b == l && l == r ? t :
  545. t == b && l == r ? (t + ' ' + l) :
  546. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  547. }
  548. return val;
  549. }
  550. val += opt(padding, 'padding') + opt(margin, 'margin');
  551. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  552. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  553. return b ? b + ";;" : ';'
  554. });
  555. },
  556. /**
  557. * 深度克隆对象,从source到target
  558. * @name clone
  559. * @grammar UE.utils.clone(source) => anthorObj 新的对象是完整的source的副本
  560. * @grammar UE.utils.clone(source,target) => target包含了source的所有内容,重名会覆盖
  561. */
  562. clone:function (source, target) {
  563. var tmp;
  564. target = target || {};
  565. for (var i in source) {
  566. if (source.hasOwnProperty(i)) {
  567. tmp = source[i];
  568. if (typeof tmp == 'object') {
  569. target[i] = utils.isArray(tmp) ? [] : {};
  570. utils.clone(source[i], target[i])
  571. } else {
  572. target[i] = tmp;
  573. }
  574. }
  575. }
  576. return target;
  577. },
  578. /**
  579. * 转换cm/pt到px
  580. * @name transUnitToPx
  581. * @grammar UE.utils.transUnitToPx('20pt') => '27px'
  582. * @grammar UE.utils.transUnitToPx('0pt') => '0'
  583. */
  584. transUnitToPx : function(val){
  585. if(!/(pt|cm)/.test(val)){
  586. return val
  587. }
  588. var unit;
  589. val.replace(/([\d.]+)(\w+)/,function(str,v,u){
  590. val = v;
  591. unit = u;
  592. });
  593. switch(unit){
  594. case 'cm':
  595. val = parseFloat(val) * 25;
  596. break;
  597. case 'pt':
  598. val = Math.round(parseFloat(val) * 96 / 72);
  599. }
  600. return val + (val?'px':'');
  601. },
  602. /**
  603. * DomReady方法,回调函数将在dom树ready完成后执行
  604. * @name domReady
  605. * @grammar UE.utils.domReady(fn) => fn //返回一个延迟执行的方法
  606. */
  607. domReady:function () {
  608. var fnArr = [];
  609. function doReady(doc) {
  610. //确保onready只执行一次
  611. doc.isReady = true;
  612. for (var ci; ci = fnArr.pop();ci()){}
  613. }
  614. return function (onready,win) {
  615. win = win || window;
  616. var doc = win.document;
  617. onready && fnArr.push(onready);
  618. if (doc.readyState === "complete") {
  619. doReady(doc);
  620. }else{
  621. doc.isReady && doReady(doc);
  622. if (browser.ie) {
  623. (function () {
  624. if (doc.isReady) return;
  625. try {
  626. doc.documentElement.doScroll("left");
  627. } catch (error) {
  628. setTimeout(arguments.callee, 0);
  629. return;
  630. }
  631. doReady(doc);
  632. })();
  633. win.attachEvent('onload', function(){
  634. doReady(doc)
  635. });
  636. } else {
  637. doc.addEventListener("DOMContentLoaded", function () {
  638. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  639. doReady(doc);
  640. }, false);
  641. win.addEventListener('load', function(){doReady(doc)}, false);
  642. }
  643. }
  644. }
  645. }(),
  646. /**
  647. * 动态添加css样式
  648. * @name cssRule
  649. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  650. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  651. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  652. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  653. */
  654. cssRule : browser.ie ? function(key,style,doc){
  655. var indexList,index;
  656. doc = doc || document;
  657. if(doc.indexList){
  658. indexList = doc.indexList;
  659. }else{
  660. indexList = doc.indexList = {};
  661. }
  662. var sheetStyle;
  663. if(!indexList[key]){
  664. if(style === undefined){
  665. return ''
  666. }
  667. sheetStyle = doc.createStyleSheet('',index = doc.styleSheets.length);
  668. indexList[key] = index;
  669. }else{
  670. sheetStyle = doc.styleSheets[indexList[key]];
  671. }
  672. if(style === undefined){
  673. return sheetStyle.cssText
  674. }
  675. sheetStyle.cssText = style || ''
  676. }:function(key,style,doc){
  677. doc = doc || document;
  678. var head = doc.getElementsByTagName('head')[0],node;
  679. if(!(node = doc.getElementById(key))){
  680. if(style === undefined){
  681. return ''
  682. }
  683. node = doc.createElement('style');
  684. node.id = key;
  685. head.appendChild(node)
  686. }
  687. if(style === undefined){
  688. return node.innerHTML
  689. }
  690. if(style !== ''){
  691. node.innerHTML = style;
  692. }else{
  693. head.removeChild(node)
  694. }
  695. }
  696. };
  697. /**
  698. * 判断str是否为字符串
  699. * @name isString
  700. * @grammar UE.utils.isString(str) => true|false
  701. */
  702. /**
  703. * 判断array是否为数组
  704. * @name isArray
  705. * @grammar UE.utils.isArray(obj) => true|false
  706. */
  707. /**
  708. * 判断obj对象是否为方法
  709. * @name isFunction
  710. * @grammar UE.utils.isFunction(obj) => true|false
  711. */
  712. /**
  713. * 判断obj对象是否为数字
  714. * @name isNumber
  715. * @grammar UE.utils.isNumber(obj) => true|false
  716. */
  717. utils.each(['String','Function','Array','Number','RegExp'],function(v){
  718. UE.utils['is' + v] = function(obj){
  719. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  720. }
  721. });
  722. /**
  723. * @file
  724. * @name UE.EventBase
  725. * @short EventBase
  726. * @import editor.js,core/utils.js
  727. * @desc UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  728. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  729. */
  730. var EventBase = UE.EventBase = function () {};
  731. EventBase.prototype = {
  732. /**
  733. * 注册事件监听器
  734. * @name addListener
  735. * @grammar editor.addListener(types,fn) //types为事件名称,多个可用空格分隔
  736. * @example
  737. * editor.addListener('selectionchange',function(){
  738. * console.log("选区已经变化!");
  739. * })
  740. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  741. * if(type == 'beforegetcontent'){
  742. * //do something
  743. * }else{
  744. * //do something
  745. * }
  746. * console.log(this.getContent) // this是注册的事件的编辑器实例
  747. * })
  748. */
  749. addListener:function (types, listener) {
  750. types = utils.trim(types).split(' ');
  751. for (var i = 0, ti; ti = types[i++];) {
  752. getListener(this, ti, true).push(listener);
  753. }
  754. },
  755. /**
  756. * 移除事件监听器
  757. * @name removeListener
  758. * @grammar editor.removeListener(types,fn) //types为事件名称,多个可用空格分隔
  759. * @example
  760. * //changeCallback为方法体
  761. * editor.removeListener("selectionchange",changeCallback);
  762. */
  763. removeListener:function (types, listener) {
  764. types = utils.trim(types).split(' ');
  765. for (var i = 0, ti; ti = types[i++];) {
  766. utils.removeItem(getListener(this, ti) || [], listener);
  767. }
  768. },
  769. /**
  770. * 触发事件
  771. * @name fireEvent
  772. * @grammar editor.fireEvent(types) //types为事件名称,多个可用空格分隔
  773. * @example
  774. * editor.fireEvent("selectionchange");
  775. */
  776. fireEvent:function (types) {
  777. types = utils.trim(types).split(' ');
  778. for (var i = 0, ti; ti = types[i++];) {
  779. var listeners = getListener(this, ti),
  780. r, t, k;
  781. if (listeners) {
  782. k = listeners.length;
  783. while (k--) {
  784. if(!listeners[k])continue;
  785. t = listeners[k].apply(this, arguments);
  786. if(t === true){
  787. return t;
  788. }
  789. if (t !== undefined) {
  790. r = t;
  791. }
  792. }
  793. }
  794. if (t = this['on' + ti.toLowerCase()]) {
  795. r = t.apply(this, arguments);
  796. }
  797. }
  798. return r;
  799. }
  800. };
  801. /**
  802. * 获得对象所拥有监听类型的所有监听器
  803. * @public
  804. * @function
  805. * @param {Object} obj 查询监听器的对象
  806. * @param {String} type 事件类型
  807. * @param {Boolean} force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  808. * @returns {Array} 监听器数组
  809. */
  810. function getListener(obj, type, force) {
  811. var allListeners;
  812. type = type.toLowerCase();
  813. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  814. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  815. }
  816. ///import editor.js
  817. ///import core/dom/dom.js
  818. /**
  819. * dtd html语义化的体现类
  820. * @constructor
  821. * @namespace dtd
  822. */
  823. var dtd = dom.dtd = (function() {
  824. function _( s ) {
  825. for (var k in s) {
  826. s[k.toUpperCase()] = s[k];
  827. }
  828. return s;
  829. }
  830. function X( t ) {
  831. var a = arguments;
  832. for ( var i=1; i<a.length; i++ ) {
  833. var x = a[i];
  834. for ( var k in x ) {
  835. if (!t.hasOwnProperty(k)) {
  836. t[k] = x[k];
  837. }
  838. }
  839. }
  840. return t;
  841. }
  842. var A = _({isindex:1,fieldset:1}),
  843. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  844. C = X( _({a:1}), B ),
  845. D = X( {iframe:1}, C ),
  846. 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}),
  847. F = _({ins:1,del:1,script:1,style:1}),
  848. 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 ),
  849. 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 ),
  850. I = X( _({p:1}), H ),
  851. J = X( _({iframe:1}), H, B ),
  852. 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}),
  853. L = X( _({a:0}), J ),//a不能被切开,所以把他
  854. M = _({tr:1}),
  855. N = _({'#':1}),
  856. O = X( _({param:1}), K ),
  857. P = X( _({form:1}), A, D, E, I ),
  858. Q = _({li:1}),
  859. R = _({style:1,script:1}),
  860. S = _({base:1,link:1,meta:1,title:1}),
  861. T = X( S, R ),
  862. U = _({head:1,body:1}),
  863. V = _({html:1});
  864. 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}),
  865. //针对优酷的embed他添加了结束标识,导致粘贴进来会变成两个,暂时去掉 ,embed:1
  866. empty = _({area:1,base:1,br:1,col:1,hr:1,img:1,input:1,link:1,meta:1,param:1,embed:1});
  867. return _({
  868. // $ 表示自定的属性
  869. // body外的元素列表.
  870. $nonBodyContent: X( V, U, S ),
  871. //块结构元素列表
  872. $block : block,
  873. //内联元素列表
  874. $inline : L,
  875. $body : X( _({script:1,style:1}), block ),
  876. $cdata : _({script:1,style:1}),
  877. //自闭和元素
  878. $empty : empty,
  879. //不是自闭合,但不能让range选中里边
  880. $nonChild : _({iframe:1,textarea:1}),
  881. //列表元素列表
  882. $listItem : _({dd:1,dt:1,li:1}),
  883. //列表根元素列表
  884. $list: _({ul:1,ol:1,dl:1}),
  885. //不能认为是空的元素
  886. $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}),
  887. //如果没有子节点就可以删除的元素列表,像span,a
  888. $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}),
  889. $removeEmptyBlock : _({'p':1,'div':1}),
  890. //在table元素里的元素列表
  891. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  892. //不转换的标签
  893. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  894. html: U,
  895. head: T,
  896. style: N,
  897. script: N,
  898. body: P,
  899. base: {},
  900. link: {},
  901. meta: {},
  902. title: N,
  903. col : {},
  904. tr : _({td:1,th:1}),
  905. img : {},
  906. embed: {},
  907. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  908. noscript : P,
  909. td : P,
  910. br : {},
  911. th : P,
  912. center : P,
  913. kbd : L,
  914. button : X( I, E ),
  915. basefont : {},
  916. h5 : L,
  917. h4 : L,
  918. samp : L,
  919. h6 : L,
  920. ol : Q,
  921. h1 : L,
  922. h3 : L,
  923. option : N,
  924. h2 : L,
  925. form : X( A, D, E, I ),
  926. select : _({optgroup:1,option:1}),
  927. font : L,
  928. ins : L,
  929. menu : Q,
  930. abbr : L,
  931. label : L,
  932. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  933. code : L,
  934. tfoot : M,
  935. cite : L,
  936. li : P,
  937. input : {},
  938. iframe : P,
  939. strong : L,
  940. textarea : N,
  941. noframes : P,
  942. big : L,
  943. small : L,
  944. span :_({'#':1,br:1}),
  945. hr : L,
  946. dt : L,
  947. sub : L,
  948. optgroup : _({option:1}),
  949. param : {},
  950. bdo : L,
  951. 'var' : L,
  952. div : P,
  953. object : O,
  954. sup : L,
  955. dd : P,
  956. strike : L,
  957. area : {},
  958. dir : Q,
  959. map : X( _({area:1,form:1,p:1}), A, F, E ),
  960. applet : O,
  961. dl : _({dt:1,dd:1}),
  962. del : L,
  963. isindex : {},
  964. fieldset : X( _({legend:1}), K ),
  965. thead : M,
  966. ul : Q,
  967. acronym : L,
  968. b : L,
  969. a : X( _({a:1}), J ),
  970. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  971. caption : L,
  972. i : L,
  973. u : L,
  974. tbody : M,
  975. s : L,
  976. address : X( D, I ),
  977. tt : L,
  978. legend : L,
  979. q : L,
  980. pre : X( G, C ),
  981. p : X(_({'a':1}),L),
  982. em :L,
  983. dfn : L
  984. });
  985. })();
  986. /**
  987. * @file
  988. * @name UE.dom.domUtils
  989. * @short DomUtils
  990. * @import editor.js, core/utils.js,core/browser.js,core/dom/dtd.js
  991. * @desc UEditor封装的底层dom操作库
  992. */
  993. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  994. var tmpNode = startFromChild && node[start],
  995. parent;
  996. !tmpNode && (tmpNode = node[ltr]);
  997. while (!tmpNode && (parent = (parent || node).parentNode)) {
  998. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  999. return null;
  1000. }
  1001. tmpNode = parent[ltr];
  1002. }
  1003. if (tmpNode && fn && !fn(tmpNode)) {
  1004. return getDomNode(tmpNode, start, ltr, false, fn);
  1005. }
  1006. return tmpNode;
  1007. }
  1008. var attrFix = ie && browser.version < 9 ? {
  1009. tabindex:"tabIndex",
  1010. readonly:"readOnly",
  1011. "for":"htmlFor",
  1012. "class":"className",
  1013. maxlength:"maxLength",
  1014. cellspacing:"cellSpacing",
  1015. cellpadding:"cellPadding",
  1016. rowspan:"rowSpan",
  1017. colspan:"colSpan",
  1018. usemap:"useMap",
  1019. frameborder:"frameBorder"
  1020. } : {
  1021. tabindex:"tabIndex",
  1022. readonly:"readOnly"
  1023. },
  1024. styleBlock = utils.listToMap([
  1025. '-webkit-box', '-moz-box', 'block' ,
  1026. 'list-item' , 'table' , 'table-row-group' ,
  1027. 'table-header-group', 'table-footer-group' ,
  1028. 'table-row' , 'table-column-group' , 'table-column' ,
  1029. 'table-cell' , 'table-caption'
  1030. ]);
  1031. var domUtils = dom.domUtils = {
  1032. //节点常量
  1033. NODE_ELEMENT:1,
  1034. NODE_DOCUMENT:9,
  1035. NODE_TEXT:3,
  1036. NODE_COMMENT:8,
  1037. NODE_DOCUMENT_FRAGMENT:11,
  1038. //位置关系
  1039. POSITION_IDENTICAL:0,
  1040. POSITION_DISCONNECTED:1,
  1041. POSITION_FOLLOWING:2,
  1042. POSITION_PRECEDING:4,
  1043. POSITION_IS_CONTAINED:8,
  1044. POSITION_CONTAINS:16,
  1045. //ie6使用其他的会有一段空白出现
  1046. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1047. //-------------------------Node部分--------------------------------
  1048. keys:{
  1049. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1050. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1051. 37:1, 38:1, 39:1, 40:1,
  1052. 13:1 /*enter*/
  1053. },
  1054. /**
  1055. * 获取节点A相对于节点B的位置关系
  1056. * @name getPosition
  1057. * @grammar UE.dom.domUtils.getPosition(nodeA,nodeB) => Number
  1058. * @example
  1059. * switch (returnValue) {
  1060. * case 0: //相等,同一节点
  1061. * case 1: //无关,节点不相连
  1062. * case 2: //跟随,即节点A头部位于节点B头部的后面
  1063. * case 4: //前置,即节点A头部位于节点B头部的前面
  1064. * case 8: //被包含,即节点A被节点B包含
  1065. * case 10://组合类型,即节点A满足跟随节点B且被节点B包含。实际上,如果被包含,必定跟随,所以returnValue事实上不会存在8的情况。
  1066. * case 16://包含,即节点A包含节点B
  1067. * case 20://组合类型,即节点A满足前置节点A且包含节点B。同样,如果包含,必定前置,所以returnValue事实上也不会存在16的情况
  1068. * }
  1069. */
  1070. getPosition:function (nodeA, nodeB) {
  1071. // 如果两个节点是同一个节点
  1072. if (nodeA === nodeB) {
  1073. // domUtils.POSITION_IDENTICAL
  1074. return 0;
  1075. }
  1076. var node,
  1077. parentsA = [nodeA],
  1078. parentsB = [nodeB];
  1079. node = nodeA;
  1080. while (node = node.parentNode) {
  1081. // 如果nodeB是nodeA的祖先节点
  1082. if (node === nodeB) {
  1083. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1084. return 10;
  1085. }
  1086. parentsA.push(node);
  1087. }
  1088. node = nodeB;
  1089. while (node = node.parentNode) {
  1090. // 如果nodeA是nodeB的祖先节点
  1091. if (node === nodeA) {
  1092. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1093. return 20;
  1094. }
  1095. parentsB.push(node);
  1096. }
  1097. parentsA.reverse();
  1098. parentsB.reverse();
  1099. if (parentsA[0] !== parentsB[0]) {
  1100. // domUtils.POSITION_DISCONNECTED
  1101. return 1;
  1102. }
  1103. var i = -1;
  1104. while (i++, parentsA[i] === parentsB[i]) {
  1105. }
  1106. nodeA = parentsA[i];
  1107. nodeB = parentsB[i];
  1108. while (nodeA = nodeA.nextSibling) {
  1109. if (nodeA === nodeB) {
  1110. // domUtils.POSITION_PRECEDING
  1111. return 4
  1112. }
  1113. }
  1114. // domUtils.POSITION_FOLLOWING
  1115. return 2;
  1116. },
  1117. /**
  1118. * 返回节点node在父节点中的索引位置
  1119. * @name getNodeIndex
  1120. * @grammar UE.dom.domUtils.getNodeIndex(node) => Number //索引值从0开始
  1121. */
  1122. getNodeIndex:function (node, ignoreTextNode) {
  1123. var preNode = node,
  1124. i = 0;
  1125. while (preNode = preNode.previousSibling) {
  1126. if (ignoreTextNode && preNode.nodeType == 3) {
  1127. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1128. i++;
  1129. }
  1130. continue;
  1131. }
  1132. i++;
  1133. }
  1134. return i;
  1135. },
  1136. /**
  1137. * 检测节点node是否在节点doc的树上,实质上是检测是否被doc包含
  1138. * @name inDoc
  1139. * @grammar UE.dom.domUtils.inDoc(node,doc) => true|false
  1140. */
  1141. inDoc:function (node, doc) {
  1142. return domUtils.getPosition(node, doc) == 10;
  1143. },
  1144. /**
  1145. * 查找node节点的祖先节点
  1146. * @name findParent
  1147. * @grammar UE.dom.domUtils.findParent(node) => Element // 直接返回node节点的父节点
  1148. * @grammar UE.dom.domUtils.findParent(node,filterFn) => Element //filterFn为过滤函数,node作为参数,返回true时才会将node作为符合要求的节点返回
  1149. * @grammar UE.dom.domUtils.findParent(node,filterFn,includeSelf) => Element //includeSelf指定是否包含自身
  1150. */
  1151. findParent:function (node, filterFn, includeSelf) {
  1152. if (node && !domUtils.isBody(node)) {
  1153. node = includeSelf ? node : node.parentNode;
  1154. while (node) {
  1155. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1156. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1157. }
  1158. node = node.parentNode;
  1159. }
  1160. }
  1161. return null;
  1162. },
  1163. /**
  1164. * 通过tagName查找node节点的祖先节点
  1165. * @name findParentByTagName
  1166. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames) => Element //tagNames支持数组,区分大小写
  1167. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf) => Element //includeSelf指定是否包含自身
  1168. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf,excludeFn) => Element //excludeFn指定例外过滤条件,返回true时忽略该节点
  1169. */
  1170. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  1171. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  1172. return domUtils.findParent(node, function (node) {
  1173. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  1174. }, includeSelf);
  1175. },
  1176. /**
  1177. * 查找节点node的祖先节点集合
  1178. * @name findParents
  1179. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  1180. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  1181. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  1182. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  1183. */
  1184. findParents:function (node, includeSelf, filterFn, closerFirst) {
  1185. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  1186. while (node = domUtils.findParent(node, filterFn)) {
  1187. parents.push(node);
  1188. }
  1189. return closerFirst ? parents : parents.reverse();
  1190. },
  1191. /**
  1192. * 在节点node后面插入新节点newNode
  1193. * @name insertAfter
  1194. * @grammar UE.dom.domUtils.insertAfter(node,newNode) => newNode
  1195. */
  1196. insertAfter:function (node, newNode) {
  1197. return node.parentNode.insertBefore(newNode, node.nextSibling);
  1198. },
  1199. /**
  1200. * 删除节点node,并根据keepChildren指定是否保留子节点
  1201. * @name remove
  1202. * @grammar UE.dom.domUtils.remove(node) => node
  1203. * @grammar UE.dom.domUtils.remove(node,keepChildren) => node
  1204. */
  1205. remove:function (node, keepChildren) {
  1206. var parent = node.parentNode,
  1207. child;
  1208. if (parent) {
  1209. if (keepChildren && node.hasChildNodes()) {
  1210. while (child = node.firstChild) {
  1211. parent.insertBefore(child, node);
  1212. }
  1213. }
  1214. parent.removeChild(node);
  1215. }
  1216. return node;
  1217. },
  1218. /**
  1219. * 取得node节点在dom树上的下一个节点,即多叉树遍历
  1220. * @name getNextDomNode
  1221. * @grammar UE.dom.domUtils.getNextDomNode(node) => Element
  1222. * @example
  1223. */
  1224. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  1225. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  1226. },
  1227. /**
  1228. * 检测节点node是否属于bookmark节点
  1229. * @name isBookmarkNode
  1230. * @grammar UE.dom.domUtils.isBookmarkNode(node) => true|false
  1231. */
  1232. isBookmarkNode:function (node) {
  1233. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  1234. },
  1235. /**
  1236. * 获取节点node所在的window对象
  1237. * @name getWindow
  1238. * @grammar UE.dom.domUtils.getWindow(node) => window对象
  1239. */
  1240. getWindow:function (node) {
  1241. var doc = node.ownerDocument || node;
  1242. return doc.defaultView || doc.parentWindow;
  1243. },
  1244. /**
  1245. * 得到nodeA与nodeB公共的祖先节点
  1246. * @name getCommonAncestor
  1247. * @grammar UE.dom.domUtils.getCommonAncestor(nodeA,nodeB) => Element
  1248. */
  1249. getCommonAncestor:function (nodeA, nodeB) {
  1250. if (nodeA === nodeB)
  1251. return nodeA;
  1252. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  1253. while (parent = parent.parentNode) {
  1254. if (parent === nodeB) {
  1255. return parent;
  1256. }
  1257. parentsA.push(parent);
  1258. }
  1259. parent = nodeB;
  1260. while (parent = parent.parentNode) {
  1261. if (parent === nodeA)
  1262. return parent;
  1263. parentsB.push(parent);
  1264. }
  1265. parentsA.reverse();
  1266. parentsB.reverse();
  1267. while (i++, parentsA[i] === parentsB[i]) {
  1268. }
  1269. return i == 0 ? null : parentsA[i - 1];
  1270. },
  1271. /**
  1272. * 清除node节点左右兄弟为空的inline节点
  1273. * @name clearEmptySibling
  1274. * @grammar UE.dom.domUtils.clearEmptySibling(node)
  1275. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  1276. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  1277. * @example
  1278. * <b></b><i></i>xxxx<b>bb</b> --> xxxx<b>bb</b>
  1279. */
  1280. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  1281. function clear(next, dir) {
  1282. var tmpNode;
  1283. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  1284. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  1285. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  1286. tmpNode = next[dir];
  1287. domUtils.remove(next);
  1288. next = tmpNode;
  1289. }
  1290. }
  1291. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  1292. !ignorePre && clear(node.previousSibling, 'previousSibling');
  1293. },
  1294. /**
  1295. * 将一个文本节点node拆分成两个文本节点,offset指定拆分位置
  1296. * @name split
  1297. * @grammar UE.dom.domUtils.split(node,offset) => TextNode //返回从切分位置开始的后一个文本节点
  1298. */
  1299. split:function (node, offset) {
  1300. var doc = node.ownerDocument;
  1301. if (browser.ie && offset == node.nodeValue.length) {
  1302. var next = doc.createTextNode('');
  1303. return domUtils.insertAfter(node, next);
  1304. }
  1305. var retval = node.splitText(offset);
  1306. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  1307. if (browser.ie8) {
  1308. var tmpNode = doc.createTextNode('');
  1309. domUtils.insertAfter(retval, tmpNode);
  1310. domUtils.remove(tmpNode);
  1311. }
  1312. return retval;
  1313. },
  1314. /**
  1315. * 检测节点node是否为空节点(包括空格、换行、占位符等字符)
  1316. * @name isWhitespace
  1317. * @grammar UE.dom.domUtils.isWhitespace(node) => true|false
  1318. */
  1319. isWhitespace:function (node) {
  1320. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  1321. },
  1322. /**
  1323. * 获取元素element相对于viewport的位置坐标
  1324. * @name getXY
  1325. * @grammar UE.dom.domUtils.getXY(element) => Object //返回坐标对象{x:left,y:top}
  1326. */
  1327. getXY:function (element) {
  1328. var x = 0, y = 0;
  1329. while (element.offsetParent) {
  1330. y += element.offsetTop;
  1331. x += element.offsetLeft;
  1332. element = element.offsetParent;
  1333. }
  1334. return { 'x':x, 'y':y};
  1335. },
  1336. /**
  1337. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  1338. * @name on
  1339. * @grammar UE.dom.domUtils.on(element,type,handler) //type支持数组传入
  1340. * @example
  1341. * UE.dom.domUtils.on(document.body,"click",function(e){
  1342. * //e为事件对象,this为被点击元素对戏那个
  1343. * })
  1344. * @example
  1345. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  1346. * //evt为事件对象,this为被点击元素对象
  1347. * })
  1348. */
  1349. on:function (element, type, handler) {
  1350. var types = utils.isArray(type) ? type : [type],
  1351. k = types.length;
  1352. if (k) while (k--) {
  1353. type = types[k];
  1354. if (element.addEventListener) {
  1355. element.addEventListener(type, handler, false);
  1356. } else {
  1357. if (!handler._d) {
  1358. handler._d = {
  1359. els : []
  1360. };
  1361. }
  1362. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  1363. if (!handler._d[key] || index == -1) {
  1364. if(index == -1){
  1365. handler._d.els.push(element);
  1366. }
  1367. if(!handler._d[key]){
  1368. handler._d[key] = function (evt) {
  1369. return handler.call(evt.srcElement, evt || window.event);
  1370. };
  1371. }
  1372. element.attachEvent('on' + type, handler._d[key]);
  1373. }
  1374. }
  1375. }
  1376. element = null;
  1377. },
  1378. /**
  1379. * 解除原生DOM事件绑定
  1380. * @name un
  1381. * @grammar UE.dom.donUtils.un(element,type,handler) //参见<code><a href="#on">on</a></code>
  1382. */
  1383. un:function (element, type, handler) {
  1384. var types = utils.isArray(type) ? type : [type],
  1385. k = types.length;
  1386. if (k) while (k--) {
  1387. type = types[k];
  1388. if (element.removeEventListener) {
  1389. element.removeEventListener(type, handler, false);
  1390. } else {
  1391. var key = type + handler.toString();
  1392. try{
  1393. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  1394. }catch(e){}
  1395. if (handler._d && handler._d[key]) {
  1396. var index = utils.indexOf(handler._d.els,element);
  1397. if(index!=-1){
  1398. handler._d.els.splice(index,1);
  1399. }
  1400. handler._d.els.length == 0 && delete handler._d[key];
  1401. }
  1402. }
  1403. }
  1404. },
  1405. /**
  1406. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  1407. * @name isSameElement
  1408. * @grammar UE.dom.domUtils.isSameElement(nodeA,nodeB) => true|false
  1409. * @example
  1410. * <span style="font-size:12px">ssss</span> and <span style="font-size:12px">bbbbb</span> => true
  1411. * <span style="font-size:13px">ssss</span> and <span style="font-size:12px">bbbbb</span> => false
  1412. */
  1413. isSameElement:function (nodeA, nodeB) {
  1414. if (nodeA.tagName != nodeB.tagName) {
  1415. return false;
  1416. }
  1417. var thisAttrs = nodeA.attributes,
  1418. otherAttrs = nodeB.attributes;
  1419. if (!ie && thisAttrs.length != otherAttrs.length) {
  1420. return false;
  1421. }
  1422. var attrA, attrB, al = 0, bl = 0;
  1423. for (var i = 0; attrA = thisAttrs[i++];) {
  1424. if (attrA.nodeName == 'style') {
  1425. if (attrA.specified) {
  1426. al++;
  1427. }
  1428. if (domUtils.isSameStyle(nodeA, nodeB)) {
  1429. continue;
  1430. } else {
  1431. return false;
  1432. }
  1433. }
  1434. if (ie) {
  1435. if (attrA.specified) {
  1436. al++;
  1437. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  1438. } else {
  1439. continue;
  1440. }
  1441. } else {
  1442. attrB = nodeB.attributes[attrA.nodeName];
  1443. }
  1444. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  1445. return false;
  1446. }
  1447. }
  1448. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  1449. if (ie) {
  1450. for (i = 0; attrB = otherAttrs[i++];) {
  1451. if (attrB.specified) {
  1452. bl++;
  1453. }
  1454. }
  1455. if (al != bl) {
  1456. return false;
  1457. }
  1458. }
  1459. return true;
  1460. },
  1461. /**
  1462. * 判断节点nodeA与节点nodeB的元素属性是否一致
  1463. * @name isSameStyle
  1464. * @grammar UE.dom.domUtils.isSameStyle(nodeA,nodeB) => true|false
  1465. */
  1466. isSameStyle:function (nodeA, nodeB) {
  1467. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  1468. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  1469. if (browser.opera) {
  1470. styleA = nodeA.style;
  1471. styleB = nodeB.style;
  1472. if (styleA.length != styleB.length)
  1473. return false;
  1474. for (var p in styleA) {
  1475. if (/^(\d+|csstext)$/i.test(p)) {
  1476. continue;
  1477. }
  1478. if (styleA[p] != styleB[p]) {
  1479. return false;
  1480. }
  1481. }
  1482. return true;
  1483. }
  1484. if (!styleA || !styleB) {
  1485. return styleA == styleB;
  1486. }
  1487. styleA = styleA.split(';');
  1488. styleB = styleB.split(';');
  1489. if (styleA.length != styleB.length) {
  1490. return false;
  1491. }
  1492. for (var i = 0, ci; ci = styleA[i++];) {
  1493. if (utils.indexOf(styleB, ci) == -1) {
  1494. return false;
  1495. }
  1496. }
  1497. return true;
  1498. },
  1499. /**
  1500. * 检查节点node是否为块元素
  1501. * @name isBlockElm
  1502. * @grammar UE.dom.domUtils.isBlockElm(node) => true|false
  1503. */
  1504. isBlockElm:function (node) {
  1505. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  1506. },
  1507. /**
  1508. * 检测node节点是否为body节点
  1509. * @name isBody
  1510. * @grammar UE.dom.domUtils.isBody(node) => true|false
  1511. */
  1512. isBody:function (node) {
  1513. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  1514. },
  1515. /**
  1516. * 以node节点为中心,将该节点的指定祖先节点parent拆分成2块
  1517. * @name breakParent
  1518. * @grammar UE.dom.domUtils.breakParent(node,parent) => node
  1519. * @desc
  1520. * <code type="html"><b>ooo</b>是node节点
  1521. * <p>xxxx<b>ooo</b>xxx</p> ==> <p>xxx</p><b>ooo</b><p>xxx</p>
  1522. * <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>
  1523. */
  1524. breakParent:function (node, parent) {
  1525. var tmpNode,
  1526. parentClone = node,
  1527. clone = node,
  1528. leftNodes,
  1529. rightNodes;
  1530. do {
  1531. parentClone = parentClone.parentNode;
  1532. if (leftNodes) {
  1533. tmpNode = parentClone.cloneNode(false);
  1534. tmpNode.appendChild(leftNodes);
  1535. leftNodes = tmpNode;
  1536. tmpNode = parentClone.cloneNode(false);
  1537. tmpNode.appendChild(rightNodes);
  1538. rightNodes = tmpNode;
  1539. } else {
  1540. leftNodes = parentClone.cloneNode(false);
  1541. rightNodes = leftNodes.cloneNode(false);
  1542. }
  1543. while (tmpNode = clone.previousSibling) {
  1544. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  1545. }
  1546. while (tmpNode = clone.nextSibling) {
  1547. rightNodes.appendChild(tmpNode);
  1548. }
  1549. clone = parentClone;
  1550. } while (parent !== parentClone);
  1551. tmpNode = parent.parentNode;
  1552. tmpNode.insertBefore(leftNodes, parent);
  1553. tmpNode.insertBefore(rightNodes, parent);
  1554. tmpNode.insertBefore(node, rightNodes);
  1555. domUtils.remove(parent);
  1556. return node;
  1557. },
  1558. /**
  1559. * 检查节点node是否是空inline节点
  1560. * @name isEmptyInlineElement
  1561. * @grammar UE.dom.domUtils.isEmptyInlineElement(node) => 1|0
  1562. * @example
  1563. * <b><i></i></b> => 1
  1564. * <b><i></i><u></u></b> => 1
  1565. * <b></b> => 1
  1566. * <b>xx<i></i></b> => 0
  1567. */
  1568. isEmptyInlineElement:function (node) {
  1569. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  1570. return 0;
  1571. }
  1572. node = node.firstChild;
  1573. while (node) {
  1574. //如果是创建的bookmark就跳过
  1575. if (domUtils.isBookmarkNode(node)) {
  1576. return 0;
  1577. }
  1578. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  1579. node.nodeType == 3 && !domUtils.isWhitespace(node)
  1580. ) {
  1581. return 0;
  1582. }
  1583. node = node.nextSibling;
  1584. }
  1585. return 1;
  1586. },
  1587. /**
  1588. * 删除node节点下的左右空白文本子节点
  1589. * @name trimWhiteTextNode
  1590. * @grammar UE.dom.domUtils.trimWhiteTextNode(node)
  1591. */
  1592. trimWhiteTextNode:function (node) {
  1593. function remove(dir) {
  1594. var child;
  1595. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  1596. node.removeChild(child);
  1597. }
  1598. }
  1599. remove('firstChild');
  1600. remove('lastChild');
  1601. },
  1602. /**
  1603. * 合并node节点下相同的子节点
  1604. * @name mergeChild
  1605. * @desc
  1606. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  1607. * @example
  1608. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  1609. * ==> UE.dom.domUtils.mergeChild(node,'span')
  1610. * <p><span style="font-size:12px;">xxaaxx</span></p>
  1611. */
  1612. mergeChild:function (node, tagName, attrs) {
  1613. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  1614. for (var i = 0, ci; ci = list[i++];) {
  1615. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  1616. continue;
  1617. }
  1618. //span单独处理
  1619. if (ci.tagName.toLowerCase() == 'span') {
  1620. if (node === ci.parentNode) {
  1621. domUtils.trimWhiteTextNode(node);
  1622. if (node.childNodes.length == 1) {
  1623. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  1624. domUtils.remove(ci, true);
  1625. continue;
  1626. }
  1627. }
  1628. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  1629. if (attrs) {
  1630. var style = attrs.style;
  1631. if (style) {
  1632. style = style.split(';');
  1633. for (var j = 0, s; s = style[j++];) {
  1634. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  1635. }
  1636. }
  1637. }
  1638. if (domUtils.isSameStyle(ci, node)) {
  1639. domUtils.remove(ci, true);
  1640. }
  1641. continue;
  1642. }
  1643. if (domUtils.isSameElement(node, ci)) {
  1644. domUtils.remove(ci, true);
  1645. }
  1646. }
  1647. },
  1648. /**
  1649. * 原生方法getElementsByTagName的封装
  1650. * @name getElementsByTagName
  1651. * @grammar UE.dom.domUtils.getElementsByTagName(node,tagName) => Array //节点集合数组
  1652. */
  1653. getElementsByTagName:function (node, name,filter) {
  1654. if(filter && utils.isString(filter)){
  1655. var className = filter;
  1656. filter = function(node){return domUtils.hasClass(node,className)}
  1657. }
  1658. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  1659. var arr = [];
  1660. for(var n = 0,ni;ni=name[n++];){
  1661. var list = node.getElementsByTagName(ni);
  1662. for (var i = 0, ci; ci = list[i++];) {
  1663. if(!filter || filter(ci))
  1664. arr.push(ci);
  1665. }
  1666. }
  1667. return arr;
  1668. },
  1669. /**
  1670. * 将节点node合并到父节点上
  1671. * @name mergeToParent
  1672. * @grammar UE.dom.domUtils.mergeToParent(node)
  1673. * @example
  1674. * <span style="color:#fff"><span style="font-size:12px">xxx</span></span> ==> <span style="color:#fff;font-size:12px">xxx</span>
  1675. */
  1676. mergeToParent:function (node) {
  1677. var parent = node.parentNode;
  1678. while (parent && dtd.$removeEmpty[parent.tagName]) {
  1679. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  1680. domUtils.trimWhiteTextNode(parent);
  1681. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  1682. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  1683. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  1684. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  1685. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  1686. parent = parent.parentNode;
  1687. continue;
  1688. } else {
  1689. parent.style.cssText += ";" + node.style.cssText;
  1690. //trace:952 a标签要保持下划线
  1691. if (parent.tagName == 'A') {
  1692. parent.style.textDecoration = 'underline';
  1693. }
  1694. }
  1695. }
  1696. if (parent.tagName != 'A') {
  1697. parent === node.parentNode && domUtils.remove(node, true);
  1698. break;
  1699. }
  1700. }
  1701. parent = parent.parentNode;
  1702. }
  1703. },
  1704. /**
  1705. * 合并节点node的左右兄弟节点
  1706. * @name mergeSibling
  1707. * @grammar UE.dom.domUtils.mergeSibling(node)
  1708. * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre) //ignorePre指定是否忽略左兄弟
  1709. * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre,ignoreNext) //ignoreNext指定是否忽略右兄弟
  1710. * @example
  1711. * <b>xxxx</b><b>ooo</b><b>xxxx</b> ==> <b>xxxxoooxxxx</b>
  1712. */
  1713. mergeSibling:function (node, ignorePre, ignoreNext) {
  1714. function merge(rtl, start, node) {
  1715. var next;
  1716. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  1717. while (next.firstChild) {
  1718. if (start == 'firstChild') {
  1719. node.insertBefore(next.lastChild, node.firstChild);
  1720. } else {
  1721. node.appendChild(next.firstChild);
  1722. }
  1723. }
  1724. domUtils.remove(next);
  1725. }
  1726. }
  1727. !ignorePre && merge('previousSibling', 'firstChild', node);
  1728. !ignoreNext && merge('nextSibling', 'lastChild', node);
  1729. },
  1730. /**
  1731. * 设置节点node及其子节点不会被选中
  1732. * @name unSelectable
  1733. * @grammar UE.dom.domUtils.unSelectable(node)
  1734. */
  1735. unSelectable:ie || browser.opera ? function (node) {
  1736. //for ie9
  1737. node.onselectstart = function () {
  1738. return false;
  1739. };
  1740. node.onclick = node.onkeyup = node.onkeydown = function () {
  1741. return false;
  1742. };
  1743. node.unselectable = 'on';
  1744. node.setAttribute("unselectable", "on");
  1745. for (var i = 0, ci; ci = node.all[i++];) {
  1746. switch (ci.tagName.toLowerCase()) {
  1747. case 'iframe' :
  1748. case 'textarea' :
  1749. case 'input' :
  1750. case 'select' :
  1751. break;
  1752. default :
  1753. ci.unselectable = 'on';
  1754. node.setAttribute("unselectable", "on");
  1755. }
  1756. }
  1757. } : function (node) {
  1758. node.style.MozUserSelect =
  1759. node.style.webkitUserSelect =
  1760. node.style.KhtmlUserSelect = 'none';
  1761. },
  1762. /**
  1763. * 删除节点node上的属性attrNames,attrNames为属性名称数组
  1764. * @name removeAttributes
  1765. * @grammar UE.dom.domUtils.removeAttributes(node,attrNames)
  1766. * @example
  1767. * //Before remove
  1768. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  1769. * //Remove
  1770. * UE.dom.domUtils.removeAttributes(node,["id","name"]);
  1771. * //After remove
  1772. * <span style="font-size:14px;">xxxxx</span>
  1773. */
  1774. removeAttributes:function (node, attrNames) {
  1775. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  1776. for (var i = 0, ci; ci = attrNames[i++];) {
  1777. ci = attrFix[ci] || ci;
  1778. switch (ci) {
  1779. case 'className':
  1780. node[ci] = '';
  1781. break;
  1782. case 'style':
  1783. node.style.cssText = '';
  1784. !browser.ie && node.removeAttributeNode(node.getAttributeNode('style'))
  1785. }
  1786. node.removeAttribute(ci);
  1787. }
  1788. },
  1789. /**
  1790. * 在doc下创建一个标签名为tag,属性为attrs的元素
  1791. * @name createElement
  1792. * @grammar UE.dom.domUtils.createElement(doc,tag,attrs) => Node //返回创建的节点
  1793. */
  1794. createElement:function (doc, tag, attrs) {
  1795. return domUtils.setAttributes(doc.createElement(tag), attrs)
  1796. },
  1797. /**
  1798. * 为节点node添加属性attrs,attrs为属性键值对
  1799. * @name setAttributes
  1800. * @grammar UE.dom.domUtils.setAttributes(node,attrs) => node
  1801. */
  1802. setAttributes:function (node, attrs) {
  1803. for (var attr in attrs) {
  1804. if(attrs.hasOwnProperty(attr)){
  1805. var value = attrs[attr];
  1806. switch (attr) {
  1807. case 'class':
  1808. //ie下要这样赋值,setAttribute不起作用
  1809. node.className = value;
  1810. break;
  1811. case 'style' :
  1812. node.style.cssText = node.style.cssText + ";" + value;
  1813. break;
  1814. case 'innerHTML':
  1815. node[attr] = value;
  1816. break;
  1817. case 'value':
  1818. node.value = value;
  1819. break;
  1820. default:
  1821. node.setAttribute(attrFix[attr] || attr, value);
  1822. }
  1823. }
  1824. }
  1825. return node;
  1826. },
  1827. /**
  1828. * 获取元素element的计算样式
  1829. * @name getComputedStyle
  1830. * @grammar UE.dom.domUtils.getComputedStyle(element,styleName) => String //返回对应样式名称的样式值
  1831. * @example
  1832. * getComputedStyle(document.body,"font-size") => "15px"
  1833. * getComputedStyle(form,"color") => "#ffccdd"
  1834. */
  1835. getComputedStyle:function (element, styleName) {
  1836. //一下的属性单独处理
  1837. var pros = 'width height top left';
  1838. if(pros.indexOf(styleName) > -1){
  1839. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  1840. }
  1841. //忽略文本节点
  1842. if (element.nodeType == 3) {
  1843. element = element.parentNode;
  1844. }
  1845. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  1846. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  1847. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  1848. var span = element.ownerDocument.createElement('span');
  1849. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  1850. span.innerHTML = '.';
  1851. element.appendChild(span);
  1852. var result = span.offsetHeight;
  1853. element.removeChild(span);
  1854. span = null;
  1855. return result + 'px';
  1856. }
  1857. try {
  1858. var value = domUtils.getStyle(element, styleName) ||
  1859. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  1860. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  1861. } catch (e) {
  1862. return "";
  1863. }
  1864. return utils.transUnitToPx(utils.fixColor(styleName, value));
  1865. },
  1866. /**
  1867. * 在元素element上删除classNames,支持同时删除多个
  1868. * @name removeClasses
  1869. * @grammar UE.dom.domUtils.removeClasses(element,classNames)
  1870. * @example
  1871. * //执行方法前的dom结构
  1872. * <span class="test1 test2 test3">xxx</span>
  1873. * //执行方法
  1874. * UE.dom.domUtils.removeClasses(element,["test1","test3"])
  1875. * //执行方法后的dom结构
  1876. * <span class="test2">xxx</span>
  1877. */
  1878. removeClasses:function (elm, classNames) {
  1879. classNames = utils.isArray(classNames) ? classNames :
  1880. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  1881. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  1882. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  1883. }
  1884. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  1885. if(cls){
  1886. elm.className = cls;
  1887. }else{
  1888. domUtils.removeAttributes(elm,['class']);
  1889. }
  1890. },
  1891. /**
  1892. * 在元素element上增加一个样式类className,支持以空格分开的多个类名
  1893. * 如果相同的类名将不会添加
  1894. * @name addClass
  1895. * @grammar UE.dom.domUtils.addClass(element,classNames)
  1896. */
  1897. addClass:function (elm, classNames) {
  1898. if(!elm)return;
  1899. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  1900. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  1901. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  1902. elm.className += ' ' + ci;
  1903. }
  1904. }
  1905. },
  1906. /**
  1907. * 判断元素element是否包含样式类名className,支持以空格分开的多个类名,多个类名顺序不同也可以比较
  1908. * @name hasClass
  1909. * @grammar UE.dom.domUtils.hasClass(element,className) =>true|false
  1910. */
  1911. hasClass:function (element, className) {
  1912. if(utils.isRegExp(className)){
  1913. return className.test(element.className)
  1914. }
  1915. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  1916. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  1917. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  1918. return false;
  1919. }
  1920. }
  1921. return i - 1 == className.length;
  1922. },
  1923. /**
  1924. * 阻止事件默认行为
  1925. * @param {Event} evt 需要组织的事件对象
  1926. */
  1927. preventDefault:function (evt) {
  1928. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  1929. },
  1930. /**
  1931. * 删除元素element的样式
  1932. * @grammar UE.dom.domUtils.removeStyle(element,name) 删除的样式名称
  1933. */
  1934. removeStyle:function (element, name) {
  1935. if(browser.ie && browser.version > 8){
  1936. element.style.cssText = element.style.cssText.replace(new RegExp(name + '\s*:\s*[^;]+;?'),'')
  1937. }else{
  1938. if (element.style.removeProperty) {
  1939. element.style.removeProperty (name);
  1940. }else {
  1941. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  1942. }
  1943. }
  1944. if (!element.style.cssText) {
  1945. domUtils.removeAttributes(element, ['style']);
  1946. }
  1947. },
  1948. /**
  1949. * 获取元素element的某个样式值
  1950. * @name getStyle
  1951. * @grammar UE.dom.domUtils.getStyle(element,name) => String
  1952. */
  1953. getStyle:function (element, name) {
  1954. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  1955. return utils.fixColor(name, value);
  1956. },
  1957. /**
  1958. * 为元素element设置样式属性值
  1959. * @name setStyle
  1960. * @grammar UE.dom.domUtils.setStyle(element,name,value)
  1961. */
  1962. setStyle:function (element, name, value) {
  1963. element.style[utils.cssStyleToDomStyle(name)] = value;
  1964. },
  1965. /**
  1966. * 为元素element设置样式属性值
  1967. * @name setStyles
  1968. * @grammar UE.dom.domUtils.setStyle(element,styles) //styles为样式键值对
  1969. */
  1970. setStyles:function (element, styles) {
  1971. for (var name in styles) {
  1972. if (styles.hasOwnProperty(name)) {
  1973. domUtils.setStyle(element, name, styles[name]);
  1974. }
  1975. }
  1976. },
  1977. /**
  1978. * 删除_moz_dirty属性
  1979. * @function
  1980. */
  1981. removeDirtyAttr:function (node) {
  1982. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  1983. ci.removeAttribute('_moz_dirty');
  1984. }
  1985. node.removeAttribute('_moz_dirty');
  1986. },
  1987. /**
  1988. * 返回子节点的数量
  1989. * @function
  1990. * @param {Node} node 父节点
  1991. * @param {Function} fn 过滤子节点的规则,若为空,则得到所有子节点的数量
  1992. * @return {Number} 符合条件子节点的数量
  1993. */
  1994. getChildCount:function (node, fn) {
  1995. var count = 0, first = node.firstChild;
  1996. fn = fn || function () {
  1997. return 1;
  1998. };
  1999. while (first) {
  2000. if (fn(first)) {
  2001. count++;
  2002. }
  2003. first = first.nextSibling;
  2004. }
  2005. return count;
  2006. },
  2007. /**
  2008. * 判断是否为空节点
  2009. * @function
  2010. * @param {Node} node 节点
  2011. * @return {Boolean} 是否为空节点
  2012. */
  2013. isEmptyNode:function (node) {
  2014. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  2015. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  2016. }) == 0
  2017. },
  2018. /**
  2019. * 清空节点所有的className
  2020. * @function
  2021. * @param {Array} nodes 节点数组
  2022. */
  2023. clearSelectedArr:function (nodes) {
  2024. var node;
  2025. while (node = nodes.pop()) {
  2026. domUtils.removeAttributes(node, ['class']);
  2027. }
  2028. },
  2029. /**
  2030. * 将显示区域滚动到显示节点的位置
  2031. * @function
  2032. * @param {Node} node 节点
  2033. * @param {window} win window对象
  2034. * @param {Number} offsetTop 距离上方的偏移量
  2035. */
  2036. scrollToView:function (node, win, offsetTop) {
  2037. var getViewPaneSize = function () {
  2038. var doc = win.document,
  2039. mode = doc.compatMode == 'CSS1Compat';
  2040. return {
  2041. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  2042. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  2043. };
  2044. },
  2045. getScrollPosition = function (win) {
  2046. if ('pageXOffset' in win) {
  2047. return {
  2048. x:win.pageXOffset || 0,
  2049. y:win.pageYOffset || 0
  2050. };
  2051. }
  2052. else {
  2053. var doc = win.document;
  2054. return {
  2055. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  2056. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  2057. };
  2058. }
  2059. };
  2060. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  2061. offset += (node.offsetHeight || 0);
  2062. var elementPosition = domUtils.getXY(node);
  2063. offset += elementPosition.y;
  2064. var currentScroll = getScrollPosition(win).y;
  2065. // offset += 50;
  2066. if (offset > currentScroll || offset < currentScroll - winHeight) {
  2067. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  2068. }
  2069. },
  2070. /**
  2071. * 判断节点是否为br
  2072. * @function
  2073. * @param {Node} node 节点
  2074. */
  2075. isBr:function (node) {
  2076. return node.nodeType == 1 && node.tagName == 'BR';
  2077. },
  2078. isFillChar:function (node,isInStart) {
  2079. return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length
  2080. },
  2081. isStartInblock:function (range) {
  2082. var tmpRange = range.cloneRange(),
  2083. flag = 0,
  2084. start = tmpRange.startContainer,
  2085. tmp;
  2086. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  2087. start = start.childNodes[tmpRange.startOffset];
  2088. var pre = start.previousSibling;
  2089. while(pre && domUtils.isFillChar(pre)){
  2090. start = pre;
  2091. pre = pre.previousSibling;
  2092. }
  2093. }
  2094. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  2095. tmpRange.setStartBefore(start);
  2096. start = tmpRange.startContainer;
  2097. }
  2098. while (start && domUtils.isFillChar(start)) {
  2099. tmp = start;
  2100. start = start.previousSibling
  2101. }
  2102. if (tmp) {
  2103. tmpRange.setStartBefore(tmp);
  2104. start = tmpRange.startContainer;
  2105. }
  2106. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  2107. tmpRange.setStart(start, 0).collapse(true);
  2108. }
  2109. while (!tmpRange.startOffset) {
  2110. start = tmpRange.startContainer;
  2111. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  2112. flag = 1;
  2113. break;
  2114. }
  2115. var pre = tmpRange.startContainer.previousSibling,
  2116. tmpNode;
  2117. if (!pre) {
  2118. tmpRange.setStartBefore(tmpRange.startContainer);
  2119. } else {
  2120. while (pre && domUtils.isFillChar(pre)) {
  2121. tmpNode = pre;
  2122. pre = pre.previousSibling;
  2123. }
  2124. if (tmpNode) {
  2125. tmpRange.setStartBefore(tmpNode);
  2126. } else {
  2127. tmpRange.setStartBefore(tmpRange.startContainer);
  2128. }
  2129. }
  2130. }
  2131. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  2132. },
  2133. isEmptyBlock:function (node) {
  2134. var reg = new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  2135. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  2136. return 0;
  2137. }
  2138. for (var n in dtd.$isNotEmpty) {
  2139. if (node.getElementsByTagName(n).length) {
  2140. return 0;
  2141. }
  2142. }
  2143. return 1;
  2144. },
  2145. setViewportOffset:function (element, offset) {
  2146. var left = parseInt(element.style.left) | 0;
  2147. var top = parseInt(element.style.top) | 0;
  2148. var rect = element.getBoundingClientRect();
  2149. var offsetLeft = offset.left - rect.left;
  2150. var offsetTop = offset.top - rect.top;
  2151. if (offsetLeft) {
  2152. element.style.left = left + offsetLeft + 'px';
  2153. }
  2154. if (offsetTop) {
  2155. element.style.top = top + offsetTop + 'px';
  2156. }
  2157. },
  2158. fillNode:function (doc, node) {
  2159. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  2160. node.innerHTML = '';
  2161. node.appendChild(tmpNode);
  2162. },
  2163. moveChild:function (src, tag, dir) {
  2164. while (src.firstChild) {
  2165. if (dir && tag.firstChild) {
  2166. tag.insertBefore(src.lastChild, tag.firstChild);
  2167. } else {
  2168. tag.appendChild(src.firstChild);
  2169. }
  2170. }
  2171. },
  2172. //判断是否有额外属性
  2173. hasNoAttributes:function (node) {
  2174. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  2175. },
  2176. //判断是否是编辑器自定义的参数
  2177. isCustomeNode:function (node) {
  2178. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  2179. },
  2180. isTagNode:function (node, tagName) {
  2181. return node.nodeType == 1 && new RegExp(node.tagName,'i').test(tagName)
  2182. },
  2183. /**
  2184. * 对于nodelist用filter进行过滤
  2185. * @name filterNodeList
  2186. * @since 1.2.4+
  2187. * @grammar UE.dom.domUtils.filterNodeList(nodelist,filter,onlyFirst) => 节点
  2188. * @example
  2189. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'div p') //返回第一个是div或者p的节点
  2190. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),function(n){return n.getAttribute('src')})
  2191. * //返回第一个带src属性的节点
  2192. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'i',true) //返回数组,里边都是i节点
  2193. */
  2194. filterNodeList : function(nodelist,filter,forAll){
  2195. var results = [];
  2196. if(!utils .isFunction(filter)){
  2197. var str = filter;
  2198. filter = function(n){
  2199. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  2200. };
  2201. }
  2202. utils.each(nodelist,function(n){
  2203. filter(n) && results.push(n)
  2204. });
  2205. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  2206. },
  2207. isInNodeEndBoundary : function (rng,node){
  2208. var start = rng.startContainer;
  2209. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  2210. return 0;
  2211. }
  2212. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  2213. return 0;
  2214. }
  2215. while(start !== node){
  2216. if(start.nextSibling){
  2217. return 0
  2218. };
  2219. start = start.parentNode;
  2220. }
  2221. return 1;
  2222. },
  2223. isBoundaryNode : function (node,dir){
  2224. var tmp;
  2225. while(!domUtils.isBody(node)){
  2226. tmp = node;
  2227. node = node.parentNode;
  2228. if(tmp !== node[dir]){
  2229. return false;
  2230. }
  2231. }
  2232. return true;
  2233. }
  2234. };
  2235. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  2236. ///import editor.js
  2237. ///import core/utils.js
  2238. ///import core/browser.js
  2239. ///import core/dom/dom.js
  2240. ///import core/dom/dtd.js
  2241. ///import core/dom/domUtils.js
  2242. /**
  2243. * @file
  2244. * @name UE.dom.Range
  2245. * @anthor zhanyi
  2246. * @short Range
  2247. * @import editor.js,core/utils.js,core/browser.js,core/dom/domUtils.js,core/dom/dtd.js
  2248. * @desc Range范围实现类,本类是UEditor底层核心类,统一w3cRange和ieRange之间的差异,包括接口和属性
  2249. */
  2250. (function () {
  2251. var guid = 0,
  2252. fillChar = domUtils.fillChar,
  2253. fillData;
  2254. /**
  2255. * 更新range的collapse状态
  2256. * @param {Range} range range对象
  2257. */
  2258. function updateCollapse(range) {
  2259. range.collapsed =
  2260. range.startContainer && range.endContainer &&
  2261. range.startContainer === range.endContainer &&
  2262. range.startOffset == range.endOffset;
  2263. }
  2264. function selectOneNode(rng){
  2265. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  2266. }
  2267. function setEndPoint(toStart, node, offset, range) {
  2268. //如果node是自闭合标签要处理
  2269. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  2270. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  2271. node = node.parentNode;
  2272. }
  2273. if (toStart) {
  2274. range.startContainer = node;
  2275. range.startOffset = offset;
  2276. if (!range.endContainer) {
  2277. range.collapse(true);
  2278. }
  2279. } else {
  2280. range.endContainer = node;
  2281. range.endOffset = offset;
  2282. if (!range.startContainer) {
  2283. range.collapse(false);
  2284. }
  2285. }
  2286. updateCollapse(range);
  2287. return range;
  2288. }
  2289. function execContentsAction(range, action) {
  2290. //调整边界
  2291. //range.includeBookmark();
  2292. var start = range.startContainer,
  2293. end = range.endContainer,
  2294. startOffset = range.startOffset,
  2295. endOffset = range.endOffset,
  2296. doc = range.document,
  2297. frag = doc.createDocumentFragment(),
  2298. tmpStart, tmpEnd;
  2299. if (start.nodeType == 1) {
  2300. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  2301. }
  2302. if (end.nodeType == 1) {
  2303. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  2304. }
  2305. if (start === end && start.nodeType == 3) {
  2306. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  2307. //is not clone
  2308. if (action) {
  2309. start.deleteData(startOffset, endOffset - startOffset);
  2310. range.collapse(true);
  2311. }
  2312. return frag;
  2313. }
  2314. var current, currentLevel, clone = frag,
  2315. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  2316. for (var i = 0; startParents[i] == endParents[i];) {
  2317. i++;
  2318. }
  2319. for (var j = i, si; si = startParents[j]; j++) {
  2320. current = si.nextSibling;
  2321. if (si == start) {
  2322. if (!tmpStart) {
  2323. if (range.startContainer.nodeType == 3) {
  2324. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  2325. //is not clone
  2326. if (action) {
  2327. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  2328. }
  2329. } else {
  2330. clone.appendChild(!action ? start.cloneNode(true) : start);
  2331. }
  2332. }
  2333. } else {
  2334. currentLevel = si.cloneNode(false);
  2335. clone.appendChild(currentLevel);
  2336. }
  2337. while (current) {
  2338. if (current === end || current === endParents[j]) {
  2339. break;
  2340. }
  2341. si = current.nextSibling;
  2342. clone.appendChild(!action ? current.cloneNode(true) : current);
  2343. current = si;
  2344. }
  2345. clone = currentLevel;
  2346. }
  2347. clone = frag;
  2348. if (!startParents[i]) {
  2349. clone.appendChild(startParents[i - 1].cloneNode(false));
  2350. clone = clone.firstChild;
  2351. }
  2352. for (var j = i, ei; ei = endParents[j]; j++) {
  2353. current = ei.previousSibling;
  2354. if (ei == end) {
  2355. if (!tmpEnd && range.endContainer.nodeType == 3) {
  2356. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  2357. //is not clone
  2358. if (action) {
  2359. end.deleteData(0, endOffset);
  2360. }
  2361. }
  2362. } else {
  2363. currentLevel = ei.cloneNode(false);
  2364. clone.appendChild(currentLevel);
  2365. }
  2366. //如果两端同级,右边第一次已经被开始做了
  2367. if (j != i || !startParents[i]) {
  2368. while (current) {
  2369. if (current === start) {
  2370. break;
  2371. }
  2372. ei = current.previousSibling;
  2373. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  2374. current = ei;
  2375. }
  2376. }
  2377. clone = currentLevel;
  2378. }
  2379. if (action) {
  2380. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  2381. }
  2382. tmpStart && domUtils.remove(tmpStart);
  2383. tmpEnd && domUtils.remove(tmpEnd);
  2384. return frag;
  2385. }
  2386. /**
  2387. * @name Range
  2388. * @grammar new UE.dom.Range(document) => Range 实例
  2389. * @desc 创建一个跟document绑定的空的Range实例
  2390. * - ***startContainer*** 开始边界的容器节点,可以是elementNode或者是textNode
  2391. * - ***startOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  2392. * - ***endContainer*** 结束边界的容器节点,可以是elementNode或者是textNode
  2393. * - ***endOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  2394. * - ***document*** 跟range关联的document对象
  2395. * - ***collapsed*** 是否是闭合状态
  2396. */
  2397. var Range = dom.Range = function (document) {
  2398. var me = this;
  2399. me.startContainer =
  2400. me.startOffset =
  2401. me.endContainer =
  2402. me.endOffset = null;
  2403. me.document = document;
  2404. me.collapsed = true;
  2405. };
  2406. /**
  2407. * 删除fillData
  2408. * @param doc
  2409. * @param excludeNode
  2410. */
  2411. function removeFillData(doc, excludeNode) {
  2412. try {
  2413. if (fillData && domUtils.inDoc(fillData, doc)) {
  2414. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  2415. var tmpNode = fillData.parentNode;
  2416. domUtils.remove(fillData);
  2417. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  2418. //safari的contains有bug
  2419. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  2420. ) {
  2421. fillData = tmpNode.parentNode;
  2422. domUtils.remove(tmpNode);
  2423. tmpNode = fillData;
  2424. }
  2425. } else {
  2426. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  2427. }
  2428. }
  2429. } catch (e) {
  2430. }
  2431. }
  2432. /**
  2433. *
  2434. * @param node
  2435. * @param dir
  2436. */
  2437. function mergeSibling(node, dir) {
  2438. var tmpNode;
  2439. node = node[dir];
  2440. while (node && domUtils.isFillChar(node)) {
  2441. tmpNode = node[dir];
  2442. domUtils.remove(node);
  2443. node = tmpNode;
  2444. }
  2445. }
  2446. Range.prototype = {
  2447. /**
  2448. * @name cloneContents
  2449. * @grammar range.cloneContents() => DocumentFragment
  2450. * @desc 克隆选中的内容到一个fragment里,如果选区是空的将返回null
  2451. */
  2452. cloneContents:function () {
  2453. return this.collapsed ? null : execContentsAction(this, 0);
  2454. },
  2455. /**
  2456. * @name deleteContents
  2457. * @grammar range.deleteContents() => Range
  2458. * @desc 删除当前选区范围中的所有内容并返回range实例,这时的range已经变成了闭合状态
  2459. * @example
  2460. * DOM Element :
  2461. * <b>x<i>x[x<i>xx]x</b>
  2462. * //执行方法后
  2463. * <b>x<i>x<i>|x</b>
  2464. * 注意range改变了
  2465. * range.startContainer => b
  2466. * range.startOffset => 2
  2467. * range.endContainer => b
  2468. * range.endOffset => 2
  2469. * range.collapsed => true
  2470. */
  2471. deleteContents:function () {
  2472. var txt;
  2473. if (!this.collapsed) {
  2474. execContentsAction(this, 1);
  2475. }
  2476. if (browser.webkit) {
  2477. txt = this.startContainer;
  2478. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  2479. this.setStartBefore(txt).collapse(true);
  2480. domUtils.remove(txt);
  2481. }
  2482. }
  2483. return this;
  2484. },
  2485. /**
  2486. * @name extractContents
  2487. * @grammar range.extractContents() => DocumentFragment
  2488. * @desc 将当前的内容放到一个fragment里并返回这个fragment,这时的range已经变成了闭合状态
  2489. * @example
  2490. * DOM Element :
  2491. * <b>x<i>x[x<i>xx]x</b>
  2492. * //执行方法后
  2493. * 返回的fragment里的 dom结构是
  2494. * <i>x<i>xx
  2495. * dom树上的结构是
  2496. * <b>x<i>x<i>|x</b>
  2497. * 注意range改变了
  2498. * range.startContainer => b
  2499. * range.startOffset => 2
  2500. * range.endContainer => b
  2501. * range.endOffset => 2
  2502. * range.collapsed => true
  2503. */
  2504. extractContents:function () {
  2505. return this.collapsed ? null : execContentsAction(this, 2);
  2506. },
  2507. /**
  2508. * @name setStart
  2509. * @grammar range.setStart(node,offset) => Range
  2510. * @desc 设置range的开始位置位于node节点内,偏移量为offset
  2511. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2512. */
  2513. setStart:function (node, offset) {
  2514. return setEndPoint(true, node, offset, this);
  2515. },
  2516. /**
  2517. * 设置range的结束位置位于node节点,偏移量为offset
  2518. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2519. * @name setEnd
  2520. * @grammar range.setEnd(node,offset) => Range
  2521. */
  2522. setEnd:function (node, offset) {
  2523. return setEndPoint(false, node, offset, this);
  2524. },
  2525. /**
  2526. * 将Range开始位置设置到node节点之后
  2527. * @name setStartAfter
  2528. * @grammar range.setStartAfter(node) => Range
  2529. * @example
  2530. * <b>xx<i>x|x</i>x</b>
  2531. * 执行setStartAfter(i)后
  2532. * range.startContainer =>b
  2533. * range.startOffset =>2
  2534. */
  2535. setStartAfter:function (node) {
  2536. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2537. },
  2538. /**
  2539. * 将Range开始位置设置到node节点之前
  2540. * @name setStartBefore
  2541. * @grammar range.setStartBefore(node) => Range
  2542. * @example
  2543. * <b>xx<i>x|x</i>x</b>
  2544. * 执行setStartBefore(i)后
  2545. * range.startContainer =>b
  2546. * range.startOffset =>1
  2547. */
  2548. setStartBefore:function (node) {
  2549. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  2550. },
  2551. /**
  2552. * 将Range结束位置设置到node节点之后
  2553. * @name setEndAfter
  2554. * @grammar range.setEndAfter(node) => Range
  2555. * @example
  2556. * <b>xx<i>x|x</i>x</b>
  2557. * setEndAfter(i)后
  2558. * range.endContainer =>b
  2559. * range.endtOffset =>2
  2560. */
  2561. setEndAfter:function (node) {
  2562. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2563. },
  2564. /**
  2565. * 将Range结束位置设置到node节点之前
  2566. * @name setEndBefore
  2567. * @grammar range.setEndBefore(node) => Range
  2568. * @example
  2569. * <b>xx<i>x|x</i>x</b>
  2570. * 执行setEndBefore(i)后
  2571. * range.endContainer =>b
  2572. * range.endtOffset =>1
  2573. */
  2574. setEndBefore:function (node) {
  2575. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  2576. },
  2577. /**
  2578. * 将Range开始位置设置到node节点内的开始位置
  2579. * @name setStartAtFirst
  2580. * @grammar range.setStartAtFirst(node) => Range
  2581. */
  2582. setStartAtFirst:function (node) {
  2583. return this.setStart(node, 0);
  2584. },
  2585. /**
  2586. * 将Range开始位置设置到node节点内的结束位置
  2587. * @name setStartAtLast
  2588. * @grammar range.setStartAtLast(node) => Range
  2589. */
  2590. setStartAtLast:function (node) {
  2591. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2592. },
  2593. /**
  2594. * 将Range结束位置设置到node节点内的开始位置
  2595. * @name setEndAtFirst
  2596. * @grammar range.setEndAtFirst(node) => Range
  2597. */
  2598. setEndAtFirst:function (node) {
  2599. return this.setEnd(node, 0);
  2600. },
  2601. /**
  2602. * 将Range结束位置设置到node节点内的结束位置
  2603. * @name setEndAtLast
  2604. * @grammar range.setEndAtLast(node) => Range
  2605. */
  2606. setEndAtLast:function (node) {
  2607. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2608. },
  2609. /**
  2610. * 选中完整的指定节点,并返回包含该节点的range
  2611. * @name selectNode
  2612. * @grammar range.selectNode(node) => Range
  2613. */
  2614. selectNode:function (node) {
  2615. return this.setStartBefore(node).setEndAfter(node);
  2616. },
  2617. /**
  2618. * 选中node内部的所有节点,并返回对应的range
  2619. * @name selectNodeContents
  2620. * @grammar range.selectNodeContents(node) => Range
  2621. * @example
  2622. * <b>xx[x<i>xxx</i>]xxx</b>
  2623. * 执行后
  2624. * <b>[xxx<i>xxx</i>xxx]</b>
  2625. * range.startContainer =>b
  2626. * range.startOffset =>0
  2627. * range.endContainer =>b
  2628. * range.endOffset =>3
  2629. */
  2630. selectNodeContents:function (node) {
  2631. return this.setStart(node, 0).setEndAtLast(node);
  2632. },
  2633. /**
  2634. * 克隆一个新的range对象
  2635. * @name cloneRange
  2636. * @grammar range.cloneRange() => Range
  2637. */
  2638. cloneRange:function () {
  2639. var me = this;
  2640. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  2641. },
  2642. /**
  2643. * 让选区闭合到尾部,若toStart为真,则闭合到头部
  2644. * @name collapse
  2645. * @grammar range.collapse() => Range
  2646. * @grammar range.collapse(true) => Range //闭合选区到头部
  2647. */
  2648. collapse:function (toStart) {
  2649. var me = this;
  2650. if (toStart) {
  2651. me.endContainer = me.startContainer;
  2652. me.endOffset = me.startOffset;
  2653. } else {
  2654. me.startContainer = me.endContainer;
  2655. me.startOffset = me.endOffset;
  2656. }
  2657. me.collapsed = true;
  2658. return me;
  2659. },
  2660. /**
  2661. * 调整range的边界,使其"收缩"到最小的位置
  2662. * @name shrinkBoundary
  2663. * @grammar range.shrinkBoundary() => Range //range开始位置和结束位置都调整,参见<code><a href="#adjustmentboundary">adjustmentBoundary</a></code>
  2664. * @grammar range.shrinkBoundary(true) => Range //仅调整开始位置,忽略结束位置
  2665. * @example
  2666. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  2667. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx]</b><i>xxx</i>
  2668. * [<b><i>xxxx</i>xxxxxxx</b>] ==> <b><i>[xxxx</i>xxxxxxx]</b>
  2669. */
  2670. shrinkBoundary:function (ignoreEnd) {
  2671. var me = this, child,
  2672. collapsed = me.collapsed;
  2673. function check(node){
  2674. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  2675. }
  2676. while (me.startContainer.nodeType == 1 //是element
  2677. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  2678. && check(child)) {
  2679. me.setStart(child, 0);
  2680. }
  2681. if (collapsed) {
  2682. return me.collapse(true);
  2683. }
  2684. if (!ignoreEnd) {
  2685. while (me.endContainer.nodeType == 1//是element
  2686. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  2687. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  2688. && check(child)) {
  2689. me.setEnd(child, child.childNodes.length);
  2690. }
  2691. }
  2692. return me;
  2693. },
  2694. /**
  2695. * 获取当前range所在位置的公共祖先节点,当前range位置可以位于文本节点内,也可以包含整个元素节点,也可以位于两个节点之间
  2696. * @name getCommonAncestor
  2697. * @grammar range.getCommonAncestor([includeSelf, ignoreTextNode]) => Element
  2698. * @example
  2699. * <b>xx[xx<i>xx]x</i>xxx</b> ==>getCommonAncestor() ==> b
  2700. * <b>[<img/>]</b>
  2701. * range.startContainer ==> b
  2702. * range.startOffset ==> 0
  2703. * range.endContainer ==> b
  2704. * range.endOffset ==> 1
  2705. * range.getCommonAncestor() ==> b
  2706. * range.getCommonAncestor(true) ==> img
  2707. * <b>xxx|xx</b>
  2708. * range.startContainer ==> textNode
  2709. * range.startOffset ==> 3
  2710. * range.endContainer ==> textNode
  2711. * range.endOffset ==> 3
  2712. * range.getCommonAncestor() ==> textNode
  2713. * range.getCommonAncestor(null,true) ==> b
  2714. */
  2715. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  2716. var me = this,
  2717. start = me.startContainer,
  2718. end = me.endContainer;
  2719. if (start === end) {
  2720. if (includeSelf && selectOneNode(this)) {
  2721. start = start.childNodes[me.startOffset];
  2722. if(start.nodeType == 1)
  2723. return start;
  2724. }
  2725. //只有在上来就相等的情况下才会出现是文本的情况
  2726. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  2727. }
  2728. return domUtils.getCommonAncestor(start, end);
  2729. },
  2730. /**
  2731. * 调整边界容器,如果是textNode,就调整到elementNode上
  2732. * @name trimBoundary
  2733. * @grammar range.trimBoundary([ignoreEnd]) => Range //true忽略结束边界
  2734. * @example
  2735. * DOM Element :
  2736. * <b>|xxx</b>
  2737. * startContainer = xxx; startOffset = 0
  2738. * //执行后本方法后
  2739. * startContainer = <b>; startOffset = 0
  2740. * @example
  2741. * Dom Element :
  2742. * <b>xx|x</b>
  2743. * startContainer = xxx; startOffset = 2
  2744. * //执行本方法后,xxx被实实在在地切分成两个TextNode
  2745. * startContainer = <b>; startOffset = 1
  2746. */
  2747. trimBoundary:function (ignoreEnd) {
  2748. this.txtToElmBoundary();
  2749. var start = this.startContainer,
  2750. offset = this.startOffset,
  2751. collapsed = this.collapsed,
  2752. end = this.endContainer;
  2753. if (start.nodeType == 3) {
  2754. if (offset == 0) {
  2755. this.setStartBefore(start);
  2756. } else {
  2757. if (offset >= start.nodeValue.length) {
  2758. this.setStartAfter(start);
  2759. } else {
  2760. var textNode = domUtils.split(start, offset);
  2761. //跟新结束边界
  2762. if (start === end) {
  2763. this.setEnd(textNode, this.endOffset - offset);
  2764. } else if (start.parentNode === end) {
  2765. this.endOffset += 1;
  2766. }
  2767. this.setStartBefore(textNode);
  2768. }
  2769. }
  2770. if (collapsed) {
  2771. return this.collapse(true);
  2772. }
  2773. }
  2774. if (!ignoreEnd) {
  2775. offset = this.endOffset;
  2776. end = this.endContainer;
  2777. if (end.nodeType == 3) {
  2778. if (offset == 0) {
  2779. this.setEndBefore(end);
  2780. } else {
  2781. offset < end.nodeValue.length && domUtils.split(end, offset);
  2782. this.setEndAfter(end);
  2783. }
  2784. }
  2785. }
  2786. return this;
  2787. },
  2788. /**
  2789. * 如果选区在文本的边界上,就扩展选区到文本的父节点上
  2790. * @name txtToElmBoundary
  2791. * @example
  2792. * Dom Element :
  2793. * <b> |xxx</b>
  2794. * startContainer = xxx; startOffset = 0
  2795. * //本方法执行后
  2796. * startContainer = <b>; startOffset = 0
  2797. * @example
  2798. * Dom Element :
  2799. * <b> xxx| </b>
  2800. * startContainer = xxx; startOffset = 3
  2801. * //本方法执行后
  2802. * startContainer = <b>; startOffset = 1
  2803. */
  2804. txtToElmBoundary:function () {
  2805. function adjust(r, c) {
  2806. var container = r[c + 'Container'],
  2807. offset = r[c + 'Offset'];
  2808. if (container.nodeType == 3) {
  2809. if (!offset) {
  2810. r['set' + c.replace(/(\w)/, function (a) {
  2811. return a.toUpperCase();
  2812. }) + 'Before'](container);
  2813. } else if (offset >= container.nodeValue.length) {
  2814. r['set' + c.replace(/(\w)/, function (a) {
  2815. return a.toUpperCase();
  2816. }) + 'After' ](container);
  2817. }
  2818. }
  2819. }
  2820. if (!this.collapsed) {
  2821. adjust(this, 'start');
  2822. adjust(this, 'end');
  2823. }
  2824. return this;
  2825. },
  2826. /**
  2827. * 在当前选区的开始位置前插入一个节点或者fragment,range的开始位置会在插入节点的前边
  2828. * @name insertNode
  2829. * @grammar range.insertNode(node) => Range //node可以是textNode,elementNode,fragment
  2830. * @example
  2831. * Range :
  2832. * xxx[x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2833. * 待插入Node :
  2834. * <p>ssss</p>
  2835. * 执行本方法后的Range :
  2836. * xxx[<p>ssss</p>x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2837. */
  2838. insertNode:function (node) {
  2839. var first = node, length = 1;
  2840. if (node.nodeType == 11) {
  2841. first = node.firstChild;
  2842. length = node.childNodes.length;
  2843. }
  2844. this.trimBoundary(true);
  2845. var start = this.startContainer,
  2846. offset = this.startOffset;
  2847. var nextNode = start.childNodes[ offset ];
  2848. if (nextNode) {
  2849. start.insertBefore(node, nextNode);
  2850. } else {
  2851. start.appendChild(node);
  2852. }
  2853. if (first.parentNode === this.endContainer) {
  2854. this.endOffset = this.endOffset + length;
  2855. }
  2856. return this.setStartBefore(first);
  2857. },
  2858. /**
  2859. * 设置光标闭合位置,toEnd设置为true时光标将闭合到选区的结尾
  2860. * @name setCursor
  2861. * @grammar range.setCursor([toEnd]) => Range //toEnd为true时,光标闭合到选区的末尾
  2862. */
  2863. setCursor:function (toEnd, noFillData) {
  2864. return this.collapse(!toEnd).select(noFillData);
  2865. },
  2866. /**
  2867. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  2868. * @name createBookmark
  2869. * @grammar range.createBookmark([serialize]) => Object //{start:开始标记,end:结束标记,id:serialize} serialize为真时,开始结束标记是插入节点的id,否则是插入节点的引用
  2870. */
  2871. createBookmark:function (serialize, same) {
  2872. var endNode,
  2873. startNode = this.document.createElement('span');
  2874. startNode.style.cssText = 'display:none;line-height:0px;';
  2875. startNode.appendChild(this.document.createTextNode('\u200D'));
  2876. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  2877. if (!this.collapsed) {
  2878. endNode = startNode.cloneNode(true);
  2879. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  2880. }
  2881. this.insertNode(startNode);
  2882. if (endNode) {
  2883. this.collapse().insertNode(endNode).setEndBefore(endNode);
  2884. }
  2885. this.setStartAfter(startNode);
  2886. return {
  2887. start:serialize ? startNode.id : startNode,
  2888. end:endNode ? serialize ? endNode.id : endNode : null,
  2889. id:serialize
  2890. }
  2891. },
  2892. /**
  2893. * 移动边界到书签位置,并删除插入的书签节点
  2894. * @name moveToBookmark
  2895. * @grammar range.moveToBookmark(bookmark) => Range //让当前的range选到给定bookmark的位置,bookmark对象是由range.createBookmark创建的
  2896. */
  2897. moveToBookmark:function (bookmark) {
  2898. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  2899. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  2900. this.setStartBefore(start);
  2901. domUtils.remove(start);
  2902. if (end) {
  2903. this.setEndBefore(end);
  2904. domUtils.remove(end);
  2905. } else {
  2906. this.collapse(true);
  2907. }
  2908. return this;
  2909. },
  2910. /**
  2911. * 调整range的边界,使其"放大"到最近的父block节点
  2912. * @name enlarge
  2913. * @grammar range.enlarge() => Range
  2914. * @example
  2915. * <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>
  2916. */
  2917. enlarge:function (toBlock, stopFn) {
  2918. var isBody = domUtils.isBody,
  2919. pre, node, tmp = this.document.createTextNode('');
  2920. if (toBlock) {
  2921. node = this.startContainer;
  2922. if (node.nodeType == 1) {
  2923. if (node.childNodes[this.startOffset]) {
  2924. pre = node = node.childNodes[this.startOffset]
  2925. } else {
  2926. node.appendChild(tmp);
  2927. pre = node = tmp;
  2928. }
  2929. } else {
  2930. pre = node;
  2931. }
  2932. while (1) {
  2933. if (domUtils.isBlockElm(node)) {
  2934. node = pre;
  2935. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  2936. node = pre;
  2937. }
  2938. this.setStartBefore(node);
  2939. break;
  2940. }
  2941. pre = node;
  2942. node = node.parentNode;
  2943. }
  2944. node = this.endContainer;
  2945. if (node.nodeType == 1) {
  2946. if (pre = node.childNodes[this.endOffset]) {
  2947. node.insertBefore(tmp, pre);
  2948. } else {
  2949. node.appendChild(tmp);
  2950. }
  2951. pre = node = tmp;
  2952. } else {
  2953. pre = node;
  2954. }
  2955. while (1) {
  2956. if (domUtils.isBlockElm(node)) {
  2957. node = pre;
  2958. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  2959. node = pre;
  2960. }
  2961. this.setEndAfter(node);
  2962. break;
  2963. }
  2964. pre = node;
  2965. node = node.parentNode;
  2966. }
  2967. if (tmp.parentNode === this.endContainer) {
  2968. this.endOffset--;
  2969. }
  2970. domUtils.remove(tmp);
  2971. }
  2972. // 扩展边界到最大
  2973. if (!this.collapsed) {
  2974. while (this.startOffset == 0) {
  2975. if (stopFn && stopFn(this.startContainer)) {
  2976. break;
  2977. }
  2978. if (isBody(this.startContainer)) {
  2979. break;
  2980. }
  2981. this.setStartBefore(this.startContainer);
  2982. }
  2983. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  2984. if (stopFn && stopFn(this.endContainer)) {
  2985. break;
  2986. }
  2987. if (isBody(this.endContainer)) {
  2988. break;
  2989. }
  2990. this.setEndAfter(this.endContainer);
  2991. }
  2992. }
  2993. return this;
  2994. },
  2995. /**
  2996. * 调整Range的边界,使其"缩小"到最合适的位置
  2997. * @name adjustmentBoundary
  2998. * @grammar range.adjustmentBoundary() => Range //参见<code><a href="#shrinkboundary">shrinkBoundary</a></code>
  2999. * @example
  3000. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  3001. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx</b>]<i>xxx</i>
  3002. */
  3003. adjustmentBoundary:function () {
  3004. if (!this.collapsed) {
  3005. while (!domUtils.isBody(this.startContainer) &&
  3006. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  3007. ) {
  3008. this.setStartAfter(this.startContainer);
  3009. }
  3010. while (!domUtils.isBody(this.endContainer) && !this.endOffset) {
  3011. this.setEndBefore(this.endContainer);
  3012. }
  3013. }
  3014. return this;
  3015. },
  3016. /**
  3017. * 给range选区中的内容添加给定的标签,主要用于inline标签
  3018. * @name applyInlineStyle
  3019. * @grammar range.applyInlineStyle(tagName) => Range //tagName为需要添加的样式标签名
  3020. * @grammar range.applyInlineStyle(tagName,attrs) => Range //attrs为属性json对象
  3021. * @desc
  3022. * <code type="html"><p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  3023. * <p>xx[dd<strong>yyyy</strong>]x</p> ==> range.applyInlineStyle("strong") ==> <p>xx[<strong>ddyyyy</strong>]x</p>
  3024. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong",{"style":"font-size:12px"}) ==> <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p></code>
  3025. */
  3026. applyInlineStyle:function (tagName, attrs, list) {
  3027. if (this.collapsed)return this;
  3028. this.trimBoundary().enlarge(false,
  3029. function (node) {
  3030. return node.nodeType == 1 && domUtils.isBlockElm(node)
  3031. }).adjustmentBoundary();
  3032. var bookmark = this.createBookmark(),
  3033. end = bookmark.end,
  3034. filterFn = function (node) {
  3035. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  3036. },
  3037. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  3038. node,
  3039. pre,
  3040. range = this.cloneRange();
  3041. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  3042. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  3043. range.setStartBefore(current);
  3044. node = current;
  3045. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  3046. pre = node;
  3047. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  3048. return dtd[tagName][parent.tagName];
  3049. });
  3050. }
  3051. var frag = range.setEndAfter(pre).extractContents(), elm;
  3052. if (list && list.length > 0) {
  3053. var level, top;
  3054. top = level = list[0].cloneNode(false);
  3055. for (var i = 1, ci; ci = list[i++];) {
  3056. level.appendChild(ci.cloneNode(false));
  3057. level = level.firstChild;
  3058. }
  3059. elm = level;
  3060. } else {
  3061. elm = range.document.createElement(tagName);
  3062. }
  3063. if (attrs) {
  3064. domUtils.setAttributes(elm, attrs);
  3065. }
  3066. elm.appendChild(frag);
  3067. range.insertNode(list ? top : elm);
  3068. //处理下滑线在a上的情况
  3069. var aNode;
  3070. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  3071. domUtils.setAttributes(aNode, attrs);
  3072. domUtils.remove(elm, true);
  3073. elm = aNode;
  3074. } else {
  3075. domUtils.mergeSibling(elm);
  3076. domUtils.clearEmptySibling(elm);
  3077. }
  3078. //去除子节点相同的
  3079. domUtils.mergeChild(elm, attrs);
  3080. current = domUtils.getNextDomNode(elm, false, filterFn);
  3081. domUtils.mergeToParent(elm);
  3082. if (node === end) {
  3083. break;
  3084. }
  3085. } else {
  3086. current = domUtils.getNextDomNode(current, true, filterFn);
  3087. }
  3088. }
  3089. return this.moveToBookmark(bookmark);
  3090. },
  3091. /**
  3092. * 对当前range选中的节点,去掉给定的标签节点,但标签中的内容保留,主要用于处理inline元素
  3093. * @name removeInlineStyle
  3094. * @grammar range.removeInlineStyle(tagNames) => Range //tagNames 为需要去掉的样式标签名,支持"b"或者["b","i","u"]
  3095. * @desc
  3096. * <code type="html">xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span></code>
  3097. */
  3098. removeInlineStyle:function (tagNames) {
  3099. if (this.collapsed)return this;
  3100. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  3101. this.shrinkBoundary().adjustmentBoundary();
  3102. var start = this.startContainer, end = this.endContainer;
  3103. while (1) {
  3104. if (start.nodeType == 1) {
  3105. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  3106. break;
  3107. }
  3108. if (start.tagName.toLowerCase() == 'body') {
  3109. start = null;
  3110. break;
  3111. }
  3112. }
  3113. start = start.parentNode;
  3114. }
  3115. while (1) {
  3116. if (end.nodeType == 1) {
  3117. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  3118. break;
  3119. }
  3120. if (end.tagName.toLowerCase() == 'body') {
  3121. end = null;
  3122. break;
  3123. }
  3124. }
  3125. end = end.parentNode;
  3126. }
  3127. var bookmark = this.createBookmark(),
  3128. frag,
  3129. tmpRange;
  3130. if (start) {
  3131. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  3132. frag = tmpRange.extractContents();
  3133. tmpRange.insertNode(frag);
  3134. domUtils.clearEmptySibling(start, true);
  3135. start.parentNode.insertBefore(bookmark.start, start);
  3136. }
  3137. if (end) {
  3138. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  3139. frag = tmpRange.extractContents();
  3140. tmpRange.insertNode(frag);
  3141. domUtils.clearEmptySibling(end, false, true);
  3142. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  3143. }
  3144. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  3145. return node.nodeType == 1;
  3146. }), next;
  3147. while (current && current !== bookmark.end) {
  3148. next = domUtils.getNextDomNode(current, true, function (node) {
  3149. return node.nodeType == 1;
  3150. });
  3151. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  3152. domUtils.remove(current, true);
  3153. }
  3154. current = next;
  3155. }
  3156. return this.moveToBookmark(bookmark);
  3157. },
  3158. /**
  3159. * 得到一个自闭合的节点,常用于获取自闭和的节点,例如图片节点
  3160. * @name getClosedNode
  3161. * @grammar range.getClosedNode() => node|null
  3162. * @example
  3163. * <b>xxxx[<img />]xxx</b>
  3164. */
  3165. getClosedNode:function () {
  3166. var node;
  3167. if (!this.collapsed) {
  3168. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  3169. if (selectOneNode(range)) {
  3170. var child = range.startContainer.childNodes[range.startOffset];
  3171. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  3172. node = child;
  3173. }
  3174. }
  3175. }
  3176. return node;
  3177. },
  3178. /**
  3179. * 根据当前range选中内容节点(在页面上表现为反白显示)
  3180. * @name select
  3181. * @grammar range.select(); => Range
  3182. */
  3183. select:browser.ie ? function (noFillData, textRange) {
  3184. var nativeRange;
  3185. if (!this.collapsed)
  3186. this.shrinkBoundary();
  3187. var node = this.getClosedNode();
  3188. if (node && !textRange) {
  3189. try {
  3190. nativeRange = this.document.body.createControlRange();
  3191. nativeRange.addElement(node);
  3192. nativeRange.select();
  3193. } catch (e) {}
  3194. return this;
  3195. }
  3196. var bookmark = this.createBookmark(),
  3197. start = bookmark.start,
  3198. end;
  3199. nativeRange = this.document.body.createTextRange();
  3200. nativeRange.moveToElementText(start);
  3201. nativeRange.moveStart('character', 1);
  3202. if (!this.collapsed) {
  3203. var nativeRangeEnd = this.document.body.createTextRange();
  3204. end = bookmark.end;
  3205. nativeRangeEnd.moveToElementText(end);
  3206. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  3207. } else {
  3208. if (!noFillData && this.startContainer.nodeType != 3) {
  3209. //使用<span>|x<span>固定住光标
  3210. var tmpText = this.document.createTextNode(fillChar),
  3211. tmp = this.document.createElement('span');
  3212. tmp.appendChild(this.document.createTextNode(fillChar));
  3213. start.parentNode.insertBefore(tmp, start);
  3214. start.parentNode.insertBefore(tmpText, start);
  3215. //当点b,i,u时,不能清除i上边的b
  3216. removeFillData(this.document, tmpText);
  3217. fillData = tmpText;
  3218. mergeSibling(tmp, 'previousSibling');
  3219. mergeSibling(start, 'nextSibling');
  3220. nativeRange.moveStart('character', -1);
  3221. nativeRange.collapse(true);
  3222. }
  3223. }
  3224. this.moveToBookmark(bookmark);
  3225. tmp && domUtils.remove(tmp);
  3226. //IE在隐藏状态下不支持range操作,catch一下
  3227. try {
  3228. nativeRange.select();
  3229. } catch (e) {
  3230. }
  3231. return this;
  3232. } : function (notInsertFillData) {
  3233. function checkOffset(rng){
  3234. function check(node,offset,dir){
  3235. if(node.nodeType == 3 && node.nodeValue.length < offset){
  3236. rng[dir + 'Offset'] = node.nodeValue.length
  3237. }
  3238. }
  3239. check(rng.startContainer,rng.startOffset,'start');
  3240. check(rng.endContainer,rng.endOffset,'end');
  3241. }
  3242. var win = domUtils.getWindow(this.document),
  3243. sel = win.getSelection(),
  3244. txtNode;
  3245. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  3246. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  3247. browser.gecko ? this.document.body.focus() : win.focus();
  3248. if (sel) {
  3249. sel.removeAllRanges();
  3250. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  3251. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  3252. if (this.collapsed && !notInsertFillData) {
  3253. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  3254. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  3255. // var tmp = this.document.createTextNode('');
  3256. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  3257. // }
  3258. //
  3259. //处理光标落在文本节点的情况
  3260. //处理以下的情况
  3261. //<b>|xxxx</b>
  3262. //<b>xxxx</b>|xxxx
  3263. //xxxx<b>|</b>
  3264. var start = this.startContainer,child = start;
  3265. if(start.nodeType == 1){
  3266. child = start.childNodes[this.startOffset];
  3267. }
  3268. if( !(start.nodeType == 3 && this.startOffset) &&
  3269. (child ?
  3270. (!child.previousSibling || child.previousSibling.nodeType != 3)
  3271. :
  3272. (!start.lastChild || start.lastChild.nodeType != 3)
  3273. )
  3274. ){
  3275. txtNode = this.document.createTextNode(fillChar);
  3276. //跟着前边走
  3277. this.insertNode(txtNode);
  3278. removeFillData(this.document, txtNode);
  3279. mergeSibling(txtNode, 'previousSibling');
  3280. mergeSibling(txtNode, 'nextSibling');
  3281. fillData = txtNode;
  3282. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  3283. }
  3284. }
  3285. var nativeRange = this.document.createRange();
  3286. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  3287. var child = this.startContainer.childNodes[this.startOffset];
  3288. if(!child){
  3289. //往前靠拢
  3290. child = this.startContainer.lastChild;
  3291. if( child && domUtils.isBr(child)){
  3292. this.setStartBefore(child).collapse(true);
  3293. }
  3294. }else{
  3295. //向后靠拢
  3296. while(child && domUtils.isBlockElm(child)){
  3297. if(child.nodeType == 1 && child.childNodes[0]){
  3298. child = child.childNodes[0]
  3299. }else{
  3300. break;
  3301. }
  3302. }
  3303. child && this.setStartBefore(child).collapse(true)
  3304. }
  3305. }
  3306. //是createAddress最后一位算的不准,现在这里进行微调
  3307. checkOffset(this);
  3308. nativeRange.setStart(this.startContainer, this.startOffset);
  3309. nativeRange.setEnd(this.endContainer, this.endOffset);
  3310. sel.addRange(nativeRange);
  3311. }
  3312. return this;
  3313. },
  3314. /**
  3315. * 滚动条跳到当然range开始的位置
  3316. * @name scrollToView
  3317. * @grammar range.scrollToView([win,offset]) => Range //针对window对象,若不指定,将以编辑区域的窗口为准,offset偏移量
  3318. */
  3319. scrollToView:function (win, offset) {
  3320. win = win ? window : domUtils.getWindow(this.document);
  3321. var me = this,
  3322. span = me.document.createElement('span');
  3323. //trace:717
  3324. span.innerHTML = '&nbsp;';
  3325. me.cloneRange().insertNode(span);
  3326. domUtils.scrollToView(span, win, offset);
  3327. domUtils.remove(span);
  3328. return me;
  3329. },
  3330. inFillChar : function(){
  3331. var start = this.startContainer;
  3332. if(this.collapsed && start.nodeType == 3
  3333. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  3334. ){
  3335. return true;
  3336. }
  3337. return false;
  3338. },
  3339. createAddress : function(ignoreEnd,ignoreTxt){
  3340. var addr = {},me = this;
  3341. function getAddress(isStart){
  3342. var node = isStart ? me.startContainer : me.endContainer;
  3343. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  3344. addrs = [];
  3345. for(var i = 0,ci;ci = parents[i++];){
  3346. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  3347. }
  3348. var firstIndex = 0;
  3349. if(ignoreTxt){
  3350. if(node.nodeType == 3){
  3351. var tmpNode = node;
  3352. while(tmpNode = tmpNode.previousSibling){
  3353. if(tmpNode.nodeType == 3){
  3354. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  3355. }else{
  3356. break;
  3357. }
  3358. }
  3359. firstIndex += (isStart ? me.startOffset : me.endOffset) - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  3360. }else{
  3361. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  3362. if(node){
  3363. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  3364. }else{
  3365. node = isStart ? me.startContainer : me.endContainer;
  3366. var first = node.firstChild;
  3367. while(first){
  3368. if(domUtils.isFillChar(first)){
  3369. first = first.nextSibling;
  3370. continue;
  3371. }
  3372. firstIndex++;
  3373. if(first.nodeType == 3){
  3374. while( first && first.nodeType == 3){
  3375. first = first.nextSibling;
  3376. }
  3377. }else{
  3378. first = first.nextSibling;
  3379. }
  3380. }
  3381. }
  3382. }
  3383. }else{
  3384. firstIndex = isStart ? me.startOffset : me.endOffset
  3385. }
  3386. if(firstIndex < 0){
  3387. firstIndex = 0;
  3388. }
  3389. addrs.push(firstIndex);
  3390. return addrs;
  3391. }
  3392. addr.startAddress = getAddress(true);
  3393. if(!ignoreEnd){
  3394. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  3395. }
  3396. return addr;
  3397. },
  3398. moveToAddress : function(addr,ignoreEnd){
  3399. var me = this;
  3400. function getNode(address,isStart){
  3401. var tmpNode = me.document.body,
  3402. parentNode,offset;
  3403. for(var i= 0,ci,l=address.length;i<l;i++){
  3404. ci = address[i];
  3405. parentNode = tmpNode;
  3406. tmpNode = tmpNode.childNodes[ci];
  3407. if(!tmpNode){
  3408. offset = ci;
  3409. break;
  3410. }
  3411. }
  3412. if(isStart){
  3413. if(tmpNode){
  3414. me.setStartBefore(tmpNode)
  3415. }else{
  3416. me.setStart(parentNode,offset)
  3417. }
  3418. }else{
  3419. if(tmpNode){
  3420. me.setEndBefore(tmpNode)
  3421. }else{
  3422. me.setEnd(parentNode,offset)
  3423. }
  3424. }
  3425. }
  3426. getNode(addr.startAddress,true);
  3427. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  3428. return me;
  3429. },
  3430. equals : function(rng){
  3431. for(var p in this){
  3432. if(this.hasOwnProperty(p)){
  3433. if(this[p] !== rng[p])
  3434. return false
  3435. }
  3436. }
  3437. return true;
  3438. }
  3439. };
  3440. })();
  3441. ///import editor.js
  3442. ///import core/browser.js
  3443. ///import core/dom/dom.js
  3444. ///import core/dom/dtd.js
  3445. ///import core/dom/domUtils.js
  3446. ///import core/dom/Range.js
  3447. /**
  3448. * @class baidu.editor.dom.Selection Selection类
  3449. */
  3450. (function () {
  3451. function getBoundaryInformation( range, start ) {
  3452. var getIndex = domUtils.getNodeIndex;
  3453. range = range.duplicate();
  3454. range.collapse( start );
  3455. var parent = range.parentElement();
  3456. //如果节点里没有子节点,直接退出
  3457. if ( !parent.hasChildNodes() ) {
  3458. return {container:parent, offset:0};
  3459. }
  3460. var siblings = parent.children,
  3461. child,
  3462. testRange = range.duplicate(),
  3463. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  3464. distance;
  3465. while ( startIndex <= endIndex ) {
  3466. index = Math.floor( (startIndex + endIndex) / 2 );
  3467. child = siblings[index];
  3468. testRange.moveToElementText( child );
  3469. var position = testRange.compareEndPoints( 'StartToStart', range );
  3470. if ( position > 0 ) {
  3471. endIndex = index - 1;
  3472. } else if ( position < 0 ) {
  3473. startIndex = index + 1;
  3474. } else {
  3475. //trace:1043
  3476. return {container:parent, offset:getIndex( child )};
  3477. }
  3478. }
  3479. if ( index == -1 ) {
  3480. testRange.moveToElementText( parent );
  3481. testRange.setEndPoint( 'StartToStart', range );
  3482. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  3483. siblings = parent.childNodes;
  3484. if ( !distance ) {
  3485. child = siblings[siblings.length - 1];
  3486. return {container:child, offset:child.nodeValue.length};
  3487. }
  3488. var i = siblings.length;
  3489. while ( distance > 0 ){
  3490. distance -= siblings[ --i ].nodeValue.length;
  3491. }
  3492. return {container:siblings[i], offset:-distance};
  3493. }
  3494. testRange.collapse( position > 0 );
  3495. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  3496. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  3497. if ( !distance ) {
  3498. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  3499. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  3500. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  3501. }
  3502. while ( distance > 0 ) {
  3503. try {
  3504. var pre = child;
  3505. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  3506. distance -= child.nodeValue.length;
  3507. } catch ( e ) {
  3508. return {container:parent, offset:getIndex( pre )};
  3509. }
  3510. }
  3511. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  3512. }
  3513. /**
  3514. * 将ieRange转换为Range对象
  3515. * @param {Range} ieRange ieRange对象
  3516. * @param {Range} range Range对象
  3517. * @return {Range} range 返回转换后的Range对象
  3518. */
  3519. function transformIERangeToRange( ieRange, range ) {
  3520. if ( ieRange.item ) {
  3521. range.selectNode( ieRange.item( 0 ) );
  3522. } else {
  3523. var bi = getBoundaryInformation( ieRange, true );
  3524. range.setStart( bi.container, bi.offset );
  3525. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  3526. bi = getBoundaryInformation( ieRange, false );
  3527. range.setEnd( bi.container, bi.offset );
  3528. }
  3529. }
  3530. return range;
  3531. }
  3532. /**
  3533. * 获得ieRange
  3534. * @param {Selection} sel Selection对象
  3535. * @return {ieRange} 得到ieRange
  3536. */
  3537. function _getIERange( sel ) {
  3538. var ieRange;
  3539. //ie下有可能报错
  3540. try {
  3541. ieRange = sel.getNative().createRange();
  3542. } catch ( e ) {
  3543. return null;
  3544. }
  3545. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  3546. if ( ( el.ownerDocument || el ) === sel.document ) {
  3547. return ieRange;
  3548. }
  3549. return null;
  3550. }
  3551. var Selection = dom.Selection = function ( doc ) {
  3552. var me = this, iframe;
  3553. me.document = doc;
  3554. if ( ie ) {
  3555. iframe = domUtils.getWindow( doc ).frameElement;
  3556. domUtils.on( iframe, 'beforedeactivate', function () {
  3557. me._bakIERange = me.getIERange();
  3558. } );
  3559. domUtils.on( iframe, 'activate', function () {
  3560. try {
  3561. if ( !_getIERange( me ) && me._bakIERange ) {
  3562. me._bakIERange.select();
  3563. }
  3564. } catch ( ex ) {
  3565. }
  3566. me._bakIERange = null;
  3567. } );
  3568. }
  3569. iframe = doc = null;
  3570. };
  3571. Selection.prototype = {
  3572. /**
  3573. * 获取原生seleciton对象
  3574. * @public
  3575. * @function
  3576. * @name baidu.editor.dom.Selection.getNative
  3577. * @return {Selection} 获得selection对象
  3578. */
  3579. getNative:function () {
  3580. var doc = this.document;
  3581. try {
  3582. return !doc ? null : ie ? doc.selection : domUtils.getWindow( doc ).getSelection();
  3583. } catch ( e ) {
  3584. return null;
  3585. }
  3586. },
  3587. /**
  3588. * 获得ieRange
  3589. * @public
  3590. * @function
  3591. * @name baidu.editor.dom.Selection.getIERange
  3592. * @return {ieRange} 返回ie原生的Range
  3593. */
  3594. getIERange:function () {
  3595. var ieRange = _getIERange( this );
  3596. if ( !ieRange ) {
  3597. if ( this._bakIERange ) {
  3598. return this._bakIERange;
  3599. }
  3600. }
  3601. return ieRange;
  3602. },
  3603. /**
  3604. * 缓存当前选区的range和选区的开始节点
  3605. * @public
  3606. * @function
  3607. * @name baidu.editor.dom.Selection.cache
  3608. */
  3609. cache:function () {
  3610. this.clear();
  3611. this._cachedRange = this.getRange();
  3612. this._cachedStartElement = this.getStart();
  3613. this._cachedStartElementPath = this.getStartElementPath();
  3614. },
  3615. getStartElementPath:function () {
  3616. if ( this._cachedStartElementPath ) {
  3617. return this._cachedStartElementPath;
  3618. }
  3619. var start = this.getStart();
  3620. if ( start ) {
  3621. return domUtils.findParents( start, true, null, true )
  3622. }
  3623. return [];
  3624. },
  3625. /**
  3626. * 清空缓存
  3627. * @public
  3628. * @function
  3629. * @name baidu.editor.dom.Selection.clear
  3630. */
  3631. clear:function () {
  3632. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  3633. },
  3634. /**
  3635. * 编辑器是否得到了选区
  3636. */
  3637. isFocus:function () {
  3638. try {
  3639. return browser.ie && _getIERange( this ) || !browser.ie && this.getNative().rangeCount ? true : false;
  3640. } catch ( e ) {
  3641. return false;
  3642. }
  3643. },
  3644. /**
  3645. * 获取选区对应的Range
  3646. * @public
  3647. * @function
  3648. * @name baidu.editor.dom.Selection.getRange
  3649. * @returns {baidu.editor.dom.Range} 得到Range对象
  3650. */
  3651. getRange:function () {
  3652. var me = this;
  3653. function optimze( range ) {
  3654. var child = me.document.body.firstChild,
  3655. collapsed = range.collapsed;
  3656. while ( child && child.firstChild ) {
  3657. range.setStart( child, 0 );
  3658. child = child.firstChild;
  3659. }
  3660. if ( !range.startContainer ) {
  3661. range.setStart( me.document.body, 0 )
  3662. }
  3663. if ( collapsed ) {
  3664. range.collapse( true );
  3665. }
  3666. }
  3667. if ( me._cachedRange != null ) {
  3668. return this._cachedRange;
  3669. }
  3670. var range = new baidu.editor.dom.Range( me.document );
  3671. if ( ie ) {
  3672. var nativeRange = me.getIERange();
  3673. if ( nativeRange ) {
  3674. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  3675. try{
  3676. transformIERangeToRange( nativeRange, range );
  3677. }catch(e){
  3678. optimze( range );
  3679. }
  3680. } else {
  3681. optimze( range );
  3682. }
  3683. } else {
  3684. var sel = me.getNative();
  3685. if ( sel && sel.rangeCount ) {
  3686. var firstRange = sel.getRangeAt( 0 );
  3687. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  3688. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  3689. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  3690. optimze( range );
  3691. }
  3692. } else {
  3693. //trace:1734 有可能已经不在dom树上了,标识的节点
  3694. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  3695. return this._bakRange;
  3696. }
  3697. optimze( range );
  3698. }
  3699. }
  3700. return this._bakRange = range;
  3701. },
  3702. /**
  3703. * 获取开始元素,用于状态反射
  3704. * @public
  3705. * @function
  3706. * @name baidu.editor.dom.Selection.getStart
  3707. * @return {Element} 获得开始元素
  3708. */
  3709. getStart:function () {
  3710. if ( this._cachedStartElement ) {
  3711. return this._cachedStartElement;
  3712. }
  3713. var range = ie ? this.getIERange() : this.getRange(),
  3714. tmpRange,
  3715. start, tmp, parent;
  3716. if ( ie ) {
  3717. if ( !range ) {
  3718. //todo 给第一个值可能会有问题
  3719. return this.document.body.firstChild;
  3720. }
  3721. //control元素
  3722. if ( range.item ){
  3723. return range.item( 0 );
  3724. }
  3725. tmpRange = range.duplicate();
  3726. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  3727. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  3728. tmpRange.collapse( 1 );
  3729. start = tmpRange.parentElement();
  3730. parent = tmp = range.parentElement();
  3731. while ( tmp = tmp.parentNode ) {
  3732. if ( tmp == start ) {
  3733. start = parent;
  3734. break;
  3735. }
  3736. }
  3737. } else {
  3738. range.shrinkBoundary();
  3739. start = range.startContainer;
  3740. if ( start.nodeType == 1 && start.hasChildNodes() ){
  3741. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  3742. }
  3743. if ( start.nodeType == 3 ){
  3744. return start.parentNode;
  3745. }
  3746. }
  3747. return start;
  3748. },
  3749. /**
  3750. * 得到选区中的文本
  3751. * @public
  3752. * @function
  3753. * @name baidu.editor.dom.Selection.getText
  3754. * @return {String} 选区中包含的文本
  3755. */
  3756. getText:function () {
  3757. var nativeSel, nativeRange;
  3758. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  3759. nativeRange = browser.ie ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  3760. return browser.ie ? nativeRange.text : nativeRange.toString();
  3761. }
  3762. return '';
  3763. },
  3764. clearRange : function(){
  3765. this.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  3766. }
  3767. };
  3768. })();
  3769. /**
  3770. * @file
  3771. * @name UE.Editor
  3772. * @short Editor
  3773. * @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
  3774. * @desc 编辑器主类,包含编辑器提供的大部分公用接口
  3775. */
  3776. (function () {
  3777. var uid = 0,_selectionChangeTimer;
  3778. /**
  3779. * 替换src和href
  3780. * @private
  3781. * @ignore
  3782. * @param div
  3783. */
  3784. function replaceSrc( div ) {
  3785. var imgs = div.getElementsByTagName( "img" ),
  3786. orgSrc;
  3787. for ( var i = 0, img; img = imgs[i++]; ) {
  3788. if ( orgSrc = img.getAttribute( "orgSrc" ) ) {
  3789. img.src = orgSrc;
  3790. img.removeAttribute( "orgSrc" );
  3791. }
  3792. }
  3793. var as = div.getElementsByTagName( "a" );
  3794. for ( var i = 0, ai; ai = as[i++]; i++ ) {
  3795. if ( ai.getAttribute( 'data_ue_src' ) ) {
  3796. ai.setAttribute( 'href', ai.getAttribute( 'data_ue_src' ) )
  3797. }
  3798. }
  3799. }
  3800. /**
  3801. * @private
  3802. * @ignore
  3803. * @param form 编辑器所在的form元素
  3804. * @param editor 编辑器实例对象
  3805. */
  3806. function setValue( form, editor ) {
  3807. var textarea;
  3808. if ( editor.textarea ) {
  3809. if ( utils.isString( editor.textarea ) ) {
  3810. for ( var i = 0, ti, tis = domUtils.getElementsByTagName( form, 'textarea' ); ti = tis[i++]; ) {
  3811. if ( ti.id == 'ueditor_textarea_' + editor.options.textarea ) {
  3812. textarea = ti;
  3813. break;
  3814. }
  3815. }
  3816. } else {
  3817. textarea = editor.textarea;
  3818. }
  3819. }
  3820. if ( !textarea ) {
  3821. form.appendChild( textarea = domUtils.createElement( document, 'textarea', {
  3822. 'name':editor.options.textarea,
  3823. 'id':'ueditor_textarea_' + editor.options.textarea,
  3824. 'style':"display:none"
  3825. } ) );
  3826. //不要产生多个textarea
  3827. editor.textarea = textarea;
  3828. }
  3829. textarea.value = editor.hasContents() ?
  3830. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null,null,true)):
  3831. ''
  3832. }
  3833. /**
  3834. * UEditor编辑器类
  3835. * @name Editor
  3836. * @desc 创建一个跟编辑器实例
  3837. * - ***container*** 编辑器容器对象
  3838. * - ***iframe*** 编辑区域所在的iframe对象
  3839. * - ***window*** 编辑区域所在的window
  3840. * - ***document*** 编辑区域所在的document对象
  3841. * - ***body*** 编辑区域所在的body对象
  3842. * - ***selection*** 编辑区域的选区对象
  3843. */
  3844. var Editor = UE.Editor = function ( options ) {
  3845. var me = this;
  3846. me.uid = uid++;
  3847. EventBase.call( me );
  3848. me.commands = {};
  3849. me.options = utils.extend( utils.clone(options || {}),UEDITOR_CONFIG, true );
  3850. me.shortcutkeys = {};
  3851. //设置默认的常用属性
  3852. me.setOpt( {
  3853. isShow:true,
  3854. initialContent:'欢迎使用ueditor!',
  3855. autoClearinitialContent:false,
  3856. iframeCssUrl:me.options.UEDITOR_HOME_URL + 'themes/iframe.css',
  3857. textarea:'editorValue',
  3858. focus:false,
  3859. initialFrameWidth:1000,
  3860. initialFrameHeight:me.options.minFrameHeight||320,//兼容老版本配置项
  3861. minFrameWidth:800,
  3862. minFrameHeight:220,
  3863. autoClearEmptyNode:true,
  3864. fullscreen:false,
  3865. readonly:false,
  3866. zIndex:999,
  3867. imagePopup:true,
  3868. enterTag:'p',
  3869. pageBreakTag:'_baidu_page_break_tag_',
  3870. customDomain:false,
  3871. lang:'zh-cn',
  3872. langPath:me.options.UEDITOR_HOME_URL + 'lang/',
  3873. theme:'default',
  3874. themePath:me.options.UEDITOR_HOME_URL + 'themes/',
  3875. allHtmlEnabled:false,
  3876. scaleEnabled:false,
  3877. tableNativeEditInFF:false
  3878. } );
  3879. utils.loadFile( document, {
  3880. src:me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  3881. tag:"script",
  3882. type:"text/javascript",
  3883. defer:"defer"
  3884. }, function () {
  3885. //初始化插件
  3886. for ( var pi in UE.plugins ) {
  3887. UE.plugins[pi].call( me );
  3888. }
  3889. me.langIsReady = true;
  3890. me.fireEvent( "langReady" );
  3891. });
  3892. UE.instants['ueditorInstant' + me.uid] = me;
  3893. };
  3894. Editor.prototype = {
  3895. /**
  3896. * 当编辑器ready后执行传入的fn,如果编辑器已经完成ready,就马上执行fn,fn的中的this是编辑器实例。
  3897. * 大部分的实例接口都需要放在该方法内部执行,否则在IE下可能会报错。
  3898. * @name ready
  3899. * @grammar editor.ready(fn) fn是当编辑器渲染好后执行的function
  3900. * @example
  3901. * var editor = new UE.ui.Editor();
  3902. * editor.render("myEditor");
  3903. * editor.ready(function(){
  3904. * editor.setContent("欢迎使用UEditor!");
  3905. * })
  3906. */
  3907. ready:function ( fn ) {
  3908. var me = this;
  3909. if ( fn ){
  3910. me.isReady ? fn.apply( me ) : me.addListener( 'ready', fn );
  3911. }
  3912. },
  3913. /**
  3914. * 为编辑器设置默认参数值。若用户配置为空,则以默认配置为准
  3915. * @grammar editor.setOpt(key,value); //传入一个键、值对
  3916. * @grammar editor.setOpt({ key:value}); //传入一个json对象
  3917. */
  3918. setOpt:function ( key, val ) {
  3919. var obj = {};
  3920. if ( utils.isString( key ) ) {
  3921. obj[key] = val
  3922. } else {
  3923. obj = key;
  3924. }
  3925. utils.extend( this.options, obj, true );
  3926. },
  3927. /**
  3928. * 销毁编辑器实例对象
  3929. * @name destroy
  3930. * @grammar editor.destroy();
  3931. */
  3932. destroy:function () {
  3933. var me = this;
  3934. me.fireEvent( 'destroy' );
  3935. var container = me.container.parentNode;
  3936. var textarea = me.textarea;
  3937. if(!textarea){
  3938. textarea = document.createElement('textarea');
  3939. container.parentNode.insertBefore(textarea,container);
  3940. }else{
  3941. textarea.style.display = ''
  3942. }
  3943. textarea.style.width = container.offsetWidth + 'px';
  3944. textarea.style.height = container.offsetHeight + 'px';
  3945. textarea.value = me.getContent();
  3946. textarea.id = me.key;
  3947. container.innerHTML = '';
  3948. domUtils.remove( container );
  3949. var key = me.key;
  3950. //trace:2004
  3951. for ( var p in me ) {
  3952. if ( me.hasOwnProperty( p ) ) {
  3953. delete this[p];
  3954. }
  3955. }
  3956. UE.delEditor(key);
  3957. },
  3958. /**
  3959. * 渲染编辑器的DOM到指定容器,必须且只能调用一次
  3960. * @name render
  3961. * @grammar editor.render(containerId); //可以指定一个容器ID
  3962. * @grammar editor.render(containerDom); //也可以直接指定容器对象
  3963. */
  3964. render:function ( container ) {
  3965. var me = this, options = me.options;
  3966. if ( utils.isString(container) ) {
  3967. container = document.getElementById( container );
  3968. }
  3969. if ( container ) {
  3970. var useBodyAsViewport = ie && browser.version < 9,
  3971. html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  3972. '<html xmlns=\'http://www.w3.org/1999/xhtml\'' + (!useBodyAsViewport ? ' class=\'view\'' : '') + '><head>' +
  3973. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml( options.iframeCssUrl ) + '\'/>' : '' ) +
  3974. '<style type=\'text/css\'>' +
  3975. //设置四周的留边
  3976. '.view{padding:0;word-wrap:break-word;cursor:text;height:100%;}\n' +
  3977. //设置默认字体和字号
  3978. //font-family不能呢随便改,在safari下fillchar会有解析问题
  3979. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  3980. //设置段落间距
  3981. 'p{margin:5px 0;}'
  3982. + ( options.initialStyle || '' ) +
  3983. '</style></head><body' + (useBodyAsViewport ? ' class=\'view\'' : '') + '></body>';
  3984. if ( options.customDomain && document.domain != location.hostname ) {
  3985. html += '<script>window.parent.UE.instants[\'ueditorInstant' + me.uid + '\']._setup(document);</script></html>';
  3986. container.appendChild( domUtils.createElement( document, 'iframe', {
  3987. id:'baidu_editor_' + me.uid,
  3988. width:"100%",
  3989. height:"100%",
  3990. frameborder:"0",
  3991. src:'javascript:void(function(){document.open();document.domain="' + document.domain + '";' +
  3992. 'document.write("' + html + '");document.close();}())'
  3993. } ) );
  3994. } else {
  3995. container.innerHTML = '<iframe id="' + 'baidu_editor_' + this.uid + '"' + 'width="100%" height="100%" scroll="no" frameborder="0" ></iframe>';
  3996. var doc = container.firstChild.contentWindow.document;
  3997. //去掉了原来的判断!browser.webkit,因为会导致onload注册的事件不触发
  3998. doc.open();
  3999. doc.write( html + '</html>' );
  4000. doc.close();
  4001. me._setup( doc );
  4002. }
  4003. container.style.overflow = 'hidden';
  4004. }
  4005. },
  4006. /**
  4007. * 编辑器初始化
  4008. * @private
  4009. * @ignore
  4010. * @param {Element} doc 编辑器Iframe中的文档对象
  4011. */
  4012. _setup:function ( doc ) {
  4013. var me = this,
  4014. options = me.options;
  4015. if ( ie ) {
  4016. doc.body.disabled = true;
  4017. doc.body.contentEditable = true;
  4018. doc.body.disabled = false;
  4019. } else {
  4020. doc.body.contentEditable = true;
  4021. doc.body.spellcheck = false;
  4022. }
  4023. me.document = doc;
  4024. me.window = doc.defaultView || doc.parentWindow;
  4025. me.iframe = me.window.frameElement;
  4026. me.body = doc.body;
  4027. //设置编辑器最小高度
  4028. me.setHeight( Math.max(options.minFrameHeight, options.initialFrameHeight));
  4029. me.selection = new dom.Selection( doc );
  4030. //gecko初始化就能得到range,无法判断isFocus了
  4031. var geckoSel;
  4032. if ( browser.gecko && (geckoSel = this.selection.getNative()) ) {
  4033. geckoSel.removeAllRanges();
  4034. }
  4035. this._initEvents();
  4036. if ( options.initialContent ) {
  4037. if ( options.autoClearinitialContent ) {
  4038. var oldExecCommand = me.execCommand;
  4039. me.execCommand = function () {
  4040. me.fireEvent( 'firstBeforeExecCommand' );
  4041. return oldExecCommand.apply( me, arguments );
  4042. };
  4043. this._setDefaultContent( options.initialContent );
  4044. } else
  4045. this.setContent( options.initialContent, false,true );
  4046. }
  4047. //为form提交提供一个隐藏的textarea
  4048. for ( var form = this.iframe.parentNode; !domUtils.isBody( form ); form = form.parentNode ) {
  4049. if ( form.tagName == 'FORM' ) {
  4050. domUtils.on( form, 'submit', function () {
  4051. setValue( this, me );
  4052. } );
  4053. break;
  4054. }
  4055. }
  4056. //编辑器不能为空内容
  4057. if ( domUtils.isEmptyNode( me.body ) ) {
  4058. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  4059. }
  4060. //如果要求focus, 就把光标定位到内容开始
  4061. if ( options.focus ) {
  4062. setTimeout( function () {
  4063. me.focus();
  4064. //如果自动清除开着,就不需要做selectionchange;
  4065. !me.options.autoClearinitialContent && me._selectionChange();
  4066. },0);
  4067. }
  4068. if ( !me.container ) {
  4069. me.container = this.iframe.parentNode;
  4070. }
  4071. if ( options.fullscreen && me.ui ) {
  4072. me.ui.setFullScreen( true );
  4073. }
  4074. try {
  4075. me.document.execCommand( '2D-position', false, false );
  4076. } catch ( e ) {}
  4077. try {
  4078. me.document.execCommand( 'enableInlineTableEditing', false, false );
  4079. } catch ( e ) {}
  4080. try {
  4081. me.document.execCommand( 'enableObjectResizing', false, false );
  4082. } catch ( e ) {
  4083. // domUtils.on(me.body,browser.ie ? 'resizestart' : 'resize', function( evt ) {
  4084. // domUtils.preventDefault(evt)
  4085. // });
  4086. }
  4087. me._bindshortcutKeys();
  4088. me.isReady = 1;
  4089. me.fireEvent( 'ready' );
  4090. options.onready && options.onready.call(me);
  4091. if ( !browser.ie ) {
  4092. domUtils.on( me.window, ['blur', 'focus'], function ( e ) {
  4093. //chrome下会出现alt+tab切换时,导致选区位置不对
  4094. if ( e.type == 'blur' ) {
  4095. me._bakRange = me.selection.getRange();
  4096. try{
  4097. me.selection.getNative().removeAllRanges();
  4098. }catch(e){}
  4099. } else {
  4100. try {
  4101. me._bakRange && me._bakRange.select();
  4102. } catch ( e ) {
  4103. }
  4104. }
  4105. } );
  4106. }
  4107. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  4108. if ( browser.gecko && browser.version <= 10902 ) {
  4109. //修复ff3.6初始化进来,不能点击获得焦点
  4110. me.body.contentEditable = false;
  4111. setTimeout( function () {
  4112. me.body.contentEditable = true;
  4113. }, 100 );
  4114. setInterval( function () {
  4115. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  4116. }, 100 )
  4117. }
  4118. !options.isShow && me.setHide();
  4119. options.readonly && me.setDisabled();
  4120. },
  4121. /**
  4122. * 同步编辑器的数据,为提交数据做准备,主要用于你是手动提交的情况
  4123. * @name sync
  4124. * @grammar editor.sync(); //从编辑器的容器向上查找,如果找到就同步数据
  4125. * @grammar editor.sync(formID); //formID制定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  4126. * @desc
  4127. * 后台取得数据得键值使用你容器上得''name''属性,如果没有就使用参数传入的''textarea''
  4128. * @example
  4129. * editor.sync();
  4130. * form.sumbit(); //form变量已经指向了form元素
  4131. *
  4132. */
  4133. sync:function ( formId ) {
  4134. var me = this,
  4135. form = formId ? document.getElementById( formId ) :
  4136. domUtils.findParent( me.iframe.parentNode, function ( node ) {
  4137. return node.tagName == 'FORM'
  4138. }, true );
  4139. form && setValue( form, me );
  4140. },
  4141. /**
  4142. * 设置编辑器高度
  4143. * @name setHeight
  4144. * @grammar editor.setHeight(number); //纯数值,不带单位
  4145. */
  4146. setHeight:function ( height ) {
  4147. if ( height !== parseInt( this.iframe.parentNode.style.height ) ) {
  4148. this.iframe.parentNode.style.height = height + 'px';
  4149. }
  4150. this.document.body.style.height = height - 20 + 'px';
  4151. },
  4152. addshortcutkey : function(cmd,keys){
  4153. var obj = {};
  4154. if(keys){
  4155. obj[cmd] = keys
  4156. }else{
  4157. obj = cmd;
  4158. }
  4159. utils.extend(this.shortcutkeys,obj)
  4160. },
  4161. _bindshortcutKeys : function(){
  4162. var me = this,shortcutkeys = this.shortcutkeys;
  4163. me.addListener('keydown',function(type,e){
  4164. var keyCode = e.keyCode || e.which;
  4165. for ( var i in shortcutkeys ) {
  4166. var tmp = shortcutkeys[i].split(',');
  4167. for(var t= 0,ti;ti=tmp[t++];){
  4168. ti = ti.split(':');
  4169. var key = ti[0],param = ti[1];
  4170. if ( /^(ctrl)(\+shift)?\+(\d+)$/.test( key.toLowerCase() ) || /^(\d+)$/.test( key ) ) {
  4171. if ( ( (RegExp.$1 == 'ctrl' ? (e.ctrlKey||e.metaKey) : 0)
  4172. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  4173. && keyCode == RegExp.$3
  4174. ) ||
  4175. keyCode == RegExp.$1
  4176. ){
  4177. me.execCommand(i,param);
  4178. domUtils.preventDefault(e);
  4179. }
  4180. }
  4181. }
  4182. }
  4183. });
  4184. },
  4185. /**
  4186. * 获取编辑器内容
  4187. * @name getContent
  4188. * @grammar editor.getContent() => String //若编辑器中只包含字符"&lt;p&gt;&lt;br /&gt;&lt;/p/&gt;"会返回空。
  4189. * @grammar editor.getContent(fn) => String
  4190. * @example
  4191. * getContent默认是会现调用hasContents来判断编辑器是否为空,如果是,就直接返回空字符串
  4192. * 你也可以传入一个fn来接替hasContents的工作,定制判断的规则
  4193. * editor.getContent(function(){
  4194. * return false //编辑器没有内容 ,getContent直接返回空
  4195. * })
  4196. */
  4197. getContent:function ( cmd, fn, isPreview ) {
  4198. var me = this;
  4199. if ( cmd && utils.isFunction( cmd ) ) {
  4200. fn = cmd;
  4201. cmd = '';
  4202. }
  4203. if ( fn ? !fn() : !this.hasContents() ) {
  4204. return '';
  4205. }
  4206. var range = me.selection.getRange(),
  4207. address = range.createAddress();
  4208. me.fireEvent( 'beforegetcontent', cmd );
  4209. var reg = new RegExp( domUtils.fillChar, 'g' ),
  4210. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  4211. html = me.body.innerHTML.replace( reg, '' ).replace( />[\t\r\n]*?</g, '><' );
  4212. me.fireEvent( 'aftergetcontent', cmd );
  4213. try{
  4214. range.moveToAddress(address).select(true);
  4215. }catch(e){}
  4216. if ( me.serialize ) {
  4217. var node = me.serialize.parseHTML( html );
  4218. node = me.serialize.transformOutput( node );
  4219. html = me.serialize.toHTML( node );
  4220. }
  4221. if ( ie && isPreview ) {
  4222. //trace:2471
  4223. //两个br会导致空行,所以这里先注视掉
  4224. html = html//.replace(/<\s*br\s*\/?\s*>/gi,'<br/><br/>')
  4225. .replace( /<p>\s*?<\/p>/g, '<p>&nbsp;</p>' );
  4226. } else {
  4227. //多个&nbsp;要转换成空格加&nbsp;的形式,要不预览时会所成一个
  4228. html = html.replace( /(&nbsp;)+/g, function ( s ) {
  4229. for ( var i = 0, str = [], l = s.split( ';' ).length - 1; i < l; i++ ) {
  4230. str.push( i % 2 == 0 ? ' ' : '&nbsp;' );
  4231. }
  4232. return str.join( '' );
  4233. } );
  4234. }
  4235. return html;
  4236. },
  4237. /**
  4238. * 取得完整的html代码,可以直接显示成完整的html文档
  4239. * @name getAllHtml
  4240. * @grammar editor.getAllHtml() => String
  4241. */
  4242. getAllHtml:function () {
  4243. var me = this,
  4244. headHtml = [],
  4245. html = '';
  4246. me.fireEvent( 'getAllHtml', headHtml );
  4247. if(browser.ie && browser.version > 8){
  4248. var headHtmlForIE9= '';
  4249. utils.each(me.document.styleSheets,function(si){
  4250. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="'+si.href+'" />': '<style>'+si.cssText+'</style>');
  4251. });
  4252. utils.each(me.document.getElementsByTagName('script'),function(si){
  4253. headHtmlForIE9 += si.outerHTML;
  4254. });
  4255. }
  4256. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  4257. + (headHtmlForIE9 || me.document.getElementsByTagName( 'head' )[0].innerHTML) + headHtml.join('\n') + '</head>'
  4258. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent( null, null, true ) + '</body></html>';
  4259. },
  4260. /**
  4261. * 得到编辑器的纯文本内容,但会保留段落格式
  4262. * @name getPlainTxt
  4263. * @grammar editor.getPlainTxt() => String
  4264. */
  4265. getPlainTxt:function () {
  4266. var reg = new RegExp( domUtils.fillChar, 'g' ),
  4267. html = this.body.innerHTML.replace( /[\n\r]/g, '' );//ie要先去了\n在处理
  4268. html = html.replace( /<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n' )
  4269. .replace( /<br\/?>/gi, '\n' )
  4270. .replace( /<[^>/]+>/g, '' )
  4271. .replace( /(\n)?<\/([^>]+)>/g, function ( a, b, c ) {
  4272. return dtd.$block[c] ? '\n' : b ? b : '';
  4273. } );
  4274. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  4275. return html.replace( reg, '' ).replace( /\u00a0/g, ' ' ).replace( /&nbsp;/g, ' ' );
  4276. },
  4277. /**
  4278. * 获取编辑器中的纯文本内容,没有段落格式
  4279. * @name getContentTxt
  4280. * @grammar editor.getContentTxt() => String
  4281. */
  4282. getContentTxt:function () {
  4283. var reg = new RegExp( domUtils.fillChar, 'g' );
  4284. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  4285. return this.body[browser.ie ? 'innerText' : 'textContent'].replace( reg, '' ).replace( /\u00a0/g, ' ' );
  4286. },
  4287. /**
  4288. * 将html设置到编辑器中, 如果是用于初始化时给编辑器赋初值,则必须放在ready方法内部执行
  4289. * @name setContent
  4290. * @grammar editor.setContent(html)
  4291. * @example
  4292. * var editor = new UE.ui.Editor()
  4293. * editor.ready(function(){
  4294. * //需要ready后执行,否则可能报错
  4295. * editor.setContent("欢迎使用UEditor!");
  4296. * })
  4297. */
  4298. setContent:function ( html, isAppendTo,notFireSelectionchange ) {
  4299. var me = this,
  4300. inline = utils.extend( {a:1, A:1}, dtd.$inline, true ),
  4301. lastTagName;
  4302. html = html
  4303. .replace( /^[ \t\r\n]*?</, '<' )
  4304. .replace( />[ \t\r\n]*?$/, '>' )
  4305. //ie有时的源码会有>&nbsp;<的情况
  4306. .replace(/>(?:(\s|&nbsp;)*?)</g,'><' )//代码高量的\n不能去除
  4307. .replace( /[\s\/]?(\w+)?>[ \t\r\n]*?<\/?(\w+)/gi, function ( a, b, c ) {
  4308. if ( b ) {
  4309. lastTagName = c;
  4310. } else {
  4311. b = lastTagName;
  4312. }
  4313. return !inline[b] && !inline[c] ? a.replace( />[ \t\r\n]*?</, '><' ) : a;
  4314. } );
  4315. html = {'html':html};
  4316. me.fireEvent( 'beforesetcontent',html );
  4317. html = html.html;
  4318. var serialize = this.serialize;
  4319. if ( serialize ) {
  4320. var node = serialize.parseHTML( html );
  4321. node = serialize.transformInput( node );
  4322. node = serialize.filter( node );
  4323. html = serialize.toHTML( node );
  4324. }
  4325. //html.replace(new RegExp('[\t\n\r' + domUtils.fillChar + ']*','g'),'');
  4326. //去掉了\t\n\r 如果有插入的代码,在源码切换所见即所得模式时,换行都丢掉了
  4327. //\r在ie下的不可见字符,在源码切换时会变成多个&nbsp;
  4328. //trace:1559
  4329. this.body.innerHTML = (isAppendTo ? this.getContent() : '') + html.replace( new RegExp( '[\r' + domUtils.fillChar + ']*', 'g' ), '' );
  4330. //处理ie6下innerHTML自动将相对路径转化成绝对路径的问题
  4331. if ( browser.ie && browser.version < 7 ) {
  4332. replaceSrc( this.document.body );
  4333. }
  4334. //给文本或者inline节点套p标签
  4335. if ( me.options.enterTag == 'p' ) {
  4336. var child = this.body.firstChild, tmpNode;
  4337. if ( !child || child.nodeType == 1 &&
  4338. (dtd.$cdata[child.tagName] ||
  4339. domUtils.isCustomeNode( child )
  4340. )
  4341. && child === this.body.lastChild ) {
  4342. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  4343. } else {
  4344. var p = me.document.createElement( 'p' );
  4345. while ( child ) {
  4346. while ( child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName]) ) {
  4347. tmpNode = child.nextSibling;
  4348. p.appendChild( child );
  4349. child = tmpNode;
  4350. }
  4351. if ( p.firstChild ) {
  4352. if ( !child ) {
  4353. me.body.appendChild( p );
  4354. break;
  4355. } else {
  4356. child.parentNode.insertBefore( p, child );
  4357. p = me.document.createElement( 'p' );
  4358. }
  4359. }
  4360. child = child.nextSibling;
  4361. }
  4362. }
  4363. }
  4364. me.fireEvent( 'aftersetcontent' );
  4365. me.fireEvent( 'contentchange' );
  4366. !notFireSelectionchange && me._selectionChange();
  4367. //清除保存的选区
  4368. me._bakRange = me._bakIERange = null;
  4369. //trace:1742 setContent后gecko能得到焦点问题
  4370. var geckoSel;
  4371. if ( browser.gecko && (geckoSel = this.selection.getNative()) ) {
  4372. geckoSel.removeAllRanges();
  4373. }
  4374. },
  4375. /**
  4376. * 让编辑器获得焦点,toEnd确定focus位置
  4377. * @name focus
  4378. * @grammar editor.focus([toEnd]) //默认focus到编辑器头部,toEnd为true时focus到内容尾部
  4379. */
  4380. focus:function ( toEnd ) {
  4381. try {
  4382. var me = this,
  4383. rng = me.selection.getRange();
  4384. if ( toEnd ) {
  4385. rng.setStartAtLast( me.body.lastChild ).setCursor( false, true );
  4386. } else {
  4387. rng.select( true );
  4388. }
  4389. } catch ( e ) {
  4390. }
  4391. },
  4392. /**
  4393. * 初始化UE事件及部分事件代理
  4394. * @private
  4395. * @ignore
  4396. */
  4397. _initEvents:function () {
  4398. var me = this,
  4399. doc = me.document,
  4400. win = me.window;
  4401. me._proxyDomEvent = utils.bind( me._proxyDomEvent, me );
  4402. domUtils.on( doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent );
  4403. domUtils.on( win, ['focus', 'blur'], me._proxyDomEvent );
  4404. domUtils.on( doc, ['mouseup', 'keydown'], function ( evt ) {
  4405. //特殊键不触发selectionchange
  4406. if ( evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey) ) {
  4407. return;
  4408. }
  4409. if ( evt.button == 2 )return;
  4410. me._selectionChange( 250, evt );
  4411. } );
  4412. //处理拖拽
  4413. //ie ff不能从外边拖入
  4414. //chrome只针对从外边拖入的内容过滤
  4415. var innerDrag = 0, source = browser.ie ? me.body : me.document, dragoverHandler;
  4416. domUtils.on( source, 'dragstart', function () {
  4417. innerDrag = 1;
  4418. } );
  4419. domUtils.on( source, browser.webkit ? 'dragover' : 'drop', function () {
  4420. return browser.webkit ?
  4421. function () {
  4422. clearTimeout( dragoverHandler );
  4423. dragoverHandler = setTimeout( function () {
  4424. if ( !innerDrag ) {
  4425. var sel = me.selection,
  4426. range = sel.getRange();
  4427. if ( range ) {
  4428. var common = range.getCommonAncestor();
  4429. if ( common && me.serialize ) {
  4430. var f = me.serialize,
  4431. node =
  4432. f.filter(
  4433. f.transformInput(
  4434. f.parseHTML(
  4435. f.word( common.innerHTML )
  4436. )
  4437. )
  4438. );
  4439. common.innerHTML = f.toHTML( node );
  4440. }
  4441. }
  4442. }
  4443. innerDrag = 0;
  4444. }, 200 );
  4445. } :
  4446. function ( e ) {
  4447. if ( !innerDrag ) {
  4448. e.preventDefault ? e.preventDefault() : (e.returnValue = false);
  4449. }
  4450. innerDrag = 0;
  4451. }
  4452. }() );
  4453. },
  4454. /**
  4455. * 触发事件代理
  4456. * @private
  4457. * @ignore
  4458. */
  4459. _proxyDomEvent:function ( evt ) {
  4460. return this.fireEvent( evt.type.replace( /^on/, '' ), evt );
  4461. },
  4462. /**
  4463. * 变化选区
  4464. * @private
  4465. * @ignore
  4466. */
  4467. _selectionChange:function ( delay, evt ) {
  4468. var me = this;
  4469. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  4470. // if ( !me.selection.isFocus() ){
  4471. // return;
  4472. // }
  4473. var hackForMouseUp = false;
  4474. var mouseX, mouseY;
  4475. if ( browser.ie && browser.version < 9 && evt && evt.type == 'mouseup' ) {
  4476. var range = this.selection.getRange();
  4477. if ( !range.collapsed ) {
  4478. hackForMouseUp = true;
  4479. mouseX = evt.clientX;
  4480. mouseY = evt.clientY;
  4481. }
  4482. }
  4483. clearTimeout( _selectionChangeTimer );
  4484. _selectionChangeTimer = setTimeout( function () {
  4485. if ( !me.selection.getNative() ) {
  4486. return;
  4487. }
  4488. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  4489. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  4490. var ieRange;
  4491. if ( hackForMouseUp && me.selection.getNative().type == 'None' ) {
  4492. ieRange = me.document.body.createTextRange();
  4493. try {
  4494. ieRange.moveToPoint( mouseX, mouseY );
  4495. } catch ( ex ) {
  4496. ieRange = null;
  4497. }
  4498. }
  4499. var bakGetIERange;
  4500. if ( ieRange ) {
  4501. bakGetIERange = me.selection.getIERange;
  4502. me.selection.getIERange = function () {
  4503. return ieRange;
  4504. };
  4505. }
  4506. me.selection.cache();
  4507. if ( bakGetIERange ) {
  4508. me.selection.getIERange = bakGetIERange;
  4509. }
  4510. if ( me.selection._cachedRange && me.selection._cachedStartElement ) {
  4511. me.fireEvent( 'beforeselectionchange' );
  4512. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  4513. me.fireEvent( 'selectionchange', !!evt );
  4514. me.fireEvent( 'afterselectionchange' );
  4515. me.selection.clear();
  4516. }
  4517. }, delay || 50 );
  4518. },
  4519. _callCmdFn:function ( fnName, args ) {
  4520. var cmdName = args[0].toLowerCase(),
  4521. cmd, cmdFn;
  4522. cmd = this.commands[cmdName] || UE.commands[cmdName];
  4523. cmdFn = cmd && cmd[fnName];
  4524. //没有querycommandstate或者没有command的都默认返回0
  4525. if ( (!cmd || !cmdFn) && fnName == 'queryCommandState' ) {
  4526. return 0;
  4527. } else if ( cmdFn ) {
  4528. return cmdFn.apply( this, args );
  4529. }
  4530. },
  4531. /**
  4532. * 执行编辑命令cmdName,完成富文本编辑效果
  4533. * @name execCommand
  4534. * @grammar editor.execCommand(cmdName) => {*}
  4535. */
  4536. execCommand:function ( cmdName ) {
  4537. cmdName = cmdName.toLowerCase();
  4538. var me = this,
  4539. result,
  4540. cmd = me.commands[cmdName] || UE.commands[cmdName];
  4541. if ( !cmd || !cmd.execCommand ) {
  4542. return null;
  4543. }
  4544. if ( !cmd.notNeedUndo && !me.__hasEnterExecCommand ) {
  4545. me.__hasEnterExecCommand = true;
  4546. if ( me.queryCommandState( cmdName ) != -1 ) {
  4547. me.fireEvent( 'beforeexeccommand', cmdName );
  4548. result = this._callCmdFn( 'execCommand', arguments );
  4549. !me._ignoreContentChange && me.fireEvent('contentchange');
  4550. me.fireEvent( 'afterexeccommand', cmdName );
  4551. }
  4552. me.__hasEnterExecCommand = false;
  4553. } else {
  4554. result = this._callCmdFn( 'execCommand', arguments );
  4555. !me._ignoreContentChange && me.fireEvent('contentchange')
  4556. }
  4557. !me._ignoreContentChange && me._selectionChange();
  4558. return result;
  4559. },
  4560. /**
  4561. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  4562. * @name queryCommandState
  4563. * @grammar editor.queryCommandState(cmdName) => (-1|0|1)
  4564. * @desc
  4565. * * ''-1'' 当前命令不可用
  4566. * * ''0'' 当前命令可用
  4567. * * ''1'' 当前命令已经执行过了
  4568. */
  4569. queryCommandState:function ( cmdName ) {
  4570. return this._callCmdFn( 'queryCommandState', arguments );
  4571. },
  4572. /**
  4573. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  4574. * @name queryCommandValue
  4575. * @grammar editor.queryCommandValue(cmdName) => {*}
  4576. */
  4577. queryCommandValue:function ( cmdName ) {
  4578. return this._callCmdFn( 'queryCommandValue', arguments );
  4579. },
  4580. /**
  4581. * 检查编辑区域中是否有内容,若包含tags中的节点类型,直接返回true
  4582. * @name hasContents
  4583. * @desc
  4584. * 默认有文本内容,或者有以下节点都不认为是空
  4585. * <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>
  4586. * @grammar editor.hasContents() => (true|false)
  4587. * @grammar editor.hasContents(tags) => (true|false) //若文档中包含tags数组里对应的tag,直接返回true
  4588. * @example
  4589. * editor.hasContents(['span']) //如果编辑器里有这些,不认为是空
  4590. */
  4591. hasContents:function ( tags ) {
  4592. if ( tags ) {
  4593. for ( var i = 0, ci; ci = tags[i++]; ) {
  4594. if ( this.document.getElementsByTagName( ci ).length > 0 ) {
  4595. return true;
  4596. }
  4597. }
  4598. }
  4599. if ( !domUtils.isEmptyBlock( this.body ) ) {
  4600. return true
  4601. }
  4602. //随时添加,定义的特殊标签如果存在,不能认为是空
  4603. tags = ['div'];
  4604. for ( i = 0; ci = tags[i++]; ) {
  4605. var nodes = domUtils.getElementsByTagName( this.document, ci );
  4606. for ( var n = 0, cn; cn = nodes[n++]; ) {
  4607. if ( domUtils.isCustomeNode( cn ) ) {
  4608. return true;
  4609. }
  4610. }
  4611. }
  4612. return false;
  4613. },
  4614. /**
  4615. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  4616. * @name reset
  4617. * @desc
  4618. * * 清空编辑器内容
  4619. * * 清空回退列表
  4620. * @grammar editor.reset()
  4621. */
  4622. reset:function () {
  4623. this.fireEvent( 'reset' );
  4624. },
  4625. setEnabled:function () {
  4626. var me = this, range;
  4627. if ( me.body.contentEditable == 'false' ) {
  4628. me.body.contentEditable = true;
  4629. range = me.selection.getRange();
  4630. //有可能内容丢失了
  4631. try {
  4632. range.moveToBookmark( me.lastBk );
  4633. delete me.lastBk
  4634. } catch ( e ) {
  4635. range.setStartAtFirst( me.body ).collapse( true )
  4636. }
  4637. range.select( true );
  4638. if ( me.bkqueryCommandState ) {
  4639. me.queryCommandState = me.bkqueryCommandState;
  4640. delete me.bkqueryCommandState;
  4641. }
  4642. me.fireEvent( 'selectionchange' );
  4643. }
  4644. },
  4645. /**
  4646. * 设置当前编辑区域可以编辑
  4647. * @name enable
  4648. * @grammar editor.enable()
  4649. */
  4650. enable:function(){
  4651. return this.setEnabled();
  4652. },
  4653. setDisabled:function ( except ) {
  4654. var me = this;
  4655. except = except ? utils.isArray( except ) ? except : [except] : [];
  4656. if ( me.body.contentEditable == 'true' ) {
  4657. if ( !me.lastBk ) {
  4658. me.lastBk = me.selection.getRange().createBookmark( true );
  4659. }
  4660. me.body.contentEditable = false;
  4661. me.bkqueryCommandState = me.queryCommandState;
  4662. me.queryCommandState = function ( type ) {
  4663. if ( utils.indexOf( except, type ) != -1 ) {
  4664. return me.bkqueryCommandState.apply( me, arguments );
  4665. }
  4666. return -1;
  4667. };
  4668. me.fireEvent( 'selectionchange' );
  4669. }
  4670. },
  4671. /** 设置当前编辑区域不可编辑,except中的命令除外
  4672. * @name disable
  4673. * @grammar editor.disable()
  4674. * @grammar editor.disable(except) //例外的命令,也即即使设置了disable,此处配置的命令仍然可以执行
  4675. * @example
  4676. * //禁用工具栏中除加粗和插入图片之外的所有功能
  4677. * editor.disable(['bold','insertimage']);//可以是单一的String,也可以是Array
  4678. */
  4679. disable:function(except){
  4680. return this.setDisabled(except);
  4681. },
  4682. /**
  4683. * 设置默认内容
  4684. * @ignore
  4685. * @private
  4686. * @param {String} cont 要存入的内容
  4687. */
  4688. _setDefaultContent:function () {
  4689. function clear() {
  4690. var me = this;
  4691. if ( me.document.getElementById( 'initContent' ) ) {
  4692. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  4693. me.removeListener( 'firstBeforeExecCommand focus', clear );
  4694. setTimeout( function () {
  4695. me.focus();
  4696. me._selectionChange();
  4697. },0 )
  4698. }
  4699. }
  4700. return function ( cont ) {
  4701. var me = this;
  4702. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  4703. if ( browser.ie && browser.version < 7 ) {
  4704. replaceSrc( me.body );
  4705. }
  4706. me.addListener( 'firstBeforeExecCommand focus', clear );
  4707. }
  4708. }(),
  4709. /**
  4710. * show方法的兼容版本
  4711. * @private
  4712. * @ignore
  4713. */
  4714. setShow:function () {
  4715. var me = this,range = me.selection.getRange();
  4716. if ( me.container.style.display == 'none' ) {
  4717. //有可能内容丢失了
  4718. try {
  4719. range.moveToBookmark( me.lastBk );
  4720. delete me.lastBk
  4721. } catch ( e ) {
  4722. range.setStartAtFirst( me.body ).collapse( true )
  4723. }
  4724. //ie下focus实效,所以做了个延迟
  4725. setTimeout(function(){
  4726. range.select( true );
  4727. },100);
  4728. me.container.style.display = '';
  4729. }
  4730. },
  4731. /**
  4732. * 显示编辑器
  4733. * @name show
  4734. * @grammar editor.show()
  4735. */
  4736. show:function(){
  4737. return this.setShow();
  4738. },
  4739. /**
  4740. * hide方法的兼容版本
  4741. * @private
  4742. * @ignore
  4743. */
  4744. setHide:function () {
  4745. var me = this;
  4746. if ( !me.lastBk ) {
  4747. me.lastBk = me.selection.getRange().createBookmark( true );
  4748. }
  4749. me.container.style.display = 'none'
  4750. },
  4751. /**
  4752. * 隐藏编辑器
  4753. * @name hide
  4754. * @grammar editor.hide()
  4755. */
  4756. hide:function(){
  4757. return this.setHide();
  4758. },
  4759. /**
  4760. * 根据制定的路径,获取对应的语言资源
  4761. * @name getLang
  4762. * @grammar editor.getLang(path) => (JSON|String) 路径根据的是lang目录下的语言文件的路径结构
  4763. * @example
  4764. * editor.getLang('contextMenu.delete') //如果当前是中文,那返回是的是删除
  4765. */
  4766. getLang:function ( path ) {
  4767. var lang = UE.I18N[this.options.lang];
  4768. if(!lang){
  4769. throw Error("not import language file");
  4770. }
  4771. path = (path || "").split( "." );
  4772. for ( var i = 0, ci; ci = path[i++]; ) {
  4773. lang = lang[ci];
  4774. if ( !lang )break;
  4775. }
  4776. return lang;
  4777. },
  4778. /**
  4779. * 计算编辑器当前内容的长度
  4780. * @name getContentLength
  4781. * @grammar editor.getContentLength(ingoneHtml,tagNames) =>
  4782. * @example
  4783. * editor.getLang(true)
  4784. */
  4785. getContentLength : function(ingoneHtml,tagNames){
  4786. var count = this.getContent().length;
  4787. if(ingoneHtml){
  4788. tagNames = (tagNames||[]).concat([ 'hr','img','iframe']);
  4789. count = this.getContentTxt().replace(/[\t\r\n]+/g,'').length;
  4790. for(var i= 0,ci;ci=tagNames[i++];){
  4791. count += this.document.getElementsByTagName(ci).length;
  4792. }
  4793. }
  4794. return count;
  4795. }
  4796. /**
  4797. * 得到dialog实例对象
  4798. * @name getDialog
  4799. * @grammar editor.getDialog(dialogName) => Object
  4800. * @example
  4801. * var dialog = editor.getDialog("insertimage");
  4802. * dialog.open(); //打开dialog
  4803. * dialog.close(); //关闭dialog
  4804. */
  4805. };
  4806. utils.inherits( Editor, EventBase );
  4807. })();
  4808. /**
  4809. * @file
  4810. * @name UE.ajax
  4811. * @short Ajax
  4812. * @desc UEditor内置的ajax请求模块
  4813. * @import core/utils.js
  4814. * @user: taoqili
  4815. * @date: 11-8-18
  4816. * @time: 下午3:18
  4817. */
  4818. UE.ajax = function() {
  4819. /**
  4820. * 创建一个ajaxRequest对象
  4821. */
  4822. var fnStr = 'XMLHttpRequest()';
  4823. try {
  4824. new ActiveXObject("Msxml2.XMLHTTP");
  4825. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  4826. } catch (e) {
  4827. try {
  4828. new ActiveXObject("Microsoft.XMLHTTP");
  4829. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  4830. } catch (e) {
  4831. }
  4832. }
  4833. var creatAjaxRequest = new Function('return new ' + fnStr);
  4834. /**
  4835. * 将json参数转化成适合ajax提交的参数列表
  4836. * @param json
  4837. */
  4838. function json2str(json) {
  4839. var strArr = [];
  4840. for (var i in json) {
  4841. //忽略默认的几个参数
  4842. if(i=="method" || i=="timeout" || i=="async") continue;
  4843. //传递过来的对象和函数不在提交之列
  4844. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  4845. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  4846. }
  4847. }
  4848. return strArr.join("&");
  4849. }
  4850. return {
  4851. /**
  4852. * @name request
  4853. * @desc 发出ajax请求,ajaxOpt中默认包含method,timeout,async,data,onsuccess以及onerror等六个,支持自定义添加参数
  4854. * @grammar UE.ajax.request(url,ajaxOpt);
  4855. * @example
  4856. * UE.ajax.request('http://www.xxxx.com/test.php',{
  4857. * //可省略,默认POST
  4858. * method:'POST',
  4859. * //可以自定义参数
  4860. * content:'这里是提交的内容',
  4861. * //也可以直接传json,但是只能命名为data,否则当做一般字符串处理
  4862. * data:{
  4863. * name:'UEditor',
  4864. * age:'1'
  4865. * }
  4866. * onsuccess:function(xhr){
  4867. * console.log(xhr.responseText);
  4868. * },
  4869. * onerror:function(xhr){
  4870. * console.log(xhr.responseText);
  4871. * }
  4872. * })
  4873. * @param ajaxOptions
  4874. */
  4875. request:function(url, ajaxOptions) {
  4876. var ajaxRequest = creatAjaxRequest(),
  4877. //是否超时
  4878. timeIsOut = false,
  4879. //默认参数
  4880. defaultAjaxOptions = {
  4881. method:"POST",
  4882. timeout:5000,
  4883. async:true,
  4884. data:{},//需要传递对象的话只能覆盖
  4885. onsuccess:function() {
  4886. },
  4887. onerror:function() {
  4888. }
  4889. };
  4890. if (typeof url === "object") {
  4891. ajaxOptions = url;
  4892. url = ajaxOptions.url;
  4893. }
  4894. if (!ajaxRequest || !url) return;
  4895. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  4896. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  4897. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  4898. if (!utils.isEmptyObject(ajaxOpts.data)){
  4899. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  4900. }
  4901. //超时检测
  4902. var timerID = setTimeout(function() {
  4903. if (ajaxRequest.readyState != 4) {
  4904. timeIsOut = true;
  4905. ajaxRequest.abort();
  4906. clearTimeout(timerID);
  4907. }
  4908. }, ajaxOpts.timeout);
  4909. var method = ajaxOpts.method.toUpperCase();
  4910. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  4911. ajaxRequest.open(method, str, ajaxOpts.async);
  4912. ajaxRequest.onreadystatechange = function() {
  4913. if (ajaxRequest.readyState == 4) {
  4914. if (!timeIsOut && ajaxRequest.status == 200) {
  4915. ajaxOpts.onsuccess(ajaxRequest);
  4916. } else {
  4917. ajaxOpts.onerror(ajaxRequest);
  4918. }
  4919. }
  4920. };
  4921. if (method == "POST") {
  4922. ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4923. ajaxRequest.send(submitStr);
  4924. } else {
  4925. ajaxRequest.send(null);
  4926. }
  4927. }
  4928. };
  4929. }();
  4930. /**
  4931. * @file
  4932. * @name UE.filterWord
  4933. * @short filterWord
  4934. * @desc 用来过滤word粘贴过来的字符串
  4935. * @import editor.js,core/utils.js
  4936. * @anthor zhanyi
  4937. */
  4938. var filterWord = UE.filterWord = function () {
  4939. //是否是word过来的内容
  4940. function isWordDocument( str ) {
  4941. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<v:)/ig.test( str );
  4942. }
  4943. //去掉小数
  4944. function transUnit( v ) {
  4945. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  4946. return utils.transUnitToPx(m);
  4947. } );
  4948. return v;
  4949. }
  4950. function filterPasteWord( str ) {
  4951. return str.replace( /[\t\r\n]+/g, "" )
  4952. .replace( /<!--[\s\S]*?-->/ig, "" )
  4953. //转换图片
  4954. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  4955. //opera能自己解析出image所这里直接返回空
  4956. if(browser.opera){
  4957. return '';
  4958. }
  4959. try{
  4960. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  4961. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  4962. src = str.match(/src=\s*"([^"]*)"/i)[1];
  4963. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  4964. } catch(e){
  4965. return '';
  4966. }
  4967. })
  4968. //针对wps添加的多余标签处理
  4969. .replace(/<\/?div[^>]*>/g,'')
  4970. //去掉多余的属性
  4971. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  4972. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  4973. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  4974. //去掉多余的属性
  4975. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)[\w-]+\2/ig, "" )
  4976. //清除多余的font/span不能匹配&nbsp;有可能是空格
  4977. .replace( /<(font|span)[^>]*>\s*<\/\1>/gi, '' )
  4978. //处理style的问题
  4979. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  4980. var n = [],
  4981. s = style.replace( /^\s+|\s+$/, '' )
  4982. .replace(/&#39;/g,'\'')
  4983. .replace( /&quot;/gi, "'" )
  4984. .split( /;\s*/g );
  4985. for ( var i = 0,v; v = s[i];i++ ) {
  4986. var name, value,
  4987. parts = v.split( ":" );
  4988. if ( parts.length == 2 ) {
  4989. name = parts[0].toLowerCase();
  4990. value = parts[1].toLowerCase();
  4991. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  4992. ||
  4993. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  4994. ){
  4995. continue;
  4996. }
  4997. switch ( name ) {
  4998. case "mso-padding-alt":
  4999. case "mso-padding-top-alt":
  5000. case "mso-padding-right-alt":
  5001. case "mso-padding-bottom-alt":
  5002. case "mso-padding-left-alt":
  5003. case "mso-margin-alt":
  5004. case "mso-margin-top-alt":
  5005. case "mso-margin-right-alt":
  5006. case "mso-margin-bottom-alt":
  5007. case "mso-margin-left-alt":
  5008. //ie下会出现挤到一起的情况
  5009. //case "mso-table-layout-alt":
  5010. case "mso-height":
  5011. case "mso-width":
  5012. case "mso-vertical-align-alt":
  5013. //trace:1819 ff下会解析出padding在table上
  5014. if(!/<table/.test(tag))
  5015. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  5016. continue;
  5017. case "horiz-align":
  5018. n[i] = "text-align:" + value;
  5019. continue;
  5020. case "vert-align":
  5021. n[i] = "vertical-align:" + value;
  5022. continue;
  5023. case "font-color":
  5024. case "mso-foreground":
  5025. n[i] = "color:" + value;
  5026. continue;
  5027. case "mso-background":
  5028. case "mso-highlight":
  5029. n[i] = "background:" + value;
  5030. continue;
  5031. case "mso-default-height":
  5032. n[i] = "min-height:" + transUnit( value );
  5033. continue;
  5034. case "mso-default-width":
  5035. n[i] = "min-width:" + transUnit( value );
  5036. continue;
  5037. case "mso-padding-between-alt":
  5038. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  5039. continue;
  5040. case "text-line-through":
  5041. if ( (value == "single") || (value == "double") ) {
  5042. n[i] = "text-decoration:line-through";
  5043. }
  5044. continue;
  5045. case "mso-zero-height":
  5046. if ( value == "yes" ) {
  5047. n[i] = "display:none";
  5048. }
  5049. continue;
  5050. case 'background':
  5051. if(value == 'initial'){
  5052. }
  5053. break;
  5054. case 'margin':
  5055. if ( !/[1-9]/.test( value ) ) {
  5056. continue;
  5057. }
  5058. }
  5059. 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 )
  5060. ||
  5061. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  5062. ) {
  5063. continue;
  5064. }
  5065. n[i] = name + ":" + parts[1];
  5066. }
  5067. }
  5068. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  5069. })
  5070. .replace(/[\d.]+(cm|pt)/g,function(str){
  5071. return utils.transUnitToPx(str)
  5072. })
  5073. }
  5074. return function ( html ) {
  5075. return (isWordDocument( html ) ? filterPasteWord( html ) : html).replace( />[ \t\r\n]*</g, '><' );
  5076. };
  5077. }();
  5078. ///import core
  5079. /**
  5080. * @description 插入内容
  5081. * @name baidu.editor.execCommand
  5082. * @param {String} cmdName inserthtml插入内容的命令
  5083. * @param {String} html 要插入的内容
  5084. * @author zhanyi
  5085. */
  5086. UE.commands['inserthtml'] = {
  5087. execCommand: function (command,html,notSerialize){
  5088. var me = this,
  5089. range,
  5090. div;
  5091. if(!html){
  5092. return;
  5093. }
  5094. range = me.selection.getRange();
  5095. div = range.document.createElement( 'div' );
  5096. div.style.display = 'inline';
  5097. var serialize = me.serialize;
  5098. if (!notSerialize && serialize) {
  5099. var node = serialize.parseHTML(html);
  5100. node = serialize.transformInput(node);
  5101. node = serialize.filter(node);
  5102. html = serialize.toHTML(node);
  5103. }
  5104. div.innerHTML = utils.trim( html );
  5105. if ( !range.collapsed ) {
  5106. var tmpNode = range.startContainer;
  5107. if(domUtils.isFillChar(tmpNode)){
  5108. range.setStartBefore(tmpNode)
  5109. }
  5110. tmpNode = range.endContainer;
  5111. if(domUtils.isFillChar(tmpNode)){
  5112. range.setEndAfter(tmpNode)
  5113. }
  5114. range.txtToElmBoundary();
  5115. //结束边界可能放到了br的前边,要把br包含进来
  5116. // x[xxx]<br/>
  5117. if(range.endContainer && range.endContainer.nodeType == 1){
  5118. tmpNode = range.endContainer.childNodes[range.endOffset];
  5119. if(tmpNode && domUtils.isBr(tmpNode)){
  5120. range.setEndAfter(tmpNode);
  5121. }
  5122. }
  5123. if(range.startOffset == 0){
  5124. tmpNode = range.startContainer;
  5125. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  5126. tmpNode = range.endContainer;
  5127. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  5128. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  5129. range.setStart(me.body.firstChild,0).collapse(true)
  5130. }
  5131. }
  5132. }
  5133. !range.collapsed && range.deleteContents();
  5134. if(range.startContainer.nodeType == 1){
  5135. var child = range.startContainer.childNodes[range.startOffset],pre;
  5136. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  5137. range.setEnd(pre,pre.childNodes.length).collapse();
  5138. while(child.firstChild){
  5139. pre.appendChild(child.firstChild);
  5140. }
  5141. domUtils.remove(child);
  5142. }
  5143. }
  5144. }
  5145. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  5146. //如果当前位置选中了fillchar要干掉,要不会产生空行
  5147. if(range.inFillChar()){
  5148. child = range.startContainer;
  5149. range.setStartBefore(child).collapse(true);
  5150. domUtils.remove(child);
  5151. }
  5152. while ( child = div.firstChild ) {
  5153. range.insertNode( child );
  5154. nextNode = child.nextSibling;
  5155. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  5156. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  5157. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  5158. if(!dtd[parent.tagName][child.nodeName]){
  5159. pre = parent;
  5160. }else{
  5161. tmp = child.parentNode;
  5162. while (tmp !== parent){
  5163. pre = tmp;
  5164. tmp = tmp.parentNode;
  5165. }
  5166. }
  5167. domUtils.breakParent( child, pre || tmp );
  5168. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  5169. var pre = child.previousSibling;
  5170. domUtils.trimWhiteTextNode(pre);
  5171. if(!pre.childNodes.length){
  5172. domUtils.remove(pre);
  5173. }
  5174. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  5175. if(!browser.ie &&
  5176. (next = child.nextSibling) &&
  5177. domUtils.isBlockElm(next) &&
  5178. next.lastChild &&
  5179. !domUtils.isBr(next.lastChild)){
  5180. next.appendChild(me.document.createElement('br'));
  5181. }
  5182. hadBreak = 1;
  5183. }
  5184. }
  5185. var next = child.nextSibling;
  5186. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  5187. range.setStart(next,0).collapse(true);
  5188. break;
  5189. }
  5190. range.setEndAfter( child ).collapse();
  5191. }
  5192. child = range.startContainer;
  5193. if(nextNode && domUtils.isBr(nextNode)){
  5194. domUtils.remove(nextNode)
  5195. }
  5196. //用chrome可能有空白展位符
  5197. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  5198. if(nextNode = child.nextSibling){
  5199. domUtils.remove(child);
  5200. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  5201. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  5202. }
  5203. }else{
  5204. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  5205. }
  5206. }
  5207. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  5208. range.select(true);
  5209. setTimeout(function(){
  5210. range = me.selection.getRange();
  5211. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  5212. me.fireEvent('afterinserthtml');
  5213. },200);
  5214. }
  5215. };
  5216. ///import core
  5217. ///commands 自动排版
  5218. ///commandsName autotypeset
  5219. ///commandsTitle 自动排版
  5220. /**
  5221. * 自动排版
  5222. * @function
  5223. * @name baidu.editor.execCommands
  5224. */
  5225. UE.plugins['autotypeset'] = function(){
  5226. this.setOpt({'autotypeset':{
  5227. mergeEmptyline : true, //合并空行
  5228. removeClass : true, //去掉冗余的class
  5229. removeEmptyline : false, //去掉空行
  5230. textAlign : "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  5231. imageBlockLine : 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  5232. pasteFilter : false, //根据规则过滤没事粘贴进来的内容
  5233. clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号
  5234. clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体
  5235. removeEmptyNode : false, // 去掉空节点
  5236. //可以去掉的标签
  5237. removeTagNames : utils.extend({div:1},dtd.$removeEmpty),
  5238. indent : false, // 行首缩进
  5239. indentValue : '2em' //行首缩进的大小
  5240. }});
  5241. var me = this,
  5242. opt = me.options.autotypeset,
  5243. remainClass = {
  5244. 'selectTdClass':1,
  5245. 'pagebreak':1,
  5246. 'anchorclass':1
  5247. },
  5248. remainTag = {
  5249. 'li':1
  5250. },
  5251. tags = {
  5252. div:1,
  5253. p:1,
  5254. //trace:2183 这些也认为是行
  5255. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  5256. span:1
  5257. },
  5258. highlightCont;
  5259. //升级了版本,但配置项目里没有autotypeset
  5260. if(!opt){
  5261. return;
  5262. }
  5263. function isLine(node,notEmpty){
  5264. if(!node || node.nodeType == 3)
  5265. return 0;
  5266. if(domUtils.isBr(node))
  5267. return 1;
  5268. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  5269. if(highlightCont && highlightCont.contains(node)
  5270. ||
  5271. node.getAttribute('pagebreak')
  5272. ){
  5273. return 0;
  5274. }
  5275. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node);
  5276. }
  5277. }
  5278. function removeNotAttributeSpan(node){
  5279. if(!node.style.cssText){
  5280. domUtils.removeAttributes(node,['style']);
  5281. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  5282. domUtils.remove(node,true);
  5283. }
  5284. }
  5285. }
  5286. function autotype(type,html){
  5287. var me = this,cont;
  5288. if(html){
  5289. if(!opt.pasteFilter){
  5290. return;
  5291. }
  5292. cont = me.document.createElement('div');
  5293. cont.innerHTML = html.html;
  5294. }else{
  5295. cont = me.document.body;
  5296. }
  5297. var nodes = domUtils.getElementsByTagName(cont,'*');
  5298. // 行首缩进,段落方向,段间距,段内间距
  5299. for(var i=0,ci;ci=nodes[i++];){
  5300. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  5301. continue;
  5302. }
  5303. //font-size
  5304. if(opt.clearFontSize && ci.style.fontSize){
  5305. domUtils.removeStyle(ci,'font-size');
  5306. removeNotAttributeSpan(ci);
  5307. }
  5308. //font-family
  5309. if(opt.clearFontFamily && ci.style.fontFamily){
  5310. domUtils.removeStyle(ci,'font-family');
  5311. removeNotAttributeSpan(ci);
  5312. }
  5313. if(isLine(ci)){
  5314. //合并空行
  5315. if(opt.mergeEmptyline ){
  5316. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  5317. while(isLine(next)){
  5318. tmpNode = next;
  5319. next = tmpNode.nextSibling;
  5320. if(isBr && (!next || next && !domUtils.isBr(next))){
  5321. break;
  5322. }
  5323. domUtils.remove(tmpNode);
  5324. }
  5325. }
  5326. //去掉空行,保留占位的空行
  5327. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  5328. if(domUtils.isBr(ci)){
  5329. next = ci.nextSibling;
  5330. if(next && !domUtils.isBr(next)){
  5331. continue;
  5332. }
  5333. }
  5334. domUtils.remove(ci);
  5335. continue;
  5336. }
  5337. }
  5338. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  5339. if(opt.indent){
  5340. ci.style.textIndent = opt.indentValue;
  5341. }
  5342. if(opt.textAlign){
  5343. ci.style.textAlign = opt.textAlign;
  5344. }
  5345. // if(opt.lineHeight)
  5346. // ci.style.lineHeight = opt.lineHeight + 'cm';
  5347. }
  5348. //去掉class,保留的class不去掉
  5349. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  5350. if(highlightCont && highlightCont.contains(ci)){
  5351. continue;
  5352. }
  5353. domUtils.removeAttributes(ci,['class']);
  5354. }
  5355. //表情不处理
  5356. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  5357. if(html){
  5358. var img = ci;
  5359. switch (opt.imageBlockLine){
  5360. case 'left':
  5361. case 'right':
  5362. case 'none':
  5363. var pN = img.parentNode,tmpNode,pre,next;
  5364. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  5365. pN = pN.parentNode;
  5366. }
  5367. tmpNode = pN;
  5368. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  5369. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  5370. pre = tmpNode.previousSibling;
  5371. next = tmpNode.nextSibling;
  5372. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  5373. pre.appendChild(tmpNode.firstChild);
  5374. while(next.firstChild){
  5375. pre.appendChild(next.firstChild);
  5376. }
  5377. domUtils.remove(tmpNode);
  5378. domUtils.remove(next);
  5379. }else{
  5380. domUtils.setStyle(tmpNode,'text-align','');
  5381. }
  5382. }
  5383. }
  5384. domUtils.setStyle(img,'float',opt.imageBlockLine);
  5385. break;
  5386. case 'center':
  5387. if(me.queryCommandValue('imagefloat') != 'center'){
  5388. pN = img.parentNode;
  5389. domUtils.setStyle(img,'float','none');
  5390. tmpNode = img;
  5391. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  5392. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  5393. tmpNode = pN;
  5394. pN = pN.parentNode;
  5395. }
  5396. var pNode = me.document.createElement('p');
  5397. domUtils.setAttributes(pNode,{
  5398. style:'text-align:center'
  5399. });
  5400. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  5401. pNode.appendChild(tmpNode);
  5402. domUtils.setStyle(tmpNode,'float','');
  5403. }
  5404. }
  5405. }else{
  5406. var range = me.selection.getRange();
  5407. range.selectNode(ci).select();
  5408. me.execCommand('imagefloat',opt.imageBlockLine);
  5409. }
  5410. }
  5411. //去掉冗余的标签
  5412. if(opt.removeEmptyNode){
  5413. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  5414. domUtils.remove(ci);
  5415. }
  5416. }
  5417. }
  5418. if(html){
  5419. html.html = cont.innerHTML;
  5420. }
  5421. }
  5422. if(opt.pasteFilter){
  5423. me.addListener('beforepaste',autotype);
  5424. }
  5425. me.commands['autotypeset'] = {
  5426. execCommand:function () {
  5427. me.removeListener('beforepaste',autotype);
  5428. if(opt.pasteFilter){
  5429. me.addListener('beforepaste',autotype);
  5430. }
  5431. autotype.call(me)
  5432. }
  5433. };
  5434. };
  5435. ///import core
  5436. ///commands 自动提交
  5437. ///commandsName autosubmit
  5438. ///commandsTitle 自动提交
  5439. UE.plugins['autosubmit'] = function(){
  5440. var me = this;
  5441. me.commands['autosubmit'] = {
  5442. execCommand:function () {
  5443. var me=this,
  5444. form = domUtils.findParentByTagName(me.iframe,"form", false);
  5445. if (form) {
  5446. if(me.fireEvent("beforesubmit")===false){
  5447. return;
  5448. }
  5449. me.sync();
  5450. form.submit();
  5451. }
  5452. }
  5453. };
  5454. //快捷键
  5455. me.addshortcutkey({
  5456. "autosubmit" : "ctrl+13" //手动提交
  5457. });
  5458. };
  5459. ///import core
  5460. ///commands 插入背景
  5461. ///commandsName background
  5462. ///commandsTitle 插入背景
  5463. ///commandsDialog dialogs\background
  5464. UE.plugins['background'] = function(){
  5465. var me = this;
  5466. me.addListener("getAllHtml",function(type,headHtml){
  5467. var body = this.body,
  5468. su = domUtils.getComputedStyle(body,"background-image"),
  5469. url="";
  5470. if(su.indexOf(me.options.imagePath)>0){
  5471. url = su.substring(su.indexOf(me.options.imagePath),su.length-1).replace(/"|\(|\)/ig,"");
  5472. }else{
  5473. url = su!="none" ? su.replace(/url\("?|"?\)/ig,""):"";
  5474. }
  5475. var html = '<style type="text/css">body{';
  5476. var bgObj = {
  5477. "background-color" : domUtils.getComputedStyle(body,"background-color")||"#ffffff",
  5478. 'background-image' : url ? 'url('+url+')' : '',
  5479. 'background-repeat':domUtils.getComputedStyle(body,"background-repeat")||"",
  5480. 'background-position': browser.ie?(domUtils.getComputedStyle(body,"background-position-x")+" "+domUtils.getComputedStyle(body,"background-position-y")):domUtils.getComputedStyle(body,"background-position"),
  5481. 'height':domUtils.getComputedStyle(body,"height")
  5482. };
  5483. for ( var name in bgObj ) {
  5484. if ( bgObj.hasOwnProperty( name ) ) {
  5485. html += name+":"+bgObj[name]+";";
  5486. }
  5487. }
  5488. html += '}</style> ';
  5489. headHtml.push(html);
  5490. });
  5491. }
  5492. ///import core
  5493. ///import plugins\inserthtml.js
  5494. ///commands 插入图片,操作图片的对齐方式
  5495. ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter
  5496. ///commandsTitle 图片,默认,居左,居右,居中
  5497. ///commandsDialog dialogs\image
  5498. /**
  5499. * Created by .
  5500. * User: zhanyi
  5501. * for image
  5502. */
  5503. UE.commands['imagefloat'] = {
  5504. execCommand:function (cmd, align) {
  5505. var me = this,
  5506. range = me.selection.getRange();
  5507. if (!range.collapsed) {
  5508. var img = range.getClosedNode();
  5509. if (img && img.tagName == 'IMG') {
  5510. switch (align) {
  5511. case 'left':
  5512. case 'right':
  5513. case 'none':
  5514. var pN = img.parentNode, tmpNode, pre, next;
  5515. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  5516. pN = pN.parentNode;
  5517. }
  5518. tmpNode = pN;
  5519. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  5520. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  5521. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  5522. }) == 1) {
  5523. pre = tmpNode.previousSibling;
  5524. next = tmpNode.nextSibling;
  5525. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  5526. pre.appendChild(tmpNode.firstChild);
  5527. while (next.firstChild) {
  5528. pre.appendChild(next.firstChild);
  5529. }
  5530. domUtils.remove(tmpNode);
  5531. domUtils.remove(next);
  5532. } else {
  5533. domUtils.setStyle(tmpNode, 'text-align', '');
  5534. }
  5535. }
  5536. range.selectNode(img).select();
  5537. }
  5538. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  5539. if(align == 'none'){
  5540. domUtils.removeAttributes(img,'align');
  5541. }
  5542. break;
  5543. case 'center':
  5544. if (me.queryCommandValue('imagefloat') != 'center') {
  5545. pN = img.parentNode;
  5546. domUtils.setStyle(img, 'float', '');
  5547. domUtils.removeAttributes(img,'align');
  5548. tmpNode = img;
  5549. while (pN && domUtils.getChildCount(pN, function (node) {
  5550. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  5551. }) == 1
  5552. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  5553. tmpNode = pN;
  5554. pN = pN.parentNode;
  5555. }
  5556. range.setStartBefore(tmpNode).setCursor(false);
  5557. pN = me.document.createElement('div');
  5558. pN.appendChild(tmpNode);
  5559. domUtils.setStyle(tmpNode, 'float', '');
  5560. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  5561. tmpNode = me.document.getElementById('_img_parent_tmp');
  5562. tmpNode.removeAttribute('id');
  5563. tmpNode = tmpNode.firstChild;
  5564. range.selectNode(tmpNode).select();
  5565. //去掉后边多余的元素
  5566. next = tmpNode.parentNode.nextSibling;
  5567. if (next && domUtils.isEmptyNode(next)) {
  5568. domUtils.remove(next);
  5569. }
  5570. }
  5571. break;
  5572. }
  5573. }
  5574. }
  5575. },
  5576. queryCommandValue:function () {
  5577. var range = this.selection.getRange(),
  5578. startNode, floatStyle;
  5579. if (range.collapsed) {
  5580. return 'none';
  5581. }
  5582. startNode = range.getClosedNode();
  5583. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  5584. floatStyle = startNode.getAttribute('align')||domUtils.getComputedStyle(startNode, 'float');
  5585. if (floatStyle == 'none') {
  5586. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  5587. }
  5588. return {
  5589. left:1,
  5590. right:1,
  5591. center:1
  5592. }[floatStyle] ? floatStyle : 'none';
  5593. }
  5594. return 'none';
  5595. },
  5596. queryCommandState:function () {
  5597. var range = this.selection.getRange(),
  5598. startNode;
  5599. if (range.collapsed) return -1;
  5600. startNode = range.getClosedNode();
  5601. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  5602. return 0;
  5603. }
  5604. return -1;
  5605. }
  5606. };
  5607. UE.commands['insertimage'] = {
  5608. execCommand:function (cmd, opt) {
  5609. opt = utils.isArray(opt) ? opt : [opt];
  5610. if (!opt.length) {
  5611. return;
  5612. }
  5613. var me = this,
  5614. range = me.selection.getRange(),
  5615. img = range.getClosedNode();
  5616. if (img && /img/i.test(img.tagName) && img.className != "edui-faked-video" && !img.getAttribute("word_img")) {
  5617. var first = opt.shift();
  5618. var floatStyle = first['floatStyle'];
  5619. delete first['floatStyle'];
  5620. //// img.style.border = (first.border||0) +"px solid #000";
  5621. //// img.style.margin = (first.margin||0) +"px";
  5622. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  5623. domUtils.setAttributes(img, first);
  5624. me.execCommand('imagefloat', floatStyle);
  5625. if (opt.length > 0) {
  5626. range.setStartAfter(img).setCursor(false, true);
  5627. me.execCommand('insertimage', opt);
  5628. }
  5629. } else {
  5630. var html = [], str = '', ci;
  5631. ci = opt[0];
  5632. if (opt.length == 1) {
  5633. str = '<img src="' + ci.src + '" ' + (ci.data_ue_src ? ' data_ue_src="' + ci.data_ue_src + '" ' : '') +
  5634. (ci.width ? 'width="' + ci.width + '" ' : '') +
  5635. (ci.height ? ' height="' + ci.height + '" ' : '') +
  5636. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  5637. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  5638. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  5639. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  5640. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  5641. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  5642. if (ci['floatStyle'] == 'center') {
  5643. str = '<p style="text-align: center">' + str + '</p>';
  5644. }
  5645. html.push(str);
  5646. } else {
  5647. for (var i = 0; ci = opt[i++];) {
  5648. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  5649. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci.data_ue_src ? ' data_ue_src="' + ci.data_ue_src + '" ' : '') +
  5650. (ci.height ? ' height="' + ci.height + '" ' : '') +
  5651. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  5652. (ci.border || '') + '" ' +
  5653. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  5654. html.push(str);
  5655. }
  5656. }
  5657. me.execCommand('insertHtml', html.join(''));
  5658. }
  5659. }
  5660. };
  5661. ///import core
  5662. ///commands 段落格式,居左,居右,居中,两端对齐
  5663. ///commandsName JustifyLeft,JustifyCenter,JustifyRight,JustifyJustify
  5664. ///commandsTitle 居左对齐,居中对齐,居右对齐,两端对齐
  5665. /**
  5666. * @description 居左右中
  5667. * @name baidu.editor.execCommand
  5668. * @param {String} cmdName justify执行对齐方式的命令
  5669. * @param {String} align 对齐方式:left居左,right居右,center居中,justify两端对齐
  5670. * @author zhanyi
  5671. */
  5672. UE.plugins['justify']=function(){
  5673. var me=this,
  5674. block = domUtils.isBlockElm,
  5675. defaultValue = {
  5676. left:1,
  5677. right:1,
  5678. center:1,
  5679. justify:1
  5680. },
  5681. doJustify = function (range, style) {
  5682. var bookmark = range.createBookmark(),
  5683. filterFn = function (node) {
  5684. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  5685. };
  5686. range.enlarge(true);
  5687. var bookmark2 = range.createBookmark(),
  5688. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  5689. tmpRange = range.cloneRange(),
  5690. tmpNode;
  5691. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  5692. if (current.nodeType == 3 || !block(current)) {
  5693. tmpRange.setStartBefore(current);
  5694. while (current && current !== bookmark2.end && !block(current)) {
  5695. tmpNode = current;
  5696. current = domUtils.getNextDomNode(current, false, null, function (node) {
  5697. return !block(node);
  5698. });
  5699. }
  5700. tmpRange.setEndAfter(tmpNode);
  5701. var common = tmpRange.getCommonAncestor();
  5702. if (!domUtils.isBody(common) && block(common)) {
  5703. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  5704. current = common;
  5705. } else {
  5706. var p = range.document.createElement('p');
  5707. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  5708. var frag = tmpRange.extractContents();
  5709. p.appendChild(frag);
  5710. tmpRange.insertNode(p);
  5711. current = p;
  5712. }
  5713. current = domUtils.getNextDomNode(current, false, filterFn);
  5714. } else {
  5715. current = domUtils.getNextDomNode(current, true, filterFn);
  5716. }
  5717. }
  5718. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  5719. };
  5720. UE.commands['justify'] = {
  5721. execCommand:function (cmdName, align) {
  5722. var range = this.selection.getRange(),
  5723. txt;
  5724. //闭合时单独处理
  5725. if (range.collapsed) {
  5726. txt = this.document.createTextNode('p');
  5727. range.insertNode(txt);
  5728. }
  5729. doJustify(range, align);
  5730. if (txt) {
  5731. range.setStartBefore(txt).collapse(true);
  5732. domUtils.remove(txt);
  5733. }
  5734. range.select();
  5735. return true;
  5736. },
  5737. queryCommandValue:function () {
  5738. var startNode = this.selection.getStart(),
  5739. value = domUtils.getComputedStyle(startNode, 'text-align');
  5740. return defaultValue[value] ? value : 'left';
  5741. },
  5742. queryCommandState:function () {
  5743. var start = this.selection.getStart(),
  5744. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  5745. return cell? -1:0;
  5746. }
  5747. };
  5748. };
  5749. ///import core
  5750. ///import plugins\removeformat.js
  5751. ///commands 字体颜色,背景色,字号,字体,下划线,删除线
  5752. ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough
  5753. ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线
  5754. /**
  5755. * @description 字体
  5756. * @name baidu.editor.execCommand
  5757. * @param {String} cmdName 执行的功能名称
  5758. * @param {String} value 传入的值
  5759. */
  5760. UE.plugins['font'] = function() {
  5761. var me = this,
  5762. fonts = {
  5763. 'forecolor':'color',
  5764. 'backcolor':'background-color',
  5765. 'fontsize':'font-size',
  5766. 'fontfamily':'font-family',
  5767. 'underline':'text-decoration',
  5768. 'strikethrough':'text-decoration'
  5769. };
  5770. me.setOpt({
  5771. 'fontfamily':[
  5772. { name:'songti',val:'宋体,SimSun'},
  5773. { name:'yahei',val:'微软雅黑,Microsoft YaHei'},
  5774. { name:'kaiti',val:'楷体,楷体_GB2312, SimKai'},
  5775. { name:'heiti',val:'黑体, SimHei'},
  5776. { name:'lishu',val:'隶书, SimLi'},
  5777. { name:'andaleMono',val:'andale mono'},
  5778. { name:'arial',val:'arial, helvetica,sans-serif'},
  5779. { name:'arialBlack',val:'arial black,avant garde'},
  5780. { name:'comicSansMs',val:'comic sans ms'},
  5781. { name:'impact',val:'impact,chicago'},
  5782. { name:'timesNewRoman',val:'times new roman'}
  5783. ],
  5784. 'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36]
  5785. });
  5786. for ( var p in fonts ) {
  5787. (function( cmd, style ) {
  5788. UE.commands[cmd] = {
  5789. execCommand : function( cmdName, value ) {
  5790. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' : 'line-through');
  5791. var me = this,
  5792. range = this.selection.getRange(),
  5793. text;
  5794. if ( value == 'default' ) {
  5795. if(range.collapsed){
  5796. text = me.document.createTextNode('font');
  5797. range.insertNode(text).select();
  5798. }
  5799. me.execCommand( 'removeFormat', 'span,a', style);
  5800. if(text){
  5801. range.setStartBefore(text).setCursor();
  5802. domUtils.remove(text);
  5803. }
  5804. } else {
  5805. if ( !range.collapsed ) {
  5806. if((cmd == 'underline'||cmd=='strikethrough') && me.queryCommandValue(cmd)){
  5807. me.execCommand( 'removeFormat', 'span,a', style );
  5808. }
  5809. range = me.selection.getRange();
  5810. range.applyInlineStyle( 'span', {'style':style + ':' + value} ).select();
  5811. } else {
  5812. var span = domUtils.findParentByTagName(range.startContainer,'span',true);
  5813. text = me.document.createTextNode('font');
  5814. if(span && !span.children.length && !span[browser.ie ? 'innerText':'textContent'].replace(fillCharReg,'').length){
  5815. //for ie hack when enter
  5816. range.insertNode(text);
  5817. if(cmd == 'underline'||cmd=='strikethrough'){
  5818. range.selectNode(text).select();
  5819. me.execCommand( 'removeFormat','span,a', style, null );
  5820. span = domUtils.findParentByTagName(text,'span',true);
  5821. range.setStartBefore(text);
  5822. }
  5823. span.style.cssText += ';' + style + ':' + value;
  5824. range.collapse(true).select();
  5825. }else{
  5826. range.insertNode(text);
  5827. range.selectNode(text).select();
  5828. span = range.document.createElement( 'span' );
  5829. if(cmd == 'underline'||cmd=='strikethrough'){
  5830. //a标签内的不处理跳过
  5831. if(domUtils.findParentByTagName(text,'a',true)){
  5832. range.setStartBefore(text).setCursor();
  5833. domUtils.remove(text);
  5834. return;
  5835. }
  5836. me.execCommand( 'removeFormat','span,a', style );
  5837. }
  5838. span.style.cssText = style + ':' + value;
  5839. text.parentNode.insertBefore(span,text);
  5840. //修复,span套span 但样式不继承的问题
  5841. if(!browser.ie || browser.ie && browser.version == 9){
  5842. var spanParent = span.parentNode;
  5843. while(!domUtils.isBlockElm(spanParent)){
  5844. if(spanParent.tagName == 'SPAN'){
  5845. //opera合并style不会加入";"
  5846. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  5847. }
  5848. spanParent = spanParent.parentNode;
  5849. }
  5850. }
  5851. if(opera){
  5852. setTimeout(function(){
  5853. range.setStart(span,0).setCursor();
  5854. });
  5855. }else{
  5856. range.setStart(span,0).setCursor();
  5857. }
  5858. //trace:981
  5859. //domUtils.mergeToParent(span)
  5860. }
  5861. domUtils.remove(text);
  5862. }
  5863. }
  5864. return true;
  5865. },
  5866. queryCommandValue : function (cmdName) {
  5867. var startNode = this.selection.getStart();
  5868. //trace:946
  5869. if(cmdName == 'underline'||cmdName=='strikethrough' ){
  5870. var tmpNode = startNode,value;
  5871. while(tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)){
  5872. if(tmpNode.nodeType == 1){
  5873. value = domUtils.getComputedStyle( tmpNode, style );
  5874. if(value != 'none'){
  5875. return value;
  5876. }
  5877. }
  5878. tmpNode = tmpNode.parentNode;
  5879. }
  5880. return 'none';
  5881. }
  5882. return domUtils.getComputedStyle( startNode, style );
  5883. },
  5884. queryCommandState : function(cmdName){
  5885. if(!(cmdName == 'underline'||cmdName=='strikethrough')){
  5886. return 0;
  5887. }
  5888. return this.queryCommandValue(cmdName) == (cmdName == 'underline' ? 'underline' : 'line-through');
  5889. }
  5890. };
  5891. })( p, fonts[p] );
  5892. }
  5893. };
  5894. ///import core
  5895. ///commands 超链接,取消链接
  5896. ///commandsName Link,Unlink
  5897. ///commandsTitle 超链接,取消链接
  5898. ///commandsDialog dialogs\link
  5899. /**
  5900. * 超链接
  5901. * @function
  5902. * @name baidu.editor.execCommand
  5903. * @param {String} cmdName link插入超链接
  5904. * @param {Object} options url地址,title标题,target是否打开新页
  5905. * @author zhanyi
  5906. */
  5907. /**
  5908. * 取消链接
  5909. * @function
  5910. * @name baidu.editor.execCommand
  5911. * @param {String} cmdName unlink取消链接
  5912. * @author zhanyi
  5913. */
  5914. (function() {
  5915. function optimize( range ) {
  5916. var start = range.startContainer,end = range.endContainer;
  5917. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  5918. range.setStartBefore( start );
  5919. }
  5920. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  5921. range.setEndAfter( end );
  5922. }
  5923. }
  5924. UE.commands['unlink'] = {
  5925. execCommand : function() {
  5926. var range = this.selection.getRange(),
  5927. bookmark;
  5928. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  5929. return;
  5930. }
  5931. bookmark = range.createBookmark();
  5932. optimize( range );
  5933. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  5934. },
  5935. queryCommandState : function(){
  5936. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  5937. }
  5938. };
  5939. function doLink(range,opt,me){
  5940. var rngClone = range.cloneRange(),
  5941. link = me.queryCommandValue('link');
  5942. optimize( range = range.adjustmentBoundary() );
  5943. var start = range.startContainer;
  5944. if(start.nodeType == 1 && link){
  5945. start = start.childNodes[range.startOffset];
  5946. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  5947. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  5948. }
  5949. }
  5950. if( !rngClone.collapsed || link){
  5951. range.removeInlineStyle( 'a' );
  5952. rngClone = range.cloneRange();
  5953. }
  5954. if ( rngClone.collapsed ) {
  5955. var a = range.document.createElement( 'a'),
  5956. text = '';
  5957. if(opt.textValue){
  5958. text = utils.html(opt.textValue);
  5959. delete opt.textValue;
  5960. }else{
  5961. text = utils.html(opt.href);
  5962. }
  5963. domUtils.setAttributes( a, opt );
  5964. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  5965. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  5966. range.setStartAfter(start).collapse(true);
  5967. }
  5968. a[browser.ie ? 'innerText' : 'textContent'] = text;
  5969. range.insertNode(a).selectNode( a );
  5970. } else {
  5971. range.applyInlineStyle( 'a', opt );
  5972. }
  5973. }
  5974. UE.commands['link'] = {
  5975. execCommand : function( cmdName, opt ) {
  5976. var range;
  5977. opt.data_ue_src && (opt.data_ue_src = utils.unhtml(opt.data_ue_src,/[<">]/g));
  5978. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  5979. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  5980. doLink(range=this.selection.getRange(),opt,this);
  5981. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  5982. range.collapse().select(true);
  5983. },
  5984. queryCommandValue : function() {
  5985. var range = this.selection.getRange(),
  5986. node;
  5987. if ( range.collapsed ) {
  5988. // node = this.selection.getStart();
  5989. //在ie下getstart()取值偏上了
  5990. node = range.startContainer;
  5991. node = node.nodeType == 1 ? node : node.parentNode;
  5992. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  5993. return node;
  5994. }
  5995. } else {
  5996. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  5997. range.shrinkBoundary();
  5998. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  5999. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  6000. common = range.getCommonAncestor();
  6001. node = domUtils.findParentByTagName( common, 'a', true );
  6002. if ( !node && common.nodeType == 1){
  6003. var as = common.getElementsByTagName( 'a' ),
  6004. ps,pe;
  6005. for ( var i = 0,ci; ci = as[i++]; ) {
  6006. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  6007. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  6008. &&
  6009. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  6010. ) {
  6011. node = ci;
  6012. break;
  6013. }
  6014. }
  6015. }
  6016. return node;
  6017. }
  6018. },
  6019. queryCommandState : function() {
  6020. //判断如果是视频的话连接不可用
  6021. //fix 853
  6022. var img = this.selection.getRange().getClosedNode(),
  6023. flag = img && (img.className == "edui-faked-video");
  6024. return flag ? -1 : 0;
  6025. }
  6026. };
  6027. })();
  6028. ///import core
  6029. ///import plugins\inserthtml.js
  6030. ///commands 插入框架
  6031. ///commandsName InsertFrame
  6032. ///commandsTitle 插入Iframe
  6033. ///commandsDialog dialogs\insertframe
  6034. UE.plugins['insertframe'] = function() {
  6035. var me =this;
  6036. function deleteIframe(){
  6037. me._iframe && delete me._iframe;
  6038. }
  6039. me.addListener("selectionchange",function(){
  6040. deleteIframe();
  6041. });
  6042. };
  6043. ///import core
  6044. ///commands 涂鸦
  6045. ///commandsName Scrawl
  6046. ///commandsTitle 涂鸦
  6047. ///commandsDialog dialogs\scrawl
  6048. UE.commands['scrawl'] = {
  6049. queryCommandState : function(){
  6050. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  6051. }
  6052. };
  6053. ///import core
  6054. ///commands 清除格式
  6055. ///commandsName RemoveFormat
  6056. ///commandsTitle 清除格式
  6057. /**
  6058. * @description 清除格式
  6059. * @name baidu.editor.execCommand
  6060. * @param {String} cmdName removeformat清除格式命令
  6061. * @param {String} tags 以逗号隔开的标签。如:span,a
  6062. * @param {String} style 样式
  6063. * @param {String} attrs 属性
  6064. * @param {String} notIncluedA 是否把a标签切开
  6065. * @author zhanyi
  6066. */
  6067. UE.plugins['removeformat'] = function(){
  6068. var me = this;
  6069. me.setOpt({
  6070. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  6071. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  6072. });
  6073. me.commands['removeformat'] = {
  6074. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  6075. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  6076. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  6077. range = new dom.Range( this.document ),
  6078. bookmark,node,parent,
  6079. filter = function( node ) {
  6080. return node.nodeType == 1;
  6081. };
  6082. function isRedundantSpan (node) {
  6083. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  6084. return 0;
  6085. }
  6086. if (browser.ie) {
  6087. //ie 下判断实效,所以只能简单用style来判断
  6088. //return node.style.cssText == '' ? 1 : 0;
  6089. var attrs = node.attributes;
  6090. if ( attrs.length ) {
  6091. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  6092. if ( attrs[i].specified ) {
  6093. return 0;
  6094. }
  6095. }
  6096. return 1;
  6097. }
  6098. }
  6099. return !node.attributes.length;
  6100. }
  6101. function doRemove( range ) {
  6102. var bookmark1 = range.createBookmark();
  6103. if ( range.collapsed ) {
  6104. range.enlarge( true );
  6105. }
  6106. //不能把a标签切了
  6107. if(!notIncludeA){
  6108. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  6109. if(aNode){
  6110. range.setStartBefore(aNode);
  6111. }
  6112. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  6113. if(aNode){
  6114. range.setEndAfter(aNode);
  6115. }
  6116. }
  6117. bookmark = range.createBookmark();
  6118. node = bookmark.start;
  6119. //切开始
  6120. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  6121. domUtils.breakParent( node, parent );
  6122. domUtils.clearEmptySibling( node );
  6123. }
  6124. if ( bookmark.end ) {
  6125. //切结束
  6126. node = bookmark.end;
  6127. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  6128. domUtils.breakParent( node, parent );
  6129. domUtils.clearEmptySibling( node );
  6130. }
  6131. //开始去除样式
  6132. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  6133. next;
  6134. while ( current ) {
  6135. if ( current == bookmark.end ) {
  6136. break;
  6137. }
  6138. next = domUtils.getNextDomNode( current, true, filter );
  6139. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  6140. if ( tagReg.test( current.tagName ) ) {
  6141. if ( style ) {
  6142. domUtils.removeStyle( current, style );
  6143. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  6144. domUtils.remove( current, true );
  6145. }
  6146. } else {
  6147. domUtils.remove( current, true );
  6148. }
  6149. } else {
  6150. //trace:939 不能把list上的样式去掉
  6151. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  6152. domUtils.removeAttributes( current, removeFormatAttributes );
  6153. if ( isRedundantSpan( current ) ){
  6154. domUtils.remove( current, true );
  6155. }
  6156. }
  6157. }
  6158. }
  6159. current = next;
  6160. }
  6161. }
  6162. //trace:1035
  6163. //trace:1096 不能把td上的样式去掉,比如边框
  6164. var pN = bookmark.start.parentNode;
  6165. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  6166. domUtils.removeAttributes( pN,removeFormatAttributes );
  6167. }
  6168. pN = bookmark.end.parentNode;
  6169. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  6170. domUtils.removeAttributes( pN,removeFormatAttributes );
  6171. }
  6172. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  6173. //清除冗余的代码 <b><bookmark></b>
  6174. var node = range.startContainer,
  6175. tmp,
  6176. collapsed = range.collapsed;
  6177. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  6178. tmp = node.parentNode;
  6179. range.setStartBefore(node);
  6180. //trace:937
  6181. //更新结束边界
  6182. if(range.startContainer === range.endContainer){
  6183. range.endOffset--;
  6184. }
  6185. domUtils.remove(node);
  6186. node = tmp;
  6187. }
  6188. if(!collapsed){
  6189. node = range.endContainer;
  6190. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  6191. tmp = node.parentNode;
  6192. range.setEndBefore(node);
  6193. domUtils.remove(node);
  6194. node = tmp;
  6195. }
  6196. }
  6197. }
  6198. range = this.selection.getRange();
  6199. doRemove( range );
  6200. range.select();
  6201. }
  6202. };
  6203. };
  6204. ///import core
  6205. ///commands 引用
  6206. ///commandsName BlockQuote
  6207. ///commandsTitle 引用
  6208. /**
  6209. *
  6210. * 引用模块实现
  6211. * @function
  6212. * @name baidu.editor.execCommand
  6213. * @param {String} cmdName blockquote引用
  6214. */
  6215. UE.plugins['blockquote'] = function(){
  6216. var me = this;
  6217. function getObj(editor){
  6218. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  6219. };
  6220. me.commands['blockquote'] = {
  6221. execCommand : function( cmdName, attrs ) {
  6222. var range = this.selection.getRange(),
  6223. obj = getObj(this),
  6224. blockquote = dtd.blockquote,
  6225. bookmark = range.createBookmark();
  6226. if ( obj ) {
  6227. var start = range.startContainer,
  6228. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  6229. end = range.endContainer,
  6230. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  6231. //处理一下li
  6232. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  6233. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  6234. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj){
  6235. domUtils.remove(obj,true);
  6236. }else{
  6237. domUtils.breakParent(startBlock,obj);
  6238. }
  6239. if(startBlock !== endBlock){
  6240. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  6241. if(obj){
  6242. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'){
  6243. domUtils.remove(obj,true);
  6244. }else{
  6245. domUtils.breakParent(endBlock,obj);
  6246. }
  6247. }
  6248. }
  6249. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  6250. for(var i=0,bi;bi=blockquotes[i++];){
  6251. if(!bi.childNodes.length){
  6252. domUtils.remove(bi);
  6253. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  6254. domUtils.remove(bi,true);
  6255. }
  6256. }
  6257. } else {
  6258. var tmpRange = range.cloneRange(),
  6259. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  6260. preNode = node,
  6261. doEnd = 1;
  6262. //调整开始
  6263. while ( 1 ) {
  6264. if ( domUtils.isBody(node) ) {
  6265. if ( preNode !== node ) {
  6266. if ( range.collapsed ) {
  6267. tmpRange.selectNode( preNode );
  6268. doEnd = 0;
  6269. } else {
  6270. tmpRange.setStartBefore( preNode );
  6271. }
  6272. }else{
  6273. tmpRange.setStart(node,0);
  6274. }
  6275. break;
  6276. }
  6277. if ( !blockquote[node.tagName] ) {
  6278. if ( range.collapsed ) {
  6279. tmpRange.selectNode( preNode );
  6280. } else{
  6281. tmpRange.setStartBefore( preNode);
  6282. }
  6283. break;
  6284. }
  6285. preNode = node;
  6286. node = node.parentNode;
  6287. }
  6288. //调整结束
  6289. if ( doEnd ) {
  6290. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  6291. while ( 1 ) {
  6292. if ( domUtils.isBody( node ) ) {
  6293. if ( preNode !== node ) {
  6294. tmpRange.setEndAfter( preNode );
  6295. } else {
  6296. tmpRange.setEnd( node, node.childNodes.length );
  6297. }
  6298. break;
  6299. }
  6300. if ( !blockquote[node.tagName] ) {
  6301. tmpRange.setEndAfter( preNode );
  6302. break;
  6303. }
  6304. preNode = node;
  6305. node = node.parentNode;
  6306. }
  6307. }
  6308. node = range.document.createElement( 'blockquote' );
  6309. domUtils.setAttributes( node, attrs );
  6310. node.appendChild( tmpRange.extractContents() );
  6311. tmpRange.insertNode( node );
  6312. //去除重复的
  6313. var childs = domUtils.getElementsByTagName(node,'blockquote');
  6314. for(var i=0,ci;ci=childs[i++];){
  6315. if(ci.parentNode){
  6316. domUtils.remove(ci,true);
  6317. }
  6318. }
  6319. }
  6320. range.moveToBookmark( bookmark ).select();
  6321. },
  6322. queryCommandState : function() {
  6323. return getObj(this) ? 1 : 0;
  6324. }
  6325. };
  6326. };
  6327. ///import core
  6328. ///commands 大小写转换
  6329. ///commandsName touppercase,tolowercase
  6330. ///commandsTitle 大写,小写
  6331. /**
  6332. * 大小写转换
  6333. * @function
  6334. * @name baidu.editor.execCommands
  6335. * @param {String} cmdName cmdName="convertcase"
  6336. */
  6337. UE.commands['touppercase'] =
  6338. UE.commands['tolowercase'] = {
  6339. execCommand:function (cmd) {
  6340. var me = this;
  6341. var rng = me.selection.getRange();
  6342. if(rng.collapsed){
  6343. return rng;
  6344. }
  6345. var bk = rng.createBookmark(),
  6346. bkEnd = bk.end,
  6347. filterFn = function( node ) {
  6348. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  6349. },
  6350. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  6351. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  6352. if ( curNode.nodeType == 3 ) {
  6353. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  6354. }
  6355. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  6356. if(curNode === bkEnd){
  6357. break;
  6358. }
  6359. }
  6360. rng.moveToBookmark(bk).select();
  6361. }
  6362. };
  6363. ///import core
  6364. ///import plugins\paragraph.js
  6365. ///commands 首行缩进
  6366. ///commandsName Outdent,Indent
  6367. ///commandsTitle 取消缩进,首行缩进
  6368. /**
  6369. * 首行缩进
  6370. * @function
  6371. * @name baidu.editor.execCommand
  6372. * @param {String} cmdName outdent取消缩进,indent缩进
  6373. */
  6374. UE.commands['indent'] = {
  6375. execCommand : function() {
  6376. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  6377. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  6378. },
  6379. queryCommandState : function() {
  6380. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  6381. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  6382. }
  6383. };
  6384. ///import core
  6385. ///commands 打印
  6386. ///commandsName Print
  6387. ///commandsTitle 打印
  6388. /**
  6389. * @description 打印
  6390. * @name baidu.editor.execCommand
  6391. * @param {String} cmdName print打印编辑器内容
  6392. * @author zhanyi
  6393. */
  6394. UE.commands['print'] = {
  6395. execCommand : function(){
  6396. this.window.print();
  6397. },
  6398. notNeedUndo : 1
  6399. };
  6400. ///import core
  6401. ///commands 预览
  6402. ///commandsName Preview
  6403. ///commandsTitle 预览
  6404. /**
  6405. * 预览
  6406. * @function
  6407. * @name baidu.editor.execCommand
  6408. * @param {String} cmdName preview预览编辑器内容
  6409. */
  6410. UE.commands['preview'] = {
  6411. execCommand : function(){
  6412. var w = window.open('', '_blank', ''),
  6413. d = w.document;
  6414. d.open();
  6415. d.write('<html><head><script src="'+this.options.UEDITOR_HOME_URL+'uparse.js"></script><script>' +
  6416. "setTimeout(function(){uParse('div',{" +
  6417. " 'highlightJsUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCore.js'," +
  6418. " 'highlightCssUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCoreDefault.css'" +
  6419. "})},300)" +
  6420. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  6421. d.close();
  6422. },
  6423. notNeedUndo : 1
  6424. };
  6425. ///import core
  6426. ///commands 全选
  6427. ///commandsName SelectAll
  6428. ///commandsTitle 全选
  6429. /**
  6430. * 选中所有
  6431. * @function
  6432. * @name baidu.editor.execCommand
  6433. * @param {String} cmdName selectall选中编辑器里的所有内容
  6434. * @author zhanyi
  6435. */
  6436. UE.plugins['selectall'] = function(){
  6437. var me = this;
  6438. me.commands['selectall'] = {
  6439. execCommand : function(){
  6440. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  6441. var me = this,body = me.body,
  6442. range = me.selection.getRange();
  6443. range.selectNodeContents(body);
  6444. if(domUtils.isEmptyBlock(body)){
  6445. //opera不能自动合并到元素的里边,要手动处理一下
  6446. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  6447. range.setStartAtFirst(body.firstChild);
  6448. }
  6449. range.collapse(true);
  6450. }
  6451. range.select(true);
  6452. },
  6453. notNeedUndo : 1
  6454. };
  6455. function isBoundaryNode(node,dir){
  6456. var tmp;
  6457. while(!domUtils.isBody(node)){
  6458. tmp = node;
  6459. node = node.parentNode;
  6460. if(tmp !== node[dir]){
  6461. return false;
  6462. }
  6463. }
  6464. return true;
  6465. }
  6466. me.addListener('keydown', function(type, evt) {
  6467. var rng = me.selection.getRange();
  6468. if(!rng.collapsed && !(evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)){
  6469. var tmpNode = rng.startContainer;
  6470. if(domUtils.isFillChar(tmpNode)){
  6471. rng.setStartBefore(tmpNode)
  6472. }
  6473. tmpNode = rng.endContainer;
  6474. if(domUtils.isFillChar(tmpNode)){
  6475. rng.setEndAfter(tmpNode)
  6476. }
  6477. rng.txtToElmBoundary();
  6478. if(rng.startOffset == 0){
  6479. tmpNode = rng.startContainer;
  6480. if(isBoundaryNode(tmpNode,'firstChild')){
  6481. tmpNode = rng.endContainer;
  6482. if(rng.endOffset == rng.endContainer.childNodes.length && isBoundaryNode(tmpNode,'lastChild') ){
  6483. me.fireEvent('saveScene');
  6484. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  6485. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  6486. me.fireEvent('saveScene');
  6487. browser.ie && me._selectionChange();
  6488. return;
  6489. }
  6490. }
  6491. }
  6492. }
  6493. });
  6494. //快捷键
  6495. me.addshortcutkey({
  6496. "selectAll" : "ctrl+65"
  6497. });
  6498. };
  6499. ///import core
  6500. ///commands 格式
  6501. ///commandsName Paragraph
  6502. ///commandsTitle 段落格式
  6503. /**
  6504. * 段落样式
  6505. * @function
  6506. * @name baidu.editor.execCommand
  6507. * @param {String} cmdName paragraph插入段落执行命令
  6508. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  6509. * @param {String} attrs 标签的属性
  6510. * @author zhanyi
  6511. */
  6512. UE.plugins['paragraph'] = function() {
  6513. var me = this,
  6514. block = domUtils.isBlockElm,
  6515. notExchange = ['TD','LI','PRE'],
  6516. doParagraph = function(range,style,attrs,sourceCmdName){
  6517. var bookmark = range.createBookmark(),
  6518. filterFn = function( node ) {
  6519. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  6520. },
  6521. para;
  6522. range.enlarge( true );
  6523. var bookmark2 = range.createBookmark(),
  6524. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  6525. tmpRange = range.cloneRange(),
  6526. tmpNode;
  6527. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  6528. if ( current.nodeType == 3 || !block( current ) ) {
  6529. tmpRange.setStartBefore( current );
  6530. while ( current && current !== bookmark2.end && !block( current ) ) {
  6531. tmpNode = current;
  6532. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  6533. return !block( node );
  6534. } );
  6535. }
  6536. tmpRange.setEndAfter( tmpNode );
  6537. para = range.document.createElement( style );
  6538. if(attrs){
  6539. domUtils.setAttributes(para,attrs);
  6540. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  6541. para.style.cssText = attrs.style;
  6542. }
  6543. }
  6544. para.appendChild( tmpRange.extractContents() );
  6545. //需要内容占位
  6546. if(domUtils.isEmptyNode(para)){
  6547. domUtils.fillChar(range.document,para);
  6548. }
  6549. tmpRange.insertNode( para );
  6550. var parent = para.parentNode;
  6551. //如果para上一级是一个block元素且不是body,td就删除它
  6552. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  6553. //存储dir,style
  6554. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  6555. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  6556. //trace:1070
  6557. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  6558. //trace:1030
  6559. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  6560. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  6561. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  6562. }
  6563. //trace:1706 选择的就是h1-6要删除
  6564. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  6565. domUtils.setAttributes(parent,attrs);
  6566. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  6567. parent.style.cssText = attrs.style;
  6568. }
  6569. domUtils.remove(para,true);
  6570. para = parent;
  6571. }else{
  6572. domUtils.remove( para.parentNode, true );
  6573. }
  6574. }
  6575. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  6576. current = parent;
  6577. }else{
  6578. current = para;
  6579. }
  6580. current = domUtils.getNextDomNode( current, false, filterFn );
  6581. } else {
  6582. current = domUtils.getNextDomNode( current, true, filterFn );
  6583. }
  6584. }
  6585. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  6586. };
  6587. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  6588. me.commands['paragraph'] = {
  6589. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  6590. var range = this.selection.getRange();
  6591. //闭合时单独处理
  6592. if(range.collapsed){
  6593. var txt = this.document.createTextNode('p');
  6594. range.insertNode(txt);
  6595. //去掉冗余的fillchar
  6596. if(browser.ie){
  6597. var node = txt.previousSibling;
  6598. if(node && domUtils.isWhitespace(node)){
  6599. domUtils.remove(node);
  6600. }
  6601. node = txt.nextSibling;
  6602. if(node && domUtils.isWhitespace(node)){
  6603. domUtils.remove(node);
  6604. }
  6605. }
  6606. }
  6607. range = doParagraph(range,style,attrs,sourceCmdName);
  6608. if(txt){
  6609. range.setStartBefore(txt).collapse(true);
  6610. pN = txt.parentNode;
  6611. domUtils.remove(txt);
  6612. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  6613. domUtils.fillNode(this.document,pN);
  6614. }
  6615. }
  6616. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  6617. var child = range.startContainer.childNodes[range.startOffset];
  6618. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  6619. range.setStart(child,0).collapse(true);
  6620. }
  6621. }
  6622. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  6623. range.select();
  6624. return true;
  6625. },
  6626. queryCommandValue : function() {
  6627. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  6628. return node ? node.tagName.toLowerCase() : '';
  6629. }
  6630. };
  6631. };
  6632. ///import core
  6633. ///commands 输入的方向
  6634. ///commandsName DirectionalityLtr,DirectionalityRtl
  6635. ///commandsTitle 从左向右输入,从右向左输入
  6636. /**
  6637. * 输入的方向
  6638. * @function
  6639. * @name baidu.editor.execCommand
  6640. * @param {String} cmdName directionality执行函数的参数
  6641. * @param {String} forward ltr从左向右输入,rtl从右向左输入
  6642. */
  6643. (function() {
  6644. var block = domUtils.isBlockElm ,
  6645. getObj = function(editor){
  6646. // var startNode = editor.selection.getStart(),
  6647. // parents;
  6648. // if ( startNode ) {
  6649. // //查找所有的是block的父亲节点
  6650. // parents = domUtils.findParents( startNode, true, block, true );
  6651. // for ( var i = 0,ci; ci = parents[i++]; ) {
  6652. // if ( ci.getAttribute( 'dir' ) ) {
  6653. // return ci;
  6654. // }
  6655. // }
  6656. // }
  6657. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n.getAttribute('dir')});
  6658. },
  6659. doDirectionality = function(range,editor,forward){
  6660. var bookmark,
  6661. filterFn = function( node ) {
  6662. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  6663. },
  6664. obj = getObj( editor );
  6665. if ( obj && range.collapsed ) {
  6666. obj.setAttribute( 'dir', forward );
  6667. return range;
  6668. }
  6669. bookmark = range.createBookmark();
  6670. range.enlarge( true );
  6671. var bookmark2 = range.createBookmark(),
  6672. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  6673. tmpRange = range.cloneRange(),
  6674. tmpNode;
  6675. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  6676. if ( current.nodeType == 3 || !block( current ) ) {
  6677. tmpRange.setStartBefore( current );
  6678. while ( current && current !== bookmark2.end && !block( current ) ) {
  6679. tmpNode = current;
  6680. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  6681. return !block( node );
  6682. } );
  6683. }
  6684. tmpRange.setEndAfter( tmpNode );
  6685. var common = tmpRange.getCommonAncestor();
  6686. if ( !domUtils.isBody( common ) && block( common ) ) {
  6687. //遍历到了block节点
  6688. common.setAttribute( 'dir', forward );
  6689. current = common;
  6690. } else {
  6691. //没有遍历到,添加一个block节点
  6692. var p = range.document.createElement( 'p' );
  6693. p.setAttribute( 'dir', forward );
  6694. var frag = tmpRange.extractContents();
  6695. p.appendChild( frag );
  6696. tmpRange.insertNode( p );
  6697. current = p;
  6698. }
  6699. current = domUtils.getNextDomNode( current, false, filterFn );
  6700. } else {
  6701. current = domUtils.getNextDomNode( current, true, filterFn );
  6702. }
  6703. }
  6704. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  6705. };
  6706. UE.commands['directionality'] = {
  6707. execCommand : function( cmdName,forward ) {
  6708. var range = this.selection.getRange();
  6709. //闭合时单独处理
  6710. if(range.collapsed){
  6711. var txt = this.document.createTextNode('d');
  6712. range.insertNode(txt);
  6713. }
  6714. doDirectionality(range,this,forward);
  6715. if(txt){
  6716. range.setStartBefore(txt).collapse(true);
  6717. domUtils.remove(txt);
  6718. }
  6719. range.select();
  6720. return true;
  6721. },
  6722. queryCommandValue : function() {
  6723. var node = getObj(this);
  6724. return node ? node.getAttribute('dir') : 'ltr';
  6725. }
  6726. };
  6727. })();
  6728. ///import core
  6729. ///import plugins\inserthtml.js
  6730. ///commands 分割线
  6731. ///commandsName Horizontal
  6732. ///commandsTitle 分隔线
  6733. /**
  6734. * 分割线
  6735. * @function
  6736. * @name baidu.editor.execCommand
  6737. * @param {String} cmdName horizontal插入分割线
  6738. */
  6739. UE.commands['horizontal'] = {
  6740. execCommand : function( cmdName ) {
  6741. var me = this;
  6742. if(me.queryCommandState(cmdName)!==-1){
  6743. me.execCommand('insertHtml','<hr>');
  6744. var range = me.selection.getRange(),
  6745. start = range.startContainer;
  6746. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  6747. var tmp;
  6748. if(tmp = start.childNodes[range.startOffset - 1]){
  6749. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  6750. if(me.options.enterTag == 'p'){
  6751. tmp = me.document.createElement('p');
  6752. range.insertNode(tmp);
  6753. range.setStart(tmp,0).setCursor();
  6754. }else{
  6755. tmp = me.document.createElement('br');
  6756. range.insertNode(tmp);
  6757. range.setStartBefore(tmp).setCursor();
  6758. }
  6759. }
  6760. }
  6761. }
  6762. return true;
  6763. }
  6764. },
  6765. //边界在table里不能加分隔线
  6766. queryCommandState : function() {
  6767. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  6768. }
  6769. };
  6770. ///import core
  6771. ///import plugins\inserthtml.js
  6772. ///commands 日期,时间
  6773. ///commandsName Date,Time
  6774. ///commandsTitle 日期,时间
  6775. /**
  6776. * 插入日期
  6777. * @function
  6778. * @name baidu.editor.execCommand
  6779. * @param {String} cmdName date插入日期
  6780. * @author zhuwenxuan
  6781. */
  6782. /**
  6783. * 插入时间
  6784. * @function
  6785. * @name baidu.editor.execCommand
  6786. * @param {String} cmdName time插入时间
  6787. * @author zhuwenxuan
  6788. */
  6789. UE.commands['time'] = UE.commands["date"] = {
  6790. execCommand : function(cmd){
  6791. var date = new Date;
  6792. this.execCommand('insertHtml',cmd == "time" ?
  6793. (date.getHours()+":"+ (date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes())+":"+(date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds())) :
  6794. (date.getFullYear()+"-"+((date.getMonth()+1)<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1)+"-"+(date.getDate()<10?"0"+date.getDate():date.getDate())));
  6795. }
  6796. };
  6797. ///import core
  6798. ///import plugins\paragraph.js
  6799. ///commands 段间距
  6800. ///commandsName RowSpacingBottom,RowSpacingTop
  6801. ///commandsTitle 段间距
  6802. /**
  6803. * @description 设置段前距,段后距
  6804. * @name baidu.editor.execCommand
  6805. * @param {String} cmdName rowspacing设置段间距
  6806. * @param {String} value 值,以px为单位
  6807. * @param {String} dir top或bottom段前后段后
  6808. * @author zhanyi
  6809. */
  6810. UE.plugins['rowspacing'] = function(){
  6811. var me = this;
  6812. me.setOpt({
  6813. 'rowspacingtop':['5', '10', '15', '20', '25'],
  6814. 'rowspacingbottom':['5', '10', '15', '20', '25']
  6815. });
  6816. me.commands['rowspacing'] = {
  6817. execCommand : function( cmdName,value,dir ) {
  6818. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  6819. return true;
  6820. },
  6821. queryCommandValue : function(cmdName,dir) {
  6822. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  6823. value;
  6824. //trace:1026
  6825. if(pN){
  6826. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  6827. return !value ? 0 : value;
  6828. }
  6829. return 0;
  6830. }
  6831. };
  6832. };
  6833. ///import core
  6834. ///import plugins\paragraph.js
  6835. ///commands 行间距
  6836. ///commandsName LineHeight
  6837. ///commandsTitle 行间距
  6838. /**
  6839. * @description 设置行内间距
  6840. * @name baidu.editor.execCommand
  6841. * @param {String} cmdName lineheight设置行内间距
  6842. * @param {String} value 值
  6843. * @author zhuwenxuan
  6844. */
  6845. UE.plugins['lineheight'] = function(){
  6846. var me = this;
  6847. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  6848. me.commands['lineheight'] = {
  6849. execCommand : function( cmdName,value ) {
  6850. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  6851. return true;
  6852. },
  6853. queryCommandValue : function() {
  6854. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  6855. if(pN){
  6856. var value = domUtils.getComputedStyle(pN,'line-height');
  6857. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  6858. }
  6859. }
  6860. };
  6861. };
  6862. ///import core
  6863. ///commands 清空文档
  6864. ///commandsName ClearDoc
  6865. ///commandsTitle 清空文档
  6866. /**
  6867. *
  6868. * 清空文档
  6869. * @function
  6870. * @name baidu.editor.execCommand
  6871. * @param {String} cmdName cleardoc清空文档
  6872. */
  6873. UE.commands['cleardoc'] = {
  6874. execCommand : function( cmdName) {
  6875. var me = this,
  6876. enterTag = me.options.enterTag,
  6877. range = me.selection.getRange();
  6878. if(enterTag == "br"){
  6879. me.body.innerHTML = "<br/>";
  6880. range.setStart(me.body,0).setCursor();
  6881. }else{
  6882. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  6883. range.setStart(me.body.firstChild,0).setCursor(false,true);
  6884. }
  6885. me.fireEvent("clearDoc");
  6886. }
  6887. };
  6888. ///import core
  6889. ///commands 锚点
  6890. ///commandsName Anchor
  6891. ///commandsTitle 锚点
  6892. ///commandsDialog dialogs\anchor
  6893. /**
  6894. * 锚点
  6895. * @function
  6896. * @name baidu.editor.execCommands
  6897. * @param {String} cmdName cmdName="anchor"插入锚点
  6898. */
  6899. UE.plugins['anchor'] = function (){
  6900. var me = this;
  6901. me.ready(function(){
  6902. utils.cssRule('anchor',
  6903. '.anchorclass{background: url(\'' + me.options.UEDITOR_HOME_URL + 'themes/default/images/anchor.gif\') no-repeat scroll left center transparent;border: 1px dotted #0000FF;cursor: auto;display: inline-block;height: 16px;width: 15px;}',me.document)
  6904. });
  6905. me.commands['anchor'] = {
  6906. execCommand:function (cmd, name) {
  6907. var range = this.selection.getRange(),img = range.getClosedNode();
  6908. if (img && img.getAttribute('anchorname')) {
  6909. if (name) {
  6910. img.setAttribute('anchorname', name);
  6911. } else {
  6912. range.setStartBefore(img).setCursor();
  6913. domUtils.remove(img);
  6914. }
  6915. } else {
  6916. if (name) {
  6917. //只在选区的开始插入
  6918. var anchor = this.document.createElement('img');
  6919. range.collapse(true);
  6920. domUtils.setAttributes(anchor,{
  6921. 'anchorname':name,
  6922. 'class':'anchorclass'
  6923. });
  6924. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  6925. }
  6926. }
  6927. }
  6928. };
  6929. };
  6930. ///import core
  6931. ///commands 字数统计
  6932. ///commandsName WordCount,wordCount
  6933. ///commandsTitle 字数统计
  6934. /**
  6935. * Created by JetBrains WebStorm.
  6936. * User: taoqili
  6937. * Date: 11-9-7
  6938. * Time: 下午8:18
  6939. * To change this template use File | Settings | File Templates.
  6940. */
  6941. UE.plugins['wordcount'] = function(){
  6942. var me = this;
  6943. me.addListener('contentchange',function(){
  6944. me.fireEvent('wordcount')
  6945. });
  6946. var timer;
  6947. me.addListener('keyup',function(){
  6948. clearTimeout(timer);
  6949. var me = this;
  6950. timer = setTimeout(function(){
  6951. me.fireEvent('wordcount')
  6952. },200)
  6953. });
  6954. };
  6955. ///import core
  6956. ///commands 添加分页功能
  6957. ///commandsName PageBreak
  6958. ///commandsTitle 分页
  6959. /**
  6960. * @description 添加分页功能
  6961. * @author zhanyi
  6962. */
  6963. UE.plugins['pagebreak'] = function () {
  6964. var me = this,
  6965. notBreakTags = ['td'];
  6966. function fillNode(node){
  6967. if(domUtils.isEmptyBlock(node)){
  6968. var firstChild = node.firstChild,tmpNode;
  6969. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  6970. tmpNode = firstChild;
  6971. firstChild = firstChild.firstChild;
  6972. }
  6973. !tmpNode && (tmpNode = node);
  6974. domUtils.fillNode(me.document,tmpNode);
  6975. }
  6976. }
  6977. //分页符样式添加
  6978. me.ready(function(){
  6979. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  6980. });
  6981. function isHr(node){
  6982. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  6983. }
  6984. me.commands['pagebreak'] = {
  6985. execCommand:function () {
  6986. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  6987. domUtils.setAttributes(hr,{
  6988. 'class' : 'pagebreak',
  6989. noshade:"noshade",
  6990. size:"5"
  6991. });
  6992. domUtils.unSelectable(hr);
  6993. //table单独处理
  6994. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  6995. parents = [], pN;
  6996. if (node) {
  6997. switch (node.tagName) {
  6998. case 'TD':
  6999. pN = node.parentNode;
  7000. if (!pN.previousSibling) {
  7001. var table = domUtils.findParentByTagName(pN, 'table');
  7002. // var tableWrapDiv = table.parentNode;
  7003. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  7004. // && tableWrapDiv.tagName == 'DIV'
  7005. // && tableWrapDiv.getAttribute('dropdrag')
  7006. // ){
  7007. // domUtils.remove(tableWrapDiv,true);
  7008. // }
  7009. table.parentNode.insertBefore(hr, table);
  7010. parents = domUtils.findParents(hr, true);
  7011. } else {
  7012. pN.parentNode.insertBefore(hr, pN);
  7013. parents = domUtils.findParents(hr);
  7014. }
  7015. pN = parents[1];
  7016. if (hr !== pN) {
  7017. domUtils.breakParent(hr, pN);
  7018. }
  7019. //table要重写绑定一下拖拽
  7020. me.fireEvent('afteradjusttable',me.document);
  7021. }
  7022. } else {
  7023. if (!range.collapsed) {
  7024. range.deleteContents();
  7025. var start = range.startContainer;
  7026. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  7027. range.setStartBefore(start).collapse(true);
  7028. domUtils.remove(start);
  7029. start = range.startContainer;
  7030. }
  7031. }
  7032. range.insertNode(hr);
  7033. var pN = hr.parentNode, nextNode;
  7034. while (!domUtils.isBody(pN)) {
  7035. domUtils.breakParent(hr, pN);
  7036. nextNode = hr.nextSibling;
  7037. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  7038. domUtils.remove(nextNode);
  7039. }
  7040. pN = hr.parentNode;
  7041. }
  7042. nextNode = hr.nextSibling;
  7043. var pre = hr.previousSibling;
  7044. if(isHr(pre)){
  7045. domUtils.remove(pre);
  7046. }else{
  7047. pre && fillNode(pre);
  7048. }
  7049. if(!nextNode){
  7050. var p = me.document.createElement('p');
  7051. hr.parentNode.appendChild(p);
  7052. domUtils.fillNode(me.document,p);
  7053. range.setStart(p,0).collapse(true);
  7054. }else{
  7055. if(isHr(nextNode)){
  7056. domUtils.remove(nextNode);
  7057. }else{
  7058. fillNode(nextNode);
  7059. }
  7060. range.setEndAfter(hr).collapse(false);
  7061. }
  7062. range.select(true);
  7063. }
  7064. }
  7065. };
  7066. };
  7067. ///import core
  7068. ///commands 本地图片引导上传
  7069. ///commandsName WordImage
  7070. ///commandsTitle 本地图片引导上传
  7071. ///commandsDialog dialogs\wordimage
  7072. UE.plugins["wordimage"] = function(){
  7073. var me = this,
  7074. images;
  7075. me.commands['wordimage'] = {
  7076. execCommand : function() {
  7077. images = domUtils.getElementsByTagName(me.document.body,"img");
  7078. var urlList = [];
  7079. for(var i=0,ci;ci=images[i++];){
  7080. var url=ci.getAttribute("word_img");
  7081. url && urlList.push(url);
  7082. }
  7083. if(images.length){
  7084. this["word_img"] = urlList;
  7085. }
  7086. },
  7087. queryCommandState: function(){
  7088. images = domUtils.getElementsByTagName(me.document.body,"img");
  7089. for(var i=0,ci;ci =images[i++];){
  7090. if(ci.getAttribute("word_img")){
  7091. return 1;
  7092. }
  7093. }
  7094. return -1;
  7095. }
  7096. };
  7097. };
  7098. ///import core
  7099. ///commands 撤销和重做
  7100. ///commandsName Undo,Redo
  7101. ///commandsTitle 撤销,重做
  7102. /**
  7103. * @description 回退
  7104. * @author zhanyi
  7105. */
  7106. UE.plugins['undo'] = function () {
  7107. var me = this,
  7108. maxUndoCount = me.options.maxUndoCount || 20,
  7109. maxInputCount = me.options.maxInputCount || 20,
  7110. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  7111. function compareAddr(indexA, indexB) {
  7112. if (indexA.length != indexB.length)
  7113. return 0;
  7114. for (var i = 0, l = indexA.length; i < l; i++) {
  7115. if (indexA[i] != indexB[i])
  7116. return 0
  7117. }
  7118. return 1;
  7119. }
  7120. function compareRangeAddress(rngAddrA, rngAddrB) {
  7121. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  7122. return 0;
  7123. }
  7124. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  7125. return 0;
  7126. }
  7127. return 1;
  7128. }
  7129. function adjustContent(cont) {
  7130. var specialAttr = /\b(?:href|src|name)="[^"]*?"/gi;
  7131. return cont.replace(specialAttr, '')
  7132. .replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (a, b, c) {
  7133. return b.toLowerCase() + '=' + c.replace(/['"]/g, '').toLowerCase()
  7134. })
  7135. .replace(/(<[\w\-]+)|([\w\-]+>)/gi, function (a, b, c) {
  7136. return (b || c).toLowerCase()
  7137. });
  7138. }
  7139. function UndoManager() {
  7140. this.list = [];
  7141. this.index = 0;
  7142. this.hasUndo = false;
  7143. this.hasRedo = false;
  7144. this.undo = function () {
  7145. if (this.hasUndo) {
  7146. var currentScene = this.getScene(),
  7147. lastScene = this.list[this.index],
  7148. lastContent = adjustContent(lastScene.content),
  7149. currentContent = adjustContent(currentScene.content);
  7150. if (lastContent != currentContent) {
  7151. this.save();
  7152. }
  7153. if (!this.list[this.index - 1] && this.list.length == 1) {
  7154. this.reset();
  7155. return;
  7156. }
  7157. while (this.list[this.index].content == this.list[this.index - 1].content) {
  7158. this.index--;
  7159. if (this.index == 0) {
  7160. return this.restore(0);
  7161. }
  7162. }
  7163. this.restore(--this.index);
  7164. }
  7165. };
  7166. this.redo = function () {
  7167. if (this.hasRedo) {
  7168. while (this.list[this.index].content == this.list[this.index + 1].content) {
  7169. this.index++;
  7170. if (this.index == this.list.length - 1) {
  7171. return this.restore(this.index);
  7172. }
  7173. }
  7174. this.restore(++this.index);
  7175. }
  7176. };
  7177. this.restore = function () {
  7178. var scene = this.list[this.index];
  7179. //trace:873
  7180. //去掉展位符
  7181. me.document.body.innerHTML = scene.content.replace(fillchar, '');
  7182. //处理undo后空格不展位的问题
  7183. if (browser.ie) {
  7184. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  7185. if(domUtils.isEmptyNode(node)){
  7186. domUtils.fillNode(me.document, node);
  7187. }
  7188. })
  7189. }
  7190. new dom.Range(me.document).moveToAddress(scene.address).select();
  7191. this.update();
  7192. this.clearKey();
  7193. //不能把自己reset了
  7194. me.fireEvent('reset', true);
  7195. };
  7196. this.getScene = function () {
  7197. var rng = me.selection.getRange(),
  7198. restoreAddress = rng.createAddress(),
  7199. rngAddress = rng.createAddress(false,true);
  7200. me.fireEvent('beforegetscene');
  7201. var cont = me.body.innerHTML.replace(fillchar, '');
  7202. browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  7203. me.fireEvent('aftergetscene');
  7204. try{
  7205. rng.moveToAddress(restoreAddress).select(true);
  7206. }catch(e){}
  7207. return {
  7208. address:rngAddress,
  7209. content:cont
  7210. }
  7211. };
  7212. this.save = function (notCompareRange) {
  7213. var currentScene = this.getScene(),
  7214. lastScene = this.list[this.index];
  7215. //内容相同位置相同不存
  7216. if (lastScene && lastScene.content == currentScene.content &&
  7217. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  7218. ) {
  7219. return;
  7220. }
  7221. this.list = this.list.slice(0, this.index + 1);
  7222. this.list.push(currentScene);
  7223. //如果大于最大数量了,就把最前的剔除
  7224. if (this.list.length > maxUndoCount) {
  7225. this.list.shift();
  7226. }
  7227. this.index = this.list.length - 1;
  7228. this.clearKey();
  7229. //跟新undo/redo状态
  7230. this.update();
  7231. };
  7232. this.update = function () {
  7233. this.hasRedo = !!this.list[this.index + 1];
  7234. this.hasUndo = !!this.list[this.index - 1];
  7235. };
  7236. this.reset = function () {
  7237. this.list = [];
  7238. this.index = 0;
  7239. this.hasUndo = false;
  7240. this.hasRedo = false;
  7241. this.clearKey();
  7242. };
  7243. this.clearKey = function () {
  7244. keycont = 0;
  7245. lastKeyCode = null;
  7246. };
  7247. }
  7248. me.undoManger = new UndoManager();
  7249. function saveScene() {
  7250. this.undoManger.save();
  7251. }
  7252. me.addListener('saveScene', function () {
  7253. me.undoManger.save();
  7254. });
  7255. me.addListener('beforeexeccommand', saveScene);
  7256. me.addListener('afterexeccommand', saveScene);
  7257. me.addListener('reset', function (type, exclude) {
  7258. if (!exclude) {
  7259. me.undoManger.reset();
  7260. }
  7261. });
  7262. me.commands['redo'] = me.commands['undo'] = {
  7263. execCommand:function (cmdName) {
  7264. me.undoManger[cmdName]();
  7265. },
  7266. queryCommandState:function (cmdName) {
  7267. return me.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  7268. },
  7269. notNeedUndo:1
  7270. };
  7271. var keys = {
  7272. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  7273. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  7274. 37:1, 38:1, 39:1, 40:1,
  7275. 13:1 /*enter*/
  7276. },
  7277. keycont = 0,
  7278. lastKeyCode;
  7279. //输入法状态下不计算字符数
  7280. var inputType = false;
  7281. me.addListener('ready', function () {
  7282. domUtils.on(me.body, 'compositionstart', function () {
  7283. inputType = true;
  7284. });
  7285. domUtils.on(me.body, 'compositionend', function () {
  7286. inputType = false;
  7287. })
  7288. });
  7289. //快捷键
  7290. me.addshortcutkey({
  7291. "Undo":"ctrl+90", //undo
  7292. "Redo":"ctrl+89" //redo
  7293. });
  7294. me.addListener('keydown', function (type, evt) {
  7295. var keyCode = evt.keyCode || evt.which;
  7296. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  7297. if (inputType)
  7298. return;
  7299. if (me.undoManger.list.length == 0 || ((keyCode == 8 || keyCode == 46) && lastKeyCode != keyCode)) {
  7300. me.fireEvent('contentchange');
  7301. me.undoManger.save(true);
  7302. lastKeyCode = keyCode;
  7303. return;
  7304. }
  7305. //trace:856
  7306. //修正第一次输入后,回退,再输入要到keycont>maxInputCount才能在回退的问题
  7307. if (me.undoManger.list.length == 2 && me.undoManger.index == 0 && keycont == 0) {
  7308. me.undoManger.list.splice(1, 1);
  7309. me.undoManger.update();
  7310. }
  7311. lastKeyCode = keyCode;
  7312. keycont++;
  7313. if (keycont >= maxInputCount || me.undoManger.mousedown) {
  7314. if (me.selection.getRange().collapsed)
  7315. me.fireEvent('contentchange');
  7316. me.undoManger.save();
  7317. me.undoManger.mousedown = false;
  7318. }
  7319. }
  7320. });
  7321. me.addListener('mousedown',function(){
  7322. me.undoManger.mousedown = true;
  7323. })
  7324. };
  7325. ///import core
  7326. ///import plugins/inserthtml.js
  7327. ///import plugins/undo.js
  7328. ///import plugins/serialize.js
  7329. ///commands 粘贴
  7330. ///commandsName PastePlain
  7331. ///commandsTitle 纯文本粘贴模式
  7332. /*
  7333. ** @description 粘贴
  7334. * @author zhanyi
  7335. */
  7336. (function() {
  7337. function getClipboardData( callback ) {
  7338. var doc = this.document;
  7339. if ( doc.getElementById( 'baidu_pastebin' ) ) {
  7340. return;
  7341. }
  7342. var range = this.selection.getRange(),
  7343. bk = range.createBookmark(),
  7344. //创建剪贴的容器div
  7345. pastebin = doc.createElement( 'div' );
  7346. pastebin.id = 'baidu_pastebin';
  7347. // Safari 要求div必须有内容,才能粘贴内容进来
  7348. browser.webkit && pastebin.appendChild( doc.createTextNode( domUtils.fillChar + domUtils.fillChar ) );
  7349. doc.body.appendChild( pastebin );
  7350. //trace:717 隐藏的span不能得到top
  7351. //bk.start.innerHTML = '&nbsp;';
  7352. bk.start.style.display = '';
  7353. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  7354. //要在现在光标平行的位置加入,否则会出现跳动的问题
  7355. domUtils.getXY( bk.start ).y + 'px';
  7356. range.selectNodeContents( pastebin ).select( true );
  7357. setTimeout( function() {
  7358. if (browser.webkit) {
  7359. for(var i=0,pastebins = doc.querySelectorAll('#baidu_pastebin'),pi;pi=pastebins[i++];){
  7360. if(domUtils.isEmptyNode(pi)){
  7361. domUtils.remove(pi);
  7362. }else{
  7363. pastebin = pi;
  7364. break;
  7365. }
  7366. }
  7367. }
  7368. try{
  7369. pastebin.parentNode.removeChild(pastebin);
  7370. }catch(e){}
  7371. range.moveToBookmark( bk ).select(true);
  7372. callback( pastebin );
  7373. }, 0 );
  7374. }
  7375. UE.plugins['paste'] = function() {
  7376. var me = this;
  7377. var word_img_flag = {flag:""};
  7378. var pasteplain = me.options.pasteplain === true;
  7379. var modify_num = {flag:""};
  7380. me.commands['pasteplain'] = {
  7381. queryCommandState: function (){
  7382. return pasteplain;
  7383. },
  7384. execCommand: function (){
  7385. pasteplain = !pasteplain|0;
  7386. },
  7387. notNeedUndo : 1
  7388. };
  7389. var txtContent,htmlContent,address;
  7390. function filter(div){
  7391. var html;
  7392. if ( div.firstChild ) {
  7393. //去掉cut中添加的边界值
  7394. var nodes = domUtils.getElementsByTagName(div,'span');
  7395. for(var i=0,ni;ni=nodes[i++];){
  7396. if(ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end'){
  7397. domUtils.remove(ni);
  7398. }
  7399. }
  7400. if(browser.webkit){
  7401. var brs = div.querySelectorAll('div br');
  7402. for(var i=0,bi;bi=brs[i++];){
  7403. var pN = bi.parentNode;
  7404. if(pN.tagName == 'DIV' && pN.childNodes.length ==1){
  7405. pN.innerHTML = '<p><br/></p>';
  7406. w
  7407. domUtils.remove(pN);
  7408. }
  7409. }
  7410. var divs = div.querySelectorAll('#baidu_pastebin');
  7411. for(var i=0,di;di=divs[i++];){
  7412. var tmpP = me.document.createElement('p');
  7413. di.parentNode.insertBefore(tmpP,di);
  7414. while(di.firstChild){
  7415. tmpP.appendChild(di.firstChild);
  7416. }
  7417. domUtils.remove(di);
  7418. }
  7419. var metas = div.querySelectorAll('meta');
  7420. for(var i=0,ci;ci=metas[i++];){
  7421. domUtils.remove(ci);
  7422. }
  7423. var brs = div.querySelectorAll('br');
  7424. for(i=0;ci=brs[i++];){
  7425. if(/^apple-/.test(ci)){
  7426. domUtils.remove(ci);
  7427. }
  7428. }
  7429. utils.each(domUtils.getElementsByTagName(div,'span',function(node){
  7430. if(node.style.cssText){
  7431. node.style.cssText = node.style.cssText.replace(/white-space[^;]+;/g,'');
  7432. if(!node.style.cssText){
  7433. domUtils.removeAttributes(node,'style');
  7434. if(domUtils.hasNoAttributes(node)){
  7435. return 1
  7436. }
  7437. }
  7438. }
  7439. return 0
  7440. }),function(si){
  7441. domUtils.remove(si,true)
  7442. })
  7443. }
  7444. if(browser.gecko){
  7445. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  7446. for(i=0;ci=dirtyNodes[i++];){
  7447. ci.removeAttribute( '_moz_dirty' );
  7448. }
  7449. }
  7450. if(!browser.ie ){
  7451. var spans = div.querySelectorAll('span.Apple-style-span');
  7452. for(var i=0,ci;ci=spans[i++];){
  7453. domUtils.remove(ci,true);
  7454. }
  7455. }
  7456. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  7457. html = div.innerHTML.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  7458. var f = me.serialize;
  7459. if(f){
  7460. //如果过滤出现问题,捕获它,直接插入内容,避免出现错误导致粘贴整个失败
  7461. try{
  7462. html = UE.filterWord(html);
  7463. var node = f.transformInput(
  7464. f.parseHTML(
  7465. //todo: 暂时不走dtd的过滤
  7466. html//, true
  7467. ),word_img_flag
  7468. );
  7469. //trace:924
  7470. //纯文本模式也要保留段落
  7471. node = f.filter(node,pasteplain ? {
  7472. whiteList: {
  7473. 'p': {'br':1,'BR':1,$:{}},
  7474. 'br':{'$':{}},
  7475. 'div':{'br':1,'BR':1,'$':{}},
  7476. 'li':{'$':{}},
  7477. 'tr':{'td':1,'$':{}},
  7478. 'td':{'$':{}}
  7479. },
  7480. blackList: {
  7481. 'style':1,
  7482. 'script':1,
  7483. 'object':1
  7484. }
  7485. } : null, !pasteplain ? modify_num : null);
  7486. if(browser.webkit){
  7487. var length = node.children.length,
  7488. child;
  7489. while((child = node.children[length-1]) && child.tag == 'br'){
  7490. node.children.splice(length-1,1);
  7491. length = node.children.length;
  7492. }
  7493. }
  7494. html = f.toHTML(node,pasteplain);
  7495. txtContent = f.filter(node,{
  7496. whiteList: {
  7497. 'p': {'br':1,'BR':1,$:{}},
  7498. 'br':{'$':{}},
  7499. 'div':{'br':1,'BR':1,'$':{},'table':1,'ul':1,'ol':1},
  7500. 'li':{'$':{}},
  7501. 'ul':{'li':1,'$':{}},
  7502. 'ol':{'li':1,'$':{}},
  7503. 'tr':{'td':1,'$':{}},
  7504. 'td':{'$':{}},
  7505. 'table': {'tr':1,'tbody':1,'td':1,'$':{}},
  7506. 'tbody': {'tr':1,'td':1,'$':{}},
  7507. h1:{'$':{}},h2:{'$':{}},h3:{'$':{}},h4:{'$':{}},h5:{'$':{}},h6:{'$':{}}
  7508. },
  7509. blackList: {
  7510. 'style':1,
  7511. 'script':1,
  7512. 'object':1
  7513. }
  7514. });
  7515. txtContent = f.toHTML(txtContent,true)
  7516. }catch(e){}
  7517. }
  7518. //自定义的处理
  7519. html = {'html':html,'txtContent':txtContent};
  7520. me.fireEvent('beforepaste',html);
  7521. //不用在走过滤了
  7522. if(html.html){
  7523. htmlContent = html.html;
  7524. address = me.selection.getRange().createAddress(true);
  7525. me.execCommand( 'insertHtml',htmlContent,true);
  7526. me.fireEvent("afterpaste");
  7527. }
  7528. }
  7529. }
  7530. me.addListener('pasteTransfer',function(cmd,plainType){
  7531. if(address && txtContent && htmlContent && txtContent != htmlContent){
  7532. var range = me.selection.getRange();
  7533. range.moveToAddress(address,true).deleteContents();
  7534. range.select(true);
  7535. me.__hasEnterExecCommand = true;
  7536. var html = htmlContent;
  7537. if(plainType === 2){
  7538. html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi,function(a,b,tagName,attrs){
  7539. tagName = tagName.toLowerCase();
  7540. if({img:1}[tagName]){
  7541. return a;
  7542. }
  7543. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi,function(str,atr,val){
  7544. if({
  7545. 'src':1,
  7546. 'href':1,
  7547. 'name':1
  7548. }[atr.toLowerCase()]){
  7549. return atr + '=' + val + ' '
  7550. }
  7551. return ''
  7552. });
  7553. if({
  7554. 'span':1,
  7555. 'div':1
  7556. }[tagName]){
  7557. return ''
  7558. }else{
  7559. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  7560. }
  7561. });
  7562. }else if(plainType){
  7563. html = txtContent;
  7564. }
  7565. me.execCommand('inserthtml',html,true);
  7566. me.__hasEnterExecCommand = false;
  7567. var tmpAddress = me.selection.getRange().createAddress(true);
  7568. address.endAddress = tmpAddress.startAddress;
  7569. }
  7570. });
  7571. me.addListener('ready',function(){
  7572. domUtils.on(me.body,'cut',function(){
  7573. var range = me.selection.getRange();
  7574. if(!range.collapsed && me.undoManger){
  7575. me.undoManger.save();
  7576. }
  7577. });
  7578. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  7579. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste',function(e){
  7580. if((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')){
  7581. return;
  7582. }
  7583. getClipboardData.call( me, function( div ) {
  7584. filter(div);
  7585. } );
  7586. });
  7587. });
  7588. };
  7589. })();
  7590. ///import core
  7591. ///commands 有序列表,无序列表
  7592. ///commandsName InsertOrderedList,InsertUnorderedList
  7593. ///commandsTitle 有序列表,无序列表
  7594. /**
  7595. * 有序列表
  7596. * @function
  7597. * @name baidu.editor.execCommand
  7598. * @param {String} cmdName insertorderlist插入有序列表
  7599. * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman
  7600. * @author zhanyi
  7601. */
  7602. /**
  7603. * 无序链接
  7604. * @function
  7605. * @name baidu.editor.execCommand
  7606. * @param {String} cmdName insertunorderlist插入无序列表
  7607. * * @param {String} style 值为:circle,disc,square
  7608. * @author zhanyi
  7609. */
  7610. UE.plugins['list'] = function () {
  7611. var me = this,
  7612. notExchange = {
  7613. 'TD':1,
  7614. 'PRE':1,
  7615. 'BLOCKQUOTE':1
  7616. };
  7617. var customStyle = {
  7618. 'cn' : 'cn-1-',
  7619. 'cn1' : 'cn-2-',
  7620. 'cn2' : 'cn-3-',
  7621. 'num': 'num-1-',
  7622. 'num1' : 'num-2-',
  7623. 'num2' : 'num-3-',
  7624. 'dash' : 'dash',
  7625. 'dot':'dot'
  7626. };
  7627. me.setOpt( {
  7628. 'insertorderedlist':{
  7629. 'num':'',
  7630. 'num1':'',
  7631. 'num2':'',
  7632. 'cn':'',
  7633. 'cn1':'',
  7634. 'cn2':'',
  7635. 'decimal':'',
  7636. 'lower-alpha':'',
  7637. 'lower-roman':'',
  7638. 'upper-alpha':'',
  7639. 'upper-roman':''
  7640. },
  7641. 'insertunorderedlist':{
  7642. 'circle':'',
  7643. 'disc':'',
  7644. 'square':'',
  7645. 'dash' : '',
  7646. 'dot':''
  7647. },
  7648. listDefaultPaddingLeft : '30',
  7649. listiconpath : 'http://bs.baidu.com/listicon/',
  7650. maxListLevel : 3//-1不限制
  7651. } );
  7652. var liiconpath = me.options.listiconpath;
  7653. //根据用户配置,调整customStyle
  7654. for(var s in customStyle){
  7655. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  7656. delete customStyle[s];
  7657. }
  7658. }
  7659. me.ready(function () {
  7660. var customCss = [];
  7661. for(var p in customStyle){
  7662. if(p == 'dash' || p == 'dot'){
  7663. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  7664. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  7665. }else{
  7666. for(var i= 0;i<99;i++){
  7667. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  7668. }
  7669. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  7670. }
  7671. switch(p){
  7672. case 'cn':
  7673. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  7674. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  7675. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  7676. break;
  7677. case 'cn1':
  7678. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  7679. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  7680. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  7681. break;
  7682. case 'cn2':
  7683. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  7684. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  7685. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  7686. break;
  7687. case 'num':
  7688. case 'num1':
  7689. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  7690. break;
  7691. case 'num2':
  7692. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  7693. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  7694. break;
  7695. case 'dash':
  7696. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  7697. break;
  7698. case 'dot':
  7699. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  7700. }
  7701. }
  7702. customCss.push('.list-paddingleft-1{padding-left:0}');
  7703. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  7704. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  7705. //如果不给宽度会在自定应样式里出现滚动条
  7706. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  7707. });
  7708. function getStyle(node){
  7709. var cls = node.className;
  7710. if(domUtils.hasClass(node,/custom_/)){
  7711. return cls.match(/custom_(\w+)/)[1]
  7712. }
  7713. return ''
  7714. }
  7715. // function checkCustomStyle(list){
  7716. // if(domUtils.hasClass(list,/custom_/)){
  7717. // return ''
  7718. // }
  7719. // var style;
  7720. // utils.each(list.childNodes,function(li){
  7721. // if(li.tagName == 'LI'){
  7722. // if(domUtils.hasClass(li,/list-/)){
  7723. // var tmpStyle = li.className.match(/list-(\w+)-(\d+)?/);
  7724. // style = tmpStyle[1]+(tmpStyle[2] && tmpStyle[2] != '1'? tmpStyle[2]:'');
  7725. // return false
  7726. // }
  7727. // }
  7728. // })
  7729. // return style;
  7730. // }
  7731. //调整索引标签
  7732. me.addListener('contentchange',function(){
  7733. utils.each(domUtils.getElementsByTagName(me.document,'ol ul'),function(node){
  7734. if(!domUtils.inDoc(node,me.document))
  7735. return;
  7736. // var style;
  7737. // if(style = checkCustomStyle(node)){
  7738. // node.className = 'custom_' + style;
  7739. // }
  7740. var index = 0,type = 2,parent = node.parentNode;
  7741. if( domUtils.hasClass(node,/custom_/)){
  7742. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  7743. type = 1;
  7744. }
  7745. }else{
  7746. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  7747. type = 3;
  7748. }
  7749. }
  7750. style = domUtils.getStyle(node, 'list-style-type');
  7751. node.style.cssText = style ? 'list-style-type:' + style : '';
  7752. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  7753. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  7754. li.style.cssText && (li.style.cssText = '');
  7755. if(!li.firstChild){
  7756. domUtils.remove(li);
  7757. return;
  7758. }
  7759. if(li.parentNode !== node){
  7760. return;
  7761. }
  7762. index++;
  7763. if(domUtils.hasClass(node,/custom_/) ){
  7764. var paddingLeft = 1,currentStyle = getStyle(node);
  7765. if(node.tagName == 'OL'){
  7766. if(currentStyle){
  7767. switch(currentStyle){
  7768. case 'cn' :
  7769. case 'cn1':
  7770. case 'cn2':
  7771. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  7772. paddingLeft = 2
  7773. }else if(index > 20){
  7774. paddingLeft = 3
  7775. }
  7776. break;
  7777. case 'num2' :
  7778. if(index > 9){
  7779. paddingLeft = 2
  7780. }
  7781. }
  7782. }
  7783. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  7784. }else{
  7785. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  7786. }
  7787. }else{
  7788. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  7789. }
  7790. var className = li.getAttribute('class');
  7791. if(className !== null && !className.replace(/\s/g,'')){
  7792. domUtils.removeAttributes(li,'class')
  7793. }
  7794. });
  7795. adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true)
  7796. })
  7797. });
  7798. function adjustList(list, tag, style,ignoreEmpty) {
  7799. var nextList = list.nextSibling;
  7800. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  7801. domUtils.moveChild(nextList, list);
  7802. if (nextList.childNodes.length == 0) {
  7803. domUtils.remove(nextList);
  7804. }
  7805. }
  7806. if(nextList && domUtils.isFillChar(nextList)){
  7807. domUtils.remove(nextList);
  7808. }
  7809. var preList = list.previousSibling;
  7810. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  7811. domUtils.moveChild(list, preList);
  7812. }
  7813. if(preList && domUtils.isFillChar(preList)){
  7814. domUtils.remove(preList);
  7815. }
  7816. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  7817. }
  7818. function setListStyle(list,style){
  7819. if(customStyle[style]){
  7820. list.className = 'custom_' + style;
  7821. }
  7822. try{
  7823. domUtils.setStyle(list, 'list-style-type', style);
  7824. }catch(e){}
  7825. }
  7826. function clearEmptySibling(node) {
  7827. var tmpNode = node.previousSibling;
  7828. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  7829. domUtils.remove(tmpNode);
  7830. }
  7831. tmpNode = node.nextSibling;
  7832. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  7833. domUtils.remove(tmpNode);
  7834. }
  7835. }
  7836. me.addListener('keydown', function (type, evt) {
  7837. function preventAndSave() {
  7838. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  7839. me.fireEvent('contentchange');
  7840. me.undoManger && me.undoManger.save();
  7841. }
  7842. function findList(node,filterFn){
  7843. while(node && !domUtils.isBody(node)){
  7844. if(filterFn(node)){
  7845. return null
  7846. }
  7847. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  7848. return node;
  7849. }
  7850. node = node.parentNode;
  7851. }
  7852. return null;
  7853. }
  7854. var keyCode = evt.keyCode || evt.which;
  7855. if (keyCode == 13 && !evt.shiftKey) {//回车
  7856. var range = me.selection.getRange(),
  7857. start = findList(range.startContainer,function (node) {
  7858. return node.tagName == 'TABLE';
  7859. }),
  7860. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  7861. return node.tagName == 'TABLE';
  7862. });
  7863. if (start && end && start === end) {
  7864. if (!range.collapsed) {
  7865. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  7866. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  7867. if (start && end && start === end) {
  7868. range.deleteContents();
  7869. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  7870. if (li && domUtils.isEmptyBlock(li)) {
  7871. pre = li.previousSibling;
  7872. next = li.nextSibling;
  7873. p = me.document.createElement('p');
  7874. domUtils.fillNode(me.document, p);
  7875. parentList = li.parentNode;
  7876. if (pre && next) {
  7877. range.setStart(next, 0).collapse(true).select(true);
  7878. domUtils.remove(li);
  7879. } else {
  7880. if (!pre && !next || !pre) {
  7881. parentList.parentNode.insertBefore(p, parentList);
  7882. } else {
  7883. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  7884. }
  7885. domUtils.remove(li);
  7886. if (!parentList.firstChild) {
  7887. domUtils.remove(parentList);
  7888. }
  7889. range.setStart(p, 0).setCursor();
  7890. }
  7891. preventAndSave();
  7892. return;
  7893. }
  7894. } else {
  7895. var tmpRange = range.cloneRange(),
  7896. bk = tmpRange.collapse(false).createBookmark();
  7897. range.deleteContents();
  7898. tmpRange.moveToBookmark(bk);
  7899. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  7900. clearEmptySibling(li);
  7901. tmpRange.select();
  7902. preventAndSave();
  7903. return;
  7904. }
  7905. }
  7906. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  7907. if (li) {
  7908. if (domUtils.isEmptyBlock(li)) {
  7909. bk = range.createBookmark();
  7910. var parentList = li.parentNode;
  7911. if (li !== parentList.lastChild) {
  7912. domUtils.breakParent(li, parentList);
  7913. clearEmptySibling(li);
  7914. } else {
  7915. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  7916. if (domUtils.isEmptyNode(parentList)) {
  7917. domUtils.remove(parentList);
  7918. }
  7919. }
  7920. //嵌套不处理
  7921. if (!dtd.$list[li.parentNode.tagName]) {
  7922. if (!domUtils.isBlockElm(li.firstChild)) {
  7923. p = me.document.createElement('p');
  7924. li.parentNode.insertBefore(p, li);
  7925. while (li.firstChild) {
  7926. p.appendChild(li.firstChild);
  7927. }
  7928. domUtils.remove(li);
  7929. } else {
  7930. domUtils.remove(li, true);
  7931. }
  7932. }
  7933. range.moveToBookmark(bk).select();
  7934. } else {
  7935. var first = li.firstChild;
  7936. if (!first || !domUtils.isBlockElm(first)) {
  7937. var p = me.document.createElement('p');
  7938. !li.firstChild && domUtils.fillNode(me.document, p);
  7939. while (li.firstChild) {
  7940. p.appendChild(li.firstChild);
  7941. }
  7942. li.appendChild(p);
  7943. first = p;
  7944. }
  7945. var span = me.document.createElement('span');
  7946. range.insertNode(span);
  7947. domUtils.breakParent(span, li);
  7948. var nextLi = span.nextSibling;
  7949. first = nextLi.firstChild;
  7950. if (!first) {
  7951. p = me.document.createElement('p');
  7952. domUtils.fillNode(me.document, p);
  7953. nextLi.appendChild(p);
  7954. first = p;
  7955. }
  7956. if (domUtils.isEmptyNode(first)) {
  7957. first.innerHTML = '';
  7958. domUtils.fillNode(me.document, first);
  7959. }
  7960. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  7961. domUtils.remove(span);
  7962. var pre = nextLi.previousSibling;
  7963. if (pre && domUtils.isEmptyBlock(pre)) {
  7964. pre.innerHTML = '<p></p>';
  7965. domUtils.fillNode(me.document, pre.firstChild);
  7966. }
  7967. }
  7968. // }
  7969. preventAndSave();
  7970. }
  7971. }
  7972. }
  7973. if (keyCode == 8) {
  7974. //修中ie中li下的问题
  7975. range = me.selection.getRange();
  7976. if (range.collapsed && domUtils.isStartInblock(range)) {
  7977. tmpRange = range.cloneRange().trimBoundary();
  7978. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  7979. //要在li的最左边,才能处理
  7980. if (li && domUtils.isStartInblock(tmpRange)) {
  7981. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  7982. if (start && start !== li.firstChild) {
  7983. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  7984. domUtils.breakParent(start,parentList);
  7985. clearEmptySibling(start);
  7986. me.fireEvent('contentchange');
  7987. range.setStart(start,0).setCursor(false,true);
  7988. me.fireEvent('saveScene');
  7989. domUtils.preventDefault(evt);
  7990. return;
  7991. }
  7992. if (li && (pre = li.previousSibling)) {
  7993. if (keyCode == 46 && li.childNodes.length) {
  7994. return;
  7995. }
  7996. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  7997. if (dtd.$list[pre.tagName]) {
  7998. pre = pre.lastChild;
  7999. }
  8000. me.undoManger && me.undoManger.save();
  8001. first = li.firstChild;
  8002. if (domUtils.isBlockElm(first)) {
  8003. if (domUtils.isEmptyNode(first)) {
  8004. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  8005. pre.appendChild(first);
  8006. range.setStart(first, 0).setCursor(false, true);
  8007. //first不是唯一的节点
  8008. while (li.firstChild) {
  8009. pre.appendChild(li.firstChild);
  8010. }
  8011. } else {
  8012. span = me.document.createElement('span');
  8013. range.insertNode(span);
  8014. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  8015. if (domUtils.isEmptyBlock(pre)) {
  8016. pre.innerHTML = '';
  8017. }
  8018. domUtils.moveChild(li, pre);
  8019. range.setStartBefore(span).collapse(true).select(true);
  8020. domUtils.remove(span);
  8021. }
  8022. } else {
  8023. if (domUtils.isEmptyNode(li)) {
  8024. var p = me.document.createElement('p');
  8025. pre.appendChild(p);
  8026. range.setStart(p, 0).setCursor();
  8027. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  8028. } else {
  8029. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  8030. while (li.firstChild) {
  8031. pre.appendChild(li.firstChild);
  8032. }
  8033. }
  8034. }
  8035. domUtils.remove(li);
  8036. me.fireEvent('contentchange');
  8037. me.fireEvent('saveScene');
  8038. domUtils.preventDefault(evt);
  8039. return;
  8040. }
  8041. //trace:980
  8042. if (li && !li.previousSibling) {
  8043. var parentList = li.parentNode;
  8044. var bk = range.createBookmark();
  8045. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  8046. parentList.parentNode.insertBefore(li,parentList);
  8047. if(domUtils.isEmptyNode(parentList)){
  8048. domUtils.remove(parentList)
  8049. }
  8050. }else{
  8051. while(li.firstChild){
  8052. parentList.parentNode.insertBefore(li.firstChild,parentList);
  8053. }
  8054. domUtils.remove(li);
  8055. if(domUtils.isEmptyNode(parentList)){
  8056. domUtils.remove(parentList)
  8057. }
  8058. }
  8059. range.moveToBookmark(bk).setCursor(false,true);
  8060. me.fireEvent('contentchange');
  8061. me.fireEvent('saveScene');
  8062. domUtils.preventDefault(evt);
  8063. return;
  8064. }
  8065. }
  8066. }
  8067. }
  8068. });
  8069. //处理tab键
  8070. me.addListener('tabkeydown',function(){
  8071. function listToArray(list){
  8072. var arr = [];
  8073. for(var p in list){
  8074. arr.push(p)
  8075. }
  8076. return arr;
  8077. }
  8078. var range = me.selection.getRange(),
  8079. listStyle = {
  8080. 'OL':listToArray(me.options.insertorderedlist),
  8081. 'UL':listToArray(me.options.insertunorderedlist)
  8082. };
  8083. //控制级数
  8084. function checkLevel(li){
  8085. if(me.options.maxListLevel != -1){
  8086. var level = li.parentNode,levelNum = 0;
  8087. while(/[ou]l/i.test(level.tagName)){
  8088. levelNum++;
  8089. level = level.parentNode;
  8090. }
  8091. if(levelNum >= me.options.maxListLevel){
  8092. return true;
  8093. }
  8094. }
  8095. }
  8096. //只以开始为准
  8097. //todo 后续改进
  8098. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  8099. if(li){
  8100. var bk;
  8101. if(range.collapsed){
  8102. if(checkLevel(li))
  8103. return true;
  8104. var parentLi = li.parentNode,
  8105. list = me.document.createElement(parentLi.tagName),
  8106. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  8107. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  8108. var currentStyle = listStyle[list.tagName][index];
  8109. setListStyle(list,currentStyle);
  8110. if(domUtils.isStartInblock(range)){
  8111. me.fireEvent('saveScene');
  8112. bk = range.createBookmark();
  8113. parentLi.insertBefore(list, li);
  8114. list.appendChild(li);
  8115. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  8116. me.fireEvent('contentchange');
  8117. range.moveToBookmark(bk).select(true);
  8118. return true;
  8119. }
  8120. }else{
  8121. me.fireEvent('saveScene');
  8122. bk = range.createBookmark();
  8123. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  8124. if(domUtils.isTagNode(ci,'ol ul')){
  8125. closeList = ci;
  8126. break;
  8127. }
  8128. }
  8129. var current = li;
  8130. if(bk.end){
  8131. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  8132. if(checkLevel(current)){
  8133. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  8134. continue;
  8135. }
  8136. var parentLi = current.parentNode,
  8137. list = me.document.createElement(parentLi.tagName),
  8138. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  8139. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  8140. var currentStyle = listStyle[list.tagName][currentIndex];
  8141. setListStyle(list,currentStyle);
  8142. parentLi.insertBefore(list, current);
  8143. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  8144. li = current.nextSibling;
  8145. list.appendChild(current);
  8146. if(!li || domUtils.isTagNode(li,'ol ul')){
  8147. if(li){
  8148. while(li = li.firstChild){
  8149. if(li.tagName == 'LI'){
  8150. break;
  8151. }
  8152. }
  8153. }else{
  8154. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  8155. }
  8156. break;
  8157. }
  8158. current = li;
  8159. }
  8160. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  8161. current = li;
  8162. }
  8163. }
  8164. me.fireEvent('contentchange');
  8165. range.moveToBookmark(bk).select();
  8166. return true;
  8167. }
  8168. }
  8169. });
  8170. me.commands['insertorderedlist'] =
  8171. me.commands['insertunorderedlist'] = {
  8172. execCommand:function (command, style) {
  8173. if (!style) {
  8174. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  8175. }
  8176. var me = this,
  8177. range = this.selection.getRange(),
  8178. filterFn = function (node) {
  8179. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  8180. },
  8181. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  8182. frag = me.document.createDocumentFragment();
  8183. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  8184. //range.shrinkBoundary();//.adjustmentBoundary();
  8185. range.adjustmentBoundary().shrinkBoundary();
  8186. var bko = range.createBookmark(true),
  8187. start = domUtils.findParentByTagName(me.document.getElementById(bko.start), 'li'),
  8188. modifyStart = 0,
  8189. end = domUtils.findParentByTagName(me.document.getElementById(bko.end), 'li'),
  8190. modifyEnd = 0,
  8191. startParent, endParent,
  8192. list, tmp;
  8193. if (start || end) {
  8194. start && (startParent = start.parentNode);
  8195. if (!bko.end) {
  8196. end = start;
  8197. }
  8198. end && (endParent = end.parentNode);
  8199. if (startParent === endParent) {
  8200. while (start !== end) {
  8201. tmp = start;
  8202. start = start.nextSibling;
  8203. if (!domUtils.isBlockElm(tmp.firstChild)) {
  8204. var p = me.document.createElement('p');
  8205. while (tmp.firstChild) {
  8206. p.appendChild(tmp.firstChild);
  8207. }
  8208. tmp.appendChild(p);
  8209. }
  8210. frag.appendChild(tmp);
  8211. }
  8212. tmp = me.document.createElement('span');
  8213. startParent.insertBefore(tmp, end);
  8214. if (!domUtils.isBlockElm(end.firstChild)) {
  8215. p = me.document.createElement('p');
  8216. while (end.firstChild) {
  8217. p.appendChild(end.firstChild);
  8218. }
  8219. end.appendChild(p);
  8220. }
  8221. frag.appendChild(end);
  8222. domUtils.breakParent(tmp, startParent);
  8223. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  8224. domUtils.remove(tmp.previousSibling);
  8225. }
  8226. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  8227. domUtils.remove(tmp.nextSibling)
  8228. }
  8229. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  8230. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  8231. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.childNodes[i++];) {
  8232. if(domUtils.isTagNode(ci,'ol ul')){
  8233. utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  8234. while(li.firstChild){
  8235. tmpFrag.appendChild(li.firstChild);
  8236. }
  8237. });
  8238. }else{
  8239. while (ci.firstChild) {
  8240. tmpFrag.appendChild(ci.firstChild);
  8241. }
  8242. }
  8243. }
  8244. tmp.parentNode.insertBefore(tmpFrag, tmp);
  8245. } else {
  8246. list = me.document.createElement(tag);
  8247. setListStyle(list,style);
  8248. list.appendChild(frag);
  8249. tmp.parentNode.insertBefore(list, tmp);
  8250. }
  8251. domUtils.remove(tmp);
  8252. list && adjustList(list, tag, style);
  8253. range.moveToBookmark(bko).select();
  8254. return;
  8255. }
  8256. //开始
  8257. if (start) {
  8258. while (start) {
  8259. tmp = start.nextSibling;
  8260. if (domUtils.isTagNode(start, 'ol ul')) {
  8261. frag.appendChild(start);
  8262. } else {
  8263. var tmpfrag = me.document.createDocumentFragment(),
  8264. hasBlock = 0;
  8265. while (start.firstChild) {
  8266. if (domUtils.isBlockElm(start.firstChild)) {
  8267. hasBlock = 1;
  8268. }
  8269. tmpfrag.appendChild(start.firstChild);
  8270. }
  8271. if (!hasBlock) {
  8272. var tmpP = me.document.createElement('p');
  8273. tmpP.appendChild(tmpfrag);
  8274. frag.appendChild(tmpP);
  8275. } else {
  8276. frag.appendChild(tmpfrag);
  8277. }
  8278. domUtils.remove(start);
  8279. }
  8280. start = tmp;
  8281. }
  8282. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  8283. if (domUtils.isEmptyNode(startParent)) {
  8284. range.setStartBefore(startParent);
  8285. domUtils.remove(startParent);
  8286. } else {
  8287. range.setStartAfter(startParent);
  8288. }
  8289. modifyStart = 1;
  8290. }
  8291. if (end && domUtils.inDoc(endParent, me.document)) {
  8292. //结束
  8293. start = endParent.firstChild;
  8294. while (start && start !== end) {
  8295. tmp = start.nextSibling;
  8296. if (domUtils.isTagNode(start, 'ol ul')) {
  8297. frag.appendChild(start);
  8298. } else {
  8299. tmpfrag = me.document.createDocumentFragment();
  8300. hasBlock = 0;
  8301. while (start.firstChild) {
  8302. if (domUtils.isBlockElm(start.firstChild)) {
  8303. hasBlock = 1;
  8304. }
  8305. tmpfrag.appendChild(start.firstChild);
  8306. }
  8307. if (!hasBlock) {
  8308. tmpP = me.document.createElement('p');
  8309. tmpP.appendChild(tmpfrag);
  8310. frag.appendChild(tmpP);
  8311. } else {
  8312. frag.appendChild(tmpfrag);
  8313. }
  8314. domUtils.remove(start);
  8315. }
  8316. start = tmp;
  8317. }
  8318. var tmpDiv = domUtils.createElement(me.document, 'div', {
  8319. 'tmpDiv':1
  8320. });
  8321. domUtils.moveChild(end, tmpDiv);
  8322. frag.appendChild(tmpDiv);
  8323. domUtils.remove(end);
  8324. endParent.parentNode.insertBefore(frag, endParent);
  8325. range.setEndBefore(endParent);
  8326. if (domUtils.isEmptyNode(endParent)) {
  8327. domUtils.remove(endParent);
  8328. }
  8329. modifyEnd = 1;
  8330. }
  8331. }
  8332. if (!modifyStart) {
  8333. range.setStartBefore(me.document.getElementById(bko.start));
  8334. }
  8335. if (bko.end && !modifyEnd) {
  8336. range.setEndAfter(me.document.getElementById(bko.end));
  8337. }
  8338. range.enlarge(true, function (node) {
  8339. return notExchange[node.tagName];
  8340. });
  8341. frag = me.document.createDocumentFragment();
  8342. var bk = range.createBookmark(),
  8343. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  8344. tmpRange = range.cloneRange(),
  8345. tmpNode,
  8346. block = domUtils.isBlockElm;
  8347. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  8348. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  8349. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  8350. while (current.firstChild) {
  8351. frag.appendChild(current.firstChild);
  8352. }
  8353. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  8354. domUtils.remove(current);
  8355. current = tmpNode;
  8356. continue;
  8357. }
  8358. tmpNode = current;
  8359. tmpRange.setStartBefore(current);
  8360. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  8361. tmpNode = current;
  8362. current = domUtils.getNextDomNode(current, false, null, function (node) {
  8363. return !notExchange[node.tagName];
  8364. });
  8365. }
  8366. if (current && block(current)) {
  8367. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  8368. if (tmp && domUtils.isBookmarkNode(tmp)) {
  8369. current = domUtils.getNextDomNode(tmp, false, filterFn);
  8370. tmpNode = tmp;
  8371. }
  8372. }
  8373. tmpRange.setEndAfter(tmpNode);
  8374. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  8375. var li = range.document.createElement('li');
  8376. li.appendChild(tmpRange.extractContents());
  8377. if(domUtils.isEmptyNode(li)){
  8378. var tmpNode = range.document.createElement('p');
  8379. while(li.firstChild){
  8380. tmpNode.appendChild(li.firstChild)
  8381. }
  8382. li.appendChild(tmpNode);
  8383. }
  8384. frag.appendChild(li);
  8385. } else {
  8386. current = domUtils.getNextDomNode(current, true, filterFn);
  8387. }
  8388. }
  8389. range.moveToBookmark(bk).collapse(true);
  8390. list = me.document.createElement(tag);
  8391. setListStyle(list,style);
  8392. list.appendChild(frag);
  8393. range.insertNode(list);
  8394. //当前list上下看能否合并
  8395. adjustList(list, tag, style,true);
  8396. //去掉冗余的tmpDiv
  8397. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  8398. if (ci.getAttribute('tmpDiv')) {
  8399. domUtils.remove(ci, true)
  8400. }
  8401. }
  8402. range.moveToBookmark(bko).select();
  8403. },
  8404. queryCommandState:function (command) {
  8405. return domUtils.filterNodeList(this.selection.getStartElementPath(), command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul') ? 1 : 0;
  8406. },
  8407. queryCommandValue:function (command) {
  8408. var node = domUtils.filterNodeList(this.selection.getStartElementPath(), command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul');
  8409. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  8410. }
  8411. };
  8412. };
  8413. ///import core
  8414. ///import plugins/serialize.js
  8415. ///import plugins/undo.js
  8416. ///commands 查看源码
  8417. ///commandsName Source
  8418. ///commandsTitle 查看源码
  8419. (function (){
  8420. function SourceFormater(config){
  8421. config = config || {};
  8422. this.indentChar = config.indentChar || ' ';
  8423. this.breakChar = config.breakChar || '\n';
  8424. this.selfClosingEnd = config.selfClosingEnd || ' />';
  8425. }
  8426. var unhtml1 = function (){
  8427. var map = { '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
  8428. function rep( m ){ return map[m]; }
  8429. return function ( str ) {
  8430. str = str + '';
  8431. return str ? str.replace( /[<>"']/g, rep ) : '';
  8432. };
  8433. }();
  8434. var inline = utils.extend({a:1,A:1},dtd.$inline,true);
  8435. function printAttrs(attrs){
  8436. var buff = [];
  8437. for (var k in attrs) {
  8438. buff.push(k + '="' + unhtml1(attrs[k]) + '"');
  8439. }
  8440. return buff.join(' ');
  8441. }
  8442. SourceFormater.prototype = {
  8443. format: function (html){
  8444. var node = UE.serialize.parseHTML(html);
  8445. this.buff = [];
  8446. this.indents = '';
  8447. this.indenting = 1;
  8448. this.visitNode(node);
  8449. return this.buff.join('');
  8450. },
  8451. visitNode: function (node){
  8452. if (node.type == 'fragment') {
  8453. this.visitChildren(node.children);
  8454. } else if (node.type == 'element') {
  8455. var selfClosing = dtd.$empty[node.tag];
  8456. this.visitTag(node.tag, node.attributes, selfClosing);
  8457. this.visitChildren(node.children);
  8458. if (!selfClosing) {
  8459. this.visitEndTag(node.tag);
  8460. }
  8461. } else if (node.type == 'comment') {
  8462. this.visitComment(node.data);
  8463. } else {
  8464. this.visitText(node.data,dtd.$notTransContent[node.parent.tag]);
  8465. }
  8466. },
  8467. visitChildren: function (children){
  8468. for (var i=0; i<children.length; i++) {
  8469. this.visitNode(children[i]);
  8470. }
  8471. },
  8472. visitTag: function (tag, attrs, selfClosing){
  8473. if (this.indenting) {
  8474. this.indent();
  8475. } else if (!inline[tag]) { // todo: 去掉a, 因为dtd的inline里面没有a
  8476. this.newline();
  8477. this.indent();
  8478. }
  8479. this.buff.push('<', tag);
  8480. var attrPart = printAttrs(attrs);
  8481. if (attrPart) {
  8482. this.buff.push(' ', attrPart);
  8483. }
  8484. if (selfClosing) {
  8485. this.buff.push(this.selfClosingEnd);
  8486. if (tag == 'br') {
  8487. this.newline();
  8488. }
  8489. } else {
  8490. this.buff.push('>');
  8491. this.indents += this.indentChar;
  8492. }
  8493. if (!inline[tag]) {
  8494. this.newline();
  8495. }
  8496. },
  8497. indent: function (){
  8498. this.buff.push(this.indents);
  8499. this.indenting = 0;
  8500. },
  8501. newline: function (){
  8502. this.buff.push(this.breakChar);
  8503. this.indenting = 1;
  8504. },
  8505. visitEndTag: function (tag){
  8506. this.indents = this.indents.slice(0, -this.indentChar.length);
  8507. if (this.indenting) {
  8508. this.indent();
  8509. } else if (!inline[tag]) {
  8510. this.newline();
  8511. this.indent();
  8512. }
  8513. this.buff.push('</', tag, '>');
  8514. },
  8515. visitText: function (text,notTrans){
  8516. if (this.indenting) {
  8517. this.indent();
  8518. }
  8519. // if(!notTrans){
  8520. // text = text.replace(/&nbsp;/g, ' ').replace(/[ ][ ]+/g, function (m){
  8521. // return new Array(m.length + 1).join('&nbsp;');
  8522. // }).replace(/(?:^ )|(?: $)/g, '&nbsp;');
  8523. // }
  8524. text = text.replace(/&nbsp;/g, ' ');
  8525. this.buff.push(text);
  8526. },
  8527. visitComment: function (text){
  8528. if (this.indenting) {
  8529. this.indent();
  8530. }
  8531. this.buff.push('<!--', text, '-->');
  8532. }
  8533. };
  8534. var sourceEditors = {
  8535. textarea: function (editor, holder){
  8536. var textarea = holder.ownerDocument.createElement('textarea');
  8537. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  8538. // todo: IE下只有onresize属性可用... 很纠结
  8539. if (browser.ie && browser.version < 8) {
  8540. textarea.style.width = holder.offsetWidth + 'px';
  8541. textarea.style.height = holder.offsetHeight + 'px';
  8542. holder.onresize = function (){
  8543. textarea.style.width = holder.offsetWidth + 'px';
  8544. textarea.style.height = holder.offsetHeight + 'px';
  8545. };
  8546. }
  8547. holder.appendChild(textarea);
  8548. return {
  8549. setContent: function (content){
  8550. textarea.value = content;
  8551. },
  8552. getContent: function (){
  8553. return textarea.value;
  8554. },
  8555. select: function (){
  8556. var range;
  8557. if (browser.ie) {
  8558. range = textarea.createTextRange();
  8559. range.collapse(true);
  8560. range.select();
  8561. } else {
  8562. //todo: chrome下无法设置焦点
  8563. textarea.setSelectionRange(0, 0);
  8564. textarea.focus();
  8565. }
  8566. },
  8567. dispose: function (){
  8568. holder.removeChild(textarea);
  8569. // todo
  8570. holder.onresize = null;
  8571. textarea = null;
  8572. holder = null;
  8573. }
  8574. };
  8575. },
  8576. codemirror: function (editor, holder){
  8577. var codeEditor = window.CodeMirror(holder, {
  8578. mode: "text/html",
  8579. tabMode: "indent",
  8580. lineNumbers: true,
  8581. lineWrapping:true
  8582. });
  8583. var dom = codeEditor.getWrapperElement();
  8584. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  8585. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  8586. codeEditor.refresh();
  8587. return {
  8588. getCodeMirror:function(){
  8589. return codeEditor;
  8590. },
  8591. setContent: function (content){
  8592. codeEditor.setValue(content);
  8593. },
  8594. getContent: function (){
  8595. return codeEditor.getValue();
  8596. },
  8597. select: function (){
  8598. codeEditor.focus();
  8599. },
  8600. dispose: function (){
  8601. holder.removeChild(dom);
  8602. dom = null;
  8603. codeEditor = null;
  8604. }
  8605. };
  8606. }
  8607. };
  8608. UE.plugins['source'] = function (){
  8609. var me = this;
  8610. var opt = this.options;
  8611. var formatter = new SourceFormater(opt.source);
  8612. var sourceMode = false;
  8613. var sourceEditor;
  8614. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  8615. me.setOpt({
  8616. sourceEditorFirst:false
  8617. });
  8618. function createSourceEditor(holder){
  8619. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  8620. }
  8621. var bakCssText;
  8622. //解决在源码模式下getContent不能得到最新的内容问题
  8623. var oldGetContent = me.getContent,
  8624. bakAddress;
  8625. me.commands['source'] = {
  8626. execCommand: function (){
  8627. sourceMode = !sourceMode;
  8628. if (sourceMode) {
  8629. bakAddress = me.selection.getRange().createAddress(false,true);
  8630. me.undoManger && me.undoManger.save(true);
  8631. if(browser.gecko){
  8632. me.body.contentEditable = false;
  8633. }
  8634. bakCssText = me.iframe.style.cssText;
  8635. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  8636. var content = formatter.format(me.hasContents() ? me.getContent() : '');
  8637. sourceEditor = createSourceEditor(me.iframe.parentNode);
  8638. sourceEditor.setContent(content);
  8639. setTimeout(function (){
  8640. sourceEditor.select();
  8641. me.addListener('fullscreenchanged', function(){
  8642. try{
  8643. sourceEditor.getCodeMirror().refresh()
  8644. }catch(e){}
  8645. });
  8646. });
  8647. //重置getContent,源码模式下取值也能是最新的数据
  8648. me.getContent = function (){
  8649. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  8650. return cont.replace(/>[\n\r\t]+([ ]{4})+/g,'>').replace(/[\n\r\t]+([ ]{4})+</g,'<').replace(/>[\n\r\t]+</g,'><');
  8651. };
  8652. } else {
  8653. me.iframe.style.cssText = bakCssText;
  8654. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  8655. cont = cont.replace(/>[\n\r\t]+([ ]{4})+/g,'>').replace(/[\n\r\t]+([ ]{4})+</g,'<').replace(/>[\n\r\t]+</g,'><');
  8656. me.setContent(cont);
  8657. sourceEditor.dispose();
  8658. sourceEditor = null;
  8659. //还原getContent方法
  8660. me.getContent = oldGetContent;
  8661. var first = me.body.firstChild;
  8662. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  8663. if(!first){
  8664. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  8665. first = me.body.firstChild;
  8666. }
  8667. //要在ifm为显示时ff才能取到selection,否则报错
  8668. //这里不能比较位置了
  8669. me.undoManger && me.undoManger.save(true);
  8670. if(browser.gecko){
  8671. var input = document.createElement('input');
  8672. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  8673. document.body.appendChild(input);
  8674. me.body.contentEditable = false;
  8675. setTimeout(function(){
  8676. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  8677. input.focus();
  8678. setTimeout(function(){
  8679. me.body.contentEditable = true;
  8680. me.selection.getRange().moveToAddress(bakAddress).select();
  8681. domUtils.remove(input);
  8682. });
  8683. });
  8684. }else{
  8685. //ie下有可能报错,比如在代码顶头的情况
  8686. try{
  8687. me.selection.getRange().moveToAddress(bakAddress).select();
  8688. }catch(e){}
  8689. }
  8690. }
  8691. this.fireEvent('sourcemodechanged', sourceMode);
  8692. },
  8693. queryCommandState: function (){
  8694. return sourceMode|0;
  8695. },
  8696. notNeedUndo : 1
  8697. };
  8698. var oldQueryCommandState = me.queryCommandState;
  8699. me.queryCommandState = function (cmdName){
  8700. cmdName = cmdName.toLowerCase();
  8701. if (sourceMode) {
  8702. //源码模式下可以开启的命令
  8703. return cmdName in {
  8704. 'source' : 1,
  8705. 'fullscreen' : 1
  8706. } ? 1 : -1
  8707. }
  8708. return oldQueryCommandState.apply(this, arguments);
  8709. };
  8710. if(opt.sourceEditor == "codemirror"){
  8711. me.addListener("ready",function(){
  8712. utils.loadFile(document,{
  8713. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  8714. tag : "script",
  8715. type : "text/javascript",
  8716. defer : "defer"
  8717. },function(){
  8718. if(opt.sourceEditorFirst){
  8719. setTimeout(function(){
  8720. me.execCommand("source");
  8721. },0);
  8722. }
  8723. });
  8724. utils.loadFile(document,{
  8725. tag : "link",
  8726. rel : "stylesheet",
  8727. type : "text/css",
  8728. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  8729. });
  8730. });
  8731. }
  8732. };
  8733. })();
  8734. ///import core
  8735. ///import plugins/undo.js
  8736. ///commands 设置回车标签p或br
  8737. ///commandsName EnterKey
  8738. ///commandsTitle 设置回车标签p或br
  8739. /**
  8740. * @description 处理回车
  8741. * @author zhanyi
  8742. */
  8743. UE.plugins['enterkey'] = function() {
  8744. var hTag,
  8745. me = this,
  8746. tag = me.options.enterTag;
  8747. me.addListener('keyup', function(type, evt) {
  8748. var keyCode = evt.keyCode || evt.which;
  8749. if (keyCode == 13) {
  8750. var range = me.selection.getRange(),
  8751. start = range.startContainer,
  8752. doSave;
  8753. //修正在h1-h6里边回车后不能嵌套p的问题
  8754. if (!browser.ie) {
  8755. if (/h\d/i.test(hTag)) {
  8756. if (browser.gecko) {
  8757. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  8758. if (!h) {
  8759. me.document.execCommand('formatBlock', false, '<p>');
  8760. doSave = 1;
  8761. }
  8762. } else {
  8763. //chrome remove div
  8764. if (start.nodeType == 1) {
  8765. var tmp = me.document.createTextNode(''),div;
  8766. range.insertNode(tmp);
  8767. div = domUtils.findParentByTagName(tmp, 'div', true);
  8768. if (div) {
  8769. var p = me.document.createElement('p');
  8770. while (div.firstChild) {
  8771. p.appendChild(div.firstChild);
  8772. }
  8773. div.parentNode.insertBefore(p, div);
  8774. domUtils.remove(div);
  8775. range.setStartBefore(tmp).setCursor();
  8776. doSave = 1;
  8777. }
  8778. domUtils.remove(tmp);
  8779. }
  8780. }
  8781. if (me.undoManger && doSave) {
  8782. me.undoManger.save();
  8783. }
  8784. }
  8785. //没有站位符,会出现多行的问题
  8786. browser.opera && range.select();
  8787. }
  8788. // if(browser.ie){
  8789. // range = me.selection.getRange();
  8790. // start = range.startContainer;
  8791. // while(start){
  8792. // if(start.nodeType == 1 && start.tagName == 'P'){
  8793. // break;
  8794. // }
  8795. // start = start.parentNode;
  8796. // }
  8797. // if(start && domUtils.isEmptyBlock(start)){
  8798. // start.innerHTML = '&nbsp;';
  8799. // var rng = me.selection.getRange();
  8800. // rng.setStart(start,0).setCursor(false,true);
  8801. // }
  8802. // }
  8803. setTimeout(function() {
  8804. me.selection.getRange().scrollToView(me.autoHeightEnabled, me.autoHeightEnabled ? domUtils.getXY(me.iframe).y : 0);
  8805. }, 50);
  8806. }
  8807. });
  8808. me.addListener('keydown', function(type, evt) {
  8809. var keyCode = evt.keyCode || evt.which;
  8810. if (keyCode == 13) {//回车
  8811. if (me.undoManger) {
  8812. me.undoManger.save();
  8813. }
  8814. hTag = '';
  8815. var range = me.selection.getRange();
  8816. if (!range.collapsed) {
  8817. //跨td不能删
  8818. var start = range.startContainer,
  8819. end = range.endContainer,
  8820. startTd = domUtils.findParentByTagName(start, 'td', true),
  8821. endTd = domUtils.findParentByTagName(end, 'td', true);
  8822. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  8823. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  8824. return;
  8825. }
  8826. }
  8827. if (tag == 'p') {
  8828. if (!browser.ie) {
  8829. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  8830. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  8831. //trace:2431
  8832. if (!start && !browser.opera) {
  8833. me.document.execCommand('formatBlock', false, '<p>');
  8834. if (browser.gecko) {
  8835. range = me.selection.getRange();
  8836. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  8837. start && domUtils.removeDirtyAttr(start);
  8838. }
  8839. } else {
  8840. hTag = start.tagName;
  8841. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  8842. }
  8843. }
  8844. } else {
  8845. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  8846. if (!range.collapsed) {
  8847. range.deleteContents();
  8848. start = range.startContainer;
  8849. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  8850. while (start.nodeType == 1) {
  8851. if (dtd.$empty[start.tagName]) {
  8852. range.setStartBefore(start).setCursor();
  8853. if (me.undoManger) {
  8854. me.undoManger.save();
  8855. }
  8856. return false;
  8857. }
  8858. if (!start.firstChild) {
  8859. var br = range.document.createElement('br');
  8860. start.appendChild(br);
  8861. range.setStart(start, 0).setCursor();
  8862. if (me.undoManger) {
  8863. me.undoManger.save();
  8864. }
  8865. return false;
  8866. }
  8867. start = start.firstChild;
  8868. }
  8869. if (start === range.startContainer.childNodes[range.startOffset]) {
  8870. br = range.document.createElement('br');
  8871. range.insertNode(br).setCursor();
  8872. } else {
  8873. range.setStart(start, 0).setCursor();
  8874. }
  8875. } else {
  8876. br = range.document.createElement('br');
  8877. range.insertNode(br).setStartAfter(br).setCursor();
  8878. }
  8879. } else {
  8880. br = range.document.createElement('br');
  8881. range.insertNode(br);
  8882. var parent = br.parentNode;
  8883. if (parent.lastChild === br) {
  8884. br.parentNode.insertBefore(br.cloneNode(true), br);
  8885. range.setStartBefore(br);
  8886. } else {
  8887. range.setStartAfter(br);
  8888. }
  8889. range.setCursor();
  8890. }
  8891. }
  8892. }
  8893. });
  8894. };
  8895. /*
  8896. * 处理特殊键的兼容性问题
  8897. */
  8898. UE.plugins['keystrokes'] = function() {
  8899. var me = this;
  8900. me.addListener('keydown', function(type, evt) {
  8901. var keyCode = evt.keyCode || evt.which,
  8902. rng = me.selection.getRange();
  8903. //处理全选的情况
  8904. if(!rng.collapsed && !(evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey || keyCode == 9 )){
  8905. var tmpNode = rng.startContainer;
  8906. if(domUtils.isFillChar(tmpNode)){
  8907. rng.setStartBefore(tmpNode)
  8908. }
  8909. tmpNode = rng.endContainer;
  8910. if(domUtils.isFillChar(tmpNode)){
  8911. rng.setEndAfter(tmpNode)
  8912. }
  8913. rng.txtToElmBoundary();
  8914. //结束边界可能放到了br的前边,要把br包含进来
  8915. // x[xxx]<br/>
  8916. if(rng.endContainer && rng.endContainer.nodeType == 1){
  8917. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  8918. if(tmpNode && domUtils.isBr(tmpNode)){
  8919. rng.setEndAfter(tmpNode);
  8920. }
  8921. }
  8922. if(rng.startOffset == 0){
  8923. tmpNode = rng.startContainer;
  8924. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  8925. tmpNode = rng.endContainer;
  8926. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  8927. me.fireEvent('saveScene');
  8928. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  8929. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  8930. browser.ie && me._selectionChange();
  8931. domUtils.preventDefault(evt);
  8932. return;
  8933. }
  8934. }
  8935. }
  8936. }
  8937. //处理backspace/del
  8938. if (keyCode == 8) {//|| keyCode == 46
  8939. var start,end;
  8940. //避免按两次删除才能生效的问题
  8941. if(rng.inFillChar()){
  8942. start = rng.startContainer;
  8943. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  8944. if(domUtils.isFillChar(start)){
  8945. domUtils.remove(start)
  8946. }else{
  8947. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  8948. }
  8949. }
  8950. //解决选中control元素不能删除的问题
  8951. if (start = rng.getClosedNode()) {
  8952. me.fireEvent('saveScene');
  8953. rng.setStartBefore(start);
  8954. domUtils.remove(start);
  8955. rng.setCursor();
  8956. me.fireEvent('saveScene');
  8957. domUtils.preventDefault(evt);
  8958. return;
  8959. }
  8960. //阻止在table上的删除
  8961. if (!browser.ie) {
  8962. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  8963. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  8964. if (start && !end || !start && end || start !== end) {
  8965. evt.preventDefault();
  8966. return;
  8967. }
  8968. }
  8969. }
  8970. //处理tab键的逻辑
  8971. if (keyCode == 9) {
  8972. //不处理以下标签
  8973. var excludeTagNameForTabKey = {
  8974. 'ol' : 1,
  8975. 'ul' : 1,
  8976. 'table':1
  8977. };
  8978. //处理组件里的tab按下事件
  8979. if(me.fireEvent('tabkeydown')){
  8980. domUtils.preventDefault(evt);
  8981. return;
  8982. }
  8983. range = me.selection.getRange();
  8984. me.fireEvent('saveScene');
  8985. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  8986. txt += tabNode;
  8987. }
  8988. var span = me.document.createElement('span');
  8989. span.innerHTML = txt + domUtils.fillChar;
  8990. if (range.collapsed) {
  8991. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  8992. } else {
  8993. //普通的情况
  8994. start = domUtils.findParent(range.startContainer, filterFn);
  8995. end = domUtils.findParent(range.endContainer, filterFn);
  8996. if (start && end && start === end) {
  8997. range.deleteContents();
  8998. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  8999. } else {
  9000. var bookmark = range.createBookmark(),
  9001. filterFn = function(node) {
  9002. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  9003. };
  9004. range.enlarge(true);
  9005. var bookmark2 = range.createBookmark(),
  9006. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  9007. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  9008. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  9009. current = domUtils.getNextDomNode(current, false, filterFn);
  9010. }
  9011. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  9012. }
  9013. }
  9014. domUtils.preventDefault(evt)
  9015. }
  9016. //trace:1634
  9017. //ff的del键在容器空的时候,也会删除
  9018. if(browser.gecko && keyCode == 46){
  9019. range = me.selection.getRange();
  9020. if(range.collapsed){
  9021. start = range.startContainer;
  9022. if(domUtils.isEmptyBlock(start)){
  9023. var parent = start.parentNode;
  9024. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  9025. start = parent;
  9026. parent = parent.parentNode;
  9027. }
  9028. if(start === parent.lastChild)
  9029. evt.preventDefault();
  9030. return;
  9031. }
  9032. }
  9033. }
  9034. });
  9035. me.addListener('keyup', function(type, evt) {
  9036. var keyCode = evt.keyCode || evt.which,
  9037. rng;
  9038. if(keyCode == 8){
  9039. rng = me.selection.getRange();
  9040. //处理当删除到body时,要重新给p标签展位
  9041. if(rng.collapsed && domUtils.isBody(rng.startContainer)){
  9042. var tmpNode = domUtils.createElement(me.document,'p',{
  9043. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  9044. });
  9045. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  9046. }
  9047. // //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  9048. if(browser.chrome && rng.collapsed && rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer)){
  9049. rng.select(true);
  9050. }
  9051. }
  9052. })
  9053. };
  9054. ///import core
  9055. ///commands 修复chrome下图片不能点击的问题
  9056. ///commandsName FixImgClick
  9057. ///commandsTitle 修复chrome下图片不能点击的问题
  9058. //修复chrome下图片不能点击的问题
  9059. //todo 可以改大小
  9060. UE.plugins['fiximgclick'] = function() {
  9061. var me = this;
  9062. if ( browser.webkit ) {
  9063. me.addListener( 'click', function( type, e ) {
  9064. if ( e.target.tagName == 'IMG' ) {
  9065. var range = new dom.Range( me.document );
  9066. range.selectNode( e.target ).select();
  9067. }
  9068. } );
  9069. }
  9070. };
  9071. ///import core
  9072. ///commands 为非ie浏览器自动添加a标签
  9073. ///commandsName AutoLink
  9074. ///commandsTitle 自动增加链接
  9075. /**
  9076. * @description 为非ie浏览器自动添加a标签
  9077. * @author zhanyi
  9078. */
  9079. UE.plugins['autolink'] = function() {
  9080. var cont = 0;
  9081. if (browser.ie) {
  9082. return;
  9083. }
  9084. var me = this;
  9085. me.addListener('reset',function(){
  9086. cont = 0;
  9087. });
  9088. me.addListener('keydown', function(type, evt) {
  9089. var keyCode = evt.keyCode || evt.which;
  9090. if (keyCode == 32 || keyCode == 13) {
  9091. var sel = me.selection.getNative(),
  9092. range = sel.getRangeAt(0).cloneRange(),
  9093. offset,
  9094. charCode;
  9095. var start = range.startContainer;
  9096. while (start.nodeType == 1 && range.startOffset > 0) {
  9097. start = range.startContainer.childNodes[range.startOffset - 1];
  9098. if (!start){
  9099. break;
  9100. }
  9101. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  9102. range.collapse(true);
  9103. start = range.startContainer;
  9104. }
  9105. do{
  9106. if (range.startOffset == 0) {
  9107. start = range.startContainer.previousSibling;
  9108. while (start && start.nodeType == 1) {
  9109. start = start.lastChild;
  9110. }
  9111. if (!start || domUtils.isFillChar(start)){
  9112. break;
  9113. }
  9114. offset = start.nodeValue.length;
  9115. } else {
  9116. start = range.startContainer;
  9117. offset = range.startOffset;
  9118. }
  9119. range.setStart(start, offset - 1);
  9120. charCode = range.toString().charCodeAt(0);
  9121. } while (charCode != 160 && charCode != 32);
  9122. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  9123. while(range.toString().length){
  9124. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  9125. break;
  9126. }
  9127. try{
  9128. range.setStart(range.startContainer,range.startOffset+1);
  9129. }catch(e){
  9130. //trace:2121
  9131. var start = range.startContainer;
  9132. while(!(next = start.nextSibling)){
  9133. if(domUtils.isBody(start)){
  9134. return;
  9135. }
  9136. start = start.parentNode;
  9137. }
  9138. range.setStart(next,0);
  9139. }
  9140. }
  9141. //range的开始边界已经在a标签里的不再处理
  9142. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  9143. return;
  9144. }
  9145. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  9146. me.undoManger && me.undoManger.save();
  9147. a.appendChild(range.extractContents());
  9148. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  9149. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  9150. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  9151. a.setAttribute('data_ue_src',utils.html(href));
  9152. a.href = utils.html(href);
  9153. range.insertNode(a);
  9154. a.parentNode.insertBefore(text, a.nextSibling);
  9155. range.setStart(text, 0);
  9156. range.collapse(true);
  9157. sel.removeAllRanges();
  9158. sel.addRange(range);
  9159. me.undoManger && me.undoManger.save();
  9160. }
  9161. }
  9162. });
  9163. };
  9164. ///import core
  9165. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  9166. ///commandsName AutoHeight,autoHeightEnabled
  9167. ///commandsTitle 自动增高
  9168. /**
  9169. * @description 自动伸展
  9170. * @author zhanyi
  9171. */
  9172. UE.plugins['autoheight'] = function () {
  9173. var me = this;
  9174. //提供开关,就算加载也可以关闭
  9175. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  9176. if (!me.autoHeightEnabled) {
  9177. return;
  9178. }
  9179. var bakOverflow,
  9180. span, tmpNode,
  9181. lastHeight = 0,
  9182. options = me.options,
  9183. currentHeight,
  9184. timer;
  9185. function adjustHeight() {
  9186. var me = this;
  9187. clearTimeout(timer);
  9188. if(isFullscreen)return;
  9189. timer = setTimeout(function () {
  9190. if (me.queryCommandState && me.queryCommandState('source') != 1) {
  9191. if (!span) {
  9192. span = me.document.createElement('span');
  9193. //trace:1764
  9194. span.style.cssText = 'display:block;width:0;margin:0;padding:0;border:0;clear:both;';
  9195. span.innerHTML = '.';
  9196. }
  9197. tmpNode = span.cloneNode(true);
  9198. me.body.appendChild(tmpNode);
  9199. currentHeight = Math.max(domUtils.getXY(tmpNode).y + tmpNode.offsetHeight,Math.max(options.minFrameHeight, options.initialFrameHeight));
  9200. if (currentHeight != lastHeight) {
  9201. me.setHeight(currentHeight);
  9202. lastHeight = currentHeight;
  9203. }
  9204. domUtils.remove(tmpNode);
  9205. }
  9206. }, 50);
  9207. }
  9208. var isFullscreen;
  9209. me.addListener('fullscreenchanged',function(cmd,f){
  9210. isFullscreen = f
  9211. });
  9212. me.addListener('destroy', function () {
  9213. me.removeListener('contentchange', adjustHeight);
  9214. me.removeListener('afterinserthtml',adjustHeight);
  9215. me.removeListener('keyup', adjustHeight);
  9216. me.removeListener('mouseup', adjustHeight);
  9217. });
  9218. me.enableAutoHeight = function () {
  9219. if (!me.autoHeightEnabled) {
  9220. return;
  9221. }
  9222. var doc = me.document;
  9223. me.autoHeightEnabled = true;
  9224. bakOverflow = doc.body.style.overflowY;
  9225. doc.body.style.overflowY = 'hidden';
  9226. me.addListener('contentchange', adjustHeight);
  9227. me.addListener('afterinserthtml',adjustHeight)
  9228. me.addListener('keyup', adjustHeight);
  9229. me.addListener('mouseup', adjustHeight);
  9230. //ff不给事件算得不对
  9231. setTimeout(function () {
  9232. adjustHeight.call(this);
  9233. }, browser.gecko ? 100 : 0);
  9234. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  9235. };
  9236. me.disableAutoHeight = function () {
  9237. me.body.style.overflowY = bakOverflow || '';
  9238. me.removeListener('contentchange', adjustHeight);
  9239. me.removeListener('keyup', adjustHeight);
  9240. me.removeListener('mouseup', adjustHeight);
  9241. me.autoHeightEnabled = false;
  9242. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  9243. };
  9244. me.addListener('ready', function () {
  9245. me.enableAutoHeight();
  9246. //trace:1764
  9247. var timer;
  9248. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  9249. clearTimeout(timer);
  9250. timer = setTimeout(function () {
  9251. adjustHeight.call(this);
  9252. }, 100);
  9253. });
  9254. });
  9255. };
  9256. ///import core
  9257. ///commands 悬浮工具栏
  9258. ///commandsName AutoFloat,autoFloatEnabled
  9259. ///commandsTitle 悬浮工具栏
  9260. /*
  9261. * modified by chengchao01
  9262. *
  9263. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  9264. */
  9265. UE.plugins['autofloat'] = function() {
  9266. var me = this,
  9267. lang = me.getLang();
  9268. me.setOpt({
  9269. topOffset:0
  9270. });
  9271. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  9272. topOffset = me.options.topOffset;
  9273. //如果不固定toolbar的位置,则直接退出
  9274. if(!optsAutoFloatEnabled){
  9275. return;
  9276. }
  9277. var uiUtils = UE.ui.uiUtils,
  9278. LteIE6 = browser.ie && browser.version <= 6,
  9279. quirks = browser.quirks;
  9280. function checkHasUI(editor){
  9281. if(!editor.ui){
  9282. alert(lang.autofloatMsg);
  9283. return 0;
  9284. }
  9285. return 1;
  9286. }
  9287. function fixIE6FixedPos(){
  9288. var docStyle = document.body.style;
  9289. docStyle.backgroundImage = 'url("about:blank")';
  9290. docStyle.backgroundAttachment = 'fixed';
  9291. }
  9292. var bakCssText,
  9293. placeHolder = document.createElement('div'),
  9294. toolbarBox,orgTop,
  9295. getPosition,
  9296. flag =true; //ie7模式下需要偏移
  9297. function setFloating(){
  9298. var toobarBoxPos = domUtils.getXY(toolbarBox),
  9299. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  9300. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  9301. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  9302. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  9303. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  9304. if (LteIE6 || (quirks && browser.ie)) {
  9305. if(toolbarBox.style.position != 'absolute'){
  9306. toolbarBox.style.position = 'absolute';
  9307. }
  9308. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  9309. } else {
  9310. if (browser.ie7Compat && flag) {
  9311. flag = false;
  9312. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  9313. }
  9314. if(toolbarBox.style.position != 'fixed'){
  9315. toolbarBox.style.position = 'fixed';
  9316. toolbarBox.style.top = topOffset +"px";
  9317. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  9318. }
  9319. }
  9320. }
  9321. function unsetFloating(){
  9322. flag = true;
  9323. if(placeHolder.parentNode){
  9324. placeHolder.parentNode.removeChild(placeHolder);
  9325. }
  9326. toolbarBox.style.cssText = bakCssText;
  9327. }
  9328. function updateFloating(){
  9329. var rect3 = getPosition(me.container);
  9330. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > 0) {
  9331. setFloating();
  9332. }else{
  9333. unsetFloating();
  9334. }
  9335. }
  9336. var defer_updateFloating = utils.defer(function(){
  9337. updateFloating();
  9338. },browser.ie ? 200 : 100,true);
  9339. me.addListener('destroy',function(){
  9340. domUtils.un(window, ['scroll','resize'], updateFloating);
  9341. me.removeListener('keydown', defer_updateFloating);
  9342. });
  9343. me.addListener('ready', function(){
  9344. if(checkHasUI(me)){
  9345. getPosition = uiUtils.getClientRect;
  9346. toolbarBox = me.ui.getDom('toolbarbox');
  9347. orgTop = getPosition(toolbarBox).top;
  9348. bakCssText = toolbarBox.style.cssText;
  9349. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  9350. if(LteIE6){
  9351. fixIE6FixedPos();
  9352. }
  9353. domUtils.on(window, ['scroll','resize'], updateFloating);
  9354. me.addListener('keydown', defer_updateFloating);
  9355. me.addListener('beforefullscreenchange', function (t, enabled){
  9356. if (enabled) {
  9357. unsetFloating();
  9358. }
  9359. });
  9360. me.addListener('fullscreenchanged', function (t, enabled){
  9361. if (!enabled) {
  9362. updateFloating();
  9363. }
  9364. });
  9365. me.addListener('sourcemodechanged', function (t, enabled){
  9366. setTimeout(function (){
  9367. updateFloating();
  9368. },0);
  9369. });
  9370. me.addListener("clearDoc",function(){
  9371. setTimeout(function(){
  9372. updateFloating();
  9373. },0);
  9374. })
  9375. }
  9376. });
  9377. };
  9378. ///import core
  9379. ///import plugins/inserthtml.js
  9380. ///commands 插入代码
  9381. ///commandsName HighlightCode
  9382. ///commandsTitle 插入代码
  9383. ///commandsDialog dialogs\highlightcode
  9384. UE.plugins['highlightcode'] = function() {
  9385. var me = this;
  9386. if(!/highlightcode/i.test(me.options.toolbars.join(''))){
  9387. return;
  9388. }
  9389. me.commands['highlightcode'] = {
  9390. execCommand: function (cmdName, code, syntax) {
  9391. var range = this.selection.getRange(),
  9392. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  9393. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  9394. if(start && end && start === end && domUtils.hasClass(start,'syntaxhighlighter')){
  9395. if(start.nextSibling){
  9396. range.setStart(start.nextSibling,0)
  9397. }else{
  9398. if(start.previousSibling){
  9399. range.setStartAtLast(start.previousSibling)
  9400. }else{
  9401. var p = me.document.createElement('p');
  9402. domUtils.fillNode(me.document,p);
  9403. start.parentNode.insertBefore(p,start);
  9404. range.setStart(p,0)
  9405. }
  9406. }
  9407. range.setCursor(false,true);
  9408. domUtils.remove(start);
  9409. }
  9410. if(code && syntax){
  9411. me.execCommand('inserthtml','<pre id="highlightcode_id" class="brush: '+syntax+';toolbar:false;">'+utils.unhtml(code)+'</pre>',true);
  9412. var pre = me.document.getElementById('highlightcode_id');
  9413. if(pre){
  9414. domUtils.removeAttributes(pre,'id');
  9415. me.window.SyntaxHighlighter.highlight(pre);
  9416. }
  9417. }
  9418. },
  9419. queryCommandState: function(){
  9420. return queryHighlight.call(this);
  9421. }
  9422. };
  9423. function queryHighlight(){
  9424. try{
  9425. var range = this.selection.getRange(),start,end;
  9426. range.adjustmentBoundary();
  9427. start = domUtils.findParent(range.startContainer,function(node){
  9428. return node.nodeType == 1 && node.tagName == 'TABLE' && domUtils.hasClass(node,'syntaxhighlighter');
  9429. },true);
  9430. end = domUtils.findParent(range.endContainer,function(node){
  9431. return node.nodeType == 1 && node.tagName == 'TABLE' && domUtils.hasClass(node,'syntaxhighlighter');
  9432. },true);
  9433. return start && end && start == end ? 1 : 0;
  9434. }catch(e){
  9435. return 0;
  9436. }
  9437. }
  9438. //不需要判断highlight的command列表
  9439. me.notNeedHighlightQuery ={
  9440. help:1,
  9441. undo:1,
  9442. redo:1,
  9443. source:1,
  9444. print:1,
  9445. searchreplace:1,
  9446. fullscreen:1,
  9447. preview:1,
  9448. insertparagraph:1,
  9449. elementpath:1,
  9450. highlightcode:1
  9451. };
  9452. //将queyCommamndState重置
  9453. var orgQuery = me.queryCommandState;
  9454. me.queryCommandState = function(cmd){
  9455. if(!me.notNeedHighlightQuery[cmd.toLowerCase()] && queryHighlight.call(this) == 1){
  9456. return -1;
  9457. }
  9458. return orgQuery.apply(this,arguments)
  9459. };
  9460. me.addListener('beforeselectionchange afterselectionchange',function(type){
  9461. me.highlight = /^b/.test(type) ? me.queryCommandState('highlightcode') : 0;
  9462. });
  9463. me.addListener("ready",function(){
  9464. //避免重复加载高亮文件
  9465. if(typeof me.XRegExp == "undefined"){
  9466. utils.loadFile(me.document,{
  9467. id : "syntaxhighlighter_js",
  9468. src : me.options.highlightJsUrl || me.options.UEDITOR_HOME_URL + "third-party/SyntaxHighlighter/shCore.js",
  9469. tag : "script",
  9470. type : "text/javascript",
  9471. defer : "defer"
  9472. },function(){
  9473. changePre.call(me);
  9474. });
  9475. }
  9476. if(!me.document.getElementById("syntaxhighlighter_css")){
  9477. utils.loadFile(me.document,{
  9478. id : "syntaxhighlighter_css",
  9479. tag : "link",
  9480. rel : "stylesheet",
  9481. type : "text/css",
  9482. href : me.options.highlightCssUrl ||me.options.UEDITOR_HOME_URL + "third-party/SyntaxHighlighter/shCoreDefault.css"
  9483. });
  9484. }
  9485. });
  9486. me.addListener("beforegetcontent beforegetscene",function(){
  9487. utils.each(domUtils.getElementsByTagName(me.body,'table','syntaxhighlighter'),function(di){
  9488. var str = [],parentCode = '';
  9489. utils.each(di.getElementsByTagName('code'),function(ci){
  9490. if(parentCode !== ci.parentNode){
  9491. parentCode = ci.parentNode;
  9492. //去掉左右空格,针对ie的不能回退的问题
  9493. str.push(utils.trim(parentCode[browser.ie?'innerText':'textContent']))
  9494. }
  9495. });
  9496. var pre = domUtils.createElement(me.document,'pre',{
  9497. 'class' : 'brush: '+di.className.replace(/\s+/g,' ').split(' ')[1]+';toolbar:false;'
  9498. });
  9499. pre.appendChild(me.document.createTextNode(str.join('\n')));
  9500. di.parentNode.replaceChild(pre,di);
  9501. });
  9502. });
  9503. me.addListener("aftergetcontent aftersetcontent aftergetscene",changePre);
  9504. //避免table插件对于代码高亮的影响
  9505. me.addListener('excludetable excludeNodeinautotype',function (cmd,target){
  9506. if(target && domUtils.findParent(target,function(node){
  9507. return domUtils.hasClass(node,'syntaxhighlighter');
  9508. },true)){
  9509. return true;
  9510. }
  9511. });
  9512. function changePre(){
  9513. var me = this;
  9514. if(!me.window||!me.window.SyntaxHighlighter)return;
  9515. utils.each(domUtils.getElementsByTagName(me.document,"pre"),function(pi){
  9516. if(domUtils.hasClass(pi,'brush')){
  9517. me.window.SyntaxHighlighter.highlight(pi);
  9518. }
  9519. });
  9520. }
  9521. me.addListener('getAllHtml',function(type,headHtml){
  9522. var coreHtml = '';
  9523. for(var i= 0,ci,divs=domUtils.getElementsByTagName(me.document,'table');ci=divs[i++];){
  9524. if(domUtils.hasClass(ci,'syntaxhighlighter')){
  9525. coreHtml = '<script type="text/javascript">window.onload = function(){SyntaxHighlighter.highlight();' +
  9526. 'setTimeout(function(){ '+
  9527. " var tables = document.getElementsByTagName('table');"+
  9528. " for(var t= 0,ti;ti=tables[t++];){"+
  9529. " if(/SyntaxHighlighter/i.test(ti.className)){"+
  9530. " var tds = ti.getElementsByTagName('td');"+
  9531. " for(var i=0,li,ri;li=tds[0].childNodes[i];i++){"+
  9532. " ri = tds[1].firstChild.childNodes[i];"+
  9533. " if(ri){"+
  9534. " ri.style.height = li.style.height = ri.offsetHeight + 'px';"+
  9535. " }"+
  9536. " }"+
  9537. " }"+
  9538. " }"+
  9539. '},100)' +
  9540. '}</script>'
  9541. break;
  9542. }
  9543. }
  9544. if(!coreHtml){
  9545. var tmpNode;
  9546. if(tmpNode = me.document.getElementById('syntaxhighlighter_css')){
  9547. domUtils.remove(tmpNode)
  9548. }
  9549. if(tmpNode = me.document.getElementById('syntaxhighlighter_js')){
  9550. domUtils.remove(tmpNode)
  9551. }
  9552. }
  9553. coreHtml && headHtml.push(coreHtml)
  9554. });
  9555. };
  9556. ///import core
  9557. ///commands 定制过滤规则
  9558. ///commandsName Serialize
  9559. ///commandsTitle 定制过滤规则
  9560. UE.plugins['serialize'] = function () {
  9561. var ie = browser.ie,
  9562. version = browser.version;
  9563. function ptToPx(value){
  9564. return /pt/.test(value) ? value.replace( /([\d.]+)pt/g, function( str ) {
  9565. return Math.round(parseFloat(str) * 96 / 72) + "px";
  9566. } ) : value;
  9567. }
  9568. var me = this, autoClearEmptyNode = me.options.autoClearEmptyNode,
  9569. EMPTY_TAG = dtd.$empty,
  9570. parseHTML = function () {
  9571. //干掉<a> 后便变得空格,保留</a> 这样的空格
  9572. var RE_PART = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  9573. RE_ATTR = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g,
  9574. EMPTY_ATTR = {checked:1,compact:1,declare:1,defer:1,disabled:1,ismap:1,multiple:1,nohref:1,noresize:1,noshade:1,nowrap:1,readonly:1,selected:1},
  9575. CDATA_TAG = {script:1,style: 1},
  9576. NEED_PARENT_TAG = {
  9577. "li": { "$": 'ul', "ul": 1, "ol": 1 },
  9578. "dd": { "$": "dl", "dl": 1 },
  9579. "dt": { "$": "dl", "dl": 1 },
  9580. "option": { "$": "select", "select": 1 },
  9581. "td": { "$": "tr", "tr": 1 },
  9582. "th": { "$": "tr", "tr": 1 },
  9583. "tr": { "$": "tbody", "tbody": 1, "thead": 1, "tfoot": 1, "table": 1 },
  9584. "tbody": { "$": "table", 'table':1,"colgroup": 1 },
  9585. "thead": { "$": "table", "table": 1 },
  9586. "tfoot": { "$": "table", "table": 1 },
  9587. "col": { "$": "colgroup","colgroup":1 }
  9588. };
  9589. var NEED_CHILD_TAG = {
  9590. "table": "td", "tbody": "td", "thead": "td", "tfoot": "td", //"tr": "td",
  9591. "colgroup": "col",
  9592. "ul": "li", "ol": "li",
  9593. "dl": "dd",
  9594. "select": "option"
  9595. };
  9596. function parse( html, callbacks ) {
  9597. var match,
  9598. nextIndex = 0,
  9599. tagName,
  9600. cdata;
  9601. RE_PART.exec( "" );
  9602. while ( (match = RE_PART.exec( html )) ) {
  9603. var tagIndex = match.index;
  9604. if ( tagIndex > nextIndex ) {
  9605. var text = html.slice( nextIndex, tagIndex );
  9606. if ( cdata ) {
  9607. cdata.push( text );
  9608. } else {
  9609. callbacks.onText( text );
  9610. }
  9611. }
  9612. nextIndex = RE_PART.lastIndex;
  9613. if ( (tagName = match[1]) ) {
  9614. tagName = tagName.toLowerCase();
  9615. if ( cdata && tagName == cdata._tag_name ) {
  9616. callbacks.onCDATA( cdata.join( '' ) );
  9617. cdata = null;
  9618. }
  9619. if ( !cdata ) {
  9620. callbacks.onTagClose( tagName );
  9621. continue;
  9622. }
  9623. }
  9624. if ( cdata ) {
  9625. cdata.push( match[0] );
  9626. continue;
  9627. }
  9628. if ( (tagName = match[3]) ) {
  9629. if ( /="/.test( tagName ) ) {
  9630. continue;
  9631. }
  9632. tagName = tagName.toLowerCase();
  9633. var attrPart = match[4],
  9634. attrMatch,
  9635. attrMap = {},
  9636. selfClosing = attrPart && attrPart.slice( -1 ) == '/';
  9637. if ( attrPart ) {
  9638. RE_ATTR.exec( "" );
  9639. while ( (attrMatch = RE_ATTR.exec( attrPart )) ) {
  9640. var attrName = attrMatch[1].toLowerCase(),
  9641. attrValue = attrMatch[2] || attrMatch[3] || attrMatch[4] || '';
  9642. if ( !attrValue && EMPTY_ATTR[attrName] ) {
  9643. attrValue = attrName;
  9644. }
  9645. if ( attrName == 'style' ) {
  9646. if ( ie && version <= 6 ) {
  9647. attrValue = attrValue.replace( /(?!;)\s*([\w-]+):/g, function ( m, p1 ) {
  9648. return p1.toLowerCase() + ':';
  9649. } );
  9650. }
  9651. }
  9652. //没有值的属性不添加
  9653. if ( attrValue ) {
  9654. attrMap[attrName] = attrValue.replace( /:\s*/g, ':' )
  9655. }
  9656. }
  9657. }
  9658. callbacks.onTagOpen( tagName, attrMap, selfClosing );
  9659. if ( !cdata && CDATA_TAG[tagName] ) {
  9660. cdata = [];
  9661. cdata._tag_name = tagName;
  9662. }
  9663. continue;
  9664. }
  9665. if ( (tagName = match[2]) ) {
  9666. callbacks.onComment( tagName );
  9667. }
  9668. }
  9669. if ( html.length > nextIndex ) {
  9670. callbacks.onText( html.slice( nextIndex, html.length ) );
  9671. }
  9672. }
  9673. return function ( html, forceDtd ) {
  9674. var fragment = {
  9675. type: 'fragment',
  9676. parent: null,
  9677. children: []
  9678. };
  9679. var currentNode = fragment;
  9680. function addChild( node ) {
  9681. node.parent = currentNode;
  9682. currentNode.children.push( node );
  9683. }
  9684. function addElement( element, open ) {
  9685. var node = element;
  9686. // 遇到结构化标签的时候
  9687. if ( NEED_PARENT_TAG[node.tag] ) {
  9688. // 考虑这种情况的时候, 结束之前的标签
  9689. // e.g. <table><tr><td>12312`<tr>`4566
  9690. while ( NEED_PARENT_TAG[currentNode.tag] && NEED_PARENT_TAG[currentNode.tag][node.tag] ) {
  9691. currentNode = currentNode.parent;
  9692. }
  9693. // 如果前一个标签和这个标签是同一级, 结束之前的标签
  9694. // e.g. <ul><li>123<li>
  9695. if ( currentNode.tag == node.tag ) {
  9696. currentNode = currentNode.parent;
  9697. }
  9698. // 向上补齐父标签
  9699. while ( NEED_PARENT_TAG[node.tag] ) {
  9700. if ( NEED_PARENT_TAG[node.tag][currentNode.tag] ) break;
  9701. node = node.parent = {
  9702. type: 'element',
  9703. tag: NEED_PARENT_TAG[node.tag]['$'],
  9704. attributes: {},
  9705. children: [node]
  9706. };
  9707. }
  9708. }
  9709. if ( forceDtd ) {
  9710. // 如果遇到这个标签不能放在前一个标签内部,则结束前一个标签,span单独处理
  9711. while ( dtd[node.tag] && !(currentNode.tag == 'span' ? utils.extend( dtd['strong'], {'a':1,'A':1} ) : (dtd[currentNode.tag] || dtd['div']))[node.tag] ) {
  9712. if ( tagEnd( currentNode ) ) continue;
  9713. if ( !currentNode.parent ) break;
  9714. currentNode = currentNode.parent;
  9715. }
  9716. }
  9717. node.parent = currentNode;
  9718. currentNode.children.push( node );
  9719. if ( open ) {
  9720. currentNode = element;
  9721. }
  9722. if ( element.attributes.style ) {
  9723. element.attributes.style = element.attributes.style.toLowerCase();
  9724. }
  9725. return element;
  9726. }
  9727. // 结束一个标签的时候,需要判断一下它是否缺少子标签
  9728. // e.g. <table></table>
  9729. function tagEnd( node ) {
  9730. var needTag;
  9731. if ( !node.children.length && (needTag = NEED_CHILD_TAG[node.tag]) ) {
  9732. addElement( {
  9733. type: 'element',
  9734. tag: needTag,
  9735. attributes: {},
  9736. children: []
  9737. }, true );
  9738. return true;
  9739. }
  9740. return false;
  9741. }
  9742. parse( html, {
  9743. onText: function ( text ) {
  9744. while ( !(dtd[currentNode.tag] || dtd['div'])['#'] ) {
  9745. //节点之间的空白不能当作节点处理
  9746. // if(/^[ \t\r\n]+$/.test( text )){
  9747. // return;
  9748. // }
  9749. if ( tagEnd( currentNode ) ) continue;
  9750. currentNode = currentNode.parent;
  9751. }
  9752. //if(/^[ \t\n\r]*/.test(text))
  9753. addChild( {
  9754. type: 'text',
  9755. data: text
  9756. } );
  9757. },
  9758. onComment: function ( text ) {
  9759. addChild( {
  9760. type: 'comment',
  9761. data: text
  9762. } );
  9763. },
  9764. onCDATA: function ( text ) {
  9765. while ( !(dtd[currentNode.tag] || dtd['div'])['#'] ) {
  9766. if ( tagEnd( currentNode ) ) continue;
  9767. currentNode = currentNode.parent;
  9768. }
  9769. addChild( {
  9770. type: 'cdata',
  9771. data: text
  9772. } );
  9773. },
  9774. onTagOpen: function ( tag, attrs, closed ) {
  9775. closed = closed || EMPTY_TAG[tag] ;
  9776. addElement( {
  9777. type: 'element',
  9778. tag: tag,
  9779. attributes: attrs,
  9780. closed: closed,
  9781. children: []
  9782. }, !closed );
  9783. },
  9784. onTagClose: function ( tag ) {
  9785. var node = currentNode;
  9786. // 向上找匹配的标签, 这里不考虑dtd的情况是因为tagOpen的时候已经处理过了, 这里不会遇到
  9787. while ( node && tag != node.tag ) {
  9788. node = node.parent;
  9789. }
  9790. if ( node ) {
  9791. // 关闭中间的标签
  9792. for ( var tnode = currentNode; tnode !== node.parent; tnode = tnode.parent ) {
  9793. tagEnd( tnode );
  9794. }
  9795. //去掉空白的inline节点
  9796. //分页,锚点保留
  9797. //|| dtd.$removeEmptyBlock[node.tag])
  9798. // if ( !node.children.length && dtd.$removeEmpty[node.tag] && !node.attributes.anchorname && node.attributes['class'] != 'pagebreak' && node.tag != 'a') {
  9799. //
  9800. // node.parent.children.pop();
  9801. // }
  9802. currentNode = node.parent;
  9803. } else {
  9804. // 如果没有找到开始标签, 则创建新标签
  9805. // eg. </div> => <div></div>
  9806. //针对视屏网站embed会给结束符,这里特殊处理一下
  9807. if ( !(dtd.$removeEmpty[tag] || dtd.$removeEmptyBlock[tag] || tag == 'embed') ) {
  9808. node = {
  9809. type: 'element',
  9810. tag: tag,
  9811. attributes: {},
  9812. children: []
  9813. };
  9814. addElement( node, true );
  9815. tagEnd( node );
  9816. currentNode = node.parent;
  9817. }
  9818. }
  9819. }
  9820. } );
  9821. // 处理这种情况, 只有开始标签没有结束标签的情况, 需要关闭开始标签
  9822. // eg. <table>
  9823. while ( currentNode !== fragment ) {
  9824. tagEnd( currentNode );
  9825. currentNode = currentNode.parent;
  9826. }
  9827. return fragment;
  9828. };
  9829. }();
  9830. var unhtml1 = function () {
  9831. var map = { '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
  9832. function rep( m ) {
  9833. return map[m];
  9834. }
  9835. return function ( str ) {
  9836. str = str + '';
  9837. return str ? str.replace( /[<>"']/g, rep ) : '';
  9838. };
  9839. }();
  9840. var toHTML = function () {
  9841. function printChildren( node, pasteplain ) {
  9842. var children = node.children;
  9843. var buff = [];
  9844. for ( var i = 0,ci; ci = children[i]; i++ ) {
  9845. buff.push( toHTML( ci, pasteplain ) );
  9846. }
  9847. return buff.join( '' );
  9848. }
  9849. function printAttrs( attrs ) {
  9850. var buff = [];
  9851. for ( var k in attrs ) {
  9852. var value = attrs[k];
  9853. if(k == 'style'){
  9854. //pt==>px
  9855. value = ptToPx(value);
  9856. //color rgb ==> hex
  9857. if(/rgba?\s*\([^)]*\)/.test(value)){
  9858. value = value.replace( /rgba?\s*\(([^)]*)\)/g, function( str ) {
  9859. return utils.fixColor('color',str);
  9860. } )
  9861. }
  9862. //过滤掉所有的white-space,在纯文本编辑器里粘贴过来的内容,到chrome中会带有span和white-space属性,导致出现不能折行的情况
  9863. //所以在这里去掉这个属性
  9864. attrs[k] = utils.optCss(value.replace(/windowtext/g,'#000'))
  9865. .replace(/white-space[^;]+;/g,'');
  9866. if(!attrs[k]){
  9867. continue;
  9868. }
  9869. }
  9870. buff.push( k + '="' + unhtml1( attrs[k] ) + '"' );
  9871. }
  9872. return buff.join( ' ' )
  9873. }
  9874. function printData( node, notTrans ) {
  9875. //trace:1399 输入html代码时空格转换成为&nbsp;
  9876. //node.data.replace(/&nbsp;/g,' ') 针对pre中的空格和出现的&nbsp;把他们在得到的html代码中都转换成为空格,为了在源码模式下显示为空格而不是&nbsp;
  9877. return notTrans ? node.data.replace(/&nbsp;/g,' ') : unhtml1( node.data ).replace(/ /g,'&nbsp;');
  9878. }
  9879. //纯文本模式下标签转换
  9880. var transHtml = {
  9881. 'li':'p',
  9882. 'h1':'p','h2':'p','h3':'p','h4':'p','h5':'p','h6':'p',
  9883. 'tr':'p',
  9884. 'br':'br',
  9885. 'div':'p',
  9886. 'p':'p'//trace:1398 碰到p标签自己要加上p,否则transHtml[tag]是undefined
  9887. };
  9888. var clearTagName ={
  9889. 'table':1,
  9890. 'tbody':1,
  9891. 'ol':1,
  9892. 'ul':1,
  9893. 'dt':1
  9894. }
  9895. function printElement( node, pasteplain ) {
  9896. if ( node.type == 'element' && !node.children.length && (dtd.$removeEmpty[node.tag]) && node.tag != 'a' && utils.isEmptyObject(node.attributes) && autoClearEmptyNode) {// 锚点保留
  9897. return html;
  9898. }
  9899. var tag = node.tag;
  9900. if ( pasteplain && tag == 'td' ) {
  9901. if ( !html ) html = '';
  9902. html += printChildren( node, pasteplain ) + '&nbsp;&nbsp;&nbsp;';
  9903. } else {
  9904. var attrs = printAttrs( node.attributes );
  9905. var html = pasteplain && clearTagName[tag] ? '' :
  9906. '<' + (pasteplain && transHtml[tag] !==undefined? transHtml[tag] : tag) + (attrs ? ' ' + attrs : '') + (EMPTY_TAG[tag] ? ' />' : '>');
  9907. if ( !EMPTY_TAG[tag] ) {
  9908. //trace:1627 ,2070
  9909. //p标签为空,将不占位这里占位符不起作用,用&nbsp;或者br
  9910. if( tag == 'p' && !node.children.length){
  9911. html += browser.ie ? '&nbsp;' : '<br/>';
  9912. }
  9913. html += printChildren( node, pasteplain );
  9914. html +=(pasteplain && clearTagName[tag] ? '' : '</' + (pasteplain && transHtml[tag]!==undefined? transHtml[tag] : tag) + '>');
  9915. }
  9916. }
  9917. return html;
  9918. }
  9919. return function ( node, pasteplain ) {
  9920. if ( node.type == 'fragment' ) {
  9921. return printChildren( node, pasteplain );
  9922. } else if ( node.type == 'element' ) {
  9923. return printElement( node, pasteplain );
  9924. } else if ( node.type == 'text' || node.type == 'cdata' ) {
  9925. return printData( node, dtd.$notTransContent[node.parent.tag] );
  9926. } else if ( node.type == 'comment' ) {
  9927. return '<!--' + node.data + '-->';
  9928. }
  9929. return '';
  9930. };
  9931. }();
  9932. var NODE_NAME_MAP = {
  9933. 'text': '#text',
  9934. 'comment': '#comment',
  9935. 'cdata': '#cdata-section',
  9936. 'fragment': '#document-fragment'
  9937. };
  9938. //写入编辑器时,调用,进行转换操作
  9939. function transNode( node, word_img_flag ) {
  9940. var sizeMap = [0, 10, 12, 16, 18, 24, 32, 48],
  9941. attr,
  9942. indexOf = utils.indexOf;
  9943. switch ( node.tag ) {
  9944. case 'script':
  9945. node.tag = 'div';
  9946. node.attributes._ue_org_tagName = 'script';
  9947. node.attributes._ue_div_script = 1;
  9948. node.attributes._ue_script_data = node.children[0] ? encodeURIComponent(node.children[0].data) : '';
  9949. node.attributes._ue_custom_node_ = 1;
  9950. node.children = [];
  9951. break;
  9952. case 'style':
  9953. node.tag = 'div';
  9954. node.attributes._ue_div_style = 1;
  9955. node.attributes._ue_org_tagName = 'style';
  9956. node.attributes._ue_style_data = node.children[0] ? encodeURIComponent(node.children[0].data) : '';
  9957. node.attributes._ue_custom_node_ = 1;
  9958. node.children = [];
  9959. break;
  9960. case 'img':
  9961. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9962. if(node.attributes.src && /^data:/.test(node.attributes.src)){
  9963. return {
  9964. type : 'fragment',
  9965. children:[]
  9966. }
  9967. }
  9968. if ( node.attributes.src && /^(?:file)/.test( node.attributes.src ) ) {
  9969. if ( !/(gif|bmp|png|jpg|jpeg)$/.test( node.attributes.src ) ) {
  9970. return {
  9971. type : 'fragment',
  9972. children:[]
  9973. }
  9974. }
  9975. node.attributes.word_img = node.attributes.src;
  9976. node.attributes.src = me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  9977. var flag = parseInt(node.attributes.width)<128||parseInt(node.attributes.height)<43;
  9978. node.attributes.style="background:url(" + (flag? me.options.themePath+me.options.theme +"/images/word.gif":me.options.langPath+me.options.lang + "/images/localimage.png")+") no-repeat center center;border:1px solid #ddd";
  9979. //node.attributes.style = 'width:395px;height:173px;';
  9980. word_img_flag && (word_img_flag.flag = 1);
  9981. }
  9982. if(browser.ie && browser.version < 7 )
  9983. node.attributes.orgSrc = node.attributes.src;
  9984. node.attributes.data_ue_src = node.attributes.data_ue_src || node.attributes.src;
  9985. break;
  9986. case 'li':
  9987. var child = node.children[0];
  9988. if ( !child || child.type != 'element' || child.tag != 'p' && dtd.p[child.tag] ) {
  9989. var tmpPNode = {
  9990. type: 'element',
  9991. tag: 'p',
  9992. attributes: {},
  9993. parent : node
  9994. };
  9995. tmpPNode.children = child ? node.children :[
  9996. browser.ie ? {
  9997. type:'text',
  9998. data:domUtils.fillChar,
  9999. parent : tmpPNode
  10000. }:
  10001. {
  10002. type : 'element',
  10003. tag : 'br',
  10004. attributes:{},
  10005. closed: true,
  10006. children: [],
  10007. parent : tmpPNode
  10008. }
  10009. ];
  10010. node.children = [tmpPNode];
  10011. }
  10012. break;
  10013. case 'table':
  10014. case 'td':
  10015. optStyle( node );
  10016. break;
  10017. case 'a'://锚点,a==>img
  10018. if ( node.attributes['anchorname'] ) {
  10019. node.tag = 'img';
  10020. node.attributes = {
  10021. 'class' : 'anchorclass',
  10022. 'anchorname':node.attributes['name']
  10023. };
  10024. node.closed = 1;
  10025. }
  10026. node.attributes.href && (node.attributes.data_ue_src = node.attributes.href);
  10027. break;
  10028. case 'b':
  10029. node.tag = node.name = 'strong';
  10030. break;
  10031. case 'i':
  10032. node.tag = node.name = 'em';
  10033. break;
  10034. case 'u':
  10035. node.tag = node.name = 'span';
  10036. node.attributes.style = (node.attributes.style || '') + ';text-decoration:underline;';
  10037. break;
  10038. case 's':
  10039. case 'del':
  10040. node.tag = node.name = 'span';
  10041. node.attributes.style = (node.attributes.style || '') + ';text-decoration:line-through;';
  10042. if ( node.children.length == 1 ) {
  10043. child = node.children[0];
  10044. if ( child.tag == node.tag ) {
  10045. node.attributes.style += ";" + child.attributes.style;
  10046. node.children = child.children;
  10047. }
  10048. }
  10049. break;
  10050. case 'span':
  10051. var style = node.attributes.style;
  10052. if ( style ) {
  10053. if ( !node.attributes.style || browser.webkit && style == "white-space:nowrap;") {
  10054. delete node.attributes.style;
  10055. }
  10056. }
  10057. //针对ff3.6span的样式不能正确继承的修复
  10058. if(browser.gecko && browser.version <= 10902 && node.parent){
  10059. var parent = node.parent;
  10060. if(parent.tag == 'span' && parent.attributes && parent.attributes.style){
  10061. node.attributes.style = parent.attributes.style + ';' + node.attributes.style;
  10062. }
  10063. }
  10064. if ( utils.isEmptyObject( node.attributes ) && autoClearEmptyNode) {
  10065. node.type = 'fragment'
  10066. }
  10067. break;
  10068. case 'font':
  10069. node.tag = node.name = 'span';
  10070. attr = node.attributes;
  10071. node.attributes = {
  10072. 'style': (attr.size ? 'font-size:' + (sizeMap[attr.size] || 12) + 'px' : '')
  10073. + ';' + (attr.color ? 'color:'+ attr.color : '')
  10074. + ';' + (attr.face ? 'font-family:'+ attr.face : '')
  10075. + ';' + (attr.style||'')
  10076. };
  10077. while(node.parent.tag == node.tag && node.parent.children.length == 1){
  10078. node.attributes.style && (node.parent.attributes.style ? (node.parent.attributes.style += ";" + node.attributes.style) : (node.parent.attributes.style = node.attributes.style));
  10079. node.parent.children = node.children;
  10080. node = node.parent;
  10081. }
  10082. break;
  10083. case 'p':
  10084. if ( node.attributes.align ) {
  10085. node.attributes.style = (node.attributes.style || '') + ';text-align:' +
  10086. node.attributes.align + ';';
  10087. delete node.attributes.align;
  10088. }
  10089. }
  10090. return node;
  10091. }
  10092. function optStyle( node ) {
  10093. if ( ie && node.attributes.style ) {
  10094. var style = node.attributes.style;
  10095. node.attributes.style = style.replace(/;\s*/g,';');
  10096. node.attributes.style = node.attributes.style.replace( /^\s*|\s*$/, '' )
  10097. }
  10098. }
  10099. //getContent调用转换
  10100. function transOutNode( node ) {
  10101. switch ( node.tag ) {
  10102. case 'div' :
  10103. if(node.attributes._ue_div_script){
  10104. node.tag = 'script';
  10105. node.children = [{type:'cdata',data:node.attributes._ue_script_data?decodeURIComponent(node.attributes._ue_script_data):'',parent:node}];
  10106. delete node.attributes._ue_div_script;
  10107. delete node.attributes._ue_script_data;
  10108. delete node.attributes._ue_custom_node_;
  10109. delete node.attributes._ue_org_tagName;
  10110. }
  10111. if(node.attributes._ue_div_style){
  10112. node.tag = 'style';
  10113. node.children = [{type:'cdata',data:node.attributes._ue_style_data?decodeURIComponent(node.attributes._ue_style_data):'',parent:node}];
  10114. delete node.attributes._ue_div_style;
  10115. delete node.attributes._ue_style_data;
  10116. delete node.attributes._ue_custom_node_;
  10117. delete node.attributes._ue_org_tagName;
  10118. }
  10119. break;
  10120. case 'table':
  10121. !node.attributes.style && delete node.attributes.style;
  10122. if ( ie && node.attributes.style ) {
  10123. optStyle( node );
  10124. }
  10125. break;
  10126. case 'td':
  10127. case 'th':
  10128. if ( /display\s*:\s*none/i.test( node.attributes.style ) ) {
  10129. return {
  10130. type: 'fragment',
  10131. children: []
  10132. };
  10133. }
  10134. if ( ie && !node.children.length ) {
  10135. var txtNode = {
  10136. type: 'text',
  10137. data:domUtils.fillChar,
  10138. parent : node
  10139. };
  10140. node.children[0] = txtNode;
  10141. }
  10142. if ( ie && node.attributes.style ) {
  10143. optStyle( node );
  10144. }
  10145. break;
  10146. case 'img'://锚点,img==>a
  10147. if ( node.attributes.anchorname ) {
  10148. node.tag = 'a';
  10149. node.attributes = {
  10150. name : node.attributes.anchorname,
  10151. anchorname : 1
  10152. };
  10153. node.closed = null;
  10154. }else{
  10155. if(node.attributes.data_ue_src){
  10156. node.attributes.src = node.attributes.data_ue_src;
  10157. delete node.attributes.data_ue_src;
  10158. }
  10159. }
  10160. break;
  10161. case 'a':
  10162. if(node.attributes.data_ue_src){
  10163. node.attributes.href = node.attributes.data_ue_src;
  10164. delete node.attributes.data_ue_src;
  10165. }
  10166. }
  10167. return node;
  10168. }
  10169. function childrenAccept( node, visit, ctx ) {
  10170. if ( !node.children || !node.children.length ) {
  10171. return node;
  10172. }
  10173. var children = node.children;
  10174. for ( var i = 0; i < children.length; i++ ) {
  10175. var newNode = visit( children[i], ctx );
  10176. if ( newNode.type == 'fragment' ) {
  10177. var args = [i, 1];
  10178. args.push.apply( args, newNode.children );
  10179. children.splice.apply( children, args );
  10180. //节点为空的就干掉,不然后边的补全操作会添加多余的节点
  10181. if ( !children.length ) {
  10182. node = {
  10183. type: 'fragment',
  10184. children: []
  10185. }
  10186. }
  10187. i --;
  10188. } else {
  10189. children[i] = newNode;
  10190. }
  10191. }
  10192. return node;
  10193. }
  10194. function Serialize( rules ) {
  10195. this.rules = rules;
  10196. }
  10197. Serialize.prototype = {
  10198. // NOTE: selector目前只支持tagName
  10199. rules: null,
  10200. // NOTE: node必须是fragment
  10201. filter: function ( node, rules, modify ) {
  10202. rules = rules || this.rules;
  10203. var whiteList = rules && rules.whiteList;
  10204. var blackList = rules && rules.blackList;
  10205. function visitNode( node, parent ) {
  10206. node.name = node.type == 'element' ?
  10207. node.tag : NODE_NAME_MAP[node.type];
  10208. if ( parent == null ) {
  10209. return childrenAccept( node, visitNode, node );
  10210. }
  10211. if ( blackList && (blackList[node.name]|| (node.attributes && node.attributes._ue_org_tagName && blackList[node.attributes._ue_org_tagName]))) {
  10212. modify && (modify.flag = 1);
  10213. return {
  10214. type: 'fragment',
  10215. children: []
  10216. };
  10217. }
  10218. if ( whiteList ) {
  10219. if ( node.type == 'element' ) {
  10220. if ( parent.type == 'fragment' ? whiteList[node.name] : whiteList[node.name] && whiteList[parent.name][node.name] ) {
  10221. var props;
  10222. if ( (props = whiteList[node.name].$) ) {
  10223. var oldAttrs = node.attributes;
  10224. var newAttrs = {};
  10225. for ( var k in props ) {
  10226. if ( oldAttrs[k] ) {
  10227. newAttrs[k] = oldAttrs[k];
  10228. }
  10229. }
  10230. node.attributes = newAttrs;
  10231. }
  10232. } else {
  10233. modify && (modify.flag = 1);
  10234. node.type = 'fragment';
  10235. // NOTE: 这里算是一个hack
  10236. node.name = parent.name;
  10237. }
  10238. } else {
  10239. // NOTE: 文本默认允许
  10240. }
  10241. }
  10242. if ( blackList || whiteList ) {
  10243. childrenAccept( node, visitNode, node );
  10244. }
  10245. return node;
  10246. }
  10247. return visitNode( node, null );
  10248. },
  10249. transformInput: function ( node, word_img_flag ) {
  10250. function visitNode( node ) {
  10251. node = transNode( node, word_img_flag );
  10252. node = childrenAccept( node, visitNode, node );
  10253. if ( me.options.pageBreakTag && node.type == 'text' && node.data.replace( /\s/g, '' ) == me.options.pageBreakTag ) {
  10254. node.type = 'element';
  10255. node.name = node.tag = 'hr';
  10256. delete node.data;
  10257. node.attributes = {
  10258. 'class' : 'pagebreak',
  10259. noshade:"noshade",
  10260. size:"5",
  10261. 'unselectable' : 'on',
  10262. 'style' : 'moz-user-select:none;-khtml-user-select: none;'
  10263. };
  10264. node.children = [];
  10265. }
  10266. //去掉多余的空格和换行
  10267. if(node.type == 'text' && !dtd.$notTransContent[node.parent.tag]){
  10268. node.data = node.data.replace(/[\r\t\n]*/g,'')//.replace(/[ ]*$/g,'')
  10269. }
  10270. return node;
  10271. }
  10272. return visitNode( node );
  10273. },
  10274. transformOutput: function ( node ) {
  10275. function visitNode( node ) {
  10276. if ( node.tag == 'hr' && node.attributes['class'] == 'pagebreak' ) {
  10277. delete node.tag;
  10278. node.type = 'text';
  10279. node.data = me.options.pageBreakTag;
  10280. delete node.children;
  10281. }
  10282. node = transOutNode( node );
  10283. node = childrenAccept( node, visitNode, node );
  10284. return node;
  10285. }
  10286. return visitNode( node );
  10287. },
  10288. toHTML: toHTML,
  10289. parseHTML: parseHTML,
  10290. word: UE.filterWord
  10291. };
  10292. me.serialize = new Serialize( me.options.serialize || {});
  10293. UE.serialize = new Serialize( {} );
  10294. };
  10295. ///import core
  10296. ///import plugins/inserthtml.js
  10297. ///commands 视频
  10298. ///commandsName InsertVideo
  10299. ///commandsTitle 插入视频
  10300. ///commandsDialog dialogs\video
  10301. UE.plugins['video'] = function (){
  10302. var me =this,
  10303. div;
  10304. /**
  10305. * 创建插入视频字符窜
  10306. * @param url 视频地址
  10307. * @param width 视频宽度
  10308. * @param height 视频高度
  10309. * @param align 视频对齐
  10310. * @param toEmbed 是否以flash代替显示
  10311. * @param addParagraph 是否需要添加P 标签
  10312. */
  10313. function creatInsertStr(url,width,height,align,toEmbed,addParagraph){
  10314. return !toEmbed ?
  10315. (addParagraph? ('<p '+ (align && align !="none" ? ( align == "center"? ' style="text-align:center;" ':' style="float:"'+ align ) : '') + '>'): '') +
  10316. '<img align="'+align+'" width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-video"' +
  10317. ' 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;" />' +
  10318. (addParagraph?'</p>':'')
  10319. :
  10320. '<embed type="application/x-shockwave-flash" class="edui-faked-video" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  10321. ' src="' + url + '" width="' + width + '" height="' + height + '" align="' + align + '"' +
  10322. ( align && align !="none" ? ' style= "'+ ( align == "center"? "display:block;":" float: "+ align ) + '"' :'' ) +
  10323. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  10324. }
  10325. function switchImgAndEmbed(img2embed){
  10326. var tmpdiv,
  10327. nodes =domUtils.getElementsByTagName(me.document, !img2embed ? "embed" : "img");
  10328. for(var i=0,node;node = nodes[i++];){
  10329. if(node.className!="edui-faked-video"){
  10330. continue;
  10331. }
  10332. tmpdiv = me.document.createElement("div");
  10333. //先看float在看align,浮动有的是时候是在float上定义的
  10334. var align = domUtils.getComputedStyle(node,'float');
  10335. align = align == 'none' ? (node.getAttribute('align') || '') : align;
  10336. tmpdiv.innerHTML = creatInsertStr(img2embed ? node.getAttribute("_url"):node.getAttribute("src"),node.width,node.height,align,img2embed);
  10337. node.parentNode.replaceChild(tmpdiv.firstChild,node);
  10338. }
  10339. }
  10340. me.addListener("beforegetcontent",function(){
  10341. switchImgAndEmbed(true);
  10342. });
  10343. me.addListener('aftersetcontent',function(){
  10344. switchImgAndEmbed(false);
  10345. });
  10346. me.addListener('aftergetcontent',function(cmdName){
  10347. if(cmdName == 'aftergetcontent' && me.queryCommandState('source')){
  10348. return;
  10349. }
  10350. switchImgAndEmbed(false);
  10351. });
  10352. me.commands["insertvideo"] = {
  10353. execCommand: function (cmd, videoObjs){
  10354. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  10355. var html = [];
  10356. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  10357. vi = videoObjs[i];
  10358. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, vi.align||"none",false,true));
  10359. }
  10360. me.execCommand("inserthtml",html.join(""));
  10361. },
  10362. queryCommandState : function(){
  10363. var img = me.selection.getRange().getClosedNode(),
  10364. flag = img && (img.className == "edui-faked-video");
  10365. return flag ? 1 : 0;
  10366. }
  10367. };
  10368. };
  10369. /**
  10370. * Created with JetBrains PhpStorm.
  10371. * User: taoqili
  10372. * Date: 12-10-12
  10373. * Time: 上午10:05
  10374. * To change this template use File | Settings | File Templates.
  10375. */
  10376. UE.plugins['table'] = function () {
  10377. var me = this,
  10378. debug = true;
  10379. function showError(e) {
  10380. if (debug) throw e;
  10381. }
  10382. //处理拖动及框选相关方法
  10383. var startTd = null, //鼠标按下时的锚点td
  10384. currentTd = null, //当前鼠标经过时的td
  10385. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  10386. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  10387. dragButton = null,
  10388. dragOver = false,
  10389. dragLine = null, //模拟的拖动线
  10390. dragTd = null; //发生拖动的目标td
  10391. var mousedown = false,
  10392. //todo 判断混乱模式
  10393. needIEHack = true;
  10394. me.setOpt({
  10395. 'maxColNum':20,
  10396. 'maxRowNum':100,
  10397. 'defaultCols':5,
  10398. 'defaultRows':5,
  10399. 'tdvalign':'top',
  10400. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  10401. 'tableDragable':false
  10402. });
  10403. me.getUETable = getUETable;
  10404. var commands = {
  10405. 'deletetable':1,
  10406. 'inserttable':1,
  10407. 'cellvalign':1,
  10408. 'insertcaption':1,
  10409. 'deletecaption':1,
  10410. 'inserttitle':1,
  10411. 'deletetitle':1,
  10412. "mergeright":1,
  10413. "mergedown":1,
  10414. "mergecells":1,
  10415. "insertrow":1,
  10416. "insertrownext":1,
  10417. "deleterow":1,
  10418. "insertcol":1,
  10419. "insertcolnext":1,
  10420. "deletecol":1,
  10421. "splittocells":1,
  10422. "splittorows":1,
  10423. "splittocols":1,
  10424. "adaptbytext":1,
  10425. "adaptbywindow":1,
  10426. "adaptbycustomer":1,
  10427. "insertparagraph":1,
  10428. "averagedistributecol":1,
  10429. "averagedistributerow":1
  10430. };
  10431. me.ready(function () {
  10432. utils.cssRule('table',
  10433. //选中的td上的样式
  10434. '.selectTdClass{background-color:#edf5fa !important}' +
  10435. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  10436. //插入的表格的默认样式
  10437. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  10438. 'td,th{ background:white; padding: 5px 10px;border: 1px solid #DDD;}' +
  10439. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  10440. 'th{border-top:2px solid #BBB;background:#F7F7F7;}' +
  10441. 'td p{margin:0;padding:0;}', me.document);
  10442. var tableCopyList, isFullCol, isFullRow;
  10443. //注册del/backspace事件
  10444. me.addListener('keydown', function (cmd, evt) {
  10445. var me = this;
  10446. var keyCode = evt.keyCode || evt.which;
  10447. if (keyCode == 8) {
  10448. var ut = getUETableBySelected(me);
  10449. if (ut && ut.selectedTds.length) {
  10450. me.fireEvent('saveScene');
  10451. if (ut.isFullCol()) {
  10452. me.execCommand('deletecol')
  10453. } else if (ut.isFullRow()) {
  10454. me.execCommand('deleterow')
  10455. } else {
  10456. me.fireEvent('delcells');
  10457. }
  10458. domUtils.preventDefault(evt);
  10459. }
  10460. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  10461. range = me.selection.getRange();
  10462. if (range.collapsed && caption && isEmptyBlock(caption)) {
  10463. me.fireEvent('saveScene');
  10464. var table = caption.parentNode;
  10465. domUtils.remove(caption);
  10466. if (table) {
  10467. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  10468. }
  10469. }
  10470. me.fireEvent('saveScene');
  10471. }
  10472. if (keyCode == 46) {
  10473. ut = getUETableBySelected(me);
  10474. if (ut) {
  10475. me.fireEvent('saveScene');
  10476. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  10477. domUtils.fillNode(me.document, ci)
  10478. }
  10479. me.fireEvent('saveScene');
  10480. domUtils.preventDefault(evt);
  10481. }
  10482. }
  10483. if (keyCode == 13) {
  10484. var rng = me.selection.getRange(),
  10485. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  10486. if (caption) {
  10487. var table = domUtils.findParentByTagName(caption, 'table');
  10488. if (!rng.collapsed) {
  10489. rng.deleteContents();
  10490. me.fireEvent('saveScene');
  10491. } else {
  10492. if (caption) {
  10493. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  10494. }
  10495. }
  10496. domUtils.preventDefault(evt);
  10497. return;
  10498. }
  10499. if (rng.collapsed) {
  10500. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  10501. if (table) {
  10502. var cell = table.rows[0].cells[0],
  10503. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  10504. preNode = table.previousSibling;
  10505. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  10506. me.execCommand('insertparagraphbeforetable');
  10507. domUtils.preventDefault(evt);
  10508. }
  10509. }
  10510. }
  10511. }
  10512. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  10513. tableCopyList = null;
  10514. table = getUETableBySelected(me);
  10515. if (table) {
  10516. var tds = table.selectedTds;
  10517. isFullCol = table.isFullCol();
  10518. isFullRow = table.isFullRow();
  10519. tableCopyList = [
  10520. [cloneCell(tds[0])]
  10521. ];
  10522. for (var i = 1, ci; ci = tds[i]; i++) {
  10523. if (ci.parentNode !== tds[i - 1].parentNode) {
  10524. tableCopyList.push([cloneCell(ci)])
  10525. } else {
  10526. tableCopyList[tableCopyList.length - 1].push(cloneCell(ci))
  10527. }
  10528. }
  10529. }
  10530. }
  10531. });
  10532. me.addListener('beforepaste', function (cmd, html) {
  10533. var me = this;
  10534. var rng = me.selection.getRange();
  10535. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  10536. var div = me.document.createElement("div");
  10537. div.innerHTML = html.html;
  10538. html.html = div[browser.ie ? 'innerText' : 'textContent'];
  10539. return;
  10540. }
  10541. var table = getUETableBySelected(me);
  10542. if (tableCopyList) {
  10543. me.fireEvent('saveScene');
  10544. var rng = me.selection.getRange();
  10545. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  10546. if (td) {
  10547. var ut = getUETable(td);
  10548. if (isFullRow) {
  10549. var rowIndex = ut.getCellInfo(td).rowIndex;
  10550. if (td.tagName == 'TH') {
  10551. rowIndex++;
  10552. }
  10553. for (var i = 0, ci; ci = tableCopyList[i++];) {
  10554. var tr = ut.insertRow(rowIndex++, "td");
  10555. for (var j = 0, cj; cj = ci[j]; j++) {
  10556. var cell = tr.cells[j];
  10557. if (!cell) {
  10558. cell = tr.insertCell(j)
  10559. }
  10560. cell.innerHTML = cj.innerHTML;
  10561. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  10562. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  10563. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  10564. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  10565. }
  10566. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  10567. if (!ci[j])
  10568. break;
  10569. cj.innerHTML = ci[j].innerHTML;
  10570. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  10571. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  10572. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  10573. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  10574. }
  10575. }
  10576. } else {
  10577. if (isFullCol) {
  10578. cellInfo = ut.getCellInfo(td);
  10579. var maxColNum = 0;
  10580. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  10581. maxColNum += cj.colSpan || 1;
  10582. }
  10583. me.__hasEnterExecCommand = true;
  10584. for (i = 0; i < maxColNum; i++) {
  10585. me.execCommand('insertcol');
  10586. }
  10587. me.__hasEnterExecCommand = false;
  10588. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  10589. if (td.tagName == 'TH') {
  10590. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  10591. }
  10592. }
  10593. for (var i = 0, ci; ci = tableCopyList[i++];) {
  10594. tmpNode = td;
  10595. for (var j = 0, cj; cj = ci[j++];) {
  10596. if (td) {
  10597. td.innerHTML = cj.innerHTML;
  10598. //todo 定制处理
  10599. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  10600. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  10601. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  10602. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  10603. preNode = td;
  10604. td = td.nextSibling;
  10605. } else {
  10606. var cloneTd = cj.cloneNode(true);
  10607. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  10608. preNode.parentNode.appendChild(cloneTd)
  10609. }
  10610. }
  10611. td = ut.getNextCell(tmpNode, true, true);
  10612. if (!tableCopyList[i])
  10613. break;
  10614. if (!td) {
  10615. var cellInfo = ut.getCellInfo(tmpNode);
  10616. ut.table.insertRow(ut.table.rows.length);
  10617. ut.update();
  10618. td = ut.getVSideCell(tmpNode, true);
  10619. }
  10620. }
  10621. }
  10622. ut.update();
  10623. } else {
  10624. table = me.document.createElement('table');
  10625. for (var i = 0, ci; ci = tableCopyList[i++];) {
  10626. var tr = table.insertRow(table.rows.length);
  10627. for (var j = 0, cj; cj = ci[j++];) {
  10628. cloneTd = cloneCell(cj);
  10629. domUtils.removeAttributes(cloneTd, ['class']);
  10630. tr.appendChild(cloneTd)
  10631. }
  10632. if (j == 2 && cloneTd.rowSpan > 1) {
  10633. cloneTd.rowSpan = 1;
  10634. }
  10635. }
  10636. var defaultValue = getDefaultValue(me),
  10637. width = me.body.offsetWidth -
  10638. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  10639. me.execCommand('insertHTML', '<table ' +
  10640. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  10641. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  10642. }
  10643. me.fireEvent('contentchange');
  10644. me.fireEvent('saveScene');
  10645. html.html = '';
  10646. } else {
  10647. var div = me.document.createElement("div"), tables;
  10648. div.innerHTML = html.html;
  10649. tables = div.getElementsByTagName("table");
  10650. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  10651. utils.each(tables, function (t) {
  10652. domUtils.remove(t)
  10653. });
  10654. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  10655. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  10656. }
  10657. } else {
  10658. utils.each(tables, function (table) {
  10659. removeStyleSize(table, true);
  10660. domUtils.removeAttributes(table, ['style', 'border']);
  10661. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  10662. if (isEmptyBlock(td)) {
  10663. domUtils.fillNode(me.document, td);
  10664. }
  10665. removeStyleSize(td, true);
  10666. // domUtils.removeAttributes(td, ['style'])
  10667. });
  10668. });
  10669. }
  10670. html.html = div.innerHTML;
  10671. }
  10672. });
  10673. me.addListener('afterpaste', function () {
  10674. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  10675. if (table.offsetWidth > me.body.offsetWidth) {
  10676. var defaultValue = getDefaultValue(me, table);
  10677. 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'
  10678. }
  10679. })
  10680. });
  10681. me.addListener('blur', function () {
  10682. tableCopyList = null;
  10683. });
  10684. var timer;
  10685. me.addListener('keydown', function () {
  10686. clearTimeout(timer);
  10687. timer = setTimeout(function () {
  10688. var rng = me.selection.getRange(),
  10689. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  10690. if (cell) {
  10691. var table = cell.parentNode.parentNode.parentNode;
  10692. if (table.offsetWidth > table.getAttribute("width")) {
  10693. cell.style.wordBreak = "break-all";
  10694. }
  10695. }
  10696. }, 100);
  10697. });
  10698. me.addListener("selectionchange", function () {
  10699. toggleDragableState(me, false, "", null);
  10700. });
  10701. //内容变化时触发索引更新
  10702. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  10703. me.addListener("contentchange", function () {
  10704. var me = this;
  10705. //尽可能排除一些不需要更新的状况
  10706. hideDragLine(me);
  10707. if (getUETableBySelected(me))return;
  10708. var rng = me.selection.getRange();
  10709. var start = rng.startContainer;
  10710. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  10711. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  10712. if (me.fireEvent("excludetable", table) === true) return;
  10713. table.ueTable = new UETable(table);
  10714. utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  10715. if (domUtils.isEmptyBlock(td) && td !== start) {
  10716. domUtils.fillNode(me.document, td);
  10717. if (browser.ie && browser.version == 6) {
  10718. td.innerHTML = '&nbsp;'
  10719. }
  10720. }
  10721. });
  10722. utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  10723. if (domUtils.isEmptyBlock(th) && th !== start) {
  10724. domUtils.fillNode(me.document, th);
  10725. if (browser.ie && browser.version == 6) {
  10726. th.innerHTML = '&nbsp;'
  10727. }
  10728. }
  10729. });
  10730. table.onmousemove = function () {
  10731. me.options.tableDragable && toggleDragButton(true, this, me);
  10732. };
  10733. table.onmouseout = function () {
  10734. toggleDragableState(me, false, "", null);
  10735. hideDragLine(me);
  10736. };
  10737. table.onclick = function (evt) {
  10738. evt = me.window.event || evt;
  10739. var target = getParentTdOrTh(evt.target || evt.srcElement);
  10740. if (!target)return;
  10741. var ut = getUETable(target),
  10742. table = ut.table,
  10743. cellInfo = ut.getCellInfo(target),
  10744. cellsRange,
  10745. rng = me.selection.getRange();
  10746. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  10747. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  10748. // ut.setSelected(cellsRange);
  10749. // return;
  10750. // }
  10751. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  10752. //
  10753. // return;
  10754. // }
  10755. if (inTableSide(table, target, evt, true)) {
  10756. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  10757. if (evt.shiftKey && ut.selectedTds.length) {
  10758. if (ut.selectedTds[0] !== endTdCol) {
  10759. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  10760. ut.setSelected(cellsRange);
  10761. } else {
  10762. rng && rng.selectNodeContents(endTdCol).select();
  10763. }
  10764. } else {
  10765. if (target !== endTdCol) {
  10766. cellsRange = ut.getCellsRange(target, endTdCol);
  10767. ut.setSelected(cellsRange);
  10768. } else {
  10769. rng && rng.selectNodeContents(endTdCol).select();
  10770. }
  10771. }
  10772. return;
  10773. }
  10774. if (inTableSide(table, target, evt)) {
  10775. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  10776. if (evt.shiftKey && ut.selectedTds.length) {
  10777. if (ut.selectedTds[0] !== endTdRow) {
  10778. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  10779. ut.setSelected(cellsRange);
  10780. } else {
  10781. rng && rng.selectNodeContents(endTdRow).select();
  10782. }
  10783. } else {
  10784. if (target !== endTdRow) {
  10785. cellsRange = ut.getCellsRange(target, endTdRow);
  10786. ut.setSelected(cellsRange);
  10787. } else {
  10788. rng && rng.selectNodeContents(endTdRow).select();
  10789. }
  10790. }
  10791. }
  10792. };
  10793. table.ondblclick = function (evt) {
  10794. evt = me.window.event || evt;
  10795. var target = getParentTdOrTh(evt.target || evt.srcElement);
  10796. if (target) {
  10797. var h;
  10798. if (h = getRelation(target, mouseCoords(evt))) {
  10799. if (h == 'h1') {
  10800. h = 'h';
  10801. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  10802. me.execCommand('adaptbywindow');
  10803. } else {
  10804. target = getUETable(target).getPreviewCell(target);
  10805. if (target) {
  10806. var rng = me.selection.getRange();
  10807. rng.selectNodeContents(target).setCursor(true, true)
  10808. }
  10809. }
  10810. }
  10811. h == 'h' && me.execCommand('adaptbytext');
  10812. }
  10813. }
  10814. }
  10815. });
  10816. switchBoderColor(true);
  10817. });
  10818. //仅IE8以上支持
  10819. if (!browser.ie || (browser.ie && browser.version > 7)) {
  10820. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  10821. }
  10822. domUtils.on(me.document, "mouseout", function (evt) {
  10823. var target = evt.target || evt.srcElement;
  10824. if (target.tagName == "TABLE") {
  10825. toggleDragableState(me, false, "", null);
  10826. }
  10827. });
  10828. me.addListener("mousedown", mouseDownEvent);
  10829. me.addListener("mouseup", mouseUpEvent);
  10830. var currentRowIndex = 0;
  10831. me.addListener("mousedown", function () {
  10832. currentRowIndex = 0;
  10833. });
  10834. me.addListener('tabkeydown', function () {
  10835. var range = this.selection.getRange(),
  10836. common = range.getCommonAncestor(true, true),
  10837. table = domUtils.findParentByTagName(common, 'table');
  10838. if (table) {
  10839. if (domUtils.findParentByTagName(common, 'caption', true)) {
  10840. var cell = domUtils.getElementsByTagName(table, 'th td');
  10841. if (cell && cell.length) {
  10842. range.setStart(cell[0], 0).setCursor(false, true)
  10843. }
  10844. } else {
  10845. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  10846. ua = getUETable(cell);
  10847. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  10848. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  10849. if (nextCell) {
  10850. if (isEmptyBlock(nextCell)) {
  10851. range.setStart(nextCell, 0).setCursor(false, true)
  10852. } else {
  10853. range.selectNodeContents(nextCell).select()
  10854. }
  10855. } else {
  10856. me.fireEvent('saveScene');
  10857. me.__hasEnterExecCommand = true;
  10858. this.execCommand('insertrownext');
  10859. me.__hasEnterExecCommand = false;
  10860. range = this.selection.getRange();
  10861. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  10862. me.fireEvent('saveScene');
  10863. }
  10864. }
  10865. return true;
  10866. }
  10867. });
  10868. browser.ie && me.addListener('selectionchange', function () {
  10869. toggleDragableState(this, false, "", null);
  10870. });
  10871. me.addListener("keydown", function (type, evt) {
  10872. var me = this;
  10873. //处理在表格的最后一个输入tab产生新的表格
  10874. var keyCode = evt.keyCode || evt.which;
  10875. if (keyCode == 8 || keyCode == 46) {
  10876. return;
  10877. }
  10878. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  10879. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  10880. var ut = getUETableBySelected(me);
  10881. if (!ut) return;
  10882. notCtrlKey && ut.clearSelected();
  10883. });
  10884. me.addListener("beforegetcontent", function () {
  10885. switchBoderColor(false);
  10886. browser.ie && utils.each(me.document.getElementsByTagName('caption'), function (ci) {
  10887. if (domUtils.isEmptyNode(ci)) {
  10888. ci.innerHTML = '&nbsp;'
  10889. }
  10890. });
  10891. });
  10892. me.addListener("aftergetcontent", function () {
  10893. switchBoderColor(true);
  10894. });
  10895. me.addListener("getAllHtml", function () {
  10896. removeSelectedClass(me.document.getElementsByTagName("td"));
  10897. });
  10898. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  10899. me.addListener("fullscreenchanged", function (type, fullscreen) {
  10900. if (!fullscreen) {
  10901. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  10902. tables = domUtils.getElementsByTagName(this.body, "table");
  10903. utils.each(tables, function (table) {
  10904. if (table.offsetWidth < me.body.offsetWidth) return false;
  10905. var tds = domUtils.getElementsByTagName(table, "td"),
  10906. backWidths = [];
  10907. utils.each(tds, function (td) {
  10908. backWidths.push(td.offsetWidth);
  10909. });
  10910. for (var i = 0, td; td = tds[i]; i++) {
  10911. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  10912. }
  10913. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  10914. });
  10915. }
  10916. });
  10917. //重写execCommand命令,用于处理框选时的处理
  10918. var oldExecCommand = me.execCommand;
  10919. me.execCommand = function (cmd) {
  10920. var me = this;
  10921. cmd = cmd.toLowerCase();
  10922. var ut = getUETableBySelected(me), tds,
  10923. range = new dom.Range(me.document),
  10924. cmdFun = me.commands[cmd] || UE.commands[cmd],
  10925. result;
  10926. if (!cmdFun) return;
  10927. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  10928. me.__hasEnterExecCommand = true;
  10929. me.fireEvent("beforeexeccommand", cmd);
  10930. tds = ut.selectedTds;
  10931. var lastState = -2, lastValue = -2, value, state;
  10932. for (var i = 0, td; td = tds[i]; i++) {
  10933. if (isEmptyBlock(td)) {
  10934. range.setStart(td, 0).setCursor(false, true)
  10935. } else {
  10936. range.selectNodeContents(td).select(true);
  10937. }
  10938. state = me.queryCommandState(cmd);
  10939. value = me.queryCommandValue(cmd);
  10940. if (state != -1) {
  10941. if (lastState !== state || lastValue !== value) {
  10942. me._ignoreContentChange = true;
  10943. result = oldExecCommand.apply(me, arguments);
  10944. me._ignoreContentChange = false;
  10945. }
  10946. lastState = me.queryCommandState(cmd);
  10947. lastValue = me.queryCommandValue(cmd);
  10948. if (domUtils.isEmptyBlock(td)) {
  10949. domUtils.fillNode(me.document, td)
  10950. }
  10951. }
  10952. }
  10953. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  10954. me.fireEvent('contentchange');
  10955. me.fireEvent("afterexeccommand", cmd);
  10956. me.__hasEnterExecCommand = false;
  10957. me._selectionChange();
  10958. } else {
  10959. result = oldExecCommand.apply(me, arguments);
  10960. }
  10961. return result;
  10962. };
  10963. });
  10964. /**
  10965. * 删除obj的宽高style,改成属性宽高
  10966. * @param obj
  10967. * @param replaceToProperty
  10968. */
  10969. function removeStyleSize(obj, replaceToProperty) {
  10970. removeStyle(obj, "width", true);
  10971. removeStyle(obj, "height", true);
  10972. }
  10973. function removeStyle(obj, styleName, replaceToProperty) {
  10974. if (obj.style[styleName]) {
  10975. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  10976. obj.style[styleName] = "";
  10977. }
  10978. }
  10979. function getParentTdOrTh(ele) {
  10980. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  10981. var td;
  10982. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  10983. return null;
  10984. }
  10985. function isEmptyBlock(node) {
  10986. var reg = new RegExp(domUtils.fillChar, 'g');
  10987. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  10988. return 0;
  10989. }
  10990. for (var n in dtd.$isNotEmpty) {
  10991. if (node.getElementsByTagName(n).length) {
  10992. return 0;
  10993. }
  10994. }
  10995. return 1;
  10996. }
  10997. function mouseCoords(evt) {
  10998. if (evt.pageX || evt.pageY) {
  10999. return { x:evt.pageX, y:evt.pageY };
  11000. }
  11001. return {
  11002. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  11003. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  11004. };
  11005. }
  11006. function mouseMoveEvent(evt) {
  11007. try {
  11008. //普通状态下鼠标移动
  11009. var target = getParentTdOrTh(evt.target || evt.srcElement),
  11010. pos;
  11011. //修改单元格大小时的鼠标移动
  11012. if (onDrag && dragTd) {
  11013. me.document.body.style.webkitUserSelect = 'none';
  11014. me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  11015. pos = mouseCoords(evt);
  11016. toggleDragableState(me, true, "", pos, target);
  11017. if (onDrag == "h") {
  11018. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  11019. } else if (onDrag == "v") {
  11020. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  11021. }
  11022. return;
  11023. }
  11024. //当鼠标处于table上时,修改移动过程中的光标状态
  11025. if (target) {
  11026. //针对使用table作为容器的组件不触发拖拽效果
  11027. if (me.fireEvent('excludetable', target) === true)
  11028. return;
  11029. pos = mouseCoords(evt);
  11030. var state = getRelation(target, pos),
  11031. table = domUtils.findParentByTagName(target, "table", true);
  11032. if (inTableSide(table, target, evt, true)) {
  11033. //toggleCursor(pos,true,"_h");
  11034. if (me.fireEvent("excludetable", table) === true) return;
  11035. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  11036. } else if (inTableSide(table, target, evt)) {
  11037. //toggleCursor(pos,true,"_v");
  11038. if (me.fireEvent("excludetable", table) === true) return;
  11039. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  11040. } else {
  11041. //toggleCursor(pos,false,"");
  11042. me.body.style.cursor = "text";
  11043. if (/\d/.test(state)) {
  11044. state = state.replace(/\d/, '');
  11045. target = getUETable(target).getPreviewCell(target, state == "v");
  11046. }
  11047. //位于第一行的顶部或者第一列的左边时不可拖动
  11048. toggleDragableState(me, target ? !!state : false, target ? state : '', pos, target);
  11049. }
  11050. // toggleDragButton(inTable(pos,table),table);
  11051. } else {
  11052. toggleDragButton(false, table, me);
  11053. }
  11054. } catch (e) {
  11055. showError(e);
  11056. }
  11057. }
  11058. var dragButtomTimer;
  11059. function toggleDragButton(show, table, editor) {
  11060. if (!show) {
  11061. if (dragOver)return;
  11062. dragButtomTimer = setTimeout(function () {
  11063. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  11064. }, 2000);
  11065. } else {
  11066. createDragButton(table, editor);
  11067. }
  11068. }
  11069. function createDragButton(table, editor) {
  11070. var pos = domUtils.getXY(table),
  11071. doc = table.ownerDocument;
  11072. if (dragButton && dragButton.parentNode)return dragButton;
  11073. dragButton = doc.createElement("div");
  11074. dragButton.contentEditable = false;
  11075. dragButton.innerHTML = "";
  11076. 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;";
  11077. domUtils.unSelectable(dragButton);
  11078. dragButton.onmouseover = function (evt) {
  11079. dragOver = true;
  11080. };
  11081. dragButton.onmouseout = function (evt) {
  11082. dragOver = false;
  11083. };
  11084. domUtils.on(dragButton, 'click', function (type, evt) {
  11085. doClick(evt, this);
  11086. });
  11087. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  11088. doDblClick(evt);
  11089. });
  11090. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  11091. domUtils.preventDefault(evt);
  11092. });
  11093. var timer;
  11094. function doClick(evt, button) {
  11095. // 部分浏览器下需要清理
  11096. clearTimeout(timer);
  11097. timer = setTimeout(function () {
  11098. editor.fireEvent("tableClicked", table, button);
  11099. }, 300);
  11100. }
  11101. function doDblClick(evt) {
  11102. clearTimeout(timer);
  11103. var ut = getUETable(table),
  11104. start = table.rows[0].cells[0],
  11105. end = ut.getLastCell(),
  11106. range = ut.getCellsRange(start, end);
  11107. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  11108. ut.setSelected(range);
  11109. }
  11110. doc.body.appendChild(dragButton);
  11111. }
  11112. // function inPosition(table, pos) {
  11113. // var tablePos = domUtils.getXY(table),
  11114. // width = table.offsetWidth,
  11115. // height = table.offsetHeight;
  11116. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  11117. // return "topLeft";
  11118. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  11119. // return "bottomRight";
  11120. // }
  11121. // }
  11122. function inTableSide(table, cell, evt, top) {
  11123. var pos = mouseCoords(evt),
  11124. state = getRelation(cell, pos);
  11125. if (top) {
  11126. var caption = table.getElementsByTagName("caption")[0],
  11127. capHeight = caption ? caption.offsetHeight : 0;
  11128. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  11129. } else {
  11130. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  11131. }
  11132. }
  11133. /**
  11134. * 获取拖动时允许的X轴坐标
  11135. * @param dragTd
  11136. * @param evt
  11137. */
  11138. function getPermissionX(dragTd, evt) {
  11139. var ut = getUETable(dragTd);
  11140. if (ut) {
  11141. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  11142. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  11143. mouseX = mouseCoords(evt).x,
  11144. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  11145. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  11146. return mouseX < left ? left : mouseX > right ? right : mouseX;
  11147. }
  11148. }
  11149. /**
  11150. * 获取拖动时允许的Y轴坐标
  11151. * @param dragTd
  11152. * @param evt
  11153. */
  11154. function getPermissionY(dragTd, evt) {
  11155. try {
  11156. var top = domUtils.getXY(dragTd).y,
  11157. mousePosY = mouseCoords(evt).y;
  11158. return mousePosY < top ? top : mousePosY;
  11159. } catch (e) {
  11160. showError(e);
  11161. }
  11162. }
  11163. /**
  11164. * 移动状态切换
  11165. * @param dragable
  11166. * @param dir
  11167. */
  11168. function toggleDragableState(editor, dragable, dir, mousePos, cell) {
  11169. try {
  11170. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  11171. if (browser.ie) {
  11172. if (dir && !mousedown && !getUETableBySelected(editor)) {
  11173. getDragLine(editor, editor.document);
  11174. showDragLineAt(dir, cell);
  11175. } else {
  11176. hideDragLine(editor)
  11177. }
  11178. }
  11179. onBorder = dragable;
  11180. } catch (e) {
  11181. showError(e);
  11182. }
  11183. }
  11184. /**
  11185. * 获取鼠标与当前单元格的相对位置
  11186. * @param ele
  11187. * @param mousePos
  11188. */
  11189. function getRelation(ele, mousePos) {
  11190. var elePos = domUtils.getXY(ele);
  11191. if (elePos.x + ele.offsetWidth - mousePos.x < 4) {
  11192. return "h";
  11193. }
  11194. if (mousePos.x - elePos.x < 4) {
  11195. return 'h1'
  11196. }
  11197. if (elePos.y + ele.offsetHeight - mousePos.y < 4) {
  11198. return "v";
  11199. }
  11200. if (mousePos.y - elePos.y < 4) {
  11201. return 'v1'
  11202. }
  11203. return '';
  11204. }
  11205. function mouseDownEvent(type, evt) {
  11206. //右键菜单单独处理
  11207. if (evt.button == 2) {
  11208. var ut = getUETableBySelected(me),
  11209. flag = false;
  11210. if (ut) {
  11211. var td = getTargetTd(me, evt);
  11212. utils.each(ut.selectedTds, function (ti) {
  11213. if (ti === td) {
  11214. flag = true;
  11215. }
  11216. });
  11217. if (!flag) {
  11218. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  11219. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th"));
  11220. ut.clearSelected()
  11221. } else {
  11222. td = ut.selectedTds[0];
  11223. setTimeout(function () {
  11224. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  11225. }, 0);
  11226. }
  11227. }
  11228. return;
  11229. }
  11230. if (evt.shiftKey) {
  11231. return;
  11232. }
  11233. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  11234. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th"));
  11235. //trace:3113
  11236. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  11237. utils.each(me.document.getElementsByTagName('table'), function (t) {
  11238. t.ueTable = null;
  11239. });
  11240. startTd = getTargetTd(me, evt);
  11241. if (!startTd) return;
  11242. var table = domUtils.findParentByTagName(startTd, "table", true);
  11243. ut = getUETable(table);
  11244. ut && ut.clearSelected();
  11245. //判断当前鼠标状态
  11246. if (!onBorder) {
  11247. me.document.body.style.webkitUserSelect = '';
  11248. mousedown = true;
  11249. me.addListener('mouseover', mouseOverEvent);
  11250. } else {
  11251. if (browser.ie && browser.version < 8) return;
  11252. var state = getRelation(startTd, mouseCoords(evt));
  11253. if (/\d/.test(state)) {
  11254. state = state.replace(/\d/, '');
  11255. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  11256. }
  11257. hideDragLine(me);
  11258. getDragLine(me, me.document);
  11259. showDragLineAt(state, startTd);
  11260. mousedown = true;
  11261. //拖动开始
  11262. onDrag = state;
  11263. dragTd = startTd;
  11264. }
  11265. }
  11266. function removeSelectedClass(cells) {
  11267. utils.each(cells, function (cell) {
  11268. domUtils.removeClasses(cell, "selectTdClass");
  11269. })
  11270. }
  11271. function addSelectedClass(cells) {
  11272. utils.each(cells, function (cell) {
  11273. domUtils.addClass(cell, "selectTdClass");
  11274. })
  11275. }
  11276. function getWidth(cell) {
  11277. if (!cell)return 0;
  11278. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  11279. }
  11280. function changeColWidth(cell, changeValue) {
  11281. if (Math.abs(changeValue) < 10) return;
  11282. var ut = getUETable(cell);
  11283. if (ut) {
  11284. var table = ut.table,
  11285. backTableWidth = getWidth(table),
  11286. defaultValue = getDefaultValue(me, table),
  11287. //这里不考虑一个都没有情况,如果一个都没有,可以认为该表格的结构可以精简
  11288. leftCells = ut.getSameEndPosCells(cell, "x"),
  11289. backLeftWidth = getWidth(leftCells[0]) - defaultValue.tdPadding * 2 - defaultValue.tdBorder,
  11290. rightCells = ut.getSameStartPosXCells(cell),
  11291. backRightWidth = getWidth(rightCells[0]) - defaultValue.tdPadding * 2 - defaultValue.tdBorder;
  11292. //整列被rowspan时存在
  11293. utils.each(leftCells, function (cell) {
  11294. if (cell.style.width) cell.style.width = "";
  11295. if (changeValue < 0)cell.style.wordBreak = "break-all";
  11296. cell.setAttribute("width", backLeftWidth + changeValue);
  11297. });
  11298. utils.each(rightCells, function (cell) {
  11299. if (cell.style.width) cell.style.width = "";
  11300. if (changeValue > 0)cell.style.wordBreak = "break-all";
  11301. cell.setAttribute("width", backRightWidth - changeValue);
  11302. });
  11303. //如果是在表格最右边拖动,则还需要调整表格宽度,否则在合并过的单元格中输入文字,表格会被撑开
  11304. if (!cell.nextSibling) {
  11305. if (table.style.width) table.style.width = "";
  11306. table.setAttribute("width", backTableWidth + changeValue);
  11307. }
  11308. }
  11309. }
  11310. function changeRowHeight(td, changeValue) {
  11311. if (Math.abs(changeValue) < 10) return;
  11312. var ut = getUETable(td);
  11313. if (ut) {
  11314. var cells = ut.getSameEndPosCells(td, "y"),
  11315. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  11316. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  11317. for (var i = 0, cell; cell = cells[i++];) {
  11318. setCellHeight(cell, changeValue, backHeight);
  11319. }
  11320. }
  11321. }
  11322. function setCellHeight(cell, height, backHeight) {
  11323. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  11324. tmpHeight = backHeight + height;
  11325. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  11326. if (cell.style.height) cell.style.height = "";
  11327. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  11328. }
  11329. function mouseUpEvent(type, evt) {
  11330. if (evt.button == 2)return;
  11331. var me = this;
  11332. //清除表格上原生跨选问题
  11333. var range = me.selection.getRange(),
  11334. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  11335. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  11336. if (start || end) {
  11337. if (start === end) {
  11338. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  11339. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  11340. if (start !== end) {
  11341. me.selection.clearRange()
  11342. }
  11343. } else {
  11344. me.selection.clearRange()
  11345. }
  11346. }
  11347. mousedown = false;
  11348. me.document.body.style.webkitUserSelect = '';
  11349. //拖拽状态下的mouseUP
  11350. if ((!browser.ie || (browser.ie && browser.version > 7)) && onDrag && dragTd) {
  11351. dragLine = me.document.getElementById('ue_tableDragLine');
  11352. var dragTdPos = domUtils.getXY(dragTd),
  11353. dragLinePos = domUtils.getXY(dragLine);
  11354. switch (onDrag) {
  11355. case "h":
  11356. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x - dragTd.offsetWidth);
  11357. break;
  11358. case "v":
  11359. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  11360. break;
  11361. default:
  11362. }
  11363. onDrag = "";
  11364. dragTd = null;
  11365. hideDragLine(me);
  11366. return;
  11367. }
  11368. //正常状态下的mouseup
  11369. if (!startTd) {
  11370. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  11371. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  11372. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  11373. if (me.fireEvent("excludetable", target) === true) return;
  11374. range = new dom.Range(me.document);
  11375. range.setStart(target, 0).setCursor(false, true);
  11376. }
  11377. } else {
  11378. var ut = getUETable(startTd),
  11379. cell = ut ? ut.selectedTds[0] : null;
  11380. if (cell) {
  11381. range = new dom.Range(me.document);
  11382. if (domUtils.isEmptyBlock(cell)) {
  11383. range.setStart(cell, 0).setCursor(false, true);
  11384. } else {
  11385. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  11386. }
  11387. } else {
  11388. range = me.selection.getRange().shrinkBoundary();
  11389. if (!range.collapsed) {
  11390. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  11391. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  11392. //在table里边的不能清除
  11393. if (start && !end || !start && end || start && end && start !== end) {
  11394. range.setCursor(false, true);
  11395. }
  11396. }
  11397. }
  11398. startTd = null;
  11399. me.removeListener('mouseover', mouseOverEvent);
  11400. }
  11401. me._selectionChange(250, evt);
  11402. }
  11403. function mouseOverEvent(type, evt) {
  11404. var me = this,
  11405. tar = evt.target || evt.srcElement;
  11406. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  11407. //需要判断两个TD是否位于同一个表格内
  11408. if (startTd && currentTd &&
  11409. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  11410. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  11411. var ut = getUETable(currentTd);
  11412. if (startTd != currentTd) {
  11413. me.document.body.style.webkitUserSelect = 'none';
  11414. me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  11415. var range = ut.getCellsRange(startTd, currentTd);
  11416. ut.setSelected(range);
  11417. } else {
  11418. me.document.body.style.webkitUserSelect = '';
  11419. ut.clearSelected();
  11420. }
  11421. }
  11422. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  11423. }
  11424. /**
  11425. * 根据当前点击的td或者table获取索引对象
  11426. * @param tdOrTable
  11427. */
  11428. function getUETable(tdOrTable) {
  11429. var tag = tdOrTable.tagName.toLowerCase();
  11430. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  11431. if (!tdOrTable.ueTable) {
  11432. tdOrTable.ueTable = new UETable(tdOrTable);
  11433. }
  11434. return tdOrTable.ueTable;
  11435. }
  11436. /**
  11437. * 根据当前框选的td来获取ueTable对象
  11438. */
  11439. function getUETableBySelected(editor) {
  11440. var table = getTableItemsByRange(editor).table;
  11441. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  11442. return table.ueTable;
  11443. }
  11444. return null;
  11445. }
  11446. function getDragLine(editor, doc) {
  11447. if (mousedown)return;
  11448. dragLine = editor.document.createElement("div");
  11449. domUtils.setAttributes(dragLine, {
  11450. id:"ue_tableDragLine",
  11451. unselectable:'on',
  11452. contenteditable:false,
  11453. 'onresizestart':'return false',
  11454. 'ondragstart':'return false',
  11455. 'onselectstart':'return false',
  11456. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  11457. });
  11458. // domUtils.on(dragLine,['resizestart','dragstart','selectstart'],function(evt){
  11459. // domUtils.preventDefault(evt);
  11460. // });
  11461. editor.body.appendChild(dragLine);
  11462. }
  11463. function hideDragLine(editor) {
  11464. if (mousedown)return;
  11465. var line;
  11466. while (line = editor.document.getElementById('ue_tableDragLine')) {
  11467. domUtils.remove(line)
  11468. }
  11469. }
  11470. /**
  11471. * 依据state(v|h)在cell位置显示横线
  11472. * @param state
  11473. * @param cell
  11474. */
  11475. function showDragLineAt(state, cell) {
  11476. if (!cell) return;
  11477. var table = domUtils.findParentByTagName(cell, "table"),
  11478. caption = table.getElementsByTagName('caption'),
  11479. width = table.offsetWidth,
  11480. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  11481. tablePos = domUtils.getXY(table),
  11482. cellPos = domUtils.getXY(cell), css;
  11483. switch (state) {
  11484. case "h":
  11485. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth - 2);
  11486. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  11487. break;
  11488. case "v":
  11489. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight - 2 );
  11490. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  11491. 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)';
  11492. break;
  11493. default:
  11494. }
  11495. }
  11496. /**
  11497. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  11498. * @param flag
  11499. */
  11500. function switchBoderColor(flag) {
  11501. var tableArr = domUtils.getElementsByTagName(me.body, "table"), color;
  11502. for (var i = 0, node; node = tableArr[i++];) {
  11503. var td = domUtils.getElementsByTagName(node, "td");
  11504. if (td[0]) {
  11505. if (flag) {
  11506. color = (td[0].style.borderColor).replace(/\s/g, "");
  11507. if (/(#ffffff)|(rgb\(255,f55,255\))/ig.test(color))
  11508. domUtils.addClass(node, "noBorderTable")
  11509. } else {
  11510. domUtils.removeClasses(node, "noBorderTable")
  11511. }
  11512. }
  11513. }
  11514. }
  11515. function getTableWidth(editor, needIEHack, defaultValue) {
  11516. var body = editor.body;
  11517. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  11518. }
  11519. UE.commands['inserttable'] = {
  11520. queryCommandState:function () {
  11521. return getTableItemsByRange(this).table ? -1 : 0;
  11522. },
  11523. execCommand:function (cmd, opt) {
  11524. function createTable(opt, tableWidth, tdWidth) {
  11525. var html = [],
  11526. rowsNum = opt.numRows,
  11527. colsNum = opt.numCols;
  11528. for (var r = 0; r < rowsNum; r++) {
  11529. html.push('<tr>');
  11530. for (var c = 0; c < colsNum; c++) {
  11531. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie ? domUtils.fillChar : '<br/>') + '</td>')
  11532. }
  11533. html.push('</tr>')
  11534. }
  11535. return '<table width="' + tableWidth + '" ><tbody>' + html.join('') + '</tbody></table>'
  11536. }
  11537. if (!opt) {
  11538. opt = utils.extend({}, {
  11539. numCols:this.options.defaultCols,
  11540. numRows:this.options.defaultRows,
  11541. tdvalign:this.options.tdvalign
  11542. })
  11543. }
  11544. var range = this.selection.getRange(),
  11545. start = range.startContainer,
  11546. firstParentBlock = domUtils.findParent(start, function (node) {
  11547. return domUtils.isBlockElm(node);
  11548. }, true);
  11549. var me = this,
  11550. defaultValue = getDefaultValue(me),
  11551. tableWidth = getTableWidth(me, needIEHack, defaultValue) - (firstParentBlock ? parseInt(domUtils.getXY(firstParentBlock).x, 10) : 0),
  11552. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  11553. //todo其他属性
  11554. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  11555. me.execCommand("inserthtml", createTable(opt, tableWidth, tdWidth));
  11556. }
  11557. };
  11558. UE.commands['insertparagraphbeforetable'] = {
  11559. queryCommandState:function () {
  11560. return getTableItemsByRange(this).cell ? 0 : -1;
  11561. },
  11562. execCommand:function () {
  11563. var table = getTableItemsByRange(this).table;
  11564. if (table) {
  11565. var p = this.document.createElement("p");
  11566. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  11567. table.parentNode.insertBefore(p, table);
  11568. this.selection.getRange().setStart(p, 0).setCursor();
  11569. }
  11570. }
  11571. };
  11572. UE.commands['deletetable'] = {
  11573. queryCommandState:function () {
  11574. var rng = this.selection.getRange();
  11575. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  11576. },
  11577. execCommand:function (cmd, table) {
  11578. var rng = this.selection.getRange();
  11579. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  11580. if (table) {
  11581. var next = table.nextSibling;
  11582. if (!next) {
  11583. next = domUtils.createElement(this.document, 'p', {
  11584. 'innerHTML':browser.ie ? domUtils.fillChar : '<br/>'
  11585. });
  11586. table.parentNode.insertBefore(next, table);
  11587. }
  11588. domUtils.remove(table);
  11589. rng = this.selection.getRange();
  11590. if (next.nodeType == 3) {
  11591. rng.setStartBefore(next)
  11592. } else {
  11593. rng.setStart(next, 0)
  11594. }
  11595. rng.setCursor(false, true)
  11596. toggleDragableState(this, false, "", null);
  11597. if (dragButton)domUtils.remove(dragButton);
  11598. }
  11599. }
  11600. };
  11601. UE.commands['cellalign'] = {
  11602. queryCommandState:function () {
  11603. return getSelectedArr(this).length ? 0 : -1
  11604. },
  11605. execCommand:function (cmd, align) {
  11606. var selectedTds = getSelectedArr(this);
  11607. if (selectedTds.length) {
  11608. for (var i = 0, ci; ci = selectedTds[i++];) {
  11609. ci.setAttribute('align', align);
  11610. }
  11611. }
  11612. }
  11613. };
  11614. UE.commands['cellvalign'] = {
  11615. queryCommandState:function () {
  11616. return getSelectedArr(this).length ? 0 : -1;
  11617. },
  11618. execCommand:function (cmd, valign) {
  11619. var selectedTds = getSelectedArr(this);
  11620. if (selectedTds.length) {
  11621. for (var i = 0, ci; ci = selectedTds[i++];) {
  11622. ci.setAttribute('vAlign', valign);
  11623. }
  11624. }
  11625. }
  11626. };
  11627. UE.commands['insertcaption'] = {
  11628. queryCommandState:function () {
  11629. var table = getTableItemsByRange(this).table;
  11630. if (table) {
  11631. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  11632. }
  11633. return -1;
  11634. },
  11635. execCommand:function () {
  11636. var table = getTableItemsByRange(this).table;
  11637. if (table) {
  11638. var caption = this.document.createElement('caption');
  11639. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  11640. table.insertBefore(caption, table.firstChild);
  11641. var range = this.selection.getRange();
  11642. range.setStart(caption, 0).setCursor();
  11643. }
  11644. }
  11645. };
  11646. UE.commands['deletecaption'] = {
  11647. queryCommandState:function () {
  11648. var rng = this.selection.getRange(),
  11649. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  11650. if (table) {
  11651. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  11652. }
  11653. return -1;
  11654. },
  11655. execCommand:function () {
  11656. var rng = this.selection.getRange(),
  11657. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  11658. if (table) {
  11659. domUtils.remove(table.getElementsByTagName('caption')[0]);
  11660. var range = this.selection.getRange();
  11661. range.setStart(table.rows[0].cells[0], 0).setCursor();
  11662. }
  11663. }
  11664. };
  11665. UE.commands['inserttitle'] = {
  11666. queryCommandState:function () {
  11667. var table = getTableItemsByRange(this).table;
  11668. if (table) {
  11669. var firstRow = table.rows[0];
  11670. return firstRow.getElementsByTagName('th').length == 0 ? 0 : -1
  11671. }
  11672. return -1;
  11673. },
  11674. execCommand:function () {
  11675. var table = getTableItemsByRange(this).table;
  11676. if (table) {
  11677. getUETable(table).insertRow(0, 'th');
  11678. }
  11679. var th = table.getElementsByTagName('th')[0];
  11680. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  11681. }
  11682. };
  11683. UE.commands['deletetitle'] = {
  11684. queryCommandState:function () {
  11685. var table = getTableItemsByRange(this).table;
  11686. if (table) {
  11687. var firstRow = table.rows[0];
  11688. return firstRow.getElementsByTagName('th').length ? 0 : -1
  11689. }
  11690. return -1;
  11691. },
  11692. execCommand:function () {
  11693. var table = getTableItemsByRange(this).table;
  11694. if (table) {
  11695. domUtils.remove(table.rows[0])
  11696. }
  11697. var td = table.getElementsByTagName('td')[0];
  11698. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  11699. }
  11700. };
  11701. UE.commands["mergeright"] = {
  11702. queryCommandState:function (cmd) {
  11703. var tableItems = getTableItemsByRange(this);
  11704. if (!tableItems.cell) return -1;
  11705. var ut = getUETable(tableItems.table);
  11706. if (ut.selectedTds.length) return -1;
  11707. var cellInfo = ut.getCellInfo(tableItems.cell),
  11708. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  11709. if (rightColIndex >= ut.colsNum) return -1;
  11710. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex];
  11711. return (rightCellInfo.rowIndex == cellInfo.rowIndex
  11712. && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  11713. },
  11714. execCommand:function (cmd) {
  11715. var rng = this.selection.getRange(),
  11716. bk = rng.createBookmark(true);
  11717. var cell = getTableItemsByRange(this).cell,
  11718. ut = getUETable(cell);
  11719. ut.mergeRight(cell);
  11720. rng.moveToBookmark(bk).select();
  11721. }
  11722. };
  11723. UE.commands["mergedown"] = {
  11724. queryCommandState:function (cmd) {
  11725. var tableItems = getTableItemsByRange(this),
  11726. cell = tableItems.cell;
  11727. if (!cell || cell.tagName == "TH") return -1;
  11728. var ut = getUETable(tableItems.table);
  11729. if (ut.selectedTds.length)return -1;
  11730. var cellInfo = ut.getCellInfo(tableItems.cell),
  11731. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  11732. // 如果处于最下边则不能f向右合并
  11733. if (downRowIndex >= ut.rowsNum) return -1;
  11734. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex];
  11735. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  11736. return (downCellInfo.colIndex == cellInfo.colIndex
  11737. && downCellInfo.colSpan == cellInfo.colSpan) && tableItems.cell.tagName !== 'TH' ? 0 : -1;
  11738. },
  11739. execCommand:function () {
  11740. var rng = this.selection.getRange(),
  11741. bk = rng.createBookmark(true);
  11742. var cell = getTableItemsByRange(this).cell,
  11743. ut = getUETable(cell);
  11744. ut.mergeDown(cell);
  11745. rng.moveToBookmark(bk).select();
  11746. }
  11747. };
  11748. UE.commands["mergecells"] = {
  11749. queryCommandState:function () {
  11750. return getUETableBySelected(this) ? 0 : -1;
  11751. },
  11752. execCommand:function () {
  11753. var ut = getUETableBySelected(this);
  11754. if (ut && ut.selectedTds.length) {
  11755. var cell = ut.selectedTds[0];
  11756. getUETableBySelected(this).mergeRange();
  11757. var rng = this.selection.getRange();
  11758. if (domUtils.isEmptyBlock(cell)) {
  11759. rng.setStart(cell, 0).collapse(true)
  11760. } else {
  11761. rng.selectNodeContents(cell)
  11762. }
  11763. rng.select();
  11764. }
  11765. }
  11766. };
  11767. UE.commands["insertrow"] = {
  11768. queryCommandState:function () {
  11769. var tableItems = getTableItemsByRange(this),
  11770. cell = tableItems.cell;
  11771. return cell && cell.tagName == "TD" && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  11772. },
  11773. execCommand:function () {
  11774. var rng = this.selection.getRange(),
  11775. bk = rng.createBookmark(true);
  11776. var cell = getTableItemsByRange(this).cell,
  11777. ut = getUETable(cell),
  11778. cellInfo = ut.getCellInfo(cell);
  11779. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  11780. if (!ut.selectedTds.length) {
  11781. ut.insertRow(cellInfo.rowIndex, cell);
  11782. } else {
  11783. var range = ut.cellsRange;
  11784. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  11785. ut.insertRow(range.beginRowIndex, cell);
  11786. }
  11787. }
  11788. rng.moveToBookmark(bk).select();
  11789. }
  11790. };
  11791. //后插入行
  11792. UE.commands["insertrownext"] = {
  11793. queryCommandState:function () {
  11794. var tableItems = getTableItemsByRange(this),
  11795. cell = tableItems.cell;
  11796. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  11797. },
  11798. execCommand:function () {
  11799. var rng = this.selection.getRange(),
  11800. bk = rng.createBookmark(true);
  11801. var cell = getTableItemsByRange(this).cell,
  11802. ut = getUETable(cell),
  11803. cellInfo = ut.getCellInfo(cell);
  11804. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  11805. if (!ut.selectedTds.length) {
  11806. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  11807. } else {
  11808. var range = ut.cellsRange;
  11809. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  11810. ut.insertRow(range.endRowIndex + 1, cell);
  11811. }
  11812. }
  11813. rng.moveToBookmark(bk).select();
  11814. }
  11815. };
  11816. UE.commands["deleterow"] = {
  11817. queryCommandState:function () {
  11818. var tableItems = getTableItemsByRange(this);
  11819. if (!tableItems.cell) {
  11820. return -1;
  11821. }
  11822. },
  11823. execCommand:function () {
  11824. var cell = getTableItemsByRange(this).cell,
  11825. ut = getUETable(cell),
  11826. cellsRange = ut.cellsRange,
  11827. cellInfo = ut.getCellInfo(cell),
  11828. preCell = ut.getVSideCell(cell),
  11829. nextCell = ut.getVSideCell(cell, true),
  11830. rng = this.selection.getRange();
  11831. if (utils.isEmptyObject(cellsRange)) {
  11832. ut.deleteRow(cellInfo.rowIndex);
  11833. } else {
  11834. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  11835. ut.deleteRow(cellsRange.beginRowIndex);
  11836. }
  11837. }
  11838. var table = ut.table;
  11839. if (!table.getElementsByTagName('td').length) {
  11840. var nextSibling = table.nextSibling;
  11841. domUtils.remove(table);
  11842. if (nextSibling) {
  11843. rng.setStart(nextSibling, 0).setCursor(false, true);
  11844. }
  11845. } else {
  11846. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  11847. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  11848. } else {
  11849. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  11850. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  11851. }
  11852. }
  11853. }
  11854. };
  11855. UE.commands["insertcol"] = {
  11856. queryCommandState:function (cmd) {
  11857. var tableItems = getTableItemsByRange(this),
  11858. cell = tableItems.cell;
  11859. return cell && (cell.tagName == "TD" || cell.tagName == 'TH') && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  11860. },
  11861. execCommand:function (cmd) {
  11862. var rng = this.selection.getRange(),
  11863. bk = rng.createBookmark(true);
  11864. if (this.queryCommandState(cmd) == -1)return;
  11865. var cell = getTableItemsByRange(this).cell,
  11866. ut = getUETable(cell),
  11867. cellInfo = ut.getCellInfo(cell);
  11868. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  11869. if (!ut.selectedTds.length) {
  11870. ut.insertCol(cellInfo.colIndex, cell);
  11871. } else {
  11872. var range = ut.cellsRange;
  11873. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  11874. ut.insertCol(range.beginColIndex, cell);
  11875. }
  11876. }
  11877. rng.moveToBookmark(bk).select(true);
  11878. }
  11879. };
  11880. UE.commands["insertcolnext"] = {
  11881. queryCommandState:function () {
  11882. var tableItems = getTableItemsByRange(this),
  11883. cell = tableItems.cell;
  11884. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  11885. },
  11886. execCommand:function () {
  11887. var rng = this.selection.getRange(),
  11888. bk = rng.createBookmark(true);
  11889. var cell = getTableItemsByRange(this).cell,
  11890. ut = getUETable(cell),
  11891. cellInfo = ut.getCellInfo(cell);
  11892. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  11893. if (!ut.selectedTds.length) {
  11894. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  11895. } else {
  11896. var range = ut.cellsRange;
  11897. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  11898. ut.insertCol(range.endColIndex + 1, cell);
  11899. }
  11900. }
  11901. rng.moveToBookmark(bk).select();
  11902. }
  11903. };
  11904. UE.commands["deletecol"] = {
  11905. queryCommandState:function () {
  11906. var tableItems = getTableItemsByRange(this);
  11907. if (!tableItems.cell) return -1;
  11908. },
  11909. execCommand:function () {
  11910. var cell = getTableItemsByRange(this).cell,
  11911. ut = getUETable(cell),
  11912. range = ut.cellsRange,
  11913. cellInfo = ut.getCellInfo(cell),
  11914. preCell = ut.getHSideCell(cell),
  11915. nextCell = ut.getHSideCell(cell, true);
  11916. if (utils.isEmptyObject(range)) {
  11917. ut.deleteCol(cellInfo.colIndex);
  11918. } else {
  11919. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  11920. ut.deleteCol(range.beginColIndex);
  11921. }
  11922. }
  11923. var table = ut.table,
  11924. rng = this.selection.getRange();
  11925. if (!table.getElementsByTagName('td').length) {
  11926. var nextSibling = table.nextSibling;
  11927. domUtils.remove(table);
  11928. if (nextSibling) {
  11929. rng.setStart(nextSibling, 0).setCursor(false, true);
  11930. }
  11931. } else {
  11932. if (domUtils.inDoc(cell, this.document)) {
  11933. rng.setStart(cell, 0).setCursor(false, true);
  11934. } else {
  11935. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  11936. rng.selectNodeContents(nextCell).setCursor(false, true);
  11937. } else {
  11938. if (preCell && domUtils.inDoc(preCell, this.document)) {
  11939. rng.selectNodeContents(preCell).setCursor(true, true);
  11940. }
  11941. }
  11942. }
  11943. }
  11944. }
  11945. };
  11946. UE.commands["splittocells"] = {
  11947. queryCommandState:function () {
  11948. var tableItems = getTableItemsByRange(this),
  11949. cell = tableItems.cell;
  11950. if (!cell) return -1;
  11951. var ut = getUETable(tableItems.table);
  11952. if (ut.selectedTds.length > 0) return -1;
  11953. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  11954. },
  11955. execCommand:function () {
  11956. var rng = this.selection.getRange(),
  11957. bk = rng.createBookmark(true);
  11958. var cell = getTableItemsByRange(this).cell,
  11959. ut = getUETable(cell);
  11960. ut.splitToCells(cell);
  11961. rng.moveToBookmark(bk).select();
  11962. }
  11963. };
  11964. UE.commands["splittorows"] = {
  11965. queryCommandState:function () {
  11966. var tableItems = getTableItemsByRange(this),
  11967. cell = tableItems.cell;
  11968. if (!cell) return -1;
  11969. var ut = getUETable(tableItems.table);
  11970. if (ut.selectedTds.length > 0) return -1;
  11971. return cell && cell.rowSpan > 1 ? 0 : -1;
  11972. },
  11973. execCommand:function () {
  11974. var rng = this.selection.getRange(),
  11975. bk = rng.createBookmark(true);
  11976. var cell = getTableItemsByRange(this).cell,
  11977. ut = getUETable(cell);
  11978. ut.splitToRows(cell);
  11979. rng.moveToBookmark(bk).select();
  11980. }
  11981. };
  11982. UE.commands["splittocols"] = {
  11983. queryCommandState:function () {
  11984. var tableItems = getTableItemsByRange(this),
  11985. cell = tableItems.cell;
  11986. if (!cell) return -1;
  11987. var ut = getUETable(tableItems.table);
  11988. if (ut.selectedTds.length > 0) return -1;
  11989. return cell && cell.colSpan > 1 ? 0 : -1;
  11990. },
  11991. execCommand:function () {
  11992. var rng = this.selection.getRange(),
  11993. bk = rng.createBookmark(true);
  11994. var cell = getTableItemsByRange(this).cell,
  11995. ut = getUETable(cell);
  11996. ut.splitToCols(cell);
  11997. rng.moveToBookmark(bk).select();
  11998. }
  11999. };
  12000. function getDefaultValue(editor, table) {
  12001. var borderMap = {
  12002. thin:'0px',
  12003. medium:'1px',
  12004. thick:'2px'
  12005. },
  12006. tableBorder, tdPadding, tdBorder, tmpValue;
  12007. if (!table) {
  12008. table = editor.document.createElement('table');
  12009. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  12010. editor.body.appendChild(table);
  12011. var td = table.getElementsByTagName('td')[0];
  12012. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  12013. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12014. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  12015. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12016. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  12017. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12018. domUtils.remove(table);
  12019. return {
  12020. tableBorder:tableBorder,
  12021. tdPadding:tdPadding,
  12022. tdBorder:tdBorder
  12023. };
  12024. } else {
  12025. td = table.getElementsByTagName('td')[0];
  12026. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  12027. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12028. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  12029. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12030. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  12031. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  12032. return {
  12033. tableBorder:tableBorder,
  12034. tdPadding:tdPadding,
  12035. tdBorder:tdBorder
  12036. };
  12037. }
  12038. }
  12039. UE.commands["adaptbytext"] =
  12040. UE.commands["adaptbywindow"] = {
  12041. queryCommandState:function () {
  12042. return getTableItemsByRange(this).table ? 0 : -1
  12043. },
  12044. execCommand:function (cmd) {
  12045. var tableItems = getTableItemsByRange(this),
  12046. table = tableItems.table;
  12047. if (table) {
  12048. var tds = table.getElementsByTagName("td");
  12049. utils.each(tds, function (td) {
  12050. td.removeAttribute("width");
  12051. });
  12052. if (cmd == 'adaptbywindow') {
  12053. table.setAttribute('width', getTableWidth(this, needIEHack, getDefaultValue(this, table)));
  12054. utils.each(tds, function (td) {
  12055. td.setAttribute("width", td.offsetWidth + "");
  12056. });
  12057. } else {
  12058. table.style.width = "";
  12059. table.removeAttribute("width");
  12060. var defaultValue = getDefaultValue(me, table);
  12061. var width = table.offsetWidth,
  12062. bodyWidth = me.body.offsetWidth;
  12063. if (width > bodyWidth) {
  12064. table.setAttribute('width', getTableWidth(me, needIEHack, defaultValue));
  12065. }
  12066. }
  12067. }
  12068. }
  12069. };
  12070. //平均分配各列
  12071. UE.commands['averagedistributecol'] = {
  12072. queryCommandState:function () {
  12073. var ut = getUETableBySelected(this);
  12074. if (!ut) return -1;
  12075. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  12076. },
  12077. execCommand:function (cmd) {
  12078. var me = this,
  12079. ut = getUETableBySelected(me);
  12080. function getAverageWidth() {
  12081. var tb = ut.table,
  12082. averageWidth, sumWidth = 0, colsNum = 0,
  12083. tbAttr = getDefaultValue(me, tb);
  12084. if (ut.isFullRow()) {
  12085. sumWidth = tb.offsetWidth;
  12086. colsNum = ut.colsNum;
  12087. } else {
  12088. var begin = ut.cellsRange.beginColIndex,
  12089. end = ut.cellsRange.endColIndex,
  12090. node;
  12091. for (var i = begin; i <= end;) {
  12092. node = ut.selectedTds[i];
  12093. sumWidth += node.offsetWidth;
  12094. i += node.colSpan;
  12095. colsNum += 1;
  12096. }
  12097. }
  12098. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  12099. return averageWidth;
  12100. }
  12101. function setAverageWidth(averageWidth) {
  12102. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  12103. node.setAttribute("width", "");
  12104. });
  12105. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  12106. utils.each(cells, function (node) {
  12107. if (node.colSpan == 1) {
  12108. node.setAttribute("width", averageWidth);
  12109. }
  12110. });
  12111. }
  12112. if (ut && ut.selectedTds.length) {
  12113. setAverageWidth(getAverageWidth());
  12114. }
  12115. }
  12116. };
  12117. //平均分配各行
  12118. UE.commands['averagedistributerow'] = {
  12119. queryCommandState:function () {
  12120. var ut = getUETableBySelected(this);
  12121. if (!ut) return -1;
  12122. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  12123. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  12124. },
  12125. execCommand:function (cmd) {
  12126. var me = this,
  12127. ut = getUETableBySelected(me);
  12128. function getAverageHeight() {
  12129. var averageHeight, rowNum, sumHeight = 0,
  12130. tb = ut.table,
  12131. tbAttr = getDefaultValue(me, tb),
  12132. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  12133. if (ut.isFullCol()) {
  12134. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  12135. thArr = domUtils.getElementsByTagName(tb, "th"),
  12136. captionHeight, thHeight;
  12137. if (captionArr.length > 0) {
  12138. captionHeight = captionArr[0].offsetHeight;
  12139. }
  12140. if (thArr.length > 0) {
  12141. thHeight = thArr[0].offsetHeight;
  12142. }
  12143. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  12144. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  12145. } else {
  12146. var begin = ut.cellsRange.beginRowIndex,
  12147. end = ut.cellsRange.endRowIndex,
  12148. count = 0,
  12149. trs = domUtils.getElementsByTagName(tb, "tr");
  12150. for (var i = begin; i <= end; i++) {
  12151. sumHeight += trs[i].offsetHeight;
  12152. count += 1;
  12153. }
  12154. rowNum = count;
  12155. }
  12156. //ie8下是混杂模式
  12157. if (browser.ie && browser.version < 9) {
  12158. averageHeight = Math.ceil(sumHeight / rowNum);
  12159. } else {
  12160. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  12161. }
  12162. return averageHeight;
  12163. }
  12164. function setAverageHeight(averageHeight) {
  12165. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  12166. utils.each(cells, function (node) {
  12167. if (node.rowSpan == 1) {
  12168. node.setAttribute("height", averageHeight);
  12169. }
  12170. });
  12171. }
  12172. if (ut && ut.selectedTds.length) {
  12173. setAverageHeight(getAverageHeight());
  12174. }
  12175. }
  12176. };
  12177. //单元格对齐方式
  12178. UE.commands['cellalignment'] = {
  12179. queryCommandState:function () {
  12180. return getTableItemsByRange(this).table ? 0 : -1
  12181. },
  12182. execCommand:function (cmd, data) {
  12183. var me = this,
  12184. ut = getUETableBySelected(me);
  12185. if (!ut) {
  12186. var start = me.selection.getStart(),
  12187. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  12188. if (!/caption/ig.test(cell.tagName)) {
  12189. domUtils.setAttributes(cell, data);
  12190. } else {
  12191. cell.style.textAlign = data.align;
  12192. cell.style.verticalAlign = data.vAlign;
  12193. }
  12194. me.selection.getRange().setCursor(true);
  12195. } else {
  12196. utils.each(ut.selectedTds, function (cell) {
  12197. domUtils.setAttributes(cell, data);
  12198. });
  12199. }
  12200. }
  12201. };
  12202. //表格对齐方式
  12203. UE.commands['tablealignment'] = {
  12204. queryCommandState:function () {
  12205. return getTableItemsByRange(this).table ? 0 : -1
  12206. },
  12207. execCommand:function (cmd, data) {
  12208. var me = this,
  12209. start = me.selection.getStart(),
  12210. table = start && domUtils.findParentByTagName(start, ["table"], true);
  12211. if (table) {
  12212. var obj = {};
  12213. obj[data[0]] = data[1];
  12214. table.style[utils.cssStyleToDomStyle("float")] = "";
  12215. table.style.margin = "";
  12216. domUtils.setStyles(table, obj);
  12217. }
  12218. }
  12219. };
  12220. //表格属性
  12221. UE.commands['edittable'] = {
  12222. queryCommandState:function () {
  12223. return getTableItemsByRange(this).table ? 0 : -1
  12224. },
  12225. execCommand:function (cmd, color) {
  12226. var rng = this.selection.getRange(),
  12227. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  12228. if (table) {
  12229. var arr = domUtils.getElementsByTagName(table, "td").concat(
  12230. domUtils.getElementsByTagName(table, "th"),
  12231. domUtils.getElementsByTagName(table, "caption")
  12232. );
  12233. utils.each(arr, function (node) {
  12234. node.style.borderColor = color;
  12235. });
  12236. }
  12237. }
  12238. };
  12239. //单元格属性
  12240. UE.commands['edittd'] = {
  12241. queryCommandState:function () {
  12242. return getTableItemsByRange(this).table ? 0 : -1
  12243. },
  12244. execCommand:function (cmd, bkColor) {
  12245. var me = this,
  12246. ut = getUETableBySelected(me);
  12247. if (!ut) {
  12248. var start = me.selection.getStart(),
  12249. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  12250. if (cell) {
  12251. cell.style.backgroundColor = bkColor;
  12252. }
  12253. } else {
  12254. utils.each(ut.selectedTds, function (cell) {
  12255. cell.style.backgroundColor = bkColor;
  12256. });
  12257. }
  12258. }
  12259. };
  12260. /**
  12261. * UE表格操作类
  12262. * @param table
  12263. * @constructor
  12264. */
  12265. function UETable(table) {
  12266. this.table = table;
  12267. this.indexTable = [];
  12268. this.selectedTds = [];
  12269. this.cellsRange = {};
  12270. this.update(table);
  12271. }
  12272. UETable.prototype = {
  12273. getMaxRows:function () {
  12274. var rows = this.table.rows, maxLen = 1;
  12275. for (var i = 0, row; row = rows[i]; i++) {
  12276. var currentMax = 1;
  12277. for (var j = 0, cj; cj = row.cells[j++];) {
  12278. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  12279. }
  12280. maxLen = Math.max(currentMax + i, maxLen);
  12281. }
  12282. return maxLen;
  12283. },
  12284. /**
  12285. * 获取当前表格的最大列数
  12286. */
  12287. getMaxCols:function () {
  12288. var rows = this.table.rows, maxLen = 0, cellRows = {};
  12289. for (var i = 0, row; row = rows[i]; i++) {
  12290. var cellsNum = 0;
  12291. for (var j = 0, cj; cj = row.cells[j++];) {
  12292. cellsNum += (cj.colSpan || 1);
  12293. if (cj.rowSpan && cj.rowSpan > 1) {
  12294. for (var k = 1; k < cj.rowSpan; k++) {
  12295. if (!cellRows['row_' + (i + k)]) {
  12296. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  12297. } else {
  12298. cellRows['row_' + (i + k)]++
  12299. }
  12300. }
  12301. }
  12302. }
  12303. cellsNum += cellRows['row_' + i] || 0;
  12304. maxLen = Math.max(cellsNum, maxLen);
  12305. }
  12306. return maxLen;
  12307. },
  12308. getCellColIndex:function (cell) {
  12309. },
  12310. /**
  12311. * 获取当前cell旁边的单元格,
  12312. * @param cell
  12313. * @param right
  12314. */
  12315. getHSideCell:function (cell, right) {
  12316. try {
  12317. var cellInfo = this.getCellInfo(cell),
  12318. previewRowIndex, previewColIndex;
  12319. var len = this.selectedTds.length,
  12320. range = this.cellsRange;
  12321. //首行或者首列没有前置单元格
  12322. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  12323. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  12324. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  12325. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  12326. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  12327. } catch (e) {
  12328. showError(e);
  12329. }
  12330. },
  12331. getTabNextCell:function (cell, preRowIndex) {
  12332. var cellInfo = this.getCellInfo(cell),
  12333. rowIndex = preRowIndex || cellInfo.rowIndex,
  12334. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  12335. nextCell;
  12336. try {
  12337. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  12338. } catch (e) {
  12339. try {
  12340. rowIndex = rowIndex * 1 + 1;
  12341. colIndex = 0;
  12342. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  12343. } catch (e) {
  12344. }
  12345. }
  12346. return nextCell;
  12347. },
  12348. /**
  12349. * 获取视觉上的后置单元格
  12350. * @param cell
  12351. * @param bottom
  12352. */
  12353. getVSideCell:function (cell, bottom, ignoreRange) {
  12354. try {
  12355. var cellInfo = this.getCellInfo(cell),
  12356. nextRowIndex, nextColIndex;
  12357. var len = this.selectedTds.length && !ignoreRange,
  12358. range = this.cellsRange;
  12359. //末行或者末列没有后置单元格
  12360. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  12361. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  12362. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  12363. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  12364. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  12365. } catch (e) {
  12366. showError(e);
  12367. }
  12368. },
  12369. /**
  12370. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  12371. */
  12372. getSameEndPosCells:function (cell, xOrY) {
  12373. try {
  12374. var flag = (xOrY.toLowerCase() === "x"),
  12375. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  12376. rows = this.table.rows,
  12377. cells = null, returns = [];
  12378. for (var i = 0; i < this.rowsNum; i++) {
  12379. cells = rows[i].cells;
  12380. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  12381. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  12382. //对应行的td已经被上面行rowSpan了
  12383. if (tmpEnd > end && flag) break;
  12384. if (cell == tmpCell || end == tmpEnd) {
  12385. //只获取单一的单元格
  12386. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  12387. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  12388. returns.push(tmpCell);
  12389. }
  12390. if (flag) break;
  12391. }
  12392. }
  12393. }
  12394. return returns;
  12395. } catch (e) {
  12396. showError(e);
  12397. }
  12398. },
  12399. setCellContent:function (cell, content) {
  12400. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  12401. },
  12402. cloneCell:cloneCell,
  12403. /**
  12404. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  12405. */
  12406. getSameStartPosXCells:function (cell) {
  12407. try {
  12408. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  12409. rows = this.table.rows, cells , returns = [];
  12410. for (var i = 0; i < this.rowsNum; i++) {
  12411. cells = rows[i].cells;
  12412. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  12413. var tmpStart = domUtils.getXY(tmpCell).x;
  12414. if (tmpStart > start) break;
  12415. if (tmpStart == start && tmpCell.colSpan == 1) {
  12416. returns.push(tmpCell);
  12417. break;
  12418. }
  12419. }
  12420. }
  12421. return returns;
  12422. } catch (e) {
  12423. showError(e);
  12424. }
  12425. },
  12426. /**
  12427. * 更新table对应的索引表
  12428. */
  12429. update:function (table) {
  12430. this.table = table || this.table;
  12431. this.selectedTds = [];
  12432. this.cellsRange = {};
  12433. this.indexTable = [];
  12434. var rows = this.table.rows,
  12435. //暂时采用rows Length,对残缺表格可能存在问题,
  12436. //todo 可以考虑取最大值
  12437. rowsNum = rows.length,
  12438. colsNum = this.getMaxCols();
  12439. this.rowsNum = rowsNum;
  12440. this.colsNum = colsNum;
  12441. for (var i = 0, len = rows.length; i < len; i++) {
  12442. this.indexTable[i] = new Array(colsNum);
  12443. }
  12444. //填充索引表
  12445. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  12446. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  12447. //修正整行被rowSpan时导致的行数计算错误
  12448. if (cell.rowSpan > rowsNum) {
  12449. cell.rowSpan = rowsNum;
  12450. }
  12451. var colIndex = cellIndex,
  12452. rowSpan = cell.rowSpan || 1,
  12453. colSpan = cell.colSpan || 1;
  12454. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  12455. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  12456. for (var j = 0; j < rowSpan; j++) {
  12457. for (var k = 0; k < colSpan; k++) {
  12458. this.indexTable[rowIndex + j][colIndex + k] = {
  12459. rowIndex:rowIndex,
  12460. cellIndex:cellIndex,
  12461. colIndex:colIndex,
  12462. rowSpan:rowSpan,
  12463. colSpan:colSpan
  12464. }
  12465. }
  12466. }
  12467. }
  12468. }
  12469. //修复残缺td
  12470. for (j = 0; j < rowsNum; j++) {
  12471. for (k = 0; k < colsNum; k++) {
  12472. if (this.indexTable[j][k] === undefined) {
  12473. row = rows[j];
  12474. cell = row.cells[row.cells.length - 1];
  12475. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  12476. this.setCellContent(cell);
  12477. if (cell.colSpan !== 1)cell.colSpan = 1;
  12478. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  12479. row.appendChild(cell);
  12480. this.indexTable[j][k] = {
  12481. rowIndex:j,
  12482. cellIndex:cell.cellIndex,
  12483. colIndex:k,
  12484. rowSpan:1,
  12485. colSpan:1
  12486. }
  12487. }
  12488. }
  12489. }
  12490. //当框选后删除行或者列后撤销,需要重建选区。
  12491. var tds = domUtils.getElementsByTagName(this.table, "td"),
  12492. selectTds = [];
  12493. utils.each(tds, function (td) {
  12494. if (domUtils.hasClass(td, "selectTdClass")) {
  12495. selectTds.push(td);
  12496. }
  12497. });
  12498. if (selectTds.length) {
  12499. var start = selectTds[0],
  12500. end = selectTds[selectTds.length - 1],
  12501. startInfo = this.getCellInfo(start),
  12502. endInfo = this.getCellInfo(end);
  12503. this.selectedTds = selectTds;
  12504. this.cellsRange = {
  12505. beginRowIndex:startInfo.rowIndex,
  12506. beginColIndex:startInfo.colIndex,
  12507. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  12508. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  12509. };
  12510. }
  12511. },
  12512. /**
  12513. * 获取单元格的索引信息
  12514. */
  12515. getCellInfo:function (cell) {
  12516. if (!cell) return;
  12517. var cellIndex = cell.cellIndex,
  12518. rowIndex = cell.parentNode.rowIndex,
  12519. rowInfo = this.indexTable[rowIndex],
  12520. numCols = this.colsNum;
  12521. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  12522. var cellInfo = rowInfo[colIndex];
  12523. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  12524. return cellInfo;
  12525. }
  12526. }
  12527. },
  12528. /**
  12529. * 根据行列号获取单元格
  12530. */
  12531. getCell:function (rowIndex, cellIndex) {
  12532. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  12533. },
  12534. /**
  12535. * 删除单元格
  12536. */
  12537. deleteCell:function (cell, rowIndex) {
  12538. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  12539. var row = this.table.rows[rowIndex];
  12540. row.deleteCell(cell.cellIndex);
  12541. },
  12542. /**
  12543. * 根据始末两个单元格获取被框选的所有单元格范围
  12544. */
  12545. getCellsRange:function (cellA, cellB) {
  12546. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  12547. var tmpBeginRowIndex = beginRowIndex,
  12548. tmpBeginColIndex = beginColIndex,
  12549. tmpEndRowIndex = endRowIndex,
  12550. tmpEndColIndex = endColIndex,
  12551. cellInfo, colIndex, rowIndex;
  12552. // 通过indexTable检查是否存在超出TableRange上边界的情况
  12553. if (beginRowIndex > 0) {
  12554. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  12555. cellInfo = me.indexTable[beginRowIndex][colIndex];
  12556. rowIndex = cellInfo.rowIndex;
  12557. if (rowIndex < beginRowIndex) {
  12558. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  12559. }
  12560. }
  12561. }
  12562. // 通过indexTable检查是否存在超出TableRange右边界的情况
  12563. if (endColIndex < me.colsNum) {
  12564. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  12565. cellInfo = me.indexTable[rowIndex][endColIndex];
  12566. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  12567. if (colIndex > endColIndex) {
  12568. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  12569. }
  12570. }
  12571. }
  12572. // 检查是否有超出TableRange下边界的情况
  12573. if (endRowIndex < me.rowsNum) {
  12574. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  12575. cellInfo = me.indexTable[endRowIndex][colIndex];
  12576. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  12577. if (rowIndex > endRowIndex) {
  12578. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  12579. }
  12580. }
  12581. }
  12582. // 检查是否有超出TableRange左边界的情况
  12583. if (beginColIndex > 0) {
  12584. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  12585. cellInfo = me.indexTable[rowIndex][beginColIndex];
  12586. colIndex = cellInfo.colIndex;
  12587. if (colIndex < beginColIndex) {
  12588. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  12589. }
  12590. }
  12591. }
  12592. //递归调用直至所有完成所有框选单元格的扩展
  12593. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  12594. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  12595. } else {
  12596. // 不需要扩展TableRange的情况
  12597. return {
  12598. beginRowIndex:beginRowIndex,
  12599. beginColIndex:beginColIndex,
  12600. endRowIndex:endRowIndex,
  12601. endColIndex:endColIndex
  12602. };
  12603. }
  12604. }
  12605. try {
  12606. var me = this,
  12607. cellAInfo = me.getCellInfo(cellA);
  12608. if (cellA === cellB) {
  12609. return {
  12610. beginRowIndex:cellAInfo.rowIndex,
  12611. beginColIndex:cellAInfo.colIndex,
  12612. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  12613. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  12614. };
  12615. }
  12616. var cellBInfo = me.getCellInfo(cellB);
  12617. // 计算TableRange的四个边
  12618. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  12619. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  12620. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  12621. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  12622. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  12623. } catch (e) {
  12624. if (debug) throw e;
  12625. }
  12626. },
  12627. /**
  12628. * 依据cellsRange获取对应的单元格集合
  12629. */
  12630. getCells:function (range) {
  12631. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  12632. this.clearSelected();
  12633. var beginRowIndex = range.beginRowIndex,
  12634. beginColIndex = range.beginColIndex,
  12635. endRowIndex = range.endRowIndex,
  12636. endColIndex = range.endColIndex,
  12637. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  12638. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  12639. for (var j = beginColIndex; j <= endColIndex; j++) {
  12640. cellInfo = this.indexTable[i][j];
  12641. rowIndex = cellInfo.rowIndex;
  12642. colIndex = cellInfo.colIndex;
  12643. // 如果Cells里已经包含了此Cell则跳过
  12644. var key = rowIndex + '|' + colIndex;
  12645. if (tdHash[key]) continue;
  12646. tdHash[key] = 1;
  12647. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  12648. return null;
  12649. }
  12650. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  12651. }
  12652. }
  12653. return returnTds;
  12654. },
  12655. /**
  12656. * 清理已经选中的单元格
  12657. */
  12658. clearSelected:function () {
  12659. removeSelectedClass(this.selectedTds);
  12660. this.selectedTds = [];
  12661. this.cellsRange = {};
  12662. },
  12663. /**
  12664. * 根据range设置已经选中的单元格
  12665. */
  12666. setSelected:function (range) {
  12667. var cells = this.getCells(range);
  12668. addSelectedClass(cells);
  12669. this.selectedTds = cells;
  12670. this.cellsRange = range;
  12671. },
  12672. isFullRow:function () {
  12673. var range = this.cellsRange;
  12674. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  12675. },
  12676. isFullCol:function () {
  12677. var range = this.cellsRange,
  12678. table = this.table,
  12679. ths = table.getElementsByTagName("th"),
  12680. rows = range.endRowIndex - range.beginRowIndex + 1;
  12681. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  12682. },
  12683. /**
  12684. * 获取视觉上的前置单元格,默认是左边,top传入时
  12685. * @param cell
  12686. * @param top
  12687. */
  12688. getNextCell:function (cell, bottom, ignoreRange) {
  12689. try {
  12690. var cellInfo = this.getCellInfo(cell),
  12691. nextRowIndex, nextColIndex;
  12692. var len = this.selectedTds.length && !ignoreRange,
  12693. range = this.cellsRange;
  12694. //末行或者末列没有后置单元格
  12695. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  12696. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  12697. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  12698. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  12699. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  12700. } catch (e) {
  12701. showError(e);
  12702. }
  12703. },
  12704. getPreviewCell:function (cell, top) {
  12705. try {
  12706. var cellInfo = this.getCellInfo(cell),
  12707. previewRowIndex, previewColIndex;
  12708. var len = this.selectedTds.length,
  12709. range = this.cellsRange;
  12710. //首行或者首列没有前置单元格
  12711. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  12712. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  12713. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  12714. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  12715. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  12716. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  12717. } catch (e) {
  12718. showError(e);
  12719. }
  12720. },
  12721. /**
  12722. * 移动单元格中的内容
  12723. */
  12724. moveContent:function (cellTo, cellFrom) {
  12725. if (isEmptyBlock(cellFrom)) return;
  12726. if (isEmptyBlock(cellTo)) {
  12727. cellTo.innerHTML = cellFrom.innerHTML;
  12728. return;
  12729. }
  12730. var child = cellTo.lastChild;
  12731. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  12732. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  12733. }
  12734. while (child = cellFrom.firstChild) {
  12735. cellTo.appendChild(child);
  12736. }
  12737. },
  12738. /**
  12739. * 向右合并单元格
  12740. */
  12741. mergeRight:function (cell) {
  12742. var cellInfo = this.getCellInfo(cell),
  12743. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  12744. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  12745. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  12746. //合并
  12747. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  12748. //被合并的单元格不应存在宽度属性
  12749. cell.removeAttribute("width");
  12750. //移动内容
  12751. this.moveContent(cell, rightCell);
  12752. //删掉被合并的Cell
  12753. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  12754. this.update();
  12755. },
  12756. /**
  12757. * 向下合并单元格
  12758. */
  12759. mergeDown:function (cell) {
  12760. var cellInfo = this.getCellInfo(cell),
  12761. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  12762. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  12763. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  12764. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  12765. cell.removeAttribute("height");
  12766. this.moveContent(cell, downCell);
  12767. this.deleteCell(downCell, downCellInfo.rowIndex);
  12768. this.update();
  12769. },
  12770. /**
  12771. * 合并整个range中的内容
  12772. */
  12773. mergeRange:function () {
  12774. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  12775. var range = this.cellsRange,
  12776. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  12777. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  12778. var index = this.indexTable,
  12779. info = this.getCellInfo(leftTopCell);
  12780. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  12781. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  12782. }
  12783. // 删除剩余的Cells
  12784. var cells = this.getCells(range),
  12785. len = cells.length, cell;
  12786. while (len--) {
  12787. cell = cells[len];
  12788. if (cell !== leftTopCell) {
  12789. this.moveContent(leftTopCell, cell);
  12790. this.deleteCell(cell);
  12791. }
  12792. }
  12793. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  12794. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  12795. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  12796. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  12797. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  12798. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  12799. leftTopCell.colSpan = 1;
  12800. }
  12801. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  12802. var rowIndex = leftTopCell.parentNode.rowIndex;
  12803. for (var i = 0; i < leftTopCell.rowSpan - 1; i++) {
  12804. var row = this.table.rows[rowIndex + 1];
  12805. row.parentNode.removeChild(row);
  12806. }
  12807. leftTopCell.rowSpan = 1;
  12808. }
  12809. this.update();
  12810. },
  12811. /**
  12812. * 插入一行单元格
  12813. */
  12814. insertRow:function (rowIndex, sourceCell) {
  12815. var numCols = this.colsNum,
  12816. table = this.table,
  12817. row = table.insertRow(rowIndex), cell,
  12818. width = parseInt((table.offsetWidth - numCols * 20 - numCols - 1) / numCols, 10);
  12819. //首行直接插入,无需考虑部分单元格被rowspan的情况
  12820. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  12821. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  12822. cell = this.cloneCell(sourceCell, true);
  12823. this.setCellContent(cell);
  12824. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12825. row.appendChild(cell);
  12826. }
  12827. } else {
  12828. var infoRow = this.indexTable[rowIndex],
  12829. cellIndex = 0;
  12830. for (colIndex = 0; colIndex < numCols; colIndex++) {
  12831. var cellInfo = infoRow[colIndex];
  12832. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  12833. if (cellInfo.rowIndex < rowIndex) {
  12834. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12835. cell.rowSpan = cellInfo.rowSpan + 1;
  12836. } else {
  12837. cell = this.cloneCell(sourceCell, true);
  12838. this.setCellContent(cell);
  12839. row.appendChild(cell);
  12840. }
  12841. }
  12842. }
  12843. //框选时插入不触发contentchange,需要手动更新索引。
  12844. this.update();
  12845. return row;
  12846. },
  12847. /**
  12848. * 删除一行单元格
  12849. * @param rowIndex
  12850. */
  12851. deleteRow:function (rowIndex) {
  12852. var row = this.table.rows[rowIndex],
  12853. infoRow = this.indexTable[rowIndex],
  12854. colsNum = this.colsNum,
  12855. count = 0; //处理计数
  12856. for (var colIndex = 0; colIndex < colsNum;) {
  12857. var cellInfo = infoRow[colIndex],
  12858. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12859. if (cell.rowSpan > 1) {
  12860. if (cellInfo.rowIndex == rowIndex) {
  12861. var clone = cell.cloneNode(true);
  12862. clone.rowSpan = cell.rowSpan - 1;
  12863. clone.innerHTML = "";
  12864. cell.rowSpan = 1;
  12865. var nextRowIndex = rowIndex + 1,
  12866. nextRow = this.table.rows[nextRowIndex],
  12867. insertCellIndex,
  12868. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  12869. if (preMerged < colIndex) {
  12870. insertCellIndex = colIndex - preMerged - 1;
  12871. //nextRow.insertCell(insertCellIndex);
  12872. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  12873. } else {
  12874. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  12875. }
  12876. count += 1;
  12877. //cell.parentNode.removeChild(cell);
  12878. }
  12879. }
  12880. colIndex += cell.colSpan || 1;
  12881. }
  12882. var deleteTds = [], cacheMap = {};
  12883. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  12884. var tmpRowIndex = infoRow[colIndex].rowIndex,
  12885. tmpCellIndex = infoRow[colIndex].cellIndex,
  12886. key = tmpRowIndex + "_" + tmpCellIndex;
  12887. if (cacheMap[key])continue;
  12888. cacheMap[key] = 1;
  12889. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  12890. deleteTds.push(cell);
  12891. }
  12892. var mergeTds = [];
  12893. utils.each(deleteTds, function (td) {
  12894. if (td.rowSpan == 1) {
  12895. td.parentNode.removeChild(td);
  12896. } else {
  12897. mergeTds.push(td);
  12898. }
  12899. });
  12900. utils.each(mergeTds, function (td) {
  12901. td.rowSpan--;
  12902. });
  12903. row.parentNode.removeChild(row);
  12904. //浏览器方法本身存在bug,采用自定义方法删除
  12905. //this.table.deleteRow(rowIndex);
  12906. this.update();
  12907. },
  12908. insertCol:function (colIndex, sourceCell, defaultValue) {
  12909. var rowsNum = this.rowsNum,
  12910. rowIndex = 0,
  12911. tableRow, cell,
  12912. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10);
  12913. function replaceTdToTh(rowIndex, cell, tableRow) {
  12914. if (rowIndex == 0) {
  12915. var th = cell.nextSibling || cell.previousSibling;
  12916. if (th.tagName == 'TH') {
  12917. th = cell.ownerDocument.createElement("th");
  12918. th.appendChild(cell.firstChild);
  12919. tableRow.insertBefore(th, cell);
  12920. domUtils.remove(cell)
  12921. }
  12922. }
  12923. }
  12924. var preCell;
  12925. if (colIndex == 0 || colIndex == this.colsNum) {
  12926. for (; rowIndex < rowsNum; rowIndex++) {
  12927. tableRow = this.table.rows[rowIndex];
  12928. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  12929. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  12930. this.setCellContent(cell);
  12931. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12932. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  12933. if (!colIndex) {
  12934. tableRow.insertBefore(cell, tableRow.cells[0]);
  12935. } else {
  12936. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  12937. }
  12938. replaceTdToTh(rowIndex, cell, tableRow)
  12939. }
  12940. } else {
  12941. for (; rowIndex < rowsNum; rowIndex++) {
  12942. var cellInfo = this.indexTable[rowIndex][colIndex];
  12943. if (cellInfo.colIndex < colIndex) {
  12944. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12945. cell.colSpan = cellInfo.colSpan + 1;
  12946. } else {
  12947. tableRow = this.table.rows[rowIndex];
  12948. preCell = tableRow.cells[cellInfo.cellIndex];
  12949. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  12950. this.setCellContent(cell);
  12951. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12952. preCell && cell.setAttribute('width', preCell.getAttribute('width'))
  12953. tableRow.insertBefore(cell, preCell);
  12954. }
  12955. replaceTdToTh(rowIndex, cell, tableRow);
  12956. }
  12957. }
  12958. //框选时插入不触发contentchange,需要手动更新索引
  12959. this.update();
  12960. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  12961. },
  12962. updateWidth:function (width, defaultValue) {
  12963. var table = this.table,
  12964. tmpWidth = getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  12965. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  12966. table.setAttribute("width", tmpWidth);
  12967. return;
  12968. }
  12969. var tds = domUtils.getElementsByTagName(this.table, "td");
  12970. utils.each(tds, function (td) {
  12971. td.setAttribute("width", width);
  12972. })
  12973. },
  12974. deleteCol:function (colIndex) {
  12975. var indexTable = this.indexTable,
  12976. tableRows = this.table.rows,
  12977. backTableWidth = this.table.getAttribute("width"),
  12978. backTdWidth = 0,
  12979. rowsNum = this.rowsNum,
  12980. cacheMap = {};
  12981. for (var rowIndex = 0; rowIndex < rowsNum;) {
  12982. var infoRow = indexTable[rowIndex],
  12983. cellInfo = infoRow[colIndex],
  12984. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  12985. // 跳过已经处理过的Cell
  12986. if (cacheMap[key])continue;
  12987. cacheMap[key] = 1;
  12988. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12989. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  12990. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  12991. if (cell.colSpan > 1) {
  12992. cell.colSpan--;
  12993. } else {
  12994. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  12995. }
  12996. rowIndex += cellInfo.rowSpan || 1;
  12997. }
  12998. this.table.setAttribute("width", backTableWidth - backTdWidth);
  12999. this.update();
  13000. },
  13001. splitToCells:function (cell) {
  13002. var me = this,
  13003. cells = this.splitToRows(cell);
  13004. utils.each(cells, function (cell) {
  13005. me.splitToCols(cell);
  13006. })
  13007. },
  13008. splitToRows:function (cell) {
  13009. var cellInfo = this.getCellInfo(cell),
  13010. rowIndex = cellInfo.rowIndex,
  13011. colIndex = cellInfo.colIndex,
  13012. results = [];
  13013. // 修改Cell的rowSpan
  13014. cell.rowSpan = 1;
  13015. results.push(cell);
  13016. // 补齐单元格
  13017. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  13018. if (i == rowIndex)continue;
  13019. var tableRow = this.table.rows[i],
  13020. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  13021. tmpCell.colSpan = cellInfo.colSpan;
  13022. this.setCellContent(tmpCell);
  13023. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13024. tmpCell.setAttribute('align', cell.getAttribute('align'));
  13025. if (cell.style.cssText) {
  13026. tmpCell.style.cssText = cell.style.cssText;
  13027. }
  13028. results.push(tmpCell);
  13029. }
  13030. this.update();
  13031. return results;
  13032. },
  13033. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  13034. var indexRow = this.indexTable[rowIndex],
  13035. num = 0;
  13036. for (var i = 0; i < colIndex;) {
  13037. var colSpan = indexRow[i].colSpan,
  13038. tmpRowIndex = indexRow[i].rowIndex;
  13039. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  13040. i += colSpan;
  13041. }
  13042. return num;
  13043. },
  13044. splitToCols:function (cell) {
  13045. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  13046. cellInfo = this.getCellInfo(cell),
  13047. rowIndex = cellInfo.rowIndex,
  13048. colIndex = cellInfo.colIndex,
  13049. results = [];
  13050. // 修改Cell的rowSpan
  13051. cell.colSpan = 1;
  13052. cell.setAttribute("width", backWidth);
  13053. results.push(cell);
  13054. // 补齐单元格
  13055. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  13056. if (j == colIndex)continue;
  13057. var tableRow = this.table.rows[rowIndex],
  13058. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  13059. tmpCell.rowSpan = cellInfo.rowSpan;
  13060. this.setCellContent(tmpCell);
  13061. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13062. tmpCell.setAttribute('align', cell.getAttribute('align'));
  13063. tmpCell.setAttribute('width', backWidth);
  13064. if (cell.style.cssText) {
  13065. tmpCell.style.cssText = cell.style.cssText;
  13066. }
  13067. //处理th的情况
  13068. if (cell.tagName == 'TH') {
  13069. var th = cell.ownerDocument.createElement('th');
  13070. th.appendChild(tmpCell.firstChild);
  13071. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  13072. th.rowSpan = tmpCell.rowSpan;
  13073. tableRow.insertBefore(th, tmpCell);
  13074. domUtils.remove(tmpCell);
  13075. }
  13076. results.push(tmpCell);
  13077. }
  13078. this.update();
  13079. return results;
  13080. },
  13081. isLastCell:function (cell, rowsNum, colsNum) {
  13082. rowsNum = rowsNum || this.rowsNum;
  13083. colsNum = colsNum || this.colsNum;
  13084. var cellInfo = this.getCellInfo(cell);
  13085. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  13086. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  13087. },
  13088. getLastCell:function (cells) {
  13089. cells = cells || this.table.getElementsByTagName("td");
  13090. var firstInfo = this.getCellInfo(cells[0]);
  13091. var me = this, last = cells[0],
  13092. tr = last.parentNode,
  13093. cellsNum = 0, cols = 0, rows;
  13094. utils.each(cells, function (cell) {
  13095. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  13096. cellsNum += cell.rowSpan * cell.colSpan || 1;
  13097. });
  13098. rows = cellsNum / cols;
  13099. utils.each(cells, function (cell) {
  13100. if (me.isLastCell(cell, rows, cols)) {
  13101. last = cell;
  13102. return false;
  13103. }
  13104. });
  13105. return last;
  13106. },
  13107. selectRow:function (rowIndex) {
  13108. var indexRow = this.indexTable[rowIndex],
  13109. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  13110. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  13111. range = this.getCellsRange(start, end);
  13112. this.setSelected(range);
  13113. },
  13114. selectTable:function () {
  13115. var tds = this.table.getElementsByTagName("td"),
  13116. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  13117. this.setSelected(range);
  13118. }
  13119. };
  13120. function getSelectedArr(editor) {
  13121. var ut = getTableItemsByRange(editor).cell || getUETableBySelected(editor);
  13122. return ut ? (ut.nodeType ? [ut] : ut.selectedTds) : [];
  13123. }
  13124. /**
  13125. * 根据当前选区获取相关的table信息
  13126. * @return {Object}
  13127. */
  13128. function getTableItemsByRange(editor) {
  13129. var start = editor.selection.getStart(),
  13130. //在table或者td边缘有可能存在选中tr的情况
  13131. cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  13132. tr = cell && cell.parentNode,
  13133. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  13134. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  13135. return {
  13136. cell:cell,
  13137. tr:tr,
  13138. table:table,
  13139. caption:caption
  13140. }
  13141. }
  13142. /**
  13143. * 获取需要触发对应点击或者move事件的td对象
  13144. * @param evt
  13145. */
  13146. function getTargetTd(editor, evt) {
  13147. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true);
  13148. //排除了非td内部以及用于代码高亮部分的td
  13149. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  13150. }
  13151. function cloneCell(cell, ingoreMerge) {
  13152. if (!cell || utils.isString(cell)) {
  13153. return this.table.ownerDocument.createElement(cell || 'td');
  13154. }
  13155. var flag = domUtils.hasClass(cell, "selectTdClass");
  13156. flag && domUtils.removeClasses(cell, "selectTdClass");
  13157. var tmpCell = cell.cloneNode(true);
  13158. if (ingoreMerge) {
  13159. tmpCell.rowSpan = tmpCell.colSpan = 1;
  13160. }
  13161. tmpCell.style.borderLeftStyle = "";
  13162. tmpCell.style.borderTopStyle = "";
  13163. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  13164. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  13165. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  13166. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  13167. flag && domUtils.addClass(cell, "selectTdClass");
  13168. return tmpCell;
  13169. }
  13170. };
  13171. ///import core
  13172. ///commands 右键菜单
  13173. ///commandsName ContextMenu
  13174. ///commandsTitle 右键菜单
  13175. /**
  13176. * 右键菜单
  13177. * @function
  13178. * @name baidu.editor.plugins.contextmenu
  13179. * @author zhanyi
  13180. */
  13181. UE.plugins['contextmenu'] = function () {
  13182. var me = this,
  13183. lang = me.getLang( "contextMenu" ),
  13184. menu,
  13185. items = me.options.contextMenu || [
  13186. {label:lang['selectall'], cmdName:'selectall'},
  13187. {
  13188. label:lang.deletecode,
  13189. cmdName:'highlightcode',
  13190. icon:'deletehighlightcode'
  13191. },
  13192. {
  13193. label:lang.cleardoc,
  13194. cmdName:'cleardoc',
  13195. exec:function () {
  13196. if ( confirm( lang.confirmclear ) ) {
  13197. this.execCommand( 'cleardoc' );
  13198. }
  13199. }
  13200. },
  13201. '-',
  13202. {
  13203. label:lang.unlink,
  13204. cmdName:'unlink'
  13205. },
  13206. '-',
  13207. {
  13208. group:lang.paragraph,
  13209. icon:'justifyjustify',
  13210. subMenu:[
  13211. {
  13212. label:lang.justifyleft,
  13213. cmdName:'justify',
  13214. value:'left'
  13215. },
  13216. {
  13217. label:lang.justifyright,
  13218. cmdName:'justify',
  13219. value:'right'
  13220. },
  13221. {
  13222. label:lang.justifycenter,
  13223. cmdName:'justify',
  13224. value:'center'
  13225. },
  13226. {
  13227. label:lang.justifyjustify,
  13228. cmdName:'justify',
  13229. value:'justify'
  13230. }
  13231. ]
  13232. },
  13233. '-',
  13234. {
  13235. group:lang.table,
  13236. icon:'table',
  13237. subMenu:[
  13238. {
  13239. label:lang.inserttable,
  13240. cmdName:'inserttable'
  13241. },
  13242. {
  13243. label:lang.deletetable,
  13244. cmdName:'deletetable'
  13245. },
  13246. '-',
  13247. {
  13248. label:lang.deleterow,
  13249. cmdName:'deleterow'
  13250. },
  13251. {
  13252. label:lang.deletecol,
  13253. cmdName:'deletecol'
  13254. },
  13255. {
  13256. label:lang.insertcol,
  13257. cmdName:'insertcol'
  13258. },
  13259. {
  13260. label:lang.insertcolnext,
  13261. cmdName:'insertcolnext'
  13262. },
  13263. {
  13264. label:lang.insertrow,
  13265. cmdName:'insertrow'
  13266. },
  13267. {
  13268. label:lang.insertrownext,
  13269. cmdName:'insertrownext'
  13270. },
  13271. '-',
  13272. {
  13273. label:lang.insertcaption,
  13274. cmdName:'insertcaption'
  13275. },
  13276. {
  13277. label:lang.deletecaption,
  13278. cmdName:'deletecaption'
  13279. },
  13280. {
  13281. label:lang.inserttitle,
  13282. cmdName:'inserttitle'
  13283. },
  13284. {
  13285. label:lang.deletetitle,
  13286. cmdName:'deletetitle'
  13287. },
  13288. '-',
  13289. {
  13290. label:lang.mergecells,
  13291. cmdName:'mergecells'
  13292. },
  13293. {
  13294. label:lang.mergeright,
  13295. cmdName:'mergeright'
  13296. },
  13297. {
  13298. label:lang.mergedown,
  13299. cmdName:'mergedown'
  13300. },
  13301. '-',
  13302. {
  13303. label:lang.splittorows,
  13304. cmdName:'splittorows'
  13305. },
  13306. {
  13307. label:lang.splittocols,
  13308. cmdName:'splittocols'
  13309. },
  13310. {
  13311. label:lang.splittocells,
  13312. cmdName:'splittocells'
  13313. },
  13314. '-',
  13315. {
  13316. label:lang.averageDiseRow,
  13317. cmdName:'averagedistributerow'
  13318. },
  13319. {
  13320. label:lang.averageDisCol,
  13321. cmdName:'averagedistributecol'
  13322. },
  13323. '-',
  13324. {
  13325. label:lang.edittd,
  13326. cmdName:'edittd',
  13327. exec:function () {
  13328. if ( UE.ui['edittd'] ) {
  13329. new UE.ui['edittd']( this );
  13330. }
  13331. this.getDialog('edittd').open();
  13332. }
  13333. },
  13334. {
  13335. label:lang.edittable,
  13336. cmdName:'edittable',
  13337. exec:function () {
  13338. if ( UE.ui['edittable'] ) {
  13339. new UE.ui['edittable']( this );
  13340. }
  13341. this.getDialog('edittable').open();
  13342. }
  13343. }
  13344. ]
  13345. },
  13346. {
  13347. group:lang.aligntd,
  13348. icon:'aligntd',
  13349. subMenu:[
  13350. {
  13351. cmdName:'cellalignment',
  13352. value:{align:'left',vAlign:'top'}
  13353. },
  13354. {
  13355. cmdName:'cellalignment',
  13356. value:{align:'center',vAlign:'top'}
  13357. },
  13358. {
  13359. cmdName:'cellalignment',
  13360. value:{align:'right',vAlign:'top'}
  13361. },
  13362. {
  13363. cmdName:'cellalignment',
  13364. value:{align:'left',vAlign:'middle'}
  13365. },
  13366. {
  13367. cmdName:'cellalignment',
  13368. value:{align:'center',vAlign:'middle'}
  13369. },
  13370. {
  13371. cmdName:'cellalignment',
  13372. value:{align:'right',vAlign:'middle'}
  13373. },
  13374. {
  13375. cmdName:'cellalignment',
  13376. value:{align:'left',vAlign:'bottom'}
  13377. },
  13378. {
  13379. cmdName:'cellalignment',
  13380. value:{align:'center',vAlign:'bottom'}
  13381. },
  13382. {
  13383. cmdName:'cellalignment',
  13384. value:{align:'right',vAlign:'bottom'}
  13385. }
  13386. ]
  13387. },
  13388. {
  13389. group:lang.aligntable,
  13390. icon:'aligntable',
  13391. subMenu:[
  13392. {
  13393. cmdName:'tablealignment',
  13394. label:lang.tableleft,
  13395. value:['float','left']
  13396. },
  13397. {
  13398. cmdName:'tablealignment',
  13399. label:lang.tablecenter,
  13400. value:['margin','0 auto']
  13401. },
  13402. {
  13403. cmdName:'tablealignment',
  13404. label:lang.tableright,
  13405. value:['float','right']
  13406. }
  13407. ]
  13408. },
  13409. '-',
  13410. {
  13411. label:lang.insertparagraphbefore,
  13412. cmdName:'insertparagraph',
  13413. value:true
  13414. },
  13415. {
  13416. label:lang.insertparagraphafter,
  13417. cmdName:'insertparagraph'
  13418. },
  13419. {
  13420. label:lang['copy'],
  13421. cmdName:'copy',
  13422. exec:function () {
  13423. alert( lang.copymsg );
  13424. },
  13425. query:function () {
  13426. return 0;
  13427. }
  13428. },
  13429. {
  13430. label:lang['paste'],
  13431. cmdName:'paste',
  13432. exec:function () {
  13433. alert( lang.pastemsg );
  13434. },
  13435. query:function () {
  13436. return 0;
  13437. }
  13438. },{
  13439. label:lang['highlightcode'],
  13440. cmdName:'highlightcode',
  13441. exec:function () {
  13442. if ( UE.ui['highlightcode'] ) {
  13443. new UE.ui['highlightcode']( this );
  13444. }
  13445. this.ui._dialogs['highlightcodeDialog'].open();
  13446. }
  13447. }
  13448. ];
  13449. if ( !items.length ) {
  13450. return;
  13451. }
  13452. var uiUtils = UE.ui.uiUtils;
  13453. me.addListener( 'contextmenu', function ( type, evt ) {
  13454. var offset = uiUtils.getViewportOffsetByEvent( evt );
  13455. me.fireEvent( 'beforeselectionchange' );
  13456. if ( menu ) {
  13457. menu.destroy();
  13458. }
  13459. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  13460. var last;
  13461. (function ( item ) {
  13462. if ( item == '-' ) {
  13463. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  13464. contextItems.push( '-' );
  13465. }
  13466. } else if ( item.hasOwnProperty( "group" ) ) {
  13467. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  13468. (function ( subItem ) {
  13469. if ( subItem == '-' ) {
  13470. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  13471. subMenu.push( '-' );
  13472. }else{
  13473. subMenu.splice(subMenu.length-1);
  13474. }
  13475. } else {
  13476. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  13477. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  13478. subMenu.push( {
  13479. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  13480. 'className':'edui-for-' +subItem.cmdName,
  13481. onclick:subItem.exec ? function () {
  13482. subItem.exec.call( me );
  13483. } : function () {
  13484. me.execCommand( subItem.cmdName, subItem.value );
  13485. }
  13486. } );
  13487. }
  13488. }
  13489. })( cj );
  13490. }
  13491. if ( subMenu.length ) {
  13492. function getLabel(){
  13493. switch (item.icon){
  13494. case "table":
  13495. return me.getLang( "contextMenu.table" );
  13496. case "justifyjustify":
  13497. return me.getLang( "contextMenu.paragraph" );
  13498. case "aligntd":
  13499. return me.getLang("contextMenu.aligntd");
  13500. case "aligntable":
  13501. return me.getLang("contextMenu.aligntable");
  13502. default :
  13503. return '';
  13504. }
  13505. }
  13506. contextItems.push( {
  13507. //todo 修正成自动获取方式
  13508. 'label':getLabel(),
  13509. className:'edui-for-' + item.icon,
  13510. 'subMenu':{
  13511. items:subMenu,
  13512. editor:me
  13513. }
  13514. } );
  13515. }
  13516. } else {
  13517. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  13518. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  13519. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  13520. //highlight todo
  13521. if ( item.cmdName == 'highlightcode' ) {
  13522. if(me.queryCommandState( item.cmdName ) == 1 && item.icon != 'deletehighlightcode'){
  13523. return;
  13524. }
  13525. if(me.queryCommandState( item.cmdName ) != 1 && item.icon == 'deletehighlightcode'){
  13526. return;
  13527. }
  13528. }
  13529. contextItems.push( {
  13530. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  13531. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  13532. onclick:item.exec ? function () {
  13533. item.exec.call( me );
  13534. } : function () {
  13535. me.execCommand( item.cmdName, item.value );
  13536. }
  13537. } );
  13538. }
  13539. }
  13540. })( ti );
  13541. }
  13542. if ( contextItems[contextItems.length - 1] == '-' ) {
  13543. contextItems.pop();
  13544. }
  13545. menu = new UE.ui.Menu( {
  13546. items:contextItems,
  13547. editor:me
  13548. } );
  13549. menu.render();
  13550. menu.showAt( offset );
  13551. domUtils.preventDefault( evt );
  13552. if ( browser.ie ) {
  13553. var ieRange;
  13554. try {
  13555. ieRange = me.selection.getNative().createRange();
  13556. } catch ( e ) {
  13557. return;
  13558. }
  13559. if ( ieRange.item ) {
  13560. var range = new dom.Range( me.document );
  13561. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  13562. }
  13563. }
  13564. } );
  13565. };
  13566. ///import core
  13567. ///commands 加粗,斜体,上标,下标
  13568. ///commandsName Bold,Italic,Subscript,Superscript
  13569. ///commandsTitle 加粗,加斜,下标,上标
  13570. /**
  13571. * b u i等基础功能实现
  13572. * @function
  13573. * @name baidu.editor.execCommands
  13574. * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。
  13575. */
  13576. UE.plugins['basestyle'] = function(){
  13577. var basestyles = {
  13578. 'bold':['strong','b'],
  13579. 'italic':['em','i'],
  13580. 'subscript':['sub'],
  13581. 'superscript':['sup']
  13582. },
  13583. getObj = function(editor,tagNames){
  13584. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  13585. },
  13586. me = this;
  13587. //添加快捷键
  13588. me.addshortcutkey({
  13589. "Bold" : "ctrl+66",//^B
  13590. "Italic" : "ctrl+73", //^I
  13591. "Underline" : "ctrl+85"//^U
  13592. });
  13593. for ( var style in basestyles ) {
  13594. (function( cmd, tagNames ) {
  13595. me.commands[cmd] = {
  13596. execCommand : function( cmdName ) {
  13597. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  13598. if ( range.collapsed ) {
  13599. if ( obj ) {
  13600. var tmpText = me.document.createTextNode('');
  13601. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  13602. range.setStartBefore(tmpText);
  13603. domUtils.remove(tmpText);
  13604. } else {
  13605. var tmpNode = range.document.createElement( tagNames[0] );
  13606. if(cmdName == 'superscript' || cmdName == 'subscript'){
  13607. tmpText = me.document.createTextNode('');
  13608. range.insertNode(tmpText)
  13609. .removeInlineStyle(['sub','sup'])
  13610. .setStartBefore(tmpText)
  13611. .collapse(true);
  13612. }
  13613. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  13614. }
  13615. range.collapse( true );
  13616. } else {
  13617. if(cmdName == 'superscript' || cmdName == 'subscript'){
  13618. if(!obj || obj.tagName.toLowerCase() != cmdName){
  13619. range.removeInlineStyle(['sub','sup']);
  13620. }
  13621. }
  13622. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  13623. }
  13624. range.select();
  13625. },
  13626. queryCommandState : function() {
  13627. return getObj(this,tagNames) ? 1 : 0;
  13628. }
  13629. };
  13630. })( style, basestyles[style] );
  13631. }
  13632. };
  13633. ///import core
  13634. ///commands 选区路径
  13635. ///commandsName ElementPath,elementPathEnabled
  13636. ///commandsTitle 选区路径
  13637. /**
  13638. * 选区路径
  13639. * @function
  13640. * @name baidu.editor.execCommand
  13641. * @param {String} cmdName elementpath选区路径
  13642. */
  13643. UE.plugins['elementpath'] = function(){
  13644. var currentLevel,
  13645. tagNames,
  13646. me = this;
  13647. me.setOpt('elementPathEnabled',true);
  13648. if(!me.options.elementPathEnabled){
  13649. return;
  13650. }
  13651. me.commands['elementpath'] = {
  13652. execCommand : function( cmdName, level ) {
  13653. var start = tagNames[level],
  13654. range = me.selection.getRange();
  13655. currentLevel = level*1;
  13656. range.selectNode(start).select();
  13657. },
  13658. queryCommandValue : function() {
  13659. //产生一个副本,不能修改原来的startElementPath;
  13660. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  13661. names = [];
  13662. tagNames = parents;
  13663. for(var i=0,ci;ci=parents[i];i++){
  13664. if(ci.nodeType == 3) {
  13665. continue;
  13666. }
  13667. var name = ci.tagName.toLowerCase();
  13668. if(name == 'img' && ci.getAttribute('anchorname')){
  13669. name = 'anchor';
  13670. }
  13671. names[i] = name;
  13672. if(currentLevel == i){
  13673. currentLevel = -1;
  13674. break;
  13675. }
  13676. }
  13677. return names;
  13678. }
  13679. };
  13680. };
  13681. ///import core
  13682. ///import plugins\removeformat.js
  13683. ///commands 格式刷
  13684. ///commandsName FormatMatch
  13685. ///commandsTitle 格式刷
  13686. /**
  13687. * 格式刷,只格式inline的
  13688. * @function
  13689. * @name baidu.editor.execCommand
  13690. * @param {String} cmdName formatmatch执行格式刷
  13691. */
  13692. UE.plugins['formatmatch'] = function(){
  13693. var me = this,
  13694. list = [],img,
  13695. flag = 0;
  13696. me.addListener('reset',function(){
  13697. list = [];
  13698. flag = 0;
  13699. });
  13700. function addList(type,evt){
  13701. if(browser.webkit){
  13702. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  13703. }
  13704. function addFormat(range){
  13705. if(text){
  13706. range.selectNode(text);
  13707. }
  13708. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  13709. }
  13710. me.undoManger && me.undoManger.save();
  13711. var range = me.selection.getRange(),
  13712. imgT = target || range.getClosedNode();
  13713. if(img && imgT && imgT.tagName == 'IMG'){
  13714. //trace:964
  13715. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  13716. img = null;
  13717. }else{
  13718. if(!img){
  13719. var collapsed = range.collapsed;
  13720. if(collapsed){
  13721. var text = me.document.createTextNode('match');
  13722. range.insertNode(text).select();
  13723. }
  13724. me.__hasEnterExecCommand = true;
  13725. //不能把block上的属性干掉
  13726. //trace:1553
  13727. var removeFormatAttributes = me.options.removeFormatAttributes;
  13728. me.options.removeFormatAttributes = '';
  13729. me.execCommand('removeformat');
  13730. me.options.removeFormatAttributes = removeFormatAttributes;
  13731. me.__hasEnterExecCommand = false;
  13732. //trace:969
  13733. range = me.selection.getRange();
  13734. if(list.length){
  13735. addFormat(range);
  13736. }
  13737. if(text){
  13738. range.setStartBefore(text).collapse(true);
  13739. }
  13740. range.select();
  13741. text && domUtils.remove(text);
  13742. }
  13743. }
  13744. me.undoManger && me.undoManger.save();
  13745. me.removeListener('mouseup',addList);
  13746. flag = 0;
  13747. }
  13748. me.commands['formatmatch'] = {
  13749. execCommand : function( cmdName ) {
  13750. if(flag){
  13751. flag = 0;
  13752. list = [];
  13753. me.removeListener('mouseup',addList);
  13754. return;
  13755. }
  13756. var range = me.selection.getRange();
  13757. img = range.getClosedNode();
  13758. if(!img || img.tagName != 'IMG'){
  13759. range.collapse(true).shrinkBoundary();
  13760. var start = range.startContainer;
  13761. list = domUtils.findParents(start,true,function(node){
  13762. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  13763. });
  13764. //a不能加入格式刷, 并且克隆节点
  13765. for(var i=0,ci;ci=list[i];i++){
  13766. if(ci.tagName == 'A'){
  13767. list.splice(i,1);
  13768. break;
  13769. }
  13770. }
  13771. }
  13772. me.addListener('mouseup',addList);
  13773. flag = 1;
  13774. },
  13775. queryCommandState : function() {
  13776. return flag;
  13777. },
  13778. notNeedUndo : 1
  13779. };
  13780. };
  13781. ///import core
  13782. ///commands 查找替换
  13783. ///commandsName SearchReplace
  13784. ///commandsTitle 查询替换
  13785. ///commandsDialog dialogs\searchreplace
  13786. /**
  13787. * @description 查找替换
  13788. * @author zhanyi
  13789. */
  13790. UE.plugins['searchreplace'] = function(){
  13791. var currentRange,
  13792. first,
  13793. me = this;
  13794. me.addListener('reset',function(){
  13795. currentRange = null;
  13796. first = null;
  13797. });
  13798. me.commands['searchreplace'] = {
  13799. execCommand : function(cmdName,opt){
  13800. var me = this,
  13801. sel = me.selection,
  13802. range,
  13803. nativeRange,
  13804. num = 0,
  13805. opt = utils.extend(opt,{
  13806. all : false,
  13807. casesensitive : false,
  13808. dir : 1
  13809. },true);
  13810. if(browser.ie){
  13811. while(1){
  13812. var tmpRange;
  13813. nativeRange = me.document.selection.createRange();
  13814. tmpRange = nativeRange.duplicate();
  13815. tmpRange.moveToElementText(me.document.body);
  13816. if(opt.all){
  13817. first = 0;
  13818. opt.dir = 1;
  13819. if(currentRange){
  13820. tmpRange.setEndPoint(opt.dir == -1 ? 'EndToStart' : 'StartToEnd',currentRange);
  13821. }
  13822. tmpRange.moveToElementText(me.document.body);
  13823. }else{
  13824. tmpRange.setEndPoint(opt.dir == -1 ? 'EndToStart' : 'StartToEnd',nativeRange);
  13825. if(opt.hasOwnProperty("replaceStr")){
  13826. tmpRange.setEndPoint(opt.dir == -1 ? 'StartToEnd' : 'EndToStart',nativeRange);
  13827. }
  13828. }
  13829. nativeRange = tmpRange.duplicate();
  13830. if(!tmpRange.findText(opt.searchStr,opt.dir,opt.casesensitive ? 4 : 0)){
  13831. currentRange = null;
  13832. tmpRange = me.document.selection.createRange();
  13833. tmpRange.scrollIntoView();
  13834. return num;
  13835. }
  13836. tmpRange.select();
  13837. //替换
  13838. if(opt.hasOwnProperty("replaceStr")){
  13839. range = sel.getRange();
  13840. range.deleteContents().insertNode(range.document.createTextNode(opt.replaceStr)).select();
  13841. currentRange = sel.getNative().createRange();
  13842. }
  13843. num++;
  13844. if(!opt.all){
  13845. break;
  13846. }
  13847. }
  13848. }else{
  13849. var w = me.window,nativeSel = sel.getNative(),tmpRange;
  13850. while(1){
  13851. if(opt.all){
  13852. if(currentRange){
  13853. currentRange.collapse(false);
  13854. nativeRange = currentRange;
  13855. }else{
  13856. nativeRange = me.document.createRange();
  13857. }
  13858. nativeRange.setStart(me.document.body,0);
  13859. nativeRange.collapse(true);
  13860. nativeSel.removeAllRanges();
  13861. nativeSel.addRange( nativeRange );
  13862. first = 0;
  13863. opt.dir = 1;
  13864. }else{
  13865. //safari弹出层,原生已经找不到range了,所以需要先选回来,再取原生
  13866. if(browser.safari){
  13867. me.selection.getRange().select();
  13868. }
  13869. nativeRange = w.getSelection().getRangeAt(0);
  13870. if(opt.hasOwnProperty("replaceStr")){
  13871. nativeRange.collapse(opt.dir == 1 ? true : false);
  13872. }
  13873. }
  13874. //如果是第一次并且海选中了内容那就要清除,为find做准备
  13875. if(!first){
  13876. nativeRange.collapse( opt.dir <0 ? true : false);
  13877. nativeSel.removeAllRanges();
  13878. nativeSel.addRange( nativeRange );
  13879. }else{
  13880. nativeSel.removeAllRanges();
  13881. }
  13882. if(!w.find(opt.searchStr,opt.casesensitive,opt.dir < 0 ? true : false) ) {
  13883. currentRange = null;
  13884. nativeSel.removeAllRanges();
  13885. return num;
  13886. }
  13887. first = 0;
  13888. range = w.getSelection().getRangeAt(0);
  13889. if(!range.collapsed){
  13890. if(opt.hasOwnProperty("replaceStr")){
  13891. range.deleteContents();
  13892. var text = w.document.createTextNode(opt.replaceStr);
  13893. range.insertNode(text);
  13894. range.selectNode(text);
  13895. nativeSel.addRange(range);
  13896. currentRange = range.cloneRange();
  13897. }
  13898. }
  13899. num++;
  13900. if(!opt.all){
  13901. break;
  13902. }
  13903. }
  13904. }
  13905. return true;
  13906. }
  13907. };
  13908. };
  13909. ///import core
  13910. ///commands 自定义样式
  13911. ///commandsName CustomStyle
  13912. ///commandsTitle 自定义样式
  13913. UE.plugins['customstyle'] = function() {
  13914. var me = this;
  13915. me.setOpt({ 'customstyle':[
  13916. {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;'},
  13917. {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;'},
  13918. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  13919. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  13920. ]});
  13921. me.commands['customstyle'] = {
  13922. execCommand : function(cmdName, obj) {
  13923. var me = this,
  13924. tagName = obj.tag,
  13925. node = domUtils.findParent(me.selection.getStart(), function(node) {
  13926. return node.getAttribute('label');
  13927. }, true),
  13928. range,bk,tmpObj = {};
  13929. for (var p in obj) {
  13930. if(obj[p]!==undefined)
  13931. tmpObj[p] = obj[p];
  13932. }
  13933. delete tmpObj.tag;
  13934. if (node && node.getAttribute('label') == obj.label) {
  13935. range = this.selection.getRange();
  13936. bk = range.createBookmark();
  13937. if (range.collapsed) {
  13938. //trace:1732 删掉自定义标签,要有p来回填站位
  13939. if(dtd.$block[node.tagName]){
  13940. var fillNode = me.document.createElement('p');
  13941. domUtils.moveChild(node, fillNode);
  13942. node.parentNode.insertBefore(fillNode, node);
  13943. domUtils.remove(node);
  13944. }else{
  13945. domUtils.remove(node,true);
  13946. }
  13947. } else {
  13948. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  13949. nodes = domUtils.getElementsByTagName(common, tagName);
  13950. if(new RegExp(tagName,'i').test(common.tagName)){
  13951. nodes.push(common);
  13952. }
  13953. for (var i = 0,ni; ni = nodes[i++];) {
  13954. if (ni.getAttribute('label') == obj.label) {
  13955. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  13956. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  13957. &&
  13958. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  13959. )
  13960. if (dtd.$block[tagName]) {
  13961. var fillNode = me.document.createElement('p');
  13962. domUtils.moveChild(ni, fillNode);
  13963. ni.parentNode.insertBefore(fillNode, ni);
  13964. }
  13965. domUtils.remove(ni, true);
  13966. }
  13967. }
  13968. node = domUtils.findParent(common, function(node) {
  13969. return node.getAttribute('label') == obj.label;
  13970. }, true);
  13971. if (node) {
  13972. domUtils.remove(node, true);
  13973. }
  13974. }
  13975. range.moveToBookmark(bk).select();
  13976. } else {
  13977. if (dtd.$block[tagName]) {
  13978. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  13979. range = me.selection.getRange();
  13980. if (!range.collapsed) {
  13981. range.collapse();
  13982. node = domUtils.findParent(me.selection.getStart(), function(node) {
  13983. return node.getAttribute('label') == obj.label;
  13984. }, true);
  13985. var pNode = me.document.createElement('p');
  13986. domUtils.insertAfter(node, pNode);
  13987. domUtils.fillNode(me.document, pNode);
  13988. range.setStart(pNode, 0).setCursor();
  13989. }
  13990. } else {
  13991. range = me.selection.getRange();
  13992. if (range.collapsed) {
  13993. node = me.document.createElement(tagName);
  13994. domUtils.setAttributes(node, tmpObj);
  13995. range.insertNode(node).setStart(node, 0).setCursor();
  13996. return;
  13997. }
  13998. bk = range.createBookmark();
  13999. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  14000. }
  14001. }
  14002. },
  14003. queryCommandValue : function() {
  14004. var parent = domUtils.filterNodeList(
  14005. this.selection.getStartElementPath(),
  14006. function(node){return node.getAttribute('label')}
  14007. );
  14008. return parent ? parent.getAttribute('label') : '';
  14009. }
  14010. };
  14011. //当去掉customstyle是,如果是块元素,用p代替
  14012. me.addListener('keyup', function(type, evt) {
  14013. var keyCode = evt.keyCode || evt.which;
  14014. if (keyCode == 32 || keyCode == 13) {
  14015. var range = me.selection.getRange();
  14016. if (range.collapsed) {
  14017. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  14018. return node.getAttribute('label');
  14019. }, true);
  14020. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  14021. var p = me.document.createElement('p');
  14022. domUtils.insertAfter(node, p);
  14023. domUtils.fillNode(me.document, p);
  14024. domUtils.remove(node);
  14025. range.setStart(p, 0).setCursor();
  14026. }
  14027. }
  14028. }
  14029. });
  14030. };
  14031. ///import core
  14032. ///commands 远程图片抓取
  14033. ///commandsName catchRemoteImage,catchremoteimageenable
  14034. ///commandsTitle 远程图片抓取
  14035. /**
  14036. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  14037. *
  14038. */
  14039. UE.plugins['catchremoteimage'] = function () {
  14040. if (this.options.catchRemoteImageEnable===false){
  14041. return;
  14042. }
  14043. var me = this;
  14044. this.setOpt({
  14045. localDomain:["127.0.0.1","localhost","img.baidu.com"],
  14046. separater:'ue_separate_ue',
  14047. catchFieldName:"upfile",
  14048. catchRemoteImageEnable:true
  14049. });
  14050. var ajax = UE.ajax,
  14051. localDomain = me.options.localDomain ,
  14052. catcherUrl = me.options.catcherUrl,
  14053. separater = me.options.separater;
  14054. function catchremoteimage(imgs, callbacks) {
  14055. var submitStr = imgs.join(separater);
  14056. var tmpOption = {
  14057. timeout:60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  14058. onsuccess:callbacks["success"],
  14059. onerror:callbacks["error"]
  14060. };
  14061. tmpOption[me.options.catchFieldName] = submitStr;
  14062. ajax.request(catcherUrl, tmpOption);
  14063. }
  14064. me.addListener("afterpaste", function () {
  14065. me.fireEvent("catchRemoteImage");
  14066. });
  14067. me.addListener("catchRemoteImage", function () {
  14068. var remoteImages = [];
  14069. var imgs = domUtils.getElementsByTagName(me.document, "img");
  14070. var test = function (src,urls) {
  14071. for (var j = 0, url; url = urls[j++];) {
  14072. if (src.indexOf(url) !== -1) {
  14073. return true;
  14074. }
  14075. }
  14076. return false;
  14077. };
  14078. for (var i = 0, ci; ci = imgs[i++];) {
  14079. if (ci.getAttribute("word_img")){
  14080. continue;
  14081. }
  14082. var src = ci.getAttribute("data_ue_src") || ci.src || "";
  14083. if (/^(https?|ftp):/i.test(src) && !test(src,localDomain)) {
  14084. remoteImages.push(src);
  14085. }
  14086. }
  14087. if (remoteImages.length) {
  14088. catchremoteimage(remoteImages, {
  14089. //成功抓取
  14090. success:function (xhr) {
  14091. try {
  14092. var info = eval("(" + xhr.responseText + ")");
  14093. } catch (e) {
  14094. return;
  14095. }
  14096. var srcUrls = info.srcUrl.split(separater),
  14097. urls = info.url.split(separater);
  14098. for (var i = 0, ci; ci = imgs[i++];) {
  14099. var src = ci.getAttribute("data_ue_src") || ci.src || "";
  14100. for (var j = 0, cj; cj = srcUrls[j++];) {
  14101. var url = urls[j - 1];
  14102. if (src == cj && url != "error") { //抓取失败时不做替换处理
  14103. //地址修正
  14104. var newSrc = me.options.catcherPath + url;
  14105. domUtils.setAttributes(ci, {
  14106. "src":newSrc,
  14107. "data_ue_src":newSrc
  14108. });
  14109. break;
  14110. }
  14111. }
  14112. }
  14113. me.fireEvent('catchremotesuccess')
  14114. },
  14115. //回调失败,本次请求超时
  14116. error:function () {
  14117. me.fireEvent("catchremoteerror");
  14118. }
  14119. });
  14120. }
  14121. });
  14122. };
  14123. ///import core
  14124. ///import plugins\inserthtml.js
  14125. ///import plugins\image.js
  14126. ///commandsName snapscreen
  14127. ///commandsTitle 截屏
  14128. /**
  14129. * 截屏插件
  14130. */
  14131. UE.plugins['snapscreen'] = function(){
  14132. var me = this,
  14133. doc,
  14134. snapplugin;
  14135. me.addListener("ready",function(){
  14136. var container = me.container;
  14137. doc = container.ownerDocument || container.document;
  14138. snapplugin = doc.createElement("object");
  14139. snapplugin.type = "application/x-pluginbaidusnap";
  14140. snapplugin.style.cssText = "position:absolute;left:-9999px;";
  14141. snapplugin.setAttribute("width","0");
  14142. snapplugin.setAttribute("height","0");
  14143. container.appendChild(snapplugin);
  14144. });
  14145. me.commands['snapscreen'] = {
  14146. execCommand: function(){
  14147. var me = this,lang = me.getLang("snapScreen_plugin");
  14148. me.setOpt({
  14149. snapscreenServerPort: 80 //屏幕截图的server端端口
  14150. ,snapscreenImgAlign: '' //截图的图片默认的排版方式
  14151. });
  14152. var editorOptions = me.options;
  14153. var onSuccess = function(rs){
  14154. try{
  14155. rs = eval("("+ rs +")");
  14156. }catch(e){
  14157. alert(lang.callBackErrorMsg);
  14158. return;
  14159. }
  14160. if(rs.state != 'SUCCESS'){
  14161. alert(rs.state);
  14162. return;
  14163. }
  14164. me.execCommand('insertimage', {
  14165. src: editorOptions.snapscreenPath + rs.url,
  14166. floatStyle: editorOptions.snapscreenImgAlign,
  14167. data_ue_src:editorOptions.snapscreenPath + rs.url
  14168. });
  14169. };
  14170. var onStartUpload = function(){
  14171. //开始截图上传
  14172. };
  14173. var onError = function(){
  14174. alert(lang.uploadErrorMsg);
  14175. };
  14176. try{
  14177. var ret =snapplugin.saveSnapshot(editorOptions.snapscreenHost, editorOptions.snapscreenServerUrl, editorOptions.snapscreenServerPort.toString());
  14178. onSuccess(ret);
  14179. }catch(e){
  14180. me.ui._dialogs['snapscreenDialog'].open();
  14181. }
  14182. },
  14183. queryCommandState: function(){
  14184. return this.highlight ? -1 :0;
  14185. }
  14186. };
  14187. }
  14188. ///import core
  14189. ///commands 插入空行
  14190. ///commandsName insertparagraph
  14191. ///commandsTitle 插入空行
  14192. /**
  14193. * 插入空行
  14194. * @function
  14195. * @name baidu.editor.execCommand
  14196. * @param {String} cmdName insertparagraph
  14197. */
  14198. UE.commands['insertparagraph'] = {
  14199. execCommand : function( cmdName,front) {
  14200. var me = this,
  14201. range = me.selection.getRange(),
  14202. start = range.startContainer,tmpNode;
  14203. while(start ){
  14204. if(domUtils.isBody(start)){
  14205. break;
  14206. }
  14207. tmpNode = start;
  14208. start = start.parentNode;
  14209. }
  14210. if(tmpNode){
  14211. var p = me.document.createElement('p');
  14212. if(front){
  14213. tmpNode.parentNode.insertBefore(p,tmpNode)
  14214. }else{
  14215. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  14216. }
  14217. domUtils.fillNode(me.document,p);
  14218. range.setStart(p,0).setCursor(false,true);
  14219. }
  14220. }
  14221. };
  14222. ///import core
  14223. ///import plugins/inserthtml.js
  14224. ///commands 百度应用
  14225. ///commandsName webapp
  14226. ///commandsTitle 百度应用
  14227. ///commandsDialog dialogs\webapp
  14228. UE.plugins['webapp'] = function () {
  14229. var me = this;
  14230. function createInsertStr( obj, toIframe, addParagraph ) {
  14231. return !toIframe ?
  14232. (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  14233. ' 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 + '" />' +
  14234. (addParagraph ? '</p>' : '')
  14235. :
  14236. '<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>';
  14237. }
  14238. function switchImgAndIframe( img2frame ) {
  14239. var tmpdiv,
  14240. nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  14241. for ( var i = 0, node; node = nodes[i++]; ) {
  14242. if ( node.className != "edui-faked-webapp" ){
  14243. continue;
  14244. }
  14245. tmpdiv = me.document.createElement( "div" );
  14246. 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 );
  14247. node.parentNode.replaceChild( tmpdiv.firstChild, node );
  14248. }
  14249. }
  14250. me.addListener( "beforegetcontent", function () {
  14251. switchImgAndIframe( true );
  14252. } );
  14253. me.addListener( 'aftersetcontent', function () {
  14254. switchImgAndIframe( false );
  14255. } );
  14256. me.addListener( 'aftergetcontent', function ( cmdName ) {
  14257. if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  14258. return;
  14259. }
  14260. switchImgAndIframe( false );
  14261. } );
  14262. me.commands['webapp'] = {
  14263. execCommand:function ( cmd, obj ) {
  14264. me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  14265. }
  14266. };
  14267. };
  14268. ///import core
  14269. ///import plugins\inserthtml.js
  14270. ///import plugins\cleardoc.js
  14271. ///commands 模板
  14272. ///commandsName template
  14273. ///commandsTitle 模板
  14274. ///commandsDialog dialogs\template
  14275. UE.plugins['template'] = function () {
  14276. UE.commands['template'] = {
  14277. execCommand:function (cmd, obj) {
  14278. obj.html && this.execCommand("inserthtml", obj.html);
  14279. }
  14280. };
  14281. this.addListener("click", function (type, evt) {
  14282. var el = evt.target || evt.srcElement,
  14283. range = this.selection.getRange();
  14284. var tnode = domUtils.findParent(el, function (node) {
  14285. if (node.className && domUtils.hasClass(node, "ue_t")) {
  14286. return node;
  14287. }
  14288. }, true);
  14289. tnode && range.selectNode(tnode).shrinkBoundary().select();
  14290. });
  14291. this.addListener("keydown", function (type, evt) {
  14292. var range = this.selection.getRange();
  14293. if (!range.collapsed) {
  14294. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  14295. var tnode = domUtils.findParent(range.startContainer, function (node) {
  14296. if (node.className && domUtils.hasClass(node, "ue_t")) {
  14297. return node;
  14298. }
  14299. }, true);
  14300. if (tnode) {
  14301. domUtils.removeClasses(tnode, ["ue_t"]);
  14302. }
  14303. }
  14304. }
  14305. });
  14306. };
  14307. ///import core
  14308. ///import plugins/inserthtml.js
  14309. ///commands 音乐
  14310. ///commandsName Music
  14311. ///commandsTitle 插入音乐
  14312. ///commandsDialog dialogs\music
  14313. UE.plugins['music'] = function () {
  14314. var me = this,
  14315. div;
  14316. /**
  14317. * 创建插入音乐字符窜
  14318. * @param url 音乐地址
  14319. * @param width 音乐宽度
  14320. * @param height 音乐高度
  14321. * @param align 阴雨对齐
  14322. * @param toEmbed 是否以flash代替显示
  14323. * @param addParagraph 是否需要添加P标签
  14324. */
  14325. function creatInsertStr(url,width,height,align,toEmbed,addParagraph){
  14326. return !toEmbed ?
  14327. (addParagraph? ('<p '+ (align !="none" ? ( align == "center"? ' style="text-align:center;" ':' style="float:"'+ align ) : '') + '>'): '') +
  14328. '<img align="'+align+'" width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  14329. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />' +
  14330. (addParagraph?'</p>':'')
  14331. :
  14332. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  14333. ' src="' + url + '" width="' + width + '" height="' + height + '" align="' + align + '"' +
  14334. ( align !="none" ? ' style= "'+ ( align == "center"? "display:block;":" float: "+ align ) + '"' :'' ) +
  14335. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  14336. }
  14337. function switchImgAndEmbed(img2embed) {
  14338. var tmpdiv,
  14339. nodes = domUtils.getElementsByTagName(me.document, !img2embed ? "embed" : "img");
  14340. for (var i = 0, node; node = nodes[i++];) {
  14341. if (node.className != "edui-faked-music") {
  14342. continue;
  14343. }
  14344. tmpdiv = me.document.createElement("div");
  14345. //先看float在看align,浮动有的是时候是在float上定义的
  14346. var align = domUtils.getComputedStyle(node,'float');
  14347. align = align == 'none' ? (node.getAttribute('align') || '') : align;
  14348. tmpdiv.innerHTML = creatInsertStr(img2embed ? node.getAttribute("_url") : node.getAttribute("src"), node.width, node.height, align, img2embed);
  14349. node.parentNode.replaceChild(tmpdiv.firstChild, node);
  14350. }
  14351. }
  14352. me.addListener("beforegetcontent", function () {
  14353. switchImgAndEmbed(true);
  14354. });
  14355. me.addListener('aftersetcontent', function () {
  14356. switchImgAndEmbed(false);
  14357. });
  14358. me.addListener('aftergetcontent', function (cmdName) {
  14359. if (cmdName == 'aftergetcontent' && me.queryCommandState('source')) {
  14360. return;
  14361. }
  14362. switchImgAndEmbed(false);
  14363. });
  14364. me.commands["music"] = {
  14365. execCommand:function (cmd, musicObj) {
  14366. var me = this,
  14367. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false, true);
  14368. me.execCommand("inserthtml",str);
  14369. },
  14370. queryCommandState:function () {
  14371. var me = this,
  14372. img = me.selection.getRange().getClosedNode(),
  14373. flag = img && (img.className == "edui-faked-music");
  14374. return flag ? 1 : 0;
  14375. }
  14376. };
  14377. };
  14378. var baidu = baidu || {};
  14379. baidu.editor = baidu.editor || {};
  14380. baidu.editor.ui = {};
  14381. (function (){
  14382. var browser = baidu.editor.browser,
  14383. domUtils = baidu.editor.dom.domUtils;
  14384. var magic = '$EDITORUI';
  14385. var root = window[magic] = {};
  14386. var uidMagic = 'ID' + magic;
  14387. var uidCount = 0;
  14388. var uiUtils = baidu.editor.ui.uiUtils = {
  14389. uid: function (obj){
  14390. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  14391. },
  14392. hook: function ( fn, callback ) {
  14393. var dg;
  14394. if (fn && fn._callbacks) {
  14395. dg = fn;
  14396. } else {
  14397. dg = function (){
  14398. var q;
  14399. if (fn) {
  14400. q = fn.apply(this, arguments);
  14401. }
  14402. var callbacks = dg._callbacks;
  14403. var k = callbacks.length;
  14404. while (k --) {
  14405. var r = callbacks[k].apply(this, arguments);
  14406. if (q === undefined) {
  14407. q = r;
  14408. }
  14409. }
  14410. return q;
  14411. };
  14412. dg._callbacks = [];
  14413. }
  14414. dg._callbacks.push(callback);
  14415. return dg;
  14416. },
  14417. createElementByHtml: function (html){
  14418. var el = document.createElement('div');
  14419. el.innerHTML = html;
  14420. el = el.firstChild;
  14421. el.parentNode.removeChild(el);
  14422. return el;
  14423. },
  14424. getViewportElement: function (){
  14425. return (browser.ie && browser.quirks) ?
  14426. document.body : document.documentElement;
  14427. },
  14428. getClientRect: function (element){
  14429. var bcr;
  14430. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  14431. try{
  14432. bcr = element.getBoundingClientRect();
  14433. }catch(e){
  14434. bcr={left:0,top:0,height:0,width:0}
  14435. }
  14436. var rect = {
  14437. left: Math.round(bcr.left),
  14438. top: Math.round(bcr.top),
  14439. height: Math.round(bcr.bottom - bcr.top),
  14440. width: Math.round(bcr.right - bcr.left)
  14441. };
  14442. var doc;
  14443. while ((doc = element.ownerDocument) !== document &&
  14444. (element = domUtils.getWindow(doc).frameElement)) {
  14445. bcr = element.getBoundingClientRect();
  14446. rect.left += bcr.left;
  14447. rect.top += bcr.top;
  14448. }
  14449. rect.bottom = rect.top + rect.height;
  14450. rect.right = rect.left + rect.width;
  14451. return rect;
  14452. },
  14453. getViewportRect: function (){
  14454. var viewportEl = uiUtils.getViewportElement();
  14455. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  14456. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  14457. return {
  14458. left: 0,
  14459. top: 0,
  14460. height: height,
  14461. width: width,
  14462. bottom: height,
  14463. right: width
  14464. };
  14465. },
  14466. setViewportOffset: function (element, offset){
  14467. var rect;
  14468. var fixedLayer = uiUtils.getFixedLayer();
  14469. if (element.parentNode === fixedLayer) {
  14470. element.style.left = offset.left + 'px';
  14471. element.style.top = offset.top + 'px';
  14472. } else {
  14473. domUtils.setViewportOffset(element, offset);
  14474. }
  14475. },
  14476. getEventOffset: function (evt){
  14477. var el = evt.target || evt.srcElement;
  14478. var rect = uiUtils.getClientRect(el);
  14479. var offset = uiUtils.getViewportOffsetByEvent(evt);
  14480. return {
  14481. left: offset.left - rect.left,
  14482. top: offset.top - rect.top
  14483. };
  14484. },
  14485. getViewportOffsetByEvent: function (evt){
  14486. var el = evt.target || evt.srcElement;
  14487. var frameEl = domUtils.getWindow(el).frameElement;
  14488. var offset = {
  14489. left: evt.clientX,
  14490. top: evt.clientY
  14491. };
  14492. if (frameEl && el.ownerDocument !== document) {
  14493. var rect = uiUtils.getClientRect(frameEl);
  14494. offset.left += rect.left;
  14495. offset.top += rect.top;
  14496. }
  14497. return offset;
  14498. },
  14499. setGlobal: function (id, obj){
  14500. root[id] = obj;
  14501. return magic + '["' + id + '"]';
  14502. },
  14503. unsetGlobal: function (id){
  14504. delete root[id];
  14505. },
  14506. copyAttributes: function (tgt, src){
  14507. var attributes = src.attributes;
  14508. var k = attributes.length;
  14509. while (k --) {
  14510. var attrNode = attributes[k];
  14511. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  14512. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  14513. }
  14514. }
  14515. if (src.className) {
  14516. domUtils.addClass(tgt,src.className);
  14517. }
  14518. if (src.style.cssText) {
  14519. tgt.style.cssText += ';' + src.style.cssText;
  14520. }
  14521. },
  14522. removeStyle: function (el, styleName){
  14523. if (el.style.removeProperty) {
  14524. el.style.removeProperty(styleName);
  14525. } else if (el.style.removeAttribute) {
  14526. el.style.removeAttribute(styleName);
  14527. } else throw '';
  14528. },
  14529. contains: function (elA, elB){
  14530. return elA && elB && (elA === elB ? false : (
  14531. elA.contains ? elA.contains(elB) :
  14532. elA.compareDocumentPosition(elB) & 16
  14533. ));
  14534. },
  14535. startDrag: function (evt, callbacks,doc){
  14536. var doc = doc || document;
  14537. var startX = evt.clientX;
  14538. var startY = evt.clientY;
  14539. function handleMouseMove(evt){
  14540. var x = evt.clientX - startX;
  14541. var y = evt.clientY - startY;
  14542. callbacks.ondragmove(x, y);
  14543. if (evt.stopPropagation) {
  14544. evt.stopPropagation();
  14545. } else {
  14546. evt.cancelBubble = true;
  14547. }
  14548. }
  14549. if (doc.addEventListener) {
  14550. function handleMouseUp(evt){
  14551. doc.removeEventListener('mousemove', handleMouseMove, true);
  14552. doc.removeEventListener('mouseup', handleMouseMove, true);
  14553. window.removeEventListener('mouseup', handleMouseUp, true);
  14554. callbacks.ondragstop();
  14555. }
  14556. doc.addEventListener('mousemove', handleMouseMove, true);
  14557. doc.addEventListener('mouseup', handleMouseUp, true);
  14558. window.addEventListener('mouseup', handleMouseUp, true);
  14559. evt.preventDefault();
  14560. } else {
  14561. var elm = evt.srcElement;
  14562. elm.setCapture();
  14563. function releaseCaptrue(){
  14564. elm.releaseCapture();
  14565. elm.detachEvent('onmousemove', handleMouseMove);
  14566. elm.detachEvent('onmouseup', releaseCaptrue);
  14567. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  14568. callbacks.ondragstop();
  14569. }
  14570. elm.attachEvent('onmousemove', handleMouseMove);
  14571. elm.attachEvent('onmouseup', releaseCaptrue);
  14572. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  14573. evt.returnValue = false;
  14574. }
  14575. callbacks.ondragstart();
  14576. },
  14577. getFixedLayer: function (){
  14578. var layer = document.getElementById('edui_fixedlayer');
  14579. if (layer == null) {
  14580. layer = document.createElement('div');
  14581. layer.id = 'edui_fixedlayer';
  14582. document.body.appendChild(layer);
  14583. if (browser.ie && browser.version <= 8) {
  14584. layer.style.position = 'absolute';
  14585. bindFixedLayer();
  14586. setTimeout(updateFixedOffset);
  14587. } else {
  14588. layer.style.position = 'fixed';
  14589. }
  14590. layer.style.left = '0';
  14591. layer.style.top = '0';
  14592. layer.style.width = '0';
  14593. layer.style.height = '0';
  14594. }
  14595. return layer;
  14596. },
  14597. makeUnselectable: function (element){
  14598. if (browser.opera || (browser.ie && browser.version < 9)) {
  14599. element.unselectable = 'on';
  14600. if (element.hasChildNodes()) {
  14601. for (var i=0; i<element.childNodes.length; i++) {
  14602. if (element.childNodes[i].nodeType == 1) {
  14603. uiUtils.makeUnselectable(element.childNodes[i]);
  14604. }
  14605. }
  14606. }
  14607. } else {
  14608. if (element.style.MozUserSelect !== undefined) {
  14609. element.style.MozUserSelect = 'none';
  14610. } else if (element.style.WebkitUserSelect !== undefined) {
  14611. element.style.WebkitUserSelect = 'none';
  14612. } else if (element.style.KhtmlUserSelect !== undefined) {
  14613. element.style.KhtmlUserSelect = 'none';
  14614. }
  14615. }
  14616. }
  14617. };
  14618. function updateFixedOffset(){
  14619. var layer = document.getElementById('edui_fixedlayer');
  14620. uiUtils.setViewportOffset(layer, {
  14621. left: 0,
  14622. top: 0
  14623. });
  14624. // layer.style.display = 'none';
  14625. // layer.style.display = 'block';
  14626. //#trace: 1354
  14627. // setTimeout(updateFixedOffset);
  14628. }
  14629. function bindFixedLayer(adjOffset){
  14630. domUtils.on(window, 'scroll', updateFixedOffset);
  14631. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  14632. }
  14633. })();
  14634. (function () {
  14635. var utils = baidu.editor.utils,
  14636. uiUtils = baidu.editor.ui.uiUtils,
  14637. EventBase = baidu.editor.EventBase,
  14638. UIBase = baidu.editor.ui.UIBase = function () {
  14639. };
  14640. UIBase.prototype = {
  14641. className:'',
  14642. uiName:'',
  14643. initOptions:function (options) {
  14644. var me = this;
  14645. for (var k in options) {
  14646. me[k] = options[k];
  14647. }
  14648. this.id = this.id || 'edui' + uiUtils.uid();
  14649. },
  14650. initUIBase:function () {
  14651. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  14652. },
  14653. render:function (holder) {
  14654. var html = this.renderHtml();
  14655. var el = uiUtils.createElementByHtml(html);
  14656. //by xuheng 给每个node添加class
  14657. var list = domUtils.getElementsByTagName(el, "*");
  14658. var theme = "edui-" + (this.theme || this.editor.options.theme);
  14659. var layer = document.getElementById('edui_fixedlayer');
  14660. for (var i = 0, node; node = list[i++];) {
  14661. domUtils.addClass(node, theme);
  14662. }
  14663. domUtils.addClass(el, theme);
  14664. if(layer){
  14665. layer.className="";
  14666. domUtils.addClass(layer,theme);
  14667. }
  14668. var seatEl = this.getDom();
  14669. if (seatEl != null) {
  14670. seatEl.parentNode.replaceChild(el, seatEl);
  14671. uiUtils.copyAttributes(el, seatEl);
  14672. } else {
  14673. if (typeof holder == 'string') {
  14674. holder = document.getElementById(holder);
  14675. }
  14676. holder = holder || uiUtils.getFixedLayer();
  14677. domUtils.addClass(holder, theme);
  14678. holder.appendChild(el);
  14679. }
  14680. this.postRender();
  14681. },
  14682. getDom:function (name) {
  14683. if (!name) {
  14684. return document.getElementById(this.id);
  14685. } else {
  14686. return document.getElementById(this.id + '_' + name);
  14687. }
  14688. },
  14689. postRender:function () {
  14690. this.fireEvent('postrender');
  14691. },
  14692. getHtmlTpl:function () {
  14693. return '';
  14694. },
  14695. formatHtml:function (tpl) {
  14696. var prefix = 'edui-' + this.uiName;
  14697. return (tpl
  14698. .replace(/##/g, this.id)
  14699. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  14700. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  14701. .replace(/\$\$/g, this._globalKey));
  14702. },
  14703. renderHtml:function () {
  14704. return this.formatHtml(this.getHtmlTpl());
  14705. },
  14706. dispose:function () {
  14707. var box = this.getDom();
  14708. if (box) baidu.editor.dom.domUtils.remove(box);
  14709. uiUtils.unsetGlobal(this.id);
  14710. }
  14711. };
  14712. utils.inherits(UIBase, EventBase);
  14713. })();
  14714. (function (){
  14715. var utils = baidu.editor.utils,
  14716. UIBase = baidu.editor.ui.UIBase,
  14717. Separator = baidu.editor.ui.Separator = function (options){
  14718. this.initOptions(options);
  14719. this.initSeparator();
  14720. };
  14721. Separator.prototype = {
  14722. uiName: 'separator',
  14723. initSeparator: function (){
  14724. this.initUIBase();
  14725. },
  14726. getHtmlTpl: function (){
  14727. return '<div id="##" class="edui-box %%"></div>';
  14728. }
  14729. };
  14730. utils.inherits(Separator, UIBase);
  14731. })();
  14732. ///import core
  14733. ///import uicore
  14734. (function (){
  14735. var utils = baidu.editor.utils,
  14736. domUtils = baidu.editor.dom.domUtils,
  14737. UIBase = baidu.editor.ui.UIBase,
  14738. uiUtils = baidu.editor.ui.uiUtils;
  14739. var Mask = baidu.editor.ui.Mask = function (options){
  14740. this.initOptions(options);
  14741. this.initUIBase();
  14742. };
  14743. Mask.prototype = {
  14744. getHtmlTpl: function (){
  14745. return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>';
  14746. },
  14747. postRender: function (){
  14748. var me = this;
  14749. domUtils.on(window, 'resize', function (){
  14750. setTimeout(function (){
  14751. if (!me.isHidden()) {
  14752. me._fill();
  14753. }
  14754. });
  14755. });
  14756. },
  14757. show: function (zIndex){
  14758. this._fill();
  14759. this.getDom().style.display = '';
  14760. this.getDom().style.zIndex = zIndex;
  14761. },
  14762. hide: function (){
  14763. this.getDom().style.display = 'none';
  14764. this.getDom().style.zIndex = '';
  14765. },
  14766. isHidden: function (){
  14767. return this.getDom().style.display == 'none';
  14768. },
  14769. _onMouseDown: function (){
  14770. return false;
  14771. },
  14772. _fill: function (){
  14773. var el = this.getDom();
  14774. var vpRect = uiUtils.getViewportRect();
  14775. el.style.width = vpRect.width + 'px';
  14776. el.style.height = vpRect.height + 'px';
  14777. }
  14778. };
  14779. utils.inherits(Mask, UIBase);
  14780. })();
  14781. ///import core
  14782. ///import uicore
  14783. (function () {
  14784. var utils = baidu.editor.utils,
  14785. uiUtils = baidu.editor.ui.uiUtils,
  14786. domUtils = baidu.editor.dom.domUtils,
  14787. UIBase = baidu.editor.ui.UIBase,
  14788. Popup = baidu.editor.ui.Popup = function (options){
  14789. this.initOptions(options);
  14790. this.initPopup();
  14791. };
  14792. var allPopups = [];
  14793. function closeAllPopup( evt,el ){
  14794. var newAll = [];
  14795. for ( var i = 0; i < allPopups.length; i++ ) {
  14796. var pop = allPopups[i];
  14797. if (!pop.isHidden()) {
  14798. if (pop.queryAutoHide(el) !== false) {
  14799. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  14800. pop.hide();
  14801. }
  14802. }
  14803. }
  14804. }
  14805. Popup.postHide = closeAllPopup;
  14806. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  14807. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  14808. Popup.prototype = {
  14809. SHADOW_RADIUS: 5,
  14810. content: null,
  14811. _hidden: false,
  14812. autoRender: true,
  14813. canSideLeft: true,
  14814. canSideUp: true,
  14815. initPopup: function (){
  14816. this.initUIBase();
  14817. allPopups.push( this );
  14818. },
  14819. getHtmlTpl: function (){
  14820. return '<div id="##" class="edui-popup %%">' +
  14821. ' <div id="##_body" class="edui-popup-body">' +
  14822. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="javascript:"></iframe>' +
  14823. ' <div class="edui-shadow"></div>' +
  14824. ' <div id="##_content" class="edui-popup-content">' +
  14825. this.getContentHtmlTpl() +
  14826. ' </div>' +
  14827. ' </div>' +
  14828. '</div>';
  14829. },
  14830. getContentHtmlTpl: function (){
  14831. if(this.content){
  14832. if (typeof this.content == 'string') {
  14833. return this.content;
  14834. }
  14835. return this.content.renderHtml();
  14836. }else{
  14837. return ''
  14838. }
  14839. },
  14840. _UIBase_postRender: UIBase.prototype.postRender,
  14841. postRender: function (){
  14842. if (this.content instanceof UIBase) {
  14843. this.content.postRender();
  14844. }
  14845. this.fireEvent('postRenderAfter');
  14846. this.hide(true);
  14847. this._UIBase_postRender();
  14848. },
  14849. _doAutoRender: function (){
  14850. if (!this.getDom() && this.autoRender) {
  14851. this.render();
  14852. }
  14853. },
  14854. mesureSize: function (){
  14855. var box = this.getDom('content');
  14856. return uiUtils.getClientRect(box);
  14857. },
  14858. fitSize: function (){
  14859. var popBodyEl = this.getDom('body');
  14860. popBodyEl.style.width = '';
  14861. popBodyEl.style.height = '';
  14862. var size = this.mesureSize();
  14863. popBodyEl.style.width = size.width + 'px';
  14864. popBodyEl.style.height = size.height + 'px';
  14865. return size;
  14866. },
  14867. showAnchor: function ( element, hoz ){
  14868. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  14869. },
  14870. showAnchorRect: function ( rect, hoz, adj ){
  14871. this._doAutoRender();
  14872. var vpRect = uiUtils.getViewportRect();
  14873. this._show();
  14874. var popSize = this.fitSize();
  14875. var sideLeft, sideUp, left, top;
  14876. if (hoz) {
  14877. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  14878. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  14879. left = (sideLeft ? rect.left - popSize.width : rect.right);
  14880. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  14881. } else {
  14882. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  14883. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  14884. left = (sideLeft ? rect.right - popSize.width : rect.left);
  14885. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  14886. }
  14887. var popEl = this.getDom();
  14888. uiUtils.setViewportOffset(popEl, {
  14889. left: left,
  14890. top: top
  14891. });
  14892. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  14893. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  14894. if(this.editor){
  14895. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  14896. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  14897. }
  14898. },
  14899. showAt: function (offset) {
  14900. var left = offset.left;
  14901. var top = offset.top;
  14902. var rect = {
  14903. left: left,
  14904. top: top,
  14905. right: left,
  14906. bottom: top,
  14907. height: 0,
  14908. width: 0
  14909. };
  14910. this.showAnchorRect(rect, false, true);
  14911. },
  14912. _show: function (){
  14913. if (this._hidden) {
  14914. var box = this.getDom();
  14915. box.style.display = '';
  14916. this._hidden = false;
  14917. // if (box.setActive) {
  14918. // box.setActive();
  14919. // }
  14920. this.fireEvent('show');
  14921. }
  14922. },
  14923. isHidden: function (){
  14924. return this._hidden;
  14925. },
  14926. show: function (){
  14927. this._doAutoRender();
  14928. this._show();
  14929. },
  14930. hide: function (notNofity){
  14931. if (!this._hidden && this.getDom()) {
  14932. // this.getDom().style.visibility = 'hidden';
  14933. this.getDom().style.display = 'none';
  14934. this._hidden = true;
  14935. if (!notNofity) {
  14936. this.fireEvent('hide');
  14937. }
  14938. }
  14939. },
  14940. queryAutoHide: function (el){
  14941. return !el || !uiUtils.contains(this.getDom(), el);
  14942. }
  14943. };
  14944. utils.inherits(Popup, UIBase);
  14945. domUtils.on( document, 'mousedown', function ( evt ) {
  14946. var el = evt.target || evt.srcElement;
  14947. closeAllPopup( evt,el );
  14948. } );
  14949. domUtils.on( window, 'scroll', function (evt,el) {
  14950. closeAllPopup( evt,el );
  14951. } );
  14952. // var lastVpRect = uiUtils.getViewportRect();
  14953. // domUtils.on( window, 'resize', function () {
  14954. // var vpRect = uiUtils.getViewportRect();
  14955. // if (vpRect.width != lastVpRect.width || vpRect.height != lastVpRect.height) {
  14956. // closeAllPopup();
  14957. // }
  14958. // } );
  14959. })();
  14960. ///import core
  14961. ///import uicore
  14962. (function (){
  14963. var utils = baidu.editor.utils,
  14964. UIBase = baidu.editor.ui.UIBase,
  14965. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  14966. this.initOptions(options);
  14967. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  14968. this.initUIBase();
  14969. };
  14970. ColorPicker.prototype = {
  14971. getHtmlTpl: function (){
  14972. return genColorPicker(this.noColorText,this.editor);
  14973. },
  14974. _onTableClick: function (evt){
  14975. var tgt = evt.target || evt.srcElement;
  14976. var color = tgt.getAttribute('data-color');
  14977. if (color) {
  14978. this.fireEvent('pickcolor', color);
  14979. }
  14980. },
  14981. _onTableOver: function (evt){
  14982. var tgt = evt.target || evt.srcElement;
  14983. var color = tgt.getAttribute('data-color');
  14984. if (color) {
  14985. this.getDom('preview').style.backgroundColor = color;
  14986. }
  14987. },
  14988. _onTableOut: function (){
  14989. this.getDom('preview').style.backgroundColor = '';
  14990. },
  14991. _onPickNoColor: function (){
  14992. this.fireEvent('picknocolor');
  14993. }
  14994. };
  14995. utils.inherits(ColorPicker, UIBase);
  14996. var COLORS = (
  14997. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  14998. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  14999. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  15000. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  15001. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  15002. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  15003. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  15004. function genColorPicker(noColorText,editor){
  15005. var html = '<div id="##" class="edui-colorpicker %%">' +
  15006. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  15007. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  15008. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  15009. '</div>' +
  15010. '<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">' +
  15011. '<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>'+
  15012. '<tr class="edui-colorpicker-tablefirstrow" >';
  15013. for (var i=0; i<COLORS.length; i++) {
  15014. if (i && i%10 === 0) {
  15015. 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"':'')+'>';
  15016. }
  15017. 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"' +
  15018. ' data-color="#'+ COLORS[i] +'"'+
  15019. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  15020. (i<10 || i>=60?'border-width:1px;':
  15021. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  15022. 'border-width:0 1px 0 1px;')+
  15023. '"' +
  15024. '></a></td>':'';
  15025. }
  15026. html += '</tr></table></div>';
  15027. return html;
  15028. }
  15029. })();
  15030. ///import core
  15031. ///import uicore
  15032. (function (){
  15033. var utils = baidu.editor.utils,
  15034. uiUtils = baidu.editor.ui.uiUtils,
  15035. UIBase = baidu.editor.ui.UIBase;
  15036. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  15037. this.initOptions(options);
  15038. this.initTablePicker();
  15039. };
  15040. TablePicker.prototype = {
  15041. defaultNumRows: 10,
  15042. defaultNumCols: 10,
  15043. maxNumRows: 20,
  15044. maxNumCols: 20,
  15045. numRows: 10,
  15046. numCols: 10,
  15047. lengthOfCellSide: 22,
  15048. initTablePicker: function (){
  15049. this.initUIBase();
  15050. },
  15051. getHtmlTpl: function (){
  15052. var me = this;
  15053. return '<div id="##" class="edui-tablepicker %%">' +
  15054. '<div class="edui-tablepicker-body">' +
  15055. '<div class="edui-infoarea">' +
  15056. '<span id="##_label" class="edui-label"></span>' +
  15057. '</div>' +
  15058. '<div class="edui-pickarea"' +
  15059. ' onmousemove="$$._onMouseMove(event, this);"' +
  15060. ' onmouseover="$$._onMouseOver(event, this);"' +
  15061. ' onmouseout="$$._onMouseOut(event, this);"' +
  15062. ' onclick="$$._onClick(event, this);"' +
  15063. '>' +
  15064. '<div id="##_overlay" class="edui-overlay"></div>' +
  15065. '</div>' +
  15066. '</div>' +
  15067. '</div>';
  15068. },
  15069. _UIBase_render: UIBase.prototype.render,
  15070. render: function (holder){
  15071. this._UIBase_render(holder);
  15072. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  15073. },
  15074. _track: function (numCols, numRows){
  15075. var style = this.getDom('overlay').style;
  15076. var sideLen = this.lengthOfCellSide;
  15077. style.width = numCols * sideLen + 'px';
  15078. style.height = numRows * sideLen + 'px';
  15079. var label = this.getDom('label');
  15080. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  15081. this.numCols = numCols;
  15082. this.numRows = numRows;
  15083. },
  15084. _onMouseOver: function (evt, el){
  15085. var rel = evt.relatedTarget || evt.fromElement;
  15086. if (!uiUtils.contains(el, rel) && el !== rel) {
  15087. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  15088. this.getDom('overlay').style.visibility = '';
  15089. }
  15090. },
  15091. _onMouseOut: function (evt, el){
  15092. var rel = evt.relatedTarget || evt.toElement;
  15093. if (!uiUtils.contains(el, rel) && el !== rel) {
  15094. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  15095. this.getDom('overlay').style.visibility = 'hidden';
  15096. }
  15097. },
  15098. _onMouseMove: function (evt, el){
  15099. var style = this.getDom('overlay').style;
  15100. var offset = uiUtils.getEventOffset(evt);
  15101. var sideLen = this.lengthOfCellSide;
  15102. var numCols = Math.ceil(offset.left / sideLen);
  15103. var numRows = Math.ceil(offset.top / sideLen);
  15104. this._track(numCols, numRows);
  15105. },
  15106. _onClick: function (){
  15107. this.fireEvent('picktable', this.numCols, this.numRows);
  15108. }
  15109. };
  15110. utils.inherits(TablePicker, UIBase);
  15111. })();
  15112. (function (){
  15113. var browser = baidu.editor.browser,
  15114. domUtils = baidu.editor.dom.domUtils,
  15115. uiUtils = baidu.editor.ui.uiUtils;
  15116. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  15117. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  15118. ( browser.ie ? (
  15119. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  15120. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  15121. : (
  15122. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  15123. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  15124. baidu.editor.ui.Stateful = {
  15125. alwalysHoverable: false,
  15126. target:null,//目标元素和this指向dom不一样
  15127. Stateful_init: function (){
  15128. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  15129. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  15130. },
  15131. Stateful_getHtmlTpl: function (){
  15132. var tpl = this._Stateful_dGetHtmlTpl();
  15133. // 使用function避免$转义
  15134. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  15135. },
  15136. Stateful_onMouseEnter: function (evt, el){
  15137. this.target=el;
  15138. if (!this.isDisabled() || this.alwalysHoverable) {
  15139. this.addState('hover');
  15140. this.fireEvent('over');
  15141. }
  15142. },
  15143. Stateful_onMouseLeave: function (evt, el){
  15144. if (!this.isDisabled() || this.alwalysHoverable) {
  15145. this.removeState('hover');
  15146. this.removeState('active');
  15147. this.fireEvent('out');
  15148. }
  15149. },
  15150. Stateful_onMouseOver: function (evt, el){
  15151. var rel = evt.relatedTarget;
  15152. if (!uiUtils.contains(el, rel) && el !== rel) {
  15153. this.Stateful_onMouseEnter(evt, el);
  15154. }
  15155. },
  15156. Stateful_onMouseOut: function (evt, el){
  15157. var rel = evt.relatedTarget;
  15158. if (!uiUtils.contains(el, rel) && el !== rel) {
  15159. this.Stateful_onMouseLeave(evt, el);
  15160. }
  15161. },
  15162. Stateful_onMouseDown: function (evt, el){
  15163. if (!this.isDisabled()) {
  15164. this.addState('active');
  15165. }
  15166. },
  15167. Stateful_onMouseUp: function (evt, el){
  15168. if (!this.isDisabled()) {
  15169. this.removeState('active');
  15170. }
  15171. },
  15172. Stateful_postRender: function (){
  15173. if (this.disabled && !this.hasState('disabled')) {
  15174. this.addState('disabled');
  15175. }
  15176. },
  15177. hasState: function (state){
  15178. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  15179. },
  15180. addState: function (state){
  15181. if (!this.hasState(state)) {
  15182. this.getStateDom().className += ' edui-state-' + state;
  15183. }
  15184. },
  15185. removeState: function (state){
  15186. if (this.hasState(state)) {
  15187. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  15188. }
  15189. },
  15190. getStateDom: function (){
  15191. return this.getDom('state');
  15192. },
  15193. isChecked: function (){
  15194. return this.hasState('checked');
  15195. },
  15196. setChecked: function (checked){
  15197. if (!this.isDisabled() && checked) {
  15198. this.addState('checked');
  15199. } else {
  15200. this.removeState('checked');
  15201. }
  15202. },
  15203. isDisabled: function (){
  15204. return this.hasState('disabled');
  15205. },
  15206. setDisabled: function (disabled){
  15207. if (disabled) {
  15208. this.removeState('hover');
  15209. this.removeState('checked');
  15210. this.removeState('active');
  15211. this.addState('disabled');
  15212. } else {
  15213. this.removeState('disabled');
  15214. }
  15215. }
  15216. };
  15217. })();
  15218. ///import core
  15219. ///import uicore
  15220. ///import ui/stateful.js
  15221. (function (){
  15222. var utils = baidu.editor.utils,
  15223. UIBase = baidu.editor.ui.UIBase,
  15224. Stateful = baidu.editor.ui.Stateful,
  15225. Button = baidu.editor.ui.Button = function (options){
  15226. this.initOptions(options);
  15227. this.initButton();
  15228. };
  15229. Button.prototype = {
  15230. uiName: 'button',
  15231. label: '',
  15232. title: '',
  15233. showIcon: true,
  15234. showText: true,
  15235. initButton: function (){
  15236. this.initUIBase();
  15237. this.Stateful_init();
  15238. },
  15239. getHtmlTpl: function (){
  15240. return '<div id="##" class="edui-box %%">' +
  15241. '<div id="##_state" stateful>' +
  15242. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  15243. ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' +
  15244. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  15245. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  15246. '</div>' +
  15247. '</div>' +
  15248. '</div></div>';
  15249. },
  15250. postRender: function (){
  15251. this.Stateful_postRender();
  15252. this.setDisabled(this.disabled)
  15253. },
  15254. _onClick: function (){
  15255. if (!this.isDisabled()) {
  15256. this.fireEvent('click');
  15257. }
  15258. }
  15259. };
  15260. utils.inherits(Button, UIBase);
  15261. utils.extend(Button.prototype, Stateful);
  15262. })();
  15263. ///import core
  15264. ///import uicore
  15265. ///import ui/stateful.js
  15266. (function (){
  15267. var utils = baidu.editor.utils,
  15268. uiUtils = baidu.editor.ui.uiUtils,
  15269. domUtils = baidu.editor.dom.domUtils,
  15270. UIBase = baidu.editor.ui.UIBase,
  15271. Stateful = baidu.editor.ui.Stateful,
  15272. SplitButton = baidu.editor.ui.SplitButton = function (options){
  15273. this.initOptions(options);
  15274. this.initSplitButton();
  15275. };
  15276. SplitButton.prototype = {
  15277. popup: null,
  15278. uiName: 'splitbutton',
  15279. title: '',
  15280. initSplitButton: function (){
  15281. this.initUIBase();
  15282. this.Stateful_init();
  15283. var me = this;
  15284. if (this.popup != null) {
  15285. var popup = this.popup;
  15286. this.popup = null;
  15287. this.setPopup(popup);
  15288. }
  15289. },
  15290. _UIBase_postRender: UIBase.prototype.postRender,
  15291. postRender: function (){
  15292. this.Stateful_postRender();
  15293. this._UIBase_postRender();
  15294. },
  15295. setPopup: function (popup){
  15296. if (this.popup === popup) return;
  15297. if (this.popup != null) {
  15298. this.popup.dispose();
  15299. }
  15300. popup.addListener('show', utils.bind(this._onPopupShow, this));
  15301. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  15302. popup.addListener('postrender', utils.bind(function (){
  15303. popup.getDom('body').appendChild(
  15304. uiUtils.createElementByHtml('<div id="' +
  15305. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  15306. (uiUtils.getClientRect(this.getDom()).width - 2) + 'px"></div>')
  15307. );
  15308. popup.getDom().className += ' ' + this.className;
  15309. }, this));
  15310. this.popup = popup;
  15311. },
  15312. _onPopupShow: function (){
  15313. this.addState('opened');
  15314. },
  15315. _onPopupHide: function (){
  15316. this.removeState('opened');
  15317. },
  15318. getHtmlTpl: function (){
  15319. return '<div id="##" class="edui-box %%">' +
  15320. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  15321. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  15322. '<div class="edui-box edui-icon"></div>' +
  15323. '</div>' +
  15324. '<div class="edui-box edui-splitborder"></div>' +
  15325. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  15326. '</div></div></div>';
  15327. },
  15328. showPopup: function (){
  15329. // 当popup往上弹出的时候,做特殊处理
  15330. var rect = uiUtils.getClientRect(this.getDom());
  15331. rect.top -= this.popup.SHADOW_RADIUS;
  15332. rect.height += this.popup.SHADOW_RADIUS;
  15333. this.popup.showAnchorRect(rect);
  15334. },
  15335. _onArrowClick: function (event, el){
  15336. if (!this.isDisabled()) {
  15337. this.showPopup();
  15338. }
  15339. },
  15340. _onButtonClick: function (){
  15341. if (!this.isDisabled()) {
  15342. this.fireEvent('buttonclick');
  15343. }
  15344. }
  15345. };
  15346. utils.inherits(SplitButton, UIBase);
  15347. utils.extend(SplitButton.prototype, Stateful, true);
  15348. })();
  15349. ///import core
  15350. ///import uicore
  15351. ///import ui/colorpicker.js
  15352. ///import ui/popup.js
  15353. ///import ui/splitbutton.js
  15354. (function (){
  15355. var utils = baidu.editor.utils,
  15356. uiUtils = baidu.editor.ui.uiUtils,
  15357. ColorPicker = baidu.editor.ui.ColorPicker,
  15358. Popup = baidu.editor.ui.Popup,
  15359. SplitButton = baidu.editor.ui.SplitButton,
  15360. ColorButton = baidu.editor.ui.ColorButton = function (options){
  15361. this.initOptions(options);
  15362. this.initColorButton();
  15363. };
  15364. ColorButton.prototype = {
  15365. initColorButton: function (){
  15366. var me = this;
  15367. this.popup = new Popup({
  15368. content: new ColorPicker({
  15369. noColorText: me.editor.getLang("clearColor"),
  15370. editor:me.editor,
  15371. onpickcolor: function (t, color){
  15372. me._onPickColor(color);
  15373. },
  15374. onpicknocolor: function (t, color){
  15375. me._onPickNoColor(color);
  15376. }
  15377. }),
  15378. editor:me.editor
  15379. });
  15380. this.initSplitButton();
  15381. },
  15382. _SplitButton_postRender: SplitButton.prototype.postRender,
  15383. postRender: function (){
  15384. this._SplitButton_postRender();
  15385. this.getDom('button_body').appendChild(
  15386. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  15387. );
  15388. this.getDom().className += ' edui-colorbutton';
  15389. },
  15390. setColor: function (color){
  15391. this.getDom('colorlump').style.backgroundColor = color;
  15392. this.color = color;
  15393. },
  15394. _onPickColor: function (color){
  15395. if (this.fireEvent('pickcolor', color) !== false) {
  15396. this.setColor(color);
  15397. this.popup.hide();
  15398. }
  15399. },
  15400. _onPickNoColor: function (color){
  15401. if (this.fireEvent('picknocolor') !== false) {
  15402. this.popup.hide();
  15403. }
  15404. }
  15405. };
  15406. utils.inherits(ColorButton, SplitButton);
  15407. })();
  15408. ///import core
  15409. ///import uicore
  15410. ///import ui/popup.js
  15411. ///import ui/tablepicker.js
  15412. ///import ui/splitbutton.js
  15413. (function (){
  15414. var utils = baidu.editor.utils,
  15415. Popup = baidu.editor.ui.Popup,
  15416. TablePicker = baidu.editor.ui.TablePicker,
  15417. SplitButton = baidu.editor.ui.SplitButton,
  15418. TableButton = baidu.editor.ui.TableButton = function (options){
  15419. this.initOptions(options);
  15420. this.initTableButton();
  15421. };
  15422. TableButton.prototype = {
  15423. initTableButton: function (){
  15424. var me = this;
  15425. this.popup = new Popup({
  15426. content: new TablePicker({
  15427. editor:me.editor,
  15428. onpicktable: function (t, numCols, numRows){
  15429. me._onPickTable(numCols, numRows);
  15430. }
  15431. }),
  15432. 'editor':me.editor
  15433. });
  15434. this.initSplitButton();
  15435. },
  15436. _onPickTable: function (numCols, numRows){
  15437. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  15438. this.popup.hide();
  15439. }
  15440. }
  15441. };
  15442. utils.inherits(TableButton, SplitButton);
  15443. })();
  15444. ///import core
  15445. ///import uicore
  15446. (function () {
  15447. var utils = baidu.editor.utils,
  15448. UIBase = baidu.editor.ui.UIBase;
  15449. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  15450. this.initOptions(options);
  15451. this.initAutoTypeSetPicker();
  15452. };
  15453. AutoTypeSetPicker.prototype = {
  15454. initAutoTypeSetPicker:function () {
  15455. this.initUIBase();
  15456. },
  15457. getHtmlTpl:function () {
  15458. var me = this.editor,
  15459. opt = me.options.autotypeset,
  15460. lang = me.getLang("autoTypeSet");
  15461. return '<div id="##" class="edui-autotypesetpicker %%">' +
  15462. '<div class="edui-autotypesetpicker-body">' +
  15463. '<table >' +
  15464. '<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>' +
  15465. '<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>' +
  15466. '<tr><td nowrap colspan="2"><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td><td colspan="2" id="textAlignValue"><input type="radio" name="textAlignValue" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="textAlignValue" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="textAlignValue" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + ' </tr>' +
  15467. '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  15468. '<td nowrap colspan="2" id="imageBlockLineValue">' +
  15469. '<input type="radio" name="imageBlockLineValue" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  15470. '<input type="radio" name="imageBlockLineValue" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  15471. '<input type="radio" name="imageBlockLineValue" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  15472. '<input type="radio" name="imageBlockLineValue" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' +
  15473. '<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>' +
  15474. '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  15475. '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  15476. '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' +
  15477. '</table>' +
  15478. '</div>' +
  15479. '</div>';
  15480. },
  15481. _UIBase_render:UIBase.prototype.render
  15482. };
  15483. utils.inherits(AutoTypeSetPicker, UIBase);
  15484. })();
  15485. ///import core
  15486. ///import uicore
  15487. ///import ui/popup.js
  15488. ///import ui/autotypesetpicker.js
  15489. ///import ui/splitbutton.js
  15490. (function (){
  15491. var utils = baidu.editor.utils,
  15492. Popup = baidu.editor.ui.Popup,
  15493. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  15494. SplitButton = baidu.editor.ui.SplitButton,
  15495. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  15496. this.initOptions(options);
  15497. this.initAutoTypeSetButton();
  15498. };
  15499. function getPara(me){
  15500. var opt = me.editor.options.autotypeset,
  15501. cont = me.getDom(),
  15502. ipts = domUtils.getElementsByTagName(cont,"input");
  15503. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  15504. if(ipt.getAttribute("type")=="checkbox"){
  15505. var attrName = ipt.getAttribute("name");
  15506. opt[attrName] && delete opt[attrName];
  15507. if(ipt.checked){
  15508. var attrValue = document.getElementById(attrName+"Value");
  15509. if(attrValue){
  15510. if(/input/ig.test(attrValue.tagName)){
  15511. opt[attrName] = attrValue.value;
  15512. }else{
  15513. var iptChilds = attrValue.getElementsByTagName("input");
  15514. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  15515. if(iptchild.checked){
  15516. opt[attrName] = iptchild.value;
  15517. break;
  15518. }
  15519. }
  15520. }
  15521. }else{
  15522. opt[attrName] = true;
  15523. }
  15524. }
  15525. }
  15526. }
  15527. var selects = domUtils.getElementsByTagName(cont,"select");
  15528. for(var i=0,si;si=selects[i++];){
  15529. var attr = si.getAttribute('name');
  15530. opt[attr] = opt[attr] ? si.value : '';
  15531. }
  15532. me.editor.options.autotypeset = opt;
  15533. }
  15534. AutoTypeSetButton.prototype = {
  15535. initAutoTypeSetButton: function (){
  15536. var me = this;
  15537. this.popup = new Popup({
  15538. //传入配置参数
  15539. content: new AutoTypeSetPicker({editor:me.editor}),
  15540. 'editor':me.editor,
  15541. hide : function(){
  15542. if (!this._hidden && this.getDom()) {
  15543. getPara(this);
  15544. this.getDom().style.display = 'none';
  15545. this._hidden = true;
  15546. this.fireEvent('hide');
  15547. }
  15548. }
  15549. });
  15550. var flag = 0;
  15551. this.popup.addListener('postRenderAfter',function(){
  15552. var popupUI = this;
  15553. if(flag)return;
  15554. var cont = this.getDom(),
  15555. btn = cont.getElementsByTagName('button')[0];
  15556. btn.onclick = function(){
  15557. getPara(popupUI);
  15558. me.editor.execCommand('autotypeset');
  15559. popupUI.hide()
  15560. };
  15561. flag = 1;
  15562. });
  15563. this.initSplitButton();
  15564. }
  15565. };
  15566. utils.inherits(AutoTypeSetButton, SplitButton);
  15567. })();
  15568. ///import core
  15569. ///import uicore
  15570. (function () {
  15571. var utils = baidu.editor.utils,
  15572. Popup = baidu.editor.ui.Popup,
  15573. Stateful = baidu.editor.ui.Stateful,
  15574. UIBase = baidu.editor.ui.UIBase;
  15575. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  15576. this.initOptions(options);
  15577. this.initCellAlignPicker();
  15578. };
  15579. CellAlignPicker.prototype = {
  15580. initCellAlignPicker:function () {
  15581. this.initUIBase();
  15582. this.Stateful_init();
  15583. },
  15584. getHtmlTpl:function () {
  15585. return '<div id="##" class="edui-cellalignpicker %%">' +
  15586. '<div class="edui-cellalignpicker-body">' +
  15587. '<table onclick="$$._onClick(event);">' +
  15588. '<tr><td index="0" stateful><div class="edui-icon edui-left"></div></td>' +
  15589. '<td index="1" stateful><div class="edui-icon edui-center"></div></td>' +
  15590. '<td index="2" stateful><div class="edui-icon edui-right"></div></td>' +
  15591. '</tr>' +
  15592. '<tr><td index="3" stateful><div class="edui-icon edui-left"></div></td>' +
  15593. '<td index="4" stateful><div class="edui-icon edui-center"></div></td>' +
  15594. '<td index="5" stateful><div class="edui-icon edui-right"></div></td>' +
  15595. '</tr>' +
  15596. '<tr><td index="6" stateful><div class="edui-icon edui-left"></div></td>' +
  15597. '<td index="7" stateful><div class="edui-icon edui-center"></div></td>' +
  15598. '<td index="8" stateful><div class="edui-icon edui-right"></div></td>' +
  15599. '</tr>' +
  15600. '</table>' +
  15601. '</div>' +
  15602. '</div>';
  15603. },
  15604. getStateDom: function (){
  15605. return this.target;
  15606. },
  15607. _onClick: function (evt){
  15608. var target= evt.target || evt.srcElement;
  15609. if(/icon/.test(target.className)){
  15610. this.items[target.parentNode.getAttribute("index")].onclick();
  15611. Popup.postHide(evt);
  15612. }
  15613. },
  15614. _UIBase_render:UIBase.prototype.render
  15615. };
  15616. utils.inherits(CellAlignPicker, UIBase);
  15617. utils.extend(CellAlignPicker.prototype, Stateful,true);
  15618. })();
  15619. ///import core
  15620. ///import uicore
  15621. (function () {
  15622. var utils = baidu.editor.utils,
  15623. Stateful = baidu.editor.ui.Stateful,
  15624. uiUtils = baidu.editor.ui.uiUtils,
  15625. UIBase = baidu.editor.ui.UIBase;
  15626. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  15627. this.initOptions(options);
  15628. this.initPastePicker();
  15629. };
  15630. PastePicker.prototype = {
  15631. initPastePicker:function () {
  15632. this.initUIBase();
  15633. this.Stateful_init();
  15634. },
  15635. getHtmlTpl:function () {
  15636. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  15637. '<div class="edui-pastecontainer">' +
  15638. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  15639. '<div class="edui-button">' +
  15640. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  15641. '<div class="edui-richtxticon"></div></div>' +
  15642. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  15643. '<div class="edui-tagicon"></div></div>' +
  15644. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  15645. '<div class="edui-plaintxticon"></div></div>' +
  15646. '</div>' +
  15647. '</div>' +
  15648. '</div>'
  15649. },
  15650. getStateDom:function () {
  15651. return this.target;
  15652. },
  15653. format:function (param) {
  15654. this.editor.ui._isTransfer = true;
  15655. this.editor.fireEvent('pasteTransfer', param);
  15656. },
  15657. _onClick:function (cur) {
  15658. var node = domUtils.getNextDomNode(cur),
  15659. screenHt = uiUtils.getViewportRect().height,
  15660. subPop = uiUtils.getClientRect(node);
  15661. if ((subPop.top + subPop.height) > screenHt)
  15662. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  15663. else
  15664. node.style.top = "";
  15665. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  15666. node.style.visibility = "visible";
  15667. domUtils.addClass(cur, "edui-state-opened");
  15668. } else {
  15669. node.style.visibility = "hidden";
  15670. domUtils.removeClasses(cur, "edui-state-opened")
  15671. }
  15672. },
  15673. _UIBase_render:UIBase.prototype.render
  15674. };
  15675. utils.inherits(PastePicker, UIBase);
  15676. utils.extend(PastePicker.prototype, Stateful, true);
  15677. })();
  15678. (function (){
  15679. var utils = baidu.editor.utils,
  15680. uiUtils = baidu.editor.ui.uiUtils,
  15681. UIBase = baidu.editor.ui.UIBase,
  15682. Toolbar = baidu.editor.ui.Toolbar = function (options){
  15683. this.initOptions(options);
  15684. this.initToolbar();
  15685. };
  15686. Toolbar.prototype = {
  15687. items: null,
  15688. initToolbar: function (){
  15689. this.items = this.items || [];
  15690. this.initUIBase();
  15691. },
  15692. add: function (item){
  15693. this.items.push(item);
  15694. },
  15695. getHtmlTpl: function (){
  15696. var buff = [];
  15697. for (var i=0; i<this.items.length; i++) {
  15698. buff[i] = this.items[i].renderHtml();
  15699. }
  15700. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  15701. buff.join('') +
  15702. '</div>'
  15703. },
  15704. postRender: function (){
  15705. var box = this.getDom();
  15706. for (var i=0; i<this.items.length; i++) {
  15707. this.items[i].postRender();
  15708. }
  15709. uiUtils.makeUnselectable(box);
  15710. },
  15711. _onMouseDown: function (){
  15712. return false;
  15713. }
  15714. };
  15715. utils.inherits(Toolbar, UIBase);
  15716. })();
  15717. ///import core
  15718. ///import uicore
  15719. ///import ui\popup.js
  15720. ///import ui\stateful.js
  15721. (function () {
  15722. var utils = baidu.editor.utils,
  15723. domUtils = baidu.editor.dom.domUtils,
  15724. uiUtils = baidu.editor.ui.uiUtils,
  15725. UIBase = baidu.editor.ui.UIBase,
  15726. Popup = baidu.editor.ui.Popup,
  15727. Stateful = baidu.editor.ui.Stateful,
  15728. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  15729. Menu = baidu.editor.ui.Menu = function (options) {
  15730. this.initOptions(options);
  15731. this.initMenu();
  15732. };
  15733. var menuSeparator = {
  15734. renderHtml:function () {
  15735. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  15736. },
  15737. postRender:function () {
  15738. },
  15739. queryAutoHide:function () {
  15740. return true;
  15741. }
  15742. };
  15743. Menu.prototype = {
  15744. items:null,
  15745. uiName:'menu',
  15746. initMenu:function () {
  15747. this.items = this.items || [];
  15748. this.initPopup();
  15749. this.initItems();
  15750. },
  15751. initItems:function () {
  15752. for (var i = 0; i < this.items.length; i++) {
  15753. var item = this.items[i];
  15754. if (item == '-') {
  15755. this.items[i] = this.getSeparator();
  15756. } else if (!(item instanceof MenuItem)) {
  15757. item.editor = this.editor;
  15758. item.theme = this.editor.options.theme;
  15759. this.items[i] = this.createItem(item);
  15760. }
  15761. }
  15762. },
  15763. getSeparator:function () {
  15764. return menuSeparator;
  15765. },
  15766. createItem:function (item) {
  15767. return new MenuItem(item);
  15768. },
  15769. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  15770. getContentHtmlTpl:function () {
  15771. if (this.items.length == 0) {
  15772. return this._Popup_getContentHtmlTpl();
  15773. }
  15774. var buff = [];
  15775. for (var i = 0; i < this.items.length; i++) {
  15776. var item = this.items[i];
  15777. buff[i] = item.renderHtml();
  15778. }
  15779. return ('<div class="%%-body">' + buff.join('') + '</div>');
  15780. },
  15781. _Popup_postRender:Popup.prototype.postRender,
  15782. postRender:function () {
  15783. var me = this;
  15784. for (var i = 0; i < this.items.length; i++) {
  15785. var item = this.items[i];
  15786. item.ownerMenu = this;
  15787. item.postRender();
  15788. }
  15789. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  15790. evt = evt || event;
  15791. var rel = evt.relatedTarget || evt.fromElement;
  15792. var el = me.getDom();
  15793. if (!uiUtils.contains(el, rel) && el !== rel) {
  15794. me.fireEvent('over');
  15795. }
  15796. });
  15797. this._Popup_postRender();
  15798. },
  15799. queryAutoHide:function (el) {
  15800. if (el) {
  15801. if (uiUtils.contains(this.getDom(), el)) {
  15802. return false;
  15803. }
  15804. for (var i = 0; i < this.items.length; i++) {
  15805. var item = this.items[i];
  15806. if (item.queryAutoHide(el) === false) {
  15807. return false;
  15808. }
  15809. }
  15810. }
  15811. },
  15812. clearItems:function () {
  15813. for (var i = 0; i < this.items.length; i++) {
  15814. var item = this.items[i];
  15815. clearTimeout(item._showingTimer);
  15816. clearTimeout(item._closingTimer);
  15817. if (item.subMenu) {
  15818. item.subMenu.destroy();
  15819. }
  15820. }
  15821. this.items = [];
  15822. },
  15823. destroy:function () {
  15824. if (this.getDom()) {
  15825. domUtils.remove(this.getDom());
  15826. }
  15827. this.clearItems();
  15828. },
  15829. dispose:function () {
  15830. this.destroy();
  15831. }
  15832. };
  15833. utils.inherits(Menu, Popup);
  15834. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  15835. this.initOptions(options);
  15836. this.initUIBase();
  15837. this.Stateful_init();
  15838. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  15839. if (options.className && options.className.indexOf("aligntd") != -1) {
  15840. var me = this;
  15841. this.subMenu = new Popup({
  15842. content:new CellAlignPicker(this.subMenu),
  15843. parentMenu:me,
  15844. editor:me.editor,
  15845. destroy:function () {
  15846. if (this.getDom()) {
  15847. domUtils.remove(this.getDom());
  15848. }
  15849. }
  15850. });
  15851. this.subMenu.addListener("postRenderAfter", function () {
  15852. domUtils.on(this.getDom(), "mouseover", function () {
  15853. me.addState('opened');
  15854. });
  15855. });
  15856. } else {
  15857. this.subMenu = new Menu(this.subMenu);
  15858. }
  15859. }
  15860. };
  15861. MenuItem.prototype = {
  15862. label:'',
  15863. subMenu:null,
  15864. ownerMenu:null,
  15865. uiName:'menuitem',
  15866. alwalysHoverable:true,
  15867. getHtmlTpl:function () {
  15868. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  15869. '<div class="%%-body">' +
  15870. this.renderLabelHtml() +
  15871. '</div>' +
  15872. '</div>';
  15873. },
  15874. postRender:function () {
  15875. var me = this;
  15876. this.addListener('over', function () {
  15877. me.ownerMenu.fireEvent('submenuover', me);
  15878. if (me.subMenu) {
  15879. me.delayShowSubMenu();
  15880. }
  15881. });
  15882. if (this.subMenu) {
  15883. this.getDom().className += ' edui-hassubmenu';
  15884. this.subMenu.render();
  15885. this.addListener('out', function () {
  15886. me.delayHideSubMenu();
  15887. });
  15888. this.subMenu.addListener('over', function () {
  15889. clearTimeout(me._closingTimer);
  15890. me._closingTimer = null;
  15891. me.addState('opened');
  15892. });
  15893. this.ownerMenu.addListener('hide', function () {
  15894. me.hideSubMenu();
  15895. });
  15896. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  15897. if (subMenu !== me) {
  15898. me.delayHideSubMenu();
  15899. }
  15900. });
  15901. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  15902. this.subMenu.queryAutoHide = function (el) {
  15903. if (el && uiUtils.contains(me.getDom(), el)) {
  15904. return false;
  15905. }
  15906. return this._bakQueryAutoHide(el);
  15907. };
  15908. }
  15909. this.getDom().style.tabIndex = '-1';
  15910. uiUtils.makeUnselectable(this.getDom());
  15911. this.Stateful_postRender();
  15912. },
  15913. delayShowSubMenu:function () {
  15914. var me = this;
  15915. if (!me.isDisabled()) {
  15916. me.addState('opened');
  15917. clearTimeout(me._showingTimer);
  15918. clearTimeout(me._closingTimer);
  15919. me._closingTimer = null;
  15920. me._showingTimer = setTimeout(function () {
  15921. me.showSubMenu();
  15922. }, 250);
  15923. }
  15924. },
  15925. delayHideSubMenu:function () {
  15926. var me = this;
  15927. if (!me.isDisabled()) {
  15928. me.removeState('opened');
  15929. clearTimeout(me._showingTimer);
  15930. if (!me._closingTimer) {
  15931. me._closingTimer = setTimeout(function () {
  15932. if (!me.hasState('opened')) {
  15933. me.hideSubMenu();
  15934. }
  15935. me._closingTimer = null;
  15936. }, 400);
  15937. }
  15938. }
  15939. },
  15940. renderLabelHtml:function () {
  15941. return '<div class="edui-arrow"></div>' +
  15942. '<div class="edui-box edui-icon"></div>' +
  15943. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  15944. },
  15945. getStateDom:function () {
  15946. return this.getDom();
  15947. },
  15948. queryAutoHide:function (el) {
  15949. if (this.subMenu && this.hasState('opened')) {
  15950. return this.subMenu.queryAutoHide(el);
  15951. }
  15952. },
  15953. _onClick:function (event, this_) {
  15954. if (this.hasState('disabled')) return;
  15955. if (this.fireEvent('click', event, this_) !== false) {
  15956. if (this.subMenu) {
  15957. this.showSubMenu();
  15958. } else {
  15959. Popup.postHide(event);
  15960. }
  15961. }
  15962. },
  15963. showSubMenu:function () {
  15964. var rect = uiUtils.getClientRect(this.getDom());
  15965. rect.right -= 5;
  15966. rect.left += 2;
  15967. rect.width -= 7;
  15968. rect.top -= 4;
  15969. rect.bottom += 4;
  15970. rect.height += 8;
  15971. this.subMenu.showAnchorRect(rect, true, true);
  15972. },
  15973. hideSubMenu:function () {
  15974. this.subMenu.hide();
  15975. }
  15976. };
  15977. utils.inherits(MenuItem, UIBase);
  15978. utils.extend(MenuItem.prototype, Stateful, true);
  15979. })();
  15980. ///import core
  15981. ///import uicore
  15982. ///import ui/menu.js
  15983. ///import ui/splitbutton.js
  15984. (function (){
  15985. // todo: menu和item提成通用list
  15986. var utils = baidu.editor.utils,
  15987. uiUtils = baidu.editor.ui.uiUtils,
  15988. Menu = baidu.editor.ui.Menu,
  15989. SplitButton = baidu.editor.ui.SplitButton,
  15990. Combox = baidu.editor.ui.Combox = function (options){
  15991. this.initOptions(options);
  15992. this.initCombox();
  15993. };
  15994. Combox.prototype = {
  15995. uiName: 'combox',
  15996. initCombox: function (){
  15997. var me = this;
  15998. this.items = this.items || [];
  15999. for (var i=0; i<this.items.length; i++) {
  16000. var item = this.items[i];
  16001. item.uiName = 'listitem';
  16002. item.index = i;
  16003. item.onclick = function (){
  16004. me.selectByIndex(this.index);
  16005. };
  16006. }
  16007. this.popup = new Menu({
  16008. items: this.items,
  16009. uiName: 'list',
  16010. editor:this.editor
  16011. });
  16012. this.initSplitButton();
  16013. },
  16014. _SplitButton_postRender: SplitButton.prototype.postRender,
  16015. postRender: function (){
  16016. this._SplitButton_postRender();
  16017. this.setLabel(this.label || '');
  16018. this.setValue(this.initValue || '');
  16019. },
  16020. showPopup: function (){
  16021. var rect = uiUtils.getClientRect(this.getDom());
  16022. rect.top += 1;
  16023. rect.bottom -= 1;
  16024. rect.height -= 2;
  16025. this.popup.showAnchorRect(rect);
  16026. },
  16027. getValue: function (){
  16028. return this.value;
  16029. },
  16030. setValue: function (value){
  16031. var index = this.indexByValue(value);
  16032. if (index != -1) {
  16033. this.selectedIndex = index;
  16034. this.setLabel(this.items[index].label);
  16035. this.value = this.items[index].value;
  16036. } else {
  16037. this.selectedIndex = -1;
  16038. this.setLabel(this.getLabelForUnknowValue(value));
  16039. this.value = value;
  16040. }
  16041. },
  16042. setLabel: function (label){
  16043. this.getDom('button_body').innerHTML = label;
  16044. this.label = label;
  16045. },
  16046. getLabelForUnknowValue: function (value){
  16047. return value;
  16048. },
  16049. indexByValue: function (value){
  16050. for (var i=0; i<this.items.length; i++) {
  16051. if (value == this.items[i].value) {
  16052. return i;
  16053. }
  16054. }
  16055. return -1;
  16056. },
  16057. getItem: function (index){
  16058. return this.items[index];
  16059. },
  16060. selectByIndex: function (index){
  16061. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  16062. this.selectedIndex = index;
  16063. this.value = this.items[index].value;
  16064. this.setLabel(this.items[index].label);
  16065. }
  16066. }
  16067. };
  16068. utils.inherits(Combox, SplitButton);
  16069. })();
  16070. ///import core
  16071. ///import uicore
  16072. ///import ui/mask.js
  16073. ///import ui/button.js
  16074. (function (){
  16075. var utils = baidu.editor.utils,
  16076. domUtils = baidu.editor.dom.domUtils,
  16077. uiUtils = baidu.editor.ui.uiUtils,
  16078. Mask = baidu.editor.ui.Mask,
  16079. UIBase = baidu.editor.ui.UIBase,
  16080. Button = baidu.editor.ui.Button,
  16081. Dialog = baidu.editor.ui.Dialog = function (options){
  16082. this.initOptions(utils.extend({
  16083. autoReset: true,
  16084. draggable: true,
  16085. onok: function (){},
  16086. oncancel: function (){},
  16087. onclose: function (t, ok){
  16088. return ok ? this.onok() : this.oncancel();
  16089. }
  16090. },options));
  16091. this.initDialog();
  16092. };
  16093. var modalMask;
  16094. var dragMask;
  16095. Dialog.prototype = {
  16096. draggable: false,
  16097. uiName: 'dialog',
  16098. initDialog: function (){
  16099. var me = this,
  16100. theme=this.editor.options.theme;
  16101. this.initUIBase();
  16102. this.modalMask = (modalMask || (modalMask = new Mask({
  16103. className: 'edui-dialog-modalmask',
  16104. theme:theme
  16105. })));
  16106. this.dragMask = (dragMask || (dragMask = new Mask({
  16107. className: 'edui-dialog-dragmask',
  16108. theme:theme
  16109. })));
  16110. this.closeButton = new Button({
  16111. className: 'edui-dialog-closebutton',
  16112. title: me.closeDialog,
  16113. theme:theme,
  16114. onclick: function (){
  16115. me.close(false);
  16116. }
  16117. });
  16118. if (this.buttons) {
  16119. for (var i=0; i<this.buttons.length; i++) {
  16120. if (!(this.buttons[i] instanceof Button)) {
  16121. this.buttons[i] = new Button(this.buttons[i]);
  16122. }
  16123. }
  16124. }
  16125. },
  16126. fitSize: function (){
  16127. var popBodyEl = this.getDom('body');
  16128. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  16129. // uiUtils.removeStyle(popBodyEl, 'width');
  16130. // uiUtils.removeStyle(popBodyEl, 'height');
  16131. // }
  16132. var size = this.mesureSize();
  16133. popBodyEl.style.width = size.width + 'px';
  16134. popBodyEl.style.height = size.height + 'px';
  16135. return size;
  16136. },
  16137. safeSetOffset: function (offset){
  16138. var me = this;
  16139. var el = me.getDom();
  16140. var vpRect = uiUtils.getViewportRect();
  16141. var rect = uiUtils.getClientRect(el);
  16142. var left = offset.left;
  16143. if (left + rect.width > vpRect.right) {
  16144. left = vpRect.right - rect.width;
  16145. }
  16146. var top = offset.top;
  16147. if (top + rect.height > vpRect.bottom) {
  16148. top = vpRect.bottom - rect.height;
  16149. }
  16150. el.style.left = Math.max(left, 0) + 'px';
  16151. el.style.top = Math.max(top, 0) + 'px';
  16152. },
  16153. showAtCenter: function (){
  16154. this.getDom().style.display = '';
  16155. var vpRect = uiUtils.getViewportRect();
  16156. var popSize = this.fitSize();
  16157. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  16158. var left = vpRect.width / 2 - popSize.width / 2;
  16159. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  16160. var popEl = this.getDom();
  16161. this.safeSetOffset({
  16162. left: Math.max(left | 0, 0),
  16163. top: Math.max(top | 0, 0)
  16164. });
  16165. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  16166. popEl.className += ' edui-state-centered';
  16167. }
  16168. this._show();
  16169. },
  16170. getContentHtml: function (){
  16171. var contentHtml = '';
  16172. if (typeof this.content == 'string') {
  16173. contentHtml = this.content;
  16174. } else if (this.iframeUrl) {
  16175. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  16176. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  16177. }
  16178. return contentHtml;
  16179. },
  16180. getHtmlTpl: function (){
  16181. var footHtml = '';
  16182. if (this.buttons) {
  16183. var buff = [];
  16184. for (var i=0; i<this.buttons.length; i++) {
  16185. buff[i] = this.buttons[i].renderHtml();
  16186. }
  16187. footHtml = '<div class="%%-foot">' +
  16188. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  16189. '</div>';
  16190. }
  16191. return '<div id="##" class="%%"><div class="%%-wrap"><div id="##_body" class="%%-body">' +
  16192. '<div class="%%-shadow"></div>' +
  16193. '<div id="##_titlebar" class="%%-titlebar">' +
  16194. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  16195. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  16196. '</div>' +
  16197. this.closeButton.renderHtml() +
  16198. '</div>' +
  16199. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  16200. footHtml +
  16201. '</div></div></div>';
  16202. },
  16203. postRender: function (){
  16204. // todo: 保持居中/记住上次关闭位置选项
  16205. if (!this.modalMask.getDom()) {
  16206. this.modalMask.render();
  16207. this.modalMask.hide();
  16208. }
  16209. if (!this.dragMask.getDom()) {
  16210. this.dragMask.render();
  16211. this.dragMask.hide();
  16212. }
  16213. var me = this;
  16214. this.addListener('show', function (){
  16215. me.modalMask.show(this.getDom().style.zIndex - 2);
  16216. });
  16217. this.addListener('hide', function (){
  16218. me.modalMask.hide();
  16219. });
  16220. if (this.buttons) {
  16221. for (var i=0; i<this.buttons.length; i++) {
  16222. this.buttons[i].postRender();
  16223. }
  16224. }
  16225. domUtils.on(window, 'resize', function (){
  16226. setTimeout(function (){
  16227. if (!me.isHidden()) {
  16228. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  16229. }
  16230. });
  16231. });
  16232. this._hide();
  16233. },
  16234. mesureSize: function (){
  16235. var body = this.getDom('body');
  16236. var width = uiUtils.getClientRect(this.getDom('content')).width;
  16237. var dialogBodyStyle = body.style;
  16238. dialogBodyStyle.width = width;
  16239. return uiUtils.getClientRect(body);
  16240. },
  16241. _onTitlebarMouseDown: function (evt, el){
  16242. if (this.draggable) {
  16243. var rect;
  16244. var vpRect = uiUtils.getViewportRect();
  16245. var me = this;
  16246. uiUtils.startDrag(evt, {
  16247. ondragstart: function (){
  16248. rect = uiUtils.getClientRect(me.getDom());
  16249. me.getDom('contmask').style.visibility = 'visible';
  16250. me.dragMask.show(me.getDom().style.zIndex - 1);
  16251. },
  16252. ondragmove: function (x, y){
  16253. var left = rect.left + x;
  16254. var top = rect.top + y;
  16255. me.safeSetOffset({
  16256. left: left,
  16257. top: top
  16258. });
  16259. },
  16260. ondragstop: function (){
  16261. me.getDom('contmask').style.visibility = 'hidden';
  16262. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  16263. me.dragMask.hide();
  16264. }
  16265. });
  16266. }
  16267. },
  16268. reset: function (){
  16269. this.getDom('content').innerHTML = this.getContentHtml();
  16270. },
  16271. _show: function (){
  16272. if (this._hidden) {
  16273. this.getDom().style.display = '';
  16274. //要高过编辑器的zindxe
  16275. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  16276. this._hidden = false;
  16277. this.fireEvent('show');
  16278. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  16279. }
  16280. },
  16281. isHidden: function (){
  16282. return this._hidden;
  16283. },
  16284. _hide: function (){
  16285. if (!this._hidden) {
  16286. this.getDom().style.display = 'none';
  16287. this.getDom().style.zIndex = '';
  16288. this._hidden = true;
  16289. this.fireEvent('hide');
  16290. }
  16291. },
  16292. open: function (){
  16293. if (this.autoReset) {
  16294. //有可能还没有渲染
  16295. try{
  16296. this.reset();
  16297. }catch(e){
  16298. this.render();
  16299. this.open()
  16300. }
  16301. }
  16302. this.showAtCenter();
  16303. if (this.iframeUrl) {
  16304. try {
  16305. this.getDom('iframe').focus();
  16306. } catch(ex){}
  16307. }
  16308. },
  16309. _onCloseButtonClick: function (evt, el){
  16310. this.close(false);
  16311. },
  16312. close: function (ok){
  16313. if (this.fireEvent('close', ok) !== false) {
  16314. this._hide();
  16315. }
  16316. }
  16317. };
  16318. utils.inherits(Dialog, UIBase);
  16319. })();
  16320. ///import core
  16321. ///import uicore
  16322. ///import ui/menu.js
  16323. ///import ui/splitbutton.js
  16324. (function (){
  16325. var utils = baidu.editor.utils,
  16326. Menu = baidu.editor.ui.Menu,
  16327. SplitButton = baidu.editor.ui.SplitButton,
  16328. MenuButton = baidu.editor.ui.MenuButton = function (options){
  16329. this.initOptions(options);
  16330. this.initMenuButton();
  16331. };
  16332. MenuButton.prototype = {
  16333. initMenuButton: function (){
  16334. var me = this;
  16335. this.uiName = "menubutton";
  16336. this.popup = new Menu({
  16337. items: me.items,
  16338. className: me.className,
  16339. editor:me.editor
  16340. });
  16341. this.popup.addListener('show', function (){
  16342. var list = this;
  16343. for (var i=0; i<list.items.length; i++) {
  16344. list.items[i].removeState('checked');
  16345. if (list.items[i].value == me._value) {
  16346. list.items[i].addState('checked');
  16347. this.value = me._value;
  16348. }
  16349. }
  16350. });
  16351. this.initSplitButton();
  16352. },
  16353. setValue : function(value){
  16354. this._value = value;
  16355. }
  16356. };
  16357. utils.inherits(MenuButton, SplitButton);
  16358. })();
  16359. //ui跟编辑器的适配層
  16360. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  16361. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据editor_config中的toolbars找到相应的进行实例化
  16362. (function () {
  16363. var utils = baidu.editor.utils;
  16364. var editorui = baidu.editor.ui;
  16365. var _Dialog = editorui.Dialog;
  16366. editorui.buttons={};
  16367. editorui.Dialog = function (options) {
  16368. var dialog = new _Dialog(options);
  16369. dialog.addListener('hide', function () {
  16370. if (dialog.editor) {
  16371. var editor = dialog.editor;
  16372. try {
  16373. if (browser.gecko) {
  16374. var y = editor.window.scrollY,
  16375. x = editor.window.scrollX;
  16376. editor.body.focus();
  16377. editor.window.scrollTo(x, y);
  16378. } else {
  16379. editor.focus();
  16380. }
  16381. } catch (ex) {
  16382. }
  16383. }
  16384. });
  16385. return dialog;
  16386. };
  16387. var iframeUrlMap = {
  16388. 'anchor':'~/dialogs/anchor/anchor.html',
  16389. 'insertimage':'~/dialogs/image/image.html',
  16390. 'link':'~/dialogs/link/link.html',
  16391. 'spechars':'~/dialogs/spechars/spechars.html',
  16392. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  16393. 'map':'~/dialogs/map/map.html',
  16394. 'gmap':'~/dialogs/gmap/gmap.html',
  16395. 'insertvideo':'~/dialogs/video/video.html',
  16396. 'help':'~/dialogs/help/help.html',
  16397. 'highlightcode':'~/dialogs/highlightcode/highlightcode.html',
  16398. 'emotion':'~/dialogs/emotion/emotion.html',
  16399. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  16400. 'attachment':'~/dialogs/attachment/attachment.html',
  16401. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  16402. 'edittip':'~/dialogs/table/edittip.html',
  16403. 'edittable':'~/dialogs/table/edittable.html',
  16404. 'edittd':'~/dialogs/table/edittd.html',
  16405. 'webapp':'~/dialogs/webapp/webapp.html',
  16406. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  16407. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  16408. 'music':'~/dialogs/music/music.html',
  16409. 'template':'~/dialogs/template/template.html',
  16410. 'background':'~/dialogs/background/background.html'
  16411. };
  16412. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  16413. var btnCmds = ['undo', 'redo', 'formatmatch',
  16414. 'bold', 'italic', 'underline', 'touppercase', 'tolowercase',
  16415. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  16416. 'blockquote', 'pasteplain', 'pagebreak',
  16417. 'selectall', 'print', 'preview', 'horizontal', 'removeformat', 'time', 'date', 'unlink',
  16418. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  16419. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable'];
  16420. for (var i = 0, ci; ci = btnCmds[i++];) {
  16421. ci = ci.toLowerCase();
  16422. editorui[ci] = function (cmd) {
  16423. return function (editor) {
  16424. var ui = new editorui.Button({
  16425. className:'edui-for-' + cmd,
  16426. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  16427. onclick:function () {
  16428. editor.execCommand(cmd);
  16429. },
  16430. theme:editor.options.theme,
  16431. showText:false
  16432. });
  16433. editorui.buttons[cmd]=ui;
  16434. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  16435. var state = editor.queryCommandState(cmd);
  16436. if (state == -1) {
  16437. ui.setDisabled(true);
  16438. ui.setChecked(false);
  16439. } else {
  16440. if (!uiReady) {
  16441. ui.setDisabled(false);
  16442. ui.setChecked(state);
  16443. }
  16444. }
  16445. });
  16446. return ui;
  16447. };
  16448. }(ci);
  16449. }
  16450. //清除文档
  16451. editorui.cleardoc = function (editor) {
  16452. var ui = new editorui.Button({
  16453. className:'edui-for-cleardoc',
  16454. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  16455. theme:editor.options.theme,
  16456. onclick:function () {
  16457. if (confirm(editor.getLang("confirmClear"))) {
  16458. editor.execCommand('cleardoc');
  16459. }
  16460. }
  16461. });
  16462. editorui.buttons["cleardoc"]=ui;
  16463. editor.addListener('selectionchange', function () {
  16464. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  16465. });
  16466. return ui;
  16467. };
  16468. //排版,图片排版,文字方向
  16469. var typeset = {
  16470. 'justify':['left', 'right', 'center', 'justify'],
  16471. 'imagefloat':['none', 'left', 'center', 'right'],
  16472. 'directionality':['ltr', 'rtl']
  16473. };
  16474. for (var p in typeset) {
  16475. (function (cmd, val) {
  16476. for (var i = 0, ci; ci = val[i++];) {
  16477. (function (cmd2) {
  16478. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  16479. var ui = new editorui.Button({
  16480. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  16481. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  16482. theme:editor.options.theme,
  16483. onclick:function () {
  16484. editor.execCommand(cmd, cmd2);
  16485. }
  16486. });
  16487. editorui.buttons[cmd]=ui;
  16488. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  16489. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  16490. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  16491. });
  16492. return ui;
  16493. };
  16494. })(ci)
  16495. }
  16496. })(p, typeset[p])
  16497. }
  16498. //字体颜色和背景颜色
  16499. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  16500. editorui[ci] = function (cmd) {
  16501. return function (editor) {
  16502. var ui = new editorui.ColorButton({
  16503. className:'edui-for-' + cmd,
  16504. color:'default',
  16505. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  16506. editor:editor,
  16507. onpickcolor:function (t, color) {
  16508. editor.execCommand(cmd, color);
  16509. },
  16510. onpicknocolor:function () {
  16511. editor.execCommand(cmd, 'default');
  16512. this.setColor('transparent');
  16513. this.color = 'default';
  16514. },
  16515. onbuttonclick:function () {
  16516. editor.execCommand(cmd, this.color);
  16517. }
  16518. });
  16519. editorui.buttons[cmd]=ui;
  16520. editor.addListener('selectionchange', function () {
  16521. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  16522. });
  16523. return ui;
  16524. };
  16525. }(ci);
  16526. }
  16527. var dialogBtns = {
  16528. noOk:['searchreplace', 'help', 'spechars', 'webapp'],
  16529. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  16530. 'insertvideo', 'highlightcode', 'insertframe','edittip','edittable', 'edittd','scrawl', 'template','music', 'background']
  16531. };
  16532. for (var p in dialogBtns) {
  16533. (function (type, vals) {
  16534. for (var i = 0, ci; ci = vals[i++];) {
  16535. //todo opera下存在问题
  16536. if (browser.opera && ci === "searchreplace") {
  16537. continue;
  16538. }
  16539. (function (cmd) {
  16540. editorui[cmd] = function (editor, iframeUrl, title) {
  16541. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  16542. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  16543. var dialog;
  16544. //没有iframeUrl不创建dialog
  16545. if (iframeUrl) {
  16546. dialog = new editorui.Dialog(utils.extend({
  16547. iframeUrl:editor.ui.mapUrl(iframeUrl),
  16548. editor:editor,
  16549. className:'edui-for-' + cmd,
  16550. title:title,
  16551. closeDialog:editor.getLang("closeDialog")
  16552. }, type == 'ok' ? {
  16553. buttons:[
  16554. {
  16555. className:'edui-okbutton',
  16556. label:editor.getLang("ok"),
  16557. editor:editor,
  16558. onclick:function () {
  16559. dialog.close(true);
  16560. }
  16561. },
  16562. {
  16563. className:'edui-cancelbutton',
  16564. label:editor.getLang("cancel"),
  16565. editor:editor,
  16566. onclick:function () {
  16567. dialog.close(false);
  16568. }
  16569. }
  16570. ]
  16571. } : {}));
  16572. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  16573. }
  16574. var ui = new editorui.Button({
  16575. className:'edui-for-' + cmd,
  16576. title:title,
  16577. onclick:function () {
  16578. if (dialog) {
  16579. switch (cmd) {
  16580. case "wordimage":
  16581. editor.execCommand("wordimage", "word_img");
  16582. if (editor.word_img) {
  16583. dialog.render();
  16584. dialog.open();
  16585. }
  16586. break;
  16587. case "scrawl":
  16588. if (editor.queryCommandState("scrawl") != -1) {
  16589. dialog.render();
  16590. dialog.open();
  16591. }
  16592. break;
  16593. default:
  16594. dialog.render();
  16595. dialog.open();
  16596. }
  16597. }
  16598. },
  16599. theme:editor.options.theme,
  16600. disabled:cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1
  16601. });
  16602. editorui.buttons[cmd]=ui;
  16603. editor.addListener('selectionchange', function () {
  16604. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  16605. var unNeedCheckState = {'edittable':1};
  16606. if (cmd in unNeedCheckState)return;
  16607. var state = editor.queryCommandState(cmd);
  16608. if (ui.getDom()) {
  16609. ui.setDisabled(state == -1);
  16610. ui.setChecked(state);
  16611. }
  16612. });
  16613. return ui;
  16614. };
  16615. })(ci.toLowerCase())
  16616. }
  16617. })(p, dialogBtns[p])
  16618. }
  16619. editorui.snapscreen = function (editor, iframeUrl, title) {
  16620. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  16621. var ui = new editorui.Button({
  16622. className:'edui-for-snapscreen',
  16623. title:title,
  16624. onclick:function () {
  16625. editor.execCommand("snapscreen");
  16626. },
  16627. theme:editor.options.theme
  16628. });
  16629. editorui.buttons['snapscreen']=ui;
  16630. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  16631. if (iframeUrl) {
  16632. var dialog = new editorui.Dialog({
  16633. iframeUrl:editor.ui.mapUrl(iframeUrl),
  16634. editor:editor,
  16635. className:'edui-for-snapscreen',
  16636. title:title,
  16637. buttons:[
  16638. {
  16639. className:'edui-okbutton',
  16640. label:editor.getLang("ok"),
  16641. editor:editor,
  16642. onclick:function () {
  16643. dialog.close(true);
  16644. }
  16645. },
  16646. {
  16647. className:'edui-cancelbutton',
  16648. label:editor.getLang("cancel"),
  16649. editor:editor,
  16650. onclick:function () {
  16651. dialog.close(false);
  16652. }
  16653. }
  16654. ]
  16655. });
  16656. dialog.render();
  16657. editor.ui._dialogs["snapscreenDialog"] = dialog;
  16658. }
  16659. editor.addListener('selectionchange', function () {
  16660. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  16661. });
  16662. return ui;
  16663. };
  16664. editorui.fontfamily = function (editor, list, title) {
  16665. list = editor.options['fontfamily'] || [];
  16666. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  16667. if(!list.length) return;
  16668. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  16669. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  16670. (function (key, val) {
  16671. items.push({
  16672. label:key,
  16673. value:val,
  16674. theme:editor.options.theme,
  16675. renderLabelHtml:function () {
  16676. return '<div class="edui-label %%-label" style="font-family:' +
  16677. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  16678. }
  16679. });
  16680. })(ci.label || langLabel, ci.val)
  16681. }
  16682. var ui = new editorui.Combox({
  16683. editor:editor,
  16684. items:items,
  16685. onselect:function (t, index) {
  16686. editor.execCommand('FontFamily', this.items[index].value);
  16687. },
  16688. onbuttonclick:function () {
  16689. this.showPopup();
  16690. },
  16691. title:title,
  16692. initValue:title,
  16693. className:'edui-for-fontfamily',
  16694. indexByValue:function (value) {
  16695. if (value) {
  16696. for (var i = 0, ci; ci = this.items[i]; i++) {
  16697. if (ci.value.indexOf(value) != -1)
  16698. return i;
  16699. }
  16700. }
  16701. return -1;
  16702. }
  16703. });
  16704. editorui.buttons['fontfamily']=ui;
  16705. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  16706. if (!uiReady) {
  16707. var state = editor.queryCommandState('FontFamily');
  16708. if (state == -1) {
  16709. ui.setDisabled(true);
  16710. } else {
  16711. ui.setDisabled(false);
  16712. var value = editor.queryCommandValue('FontFamily');
  16713. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  16714. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  16715. ui.setValue(value);
  16716. }
  16717. }
  16718. });
  16719. return ui;
  16720. };
  16721. editorui.fontsize = function (editor, list, title) {
  16722. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  16723. list = list || editor.options['fontsize'] || [];
  16724. if(!list.length) return;
  16725. var items = [];
  16726. for (var i = 0; i < list.length; i++) {
  16727. var size = list[i] + 'px';
  16728. items.push({
  16729. label:size,
  16730. value:size,
  16731. theme:editor.options.theme,
  16732. renderLabelHtml:function () {
  16733. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  16734. this.value + '">' + (this.label || '') + '</div>';
  16735. }
  16736. });
  16737. }
  16738. var ui = new editorui.Combox({
  16739. editor:editor,
  16740. items:items,
  16741. title:title,
  16742. initValue:title,
  16743. onselect:function (t, index) {
  16744. editor.execCommand('FontSize', this.items[index].value);
  16745. },
  16746. onbuttonclick:function () {
  16747. this.showPopup();
  16748. },
  16749. className:'edui-for-fontsize'
  16750. });
  16751. editorui.buttons['fontsize']=ui;
  16752. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  16753. if (!uiReady) {
  16754. var state = editor.queryCommandState('FontSize');
  16755. if (state == -1) {
  16756. ui.setDisabled(true);
  16757. } else {
  16758. ui.setDisabled(false);
  16759. ui.setValue(editor.queryCommandValue('FontSize'));
  16760. }
  16761. }
  16762. });
  16763. return ui;
  16764. };
  16765. editorui.paragraph = function (editor, list, title) {
  16766. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  16767. list = editor.options['paragraph'] || [];
  16768. if(utils.isEmptyObject(list)) return;
  16769. var items = [];
  16770. for (var i in list) {
  16771. items.push({
  16772. value:i,
  16773. label:list[i] || editor.getLang("paragraph")[i],
  16774. theme:editor.options.theme,
  16775. renderLabelHtml:function () {
  16776. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  16777. }
  16778. })
  16779. }
  16780. var ui = new editorui.Combox({
  16781. editor:editor,
  16782. items:items,
  16783. title:title,
  16784. initValue:title,
  16785. className:'edui-for-paragraph',
  16786. onselect:function (t, index) {
  16787. editor.execCommand('Paragraph', this.items[index].value);
  16788. },
  16789. onbuttonclick:function () {
  16790. this.showPopup();
  16791. }
  16792. });
  16793. editorui.buttons['paragraph']=ui;
  16794. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  16795. if (!uiReady) {
  16796. var state = editor.queryCommandState('Paragraph');
  16797. if (state == -1) {
  16798. ui.setDisabled(true);
  16799. } else {
  16800. ui.setDisabled(false);
  16801. var value = editor.queryCommandValue('Paragraph');
  16802. var index = ui.indexByValue(value);
  16803. if (index != -1) {
  16804. ui.setValue(value);
  16805. } else {
  16806. ui.setValue(ui.initValue);
  16807. }
  16808. }
  16809. }
  16810. });
  16811. return ui;
  16812. };
  16813. //自定义标题
  16814. editorui.customstyle = function (editor) {
  16815. var list = editor.options['customstyle'] || [],
  16816. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  16817. if (!list.length)return;
  16818. var langCs = editor.getLang('customstyle');
  16819. for (var i = 0, items = [], t; t = list[i++];) {
  16820. (function (t) {
  16821. var ck = {};
  16822. ck.label = t.label ? t.label : langCs[t.name];
  16823. ck.style = t.style;
  16824. ck.className = t.className;
  16825. ck.tag = t.tag;
  16826. items.push({
  16827. label:ck.label,
  16828. value:ck,
  16829. theme:editor.options.theme,
  16830. renderLabelHtml:function () {
  16831. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  16832. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  16833. + '</div>';
  16834. }
  16835. });
  16836. })(t);
  16837. }
  16838. var ui = new editorui.Combox({
  16839. editor:editor,
  16840. items:items,
  16841. title:title,
  16842. initValue:title,
  16843. className:'edui-for-customstyle',
  16844. onselect:function (t, index) {
  16845. editor.execCommand('customstyle', this.items[index].value);
  16846. },
  16847. onbuttonclick:function () {
  16848. this.showPopup();
  16849. },
  16850. indexByValue:function (value) {
  16851. for (var i = 0, ti; ti = this.items[i++];) {
  16852. if (ti.label == value) {
  16853. return i - 1
  16854. }
  16855. }
  16856. return -1;
  16857. }
  16858. });
  16859. editorui.buttons['customstyle']=ui;
  16860. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  16861. if (!uiReady) {
  16862. var state = editor.queryCommandState('customstyle');
  16863. if (state == -1) {
  16864. ui.setDisabled(true);
  16865. } else {
  16866. ui.setDisabled(false);
  16867. var value = editor.queryCommandValue('customstyle');
  16868. var index = ui.indexByValue(value);
  16869. if (index != -1) {
  16870. ui.setValue(value);
  16871. } else {
  16872. ui.setValue(ui.initValue);
  16873. }
  16874. }
  16875. }
  16876. });
  16877. return ui;
  16878. };
  16879. editorui.inserttable = function (editor, iframeUrl, title) {
  16880. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  16881. var ui = new editorui.TableButton({
  16882. editor:editor,
  16883. title:title,
  16884. className:'edui-for-inserttable',
  16885. onpicktable:function (t, numCols, numRows) {
  16886. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  16887. },
  16888. onbuttonclick:function () {
  16889. this.showPopup();
  16890. }
  16891. });
  16892. editorui.buttons['inserttable']=ui;
  16893. editor.addListener('selectionchange', function () {
  16894. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  16895. });
  16896. return ui;
  16897. };
  16898. editorui.lineheight = function (editor) {
  16899. var val = editor.options.lineheight || [];
  16900. if(!val.length)return;
  16901. for (var i = 0, ci, items = []; ci = val[i++];) {
  16902. items.push({
  16903. //todo:写死了
  16904. label:ci,
  16905. value:ci,
  16906. theme:editor.options.theme,
  16907. onclick:function () {
  16908. editor.execCommand("lineheight", this.value);
  16909. }
  16910. })
  16911. }
  16912. var ui = new editorui.MenuButton({
  16913. editor:editor,
  16914. className:'edui-for-lineheight',
  16915. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  16916. items:items,
  16917. onbuttonclick:function () {
  16918. var value = editor.queryCommandValue('LineHeight') || this.value;
  16919. editor.execCommand("LineHeight", value);
  16920. }
  16921. });
  16922. editorui.buttons['lineheight']=ui;
  16923. editor.addListener('selectionchange', function () {
  16924. var state = editor.queryCommandState('LineHeight');
  16925. if (state == -1) {
  16926. ui.setDisabled(true);
  16927. } else {
  16928. ui.setDisabled(false);
  16929. var value = editor.queryCommandValue('LineHeight');
  16930. value && ui.setValue((value + '').replace(/cm/, ''));
  16931. ui.setChecked(state)
  16932. }
  16933. });
  16934. return ui;
  16935. };
  16936. var rowspacings = ['top', 'bottom'];
  16937. for (var r = 0, ri; ri = rowspacings[r++];) {
  16938. (function (cmd) {
  16939. editorui['rowspacing' + cmd] = function (editor) {
  16940. var val = editor.options['rowspacing' + cmd] || [];
  16941. if(!val.length) return null;
  16942. for (var i = 0, ci, items = []; ci = val[i++];) {
  16943. items.push({
  16944. label:ci,
  16945. value:ci,
  16946. theme:editor.options.theme,
  16947. onclick:function () {
  16948. editor.execCommand("rowspacing", this.value, cmd);
  16949. }
  16950. })
  16951. }
  16952. var ui = new editorui.MenuButton({
  16953. editor:editor,
  16954. className:'edui-for-rowspacing' + cmd,
  16955. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  16956. items:items,
  16957. onbuttonclick:function () {
  16958. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  16959. editor.execCommand("rowspacing", value, cmd);
  16960. }
  16961. });
  16962. editorui.buttons[cmd]=ui;
  16963. editor.addListener('selectionchange', function () {
  16964. var state = editor.queryCommandState('rowspacing', cmd);
  16965. if (state == -1) {
  16966. ui.setDisabled(true);
  16967. } else {
  16968. ui.setDisabled(false);
  16969. var value = editor.queryCommandValue('rowspacing', cmd);
  16970. value && ui.setValue((value + '').replace(/%/, ''));
  16971. ui.setChecked(state)
  16972. }
  16973. });
  16974. return ui;
  16975. }
  16976. })(ri)
  16977. }
  16978. //有序,无序列表
  16979. var lists = ['insertorderedlist', 'insertunorderedlist'];
  16980. for (var l = 0, cl; cl = lists[l++];) {
  16981. (function (cmd) {
  16982. editorui[cmd] = function (editor) {
  16983. var vals = editor.options[cmd],
  16984. _onMenuClick = function () {
  16985. editor.execCommand(cmd, this.value);
  16986. }, items = [];
  16987. for (var i in vals) {
  16988. items.push({
  16989. label:vals[i] || editor.getLang()[cmd][i] || "",
  16990. value:i,
  16991. theme:editor.options.theme,
  16992. onclick:_onMenuClick
  16993. })
  16994. }
  16995. var ui = new editorui.MenuButton({
  16996. editor:editor,
  16997. className:'edui-for-' + cmd,
  16998. title:editor.getLang("labelMap." + cmd) || '',
  16999. 'items':items,
  17000. onbuttonclick:function () {
  17001. var value = editor.queryCommandValue(cmd) || this.value;
  17002. editor.execCommand(cmd, value);
  17003. }
  17004. });
  17005. editorui.buttons[cmd]=ui;
  17006. editor.addListener('selectionchange', function () {
  17007. var state = editor.queryCommandState(cmd);
  17008. if (state == -1) {
  17009. ui.setDisabled(true);
  17010. } else {
  17011. ui.setDisabled(false);
  17012. var value = editor.queryCommandValue(cmd);
  17013. ui.setValue(value);
  17014. ui.setChecked(state)
  17015. }
  17016. });
  17017. return ui;
  17018. };
  17019. })(cl)
  17020. }
  17021. editorui.fullscreen = function (editor, title) {
  17022. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  17023. var ui = new editorui.Button({
  17024. className:'edui-for-fullscreen',
  17025. title:title,
  17026. theme:editor.options.theme,
  17027. onclick:function () {
  17028. if (editor.ui) {
  17029. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  17030. }
  17031. this.setChecked(editor.ui.isFullScreen());
  17032. }
  17033. });
  17034. editorui.buttons['fullscreen']=ui;
  17035. editor.addListener('selectionchange', function () {
  17036. var state = editor.queryCommandState('fullscreen');
  17037. ui.setDisabled(state == -1);
  17038. ui.setChecked(editor.ui.isFullScreen());
  17039. });
  17040. return ui;
  17041. };
  17042. // 表情
  17043. editorui.emotion = function (editor, iframeUrl) {
  17044. var ui = new editorui.MultiMenuPop({
  17045. title:editor.options.labelMap['emotion'] || editor.getLang("labelMap.emotion") || '',
  17046. editor:editor,
  17047. className:'edui-for-emotion',
  17048. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})['emotion'] || iframeUrlMap['emotion'])
  17049. });
  17050. editorui.buttons['emotion']=ui;
  17051. editor.addListener('selectionchange', function () {
  17052. ui.setDisabled(editor.queryCommandState('emotion') == -1)
  17053. });
  17054. return ui;
  17055. };
  17056. editorui.autotypeset = function (editor) {
  17057. var ui = new editorui.AutoTypeSetButton({
  17058. editor:editor,
  17059. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  17060. className:'edui-for-autotypeset',
  17061. onbuttonclick:function () {
  17062. editor.execCommand('autotypeset')
  17063. }
  17064. });
  17065. editorui.buttons['autotypeset']=ui;
  17066. editor.addListener('selectionchange', function () {
  17067. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  17068. });
  17069. return ui;
  17070. };
  17071. })();
  17072. ///import core
  17073. ///commands 全屏
  17074. ///commandsName FullScreen
  17075. ///commandsTitle 全屏
  17076. (function () {
  17077. var utils = baidu.editor.utils,
  17078. uiUtils = baidu.editor.ui.uiUtils,
  17079. UIBase = baidu.editor.ui.UIBase,
  17080. domUtils = baidu.editor.dom.domUtils;
  17081. var nodeStack = [];
  17082. function EditorUI(options) {
  17083. this.initOptions(options);
  17084. this.initEditorUI();
  17085. }
  17086. EditorUI.prototype = {
  17087. uiName:'editor',
  17088. initEditorUI:function () {
  17089. this.editor.ui = this;
  17090. this._dialogs = {};
  17091. this.initUIBase();
  17092. this._initToolbars();
  17093. var editor = this.editor,
  17094. me = this;
  17095. editor.addListener('ready', function () {
  17096. //提供getDialog方法
  17097. editor.getDialog = function (name) {
  17098. return editor.ui._dialogs[name + "Dialog"];
  17099. };
  17100. domUtils.on(editor.window, 'scroll', function (evt) {
  17101. baidu.editor.ui.Popup.postHide(evt);
  17102. });
  17103. //提供编辑器实时宽高(全屏时宽高不变化)
  17104. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  17105. //display bottom-bar label based on config
  17106. if (editor.options.elementPathEnabled) {
  17107. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  17108. }
  17109. if (editor.options.wordCount) {
  17110. function countFn() {
  17111. setCount(editor,me);
  17112. domUtils.un(editor.document, "click", arguments.callee);
  17113. }
  17114. domUtils.on(editor.document, "click", countFn);
  17115. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  17116. }
  17117. editor.ui._scale();
  17118. if (editor.options.scaleEnabled) {
  17119. if (editor.autoHeightEnabled) {
  17120. editor.disableAutoHeight();
  17121. }
  17122. me.enableScale();
  17123. } else {
  17124. me.disableScale();
  17125. }
  17126. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  17127. editor.ui.getDom('elementpath').style.display = "none";
  17128. editor.ui.getDom('wordcount').style.display = "none";
  17129. editor.ui.getDom('scale').style.display = "none";
  17130. }
  17131. if (!editor.selection.isFocus())return;
  17132. editor.fireEvent('selectionchange', false, true);
  17133. });
  17134. editor.addListener('mousedown', function (t, evt) {
  17135. var el = evt.target || evt.srcElement;
  17136. baidu.editor.ui.Popup.postHide(evt, el);
  17137. });
  17138. editor.addListener("delcells", function () {
  17139. if (UE.ui['edittip']) {
  17140. new UE.ui['edittip'](editor);
  17141. }
  17142. editor.getDialog('edittip').open();
  17143. });
  17144. var pastePop, isPaste = false, timer;
  17145. editor.addListener("afterpaste", function () {
  17146. if(editor.queryCommandState('pasteplain'))
  17147. return;
  17148. pastePop = new baidu.editor.ui.Popup({
  17149. content:new baidu.editor.ui.PastePicker({editor:editor}),
  17150. editor:editor,
  17151. className:'edui-wordpastepop'
  17152. });
  17153. pastePop.render();
  17154. isPaste = true;
  17155. });
  17156. editor.addListener("afterinserthtml", function () {
  17157. clearTimeout(timer);
  17158. timer = setTimeout(function () {
  17159. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  17160. var span = domUtils.createElement(editor.document, 'span', {
  17161. 'style':"line-height:0px;",
  17162. 'innerHTML':'\ufeff'
  17163. }),
  17164. range = editor.selection.getRange();
  17165. range.insertNode(span);
  17166. pastePop.showAnchor(span);
  17167. domUtils.remove(span);
  17168. delete editor.ui._isTransfer;
  17169. isPaste = false;
  17170. }
  17171. }, 200)
  17172. });
  17173. editor.addListener('contextmenu', function (t, evt) {
  17174. baidu.editor.ui.Popup.postHide(evt);
  17175. });
  17176. editor.addListener('keydown', function (t, evt) {
  17177. if (pastePop) pastePop.dispose(evt);
  17178. var keyCode = evt.keyCode || evt.which;
  17179. if(evt.altKey&&keyCode==90){
  17180. UE.ui.buttons['fullscreen'].onclick();
  17181. }
  17182. });
  17183. editor.addListener('wordcount', function (type) {
  17184. setCount(this,me);
  17185. });
  17186. function setCount(editor,ui) {
  17187. editor.setOpt({
  17188. wordCount:true,
  17189. maximumWords:10000,
  17190. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  17191. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  17192. });
  17193. var opt = editor.options,
  17194. max = opt.maximumWords,
  17195. msg = opt.wordCountMsg ,
  17196. errMsg = opt.wordOverFlowMsg,
  17197. countDom = ui.getDom('wordcount');
  17198. if (!opt.wordCount) {
  17199. return;
  17200. }
  17201. var count = editor.getContentLength(true);
  17202. if (count > max) {
  17203. countDom.innerHTML = errMsg;
  17204. editor.fireEvent("wordcountoverflow");
  17205. } else {
  17206. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  17207. }
  17208. }
  17209. editor.addListener('selectionchange', function () {
  17210. if (editor.options.elementPathEnabled) {
  17211. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  17212. }
  17213. if (editor.options.scaleEnabled) {
  17214. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  17215. }
  17216. });
  17217. var popup = new baidu.editor.ui.Popup({
  17218. editor:editor,
  17219. content:'',
  17220. className:'edui-bubble',
  17221. _onEditButtonClick:function () {
  17222. this.hide();
  17223. editor.ui._dialogs.linkDialog.open();
  17224. },
  17225. _onImgEditButtonClick:function (name) {
  17226. this.hide();
  17227. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  17228. },
  17229. _onImgSetFloat:function (value) {
  17230. this.hide();
  17231. editor.execCommand("imagefloat", value);
  17232. },
  17233. _setIframeAlign:function (value) {
  17234. var frame = popup.anchorEl;
  17235. var newFrame = frame.cloneNode(true);
  17236. switch (value) {
  17237. case -2:
  17238. newFrame.setAttribute("align", "");
  17239. break;
  17240. case -1:
  17241. newFrame.setAttribute("align", "left");
  17242. break;
  17243. case 1:
  17244. newFrame.setAttribute("align", "right");
  17245. break;
  17246. }
  17247. frame.parentNode.insertBefore(newFrame, frame);
  17248. domUtils.remove(frame);
  17249. popup.anchorEl = newFrame;
  17250. popup.showAnchor(popup.anchorEl);
  17251. },
  17252. _updateIframe:function () {
  17253. editor._iframe = popup.anchorEl;
  17254. editor.ui._dialogs.insertframeDialog.open();
  17255. popup.hide();
  17256. },
  17257. _onRemoveButtonClick:function (cmdName) {
  17258. editor.execCommand(cmdName);
  17259. this.hide();
  17260. },
  17261. queryAutoHide:function (el) {
  17262. if (el && el.ownerDocument == editor.document) {
  17263. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  17264. return el !== popup.anchorEl;
  17265. }
  17266. }
  17267. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  17268. }
  17269. });
  17270. popup.render();
  17271. if (editor.options.imagePopup) {
  17272. editor.addListener('mouseover', function (t, evt) {
  17273. evt = evt || window.event;
  17274. var el = evt.target || evt.srcElement;
  17275. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  17276. var html = popup.formatHtml(
  17277. '<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;' +
  17278. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  17279. if (html) {
  17280. popup.getDom('content').innerHTML = html;
  17281. popup.anchorEl = el;
  17282. popup.showAnchor(popup.anchorEl);
  17283. } else {
  17284. popup.hide();
  17285. }
  17286. }
  17287. });
  17288. editor.addListener('selectionchange', function (t, causeByUi) {
  17289. if (!causeByUi) return;
  17290. var html = '', str = "",
  17291. img = editor.selection.getRange().getClosedNode(),
  17292. dialogs = editor.ui._dialogs;
  17293. if (img && img.tagName == 'IMG') {
  17294. var dialogName = 'insertimageDialog';
  17295. if (img.className.indexOf("edui-faked-video") != -1) {
  17296. dialogName = "insertvideoDialog"
  17297. }
  17298. if (img.className.indexOf("edui-faked-webapp") != -1) {
  17299. dialogName = "webappDialog"
  17300. }
  17301. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  17302. dialogName = "mapDialog"
  17303. }
  17304. if (img.className.indexOf("edui-faked-music") != -1) {
  17305. dialogName = "musicDialog"
  17306. }
  17307. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  17308. dialogName = "gmapDialog"
  17309. }
  17310. if (img.getAttribute("anchorname")) {
  17311. dialogName = "anchorDialog";
  17312. html = popup.formatHtml(
  17313. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  17314. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  17315. }
  17316. if (img.getAttribute("word_img")) {
  17317. //todo 放到dialog去做查询
  17318. editor.word_img = [img.getAttribute("word_img")];
  17319. dialogName = "wordimageDialog"
  17320. }
  17321. if (!dialogs[dialogName]) {
  17322. return;
  17323. }
  17324. str = '<nobr>' + editor.getLang("property") + ': '+
  17325. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  17326. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  17327. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  17328. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  17329. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  17330. !html && (html = popup.formatHtml(str))
  17331. }
  17332. if (editor.ui._dialogs.linkDialog) {
  17333. var link = editor.queryCommandValue('link');
  17334. var url;
  17335. if (link && (url = (link.getAttribute('data_ue_src') || link.getAttribute('href', 2)))) {
  17336. var txt = url;
  17337. if (url.length > 30) {
  17338. txt = url.substring(0, 20) + "...";
  17339. }
  17340. if (html) {
  17341. html += '<div style="height:5px;"></div>'
  17342. }
  17343. html += popup.formatHtml(
  17344. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  17345. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  17346. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  17347. popup.showAnchor(link);
  17348. }
  17349. }
  17350. if (html) {
  17351. popup.getDom('content').innerHTML = html;
  17352. popup.anchorEl = img || link;
  17353. popup.showAnchor(popup.anchorEl);
  17354. } else {
  17355. popup.hide();
  17356. }
  17357. });
  17358. }
  17359. },
  17360. _initToolbars:function () {
  17361. var editor = this.editor;
  17362. var toolbars = this.toolbars || [];
  17363. var toolbarUis = [];
  17364. for (var i = 0; i < toolbars.length; i++) {
  17365. var toolbar = toolbars[i];
  17366. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  17367. for (var j = 0; j < toolbar.length; j++) {
  17368. var toolbarItem = toolbar[j];
  17369. var toolbarItemUi = null;
  17370. if (typeof toolbarItem == 'string') {
  17371. toolbarItem = toolbarItem.toLowerCase();
  17372. if (toolbarItem == '|') {
  17373. toolbarItem = 'Separator';
  17374. }
  17375. if (baidu.editor.ui[toolbarItem]) {
  17376. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  17377. }
  17378. //fullscreen这里单独处理一下,放到首行去
  17379. if (toolbarItem == 'fullscreen') {
  17380. if (toolbarUis && toolbarUis[0]) {
  17381. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  17382. } else {
  17383. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  17384. }
  17385. continue;
  17386. }
  17387. } else {
  17388. toolbarItemUi = toolbarItem;
  17389. }
  17390. if (toolbarItemUi && toolbarItemUi.id) {
  17391. toolbarUi.add(toolbarItemUi);
  17392. }
  17393. }
  17394. toolbarUis[i] = toolbarUi;
  17395. }
  17396. this.toolbars = toolbarUis;
  17397. },
  17398. getHtmlTpl:function () {
  17399. return '<div id="##" class="%%">' +
  17400. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  17401. (this.toolbars.length ?
  17402. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  17403. this.renderToolbarBoxHtml() +
  17404. '</div></div>' : '') +
  17405. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  17406. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  17407. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  17408. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  17409. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  17410. '</div>' +
  17411. '</div>' +
  17412. '<div id="##_iframeholder" class="%%-iframeholder"></div>' +
  17413. //modify wdcount by matao
  17414. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  17415. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  17416. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  17417. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  17418. '</tr></table></div>' +
  17419. '<div id="##_scalelayer"></div>' +
  17420. '</div>';
  17421. },
  17422. showWordImageDialog:function () {
  17423. this.editor.execCommand("wordimage", "word_img");
  17424. this._dialogs['wordimageDialog'].open();
  17425. },
  17426. renderToolbarBoxHtml:function () {
  17427. var buff = [];
  17428. for (var i = 0; i < this.toolbars.length; i++) {
  17429. buff.push(this.toolbars[i].renderHtml());
  17430. }
  17431. return buff.join('');
  17432. },
  17433. setFullScreen:function (fullscreen) {
  17434. var editor = this.editor,
  17435. container = editor.container.parentNode.parentNode;
  17436. if (this._fullscreen != fullscreen) {
  17437. this._fullscreen = fullscreen;
  17438. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  17439. if (baidu.editor.browser.gecko) {
  17440. var bk = editor.selection.getRange().createBookmark();
  17441. }
  17442. if (fullscreen) {
  17443. while (container.tagName != "BODY") {
  17444. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  17445. nodeStack.push(position);
  17446. container.style.position = "static";
  17447. container = container.parentNode;
  17448. }
  17449. this._bakHtmlOverflow = document.documentElement.style.overflow;
  17450. this._bakBodyOverflow = document.body.style.overflow;
  17451. this._bakAutoHeight = this.editor.autoHeightEnabled;
  17452. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  17453. if (this._bakAutoHeight) {
  17454. //当全屏时不能执行自动长高
  17455. editor.autoHeightEnabled = false;
  17456. this.editor.disableAutoHeight();
  17457. }
  17458. document.documentElement.style.overflow = 'hidden';
  17459. document.body.style.overflow = 'hidden';
  17460. this._bakCssText = this.getDom().style.cssText;
  17461. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  17462. this._updateFullScreen();
  17463. } else {
  17464. while (container.tagName != "BODY") {
  17465. container.style.position = nodeStack.shift();
  17466. container = container.parentNode;
  17467. }
  17468. this.getDom().style.cssText = this._bakCssText;
  17469. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  17470. if (this._bakAutoHeight) {
  17471. editor.autoHeightEnabled = true;
  17472. this.editor.enableAutoHeight();
  17473. }
  17474. document.documentElement.style.overflow = this._bakHtmlOverflow;
  17475. document.body.style.overflow = this._bakBodyOverflow;
  17476. window.scrollTo(0, this._bakScrollTop);
  17477. }
  17478. if (baidu.editor.browser.gecko) {
  17479. var input = document.createElement('input');
  17480. document.body.appendChild(input);
  17481. editor.body.contentEditable = false;
  17482. setTimeout(function () {
  17483. input.focus();
  17484. setTimeout(function () {
  17485. editor.body.contentEditable = true;
  17486. editor.selection.getRange().moveToBookmark(bk).select(true);
  17487. baidu.editor.dom.domUtils.remove(input);
  17488. fullscreen && window.scroll(0, 0);
  17489. }, 0)
  17490. }, 0)
  17491. }
  17492. this.editor.fireEvent('fullscreenchanged', fullscreen);
  17493. this.triggerLayout();
  17494. }
  17495. },
  17496. _updateFullScreen:function () {
  17497. if (this._fullscreen) {
  17498. var vpRect = uiUtils.getViewportRect();
  17499. 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);
  17500. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  17501. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0));
  17502. }
  17503. },
  17504. _updateElementPath:function () {
  17505. var bottom = this.getDom('elementpath'), list;
  17506. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  17507. var buff = [];
  17508. for (var i = 0, ci; ci = list[i]; i++) {
  17509. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  17510. }
  17511. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  17512. } else {
  17513. bottom.style.display = 'none'
  17514. }
  17515. },
  17516. disableElementPath:function () {
  17517. var bottom = this.getDom('elementpath');
  17518. bottom.innerHTML = '';
  17519. bottom.style.display = 'none';
  17520. this.elementPathEnabled = false;
  17521. },
  17522. enableElementPath:function () {
  17523. var bottom = this.getDom('elementpath');
  17524. bottom.style.display = '';
  17525. this.elementPathEnabled = true;
  17526. this._updateElementPath();
  17527. },
  17528. _scale:function () {
  17529. var doc = document,
  17530. editor = this.editor,
  17531. editorHolder = editor.container,
  17532. editorDocument = editor.document,
  17533. toolbarBox = this.getDom("toolbarbox"),
  17534. bottombar = this.getDom("bottombar"),
  17535. scale = this.getDom("scale"),
  17536. scalelayer = this.getDom("scalelayer");
  17537. var isMouseMove = false,
  17538. position = null,
  17539. minEditorHeight = 0,
  17540. minEditorWidth = editor.options.minFrameWidth,
  17541. pageX = 0,
  17542. pageY = 0,
  17543. scaleWidth = 0,
  17544. scaleHeight = 0;
  17545. function down() {
  17546. position = domUtils.getXY(editorHolder);
  17547. if (!minEditorHeight) {
  17548. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  17549. }
  17550. 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:"
  17551. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  17552. domUtils.on(doc, "mousemove", move);
  17553. domUtils.on(editorDocument, "mouseup", up);
  17554. domUtils.on(doc, "mouseup", up);
  17555. }
  17556. var me = this;
  17557. //by xuheng 全屏时关掉缩放
  17558. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  17559. if (fullScreen) {
  17560. me.disableScale();
  17561. } else {
  17562. if (me.editor.options.scaleEnabled) {
  17563. me.enableScale();
  17564. var tmpNode = me.editor.document.createElement('span');
  17565. me.editor.body.appendChild(tmpNode);
  17566. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  17567. domUtils.remove(tmpNode)
  17568. }
  17569. }
  17570. });
  17571. function move(event) {
  17572. clearSelection();
  17573. var e = event || window.event;
  17574. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  17575. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  17576. scaleWidth = pageX - position.x;
  17577. scaleHeight = pageY - position.y;
  17578. if (scaleWidth >= minEditorWidth) {
  17579. isMouseMove = true;
  17580. scalelayer.style.width = scaleWidth + 'px';
  17581. }
  17582. if (scaleHeight >= minEditorHeight) {
  17583. isMouseMove = true;
  17584. scalelayer.style.height = scaleHeight + "px";
  17585. }
  17586. }
  17587. function up() {
  17588. if (isMouseMove) {
  17589. isMouseMove = false;
  17590. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  17591. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  17592. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2);
  17593. }
  17594. if (scalelayer) {
  17595. scalelayer.style.display = "none";
  17596. }
  17597. clearSelection();
  17598. domUtils.un(doc, "mousemove", move);
  17599. domUtils.un(editorDocument, "mouseup", up);
  17600. domUtils.un(doc, "mouseup", up);
  17601. }
  17602. function clearSelection() {
  17603. if (browser.ie)
  17604. doc.selection.clear();
  17605. else
  17606. window.getSelection().removeAllRanges();
  17607. }
  17608. this.enableScale = function () {
  17609. //trace:2868
  17610. if (editor.queryCommandState("source") == 1) return;
  17611. scale.style.display = "";
  17612. this.scaleEnabled = true;
  17613. domUtils.on(scale, "mousedown", down);
  17614. };
  17615. this.disableScale = function () {
  17616. scale.style.display = "none";
  17617. this.scaleEnabled = false;
  17618. domUtils.un(scale, "mousedown", down);
  17619. };
  17620. },
  17621. isFullScreen:function () {
  17622. return this._fullscreen;
  17623. },
  17624. postRender:function () {
  17625. UIBase.prototype.postRender.call(this);
  17626. for (var i = 0; i < this.toolbars.length; i++) {
  17627. this.toolbars[i].postRender();
  17628. }
  17629. var me = this;
  17630. var timerId,
  17631. domUtils = baidu.editor.dom.domUtils,
  17632. updateFullScreenTime = function () {
  17633. clearTimeout(timerId);
  17634. timerId = setTimeout(function () {
  17635. me._updateFullScreen();
  17636. });
  17637. };
  17638. domUtils.on(window, 'resize', updateFullScreenTime);
  17639. me.addListener('destroy', function () {
  17640. domUtils.un(window, 'resize', updateFullScreenTime);
  17641. clearTimeout(timerId);
  17642. })
  17643. },
  17644. showToolbarMsg:function (msg, flag) {
  17645. this.getDom('toolbarmsg_label').innerHTML = msg;
  17646. this.getDom('toolbarmsg').style.display = '';
  17647. //
  17648. if (!flag) {
  17649. var w = this.getDom('upload_dialog');
  17650. w.style.display = 'none';
  17651. }
  17652. },
  17653. hideToolbarMsg:function () {
  17654. this.getDom('toolbarmsg').style.display = 'none';
  17655. },
  17656. mapUrl:function (url) {
  17657. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  17658. },
  17659. triggerLayout:function () {
  17660. var dom = this.getDom();
  17661. if (dom.style.zoom == '1') {
  17662. dom.style.zoom = '100%';
  17663. } else {
  17664. dom.style.zoom = '1';
  17665. }
  17666. }
  17667. };
  17668. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  17669. var instances = {};
  17670. UE.ui.Editor = function (options) {
  17671. var editor = new baidu.editor.Editor(options);
  17672. editor.options.editor = editor;
  17673. utils.loadFile(document, {
  17674. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  17675. tag:"link",
  17676. type:"text/css",
  17677. rel:"stylesheet"
  17678. });
  17679. var oldRender = editor.render;
  17680. editor.render = function (holder) {
  17681. if (holder.constructor === String) {
  17682. editor.key = holder;
  17683. instances[holder] = editor;
  17684. }
  17685. utils.domReady(function () {
  17686. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  17687. function renderUI() {
  17688. editor.setOpt({
  17689. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  17690. });
  17691. new EditorUI(editor.options);
  17692. if (holder) {
  17693. if (holder.constructor === String) {
  17694. holder = document.getElementById(holder);
  17695. }
  17696. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  17697. if (holder && /script|textarea/ig.test(holder.tagName)) {
  17698. var newDiv = document.createElement('div');
  17699. holder.parentNode.insertBefore(newDiv, holder);
  17700. var cont = holder.value || holder.innerHTML;
  17701. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  17702. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  17703. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  17704. .replace(/>[\n\r\t]+</g, '><');
  17705. holder.className && (newDiv.className = holder.className);
  17706. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  17707. if (/textarea/i.test(holder.tagName)) {
  17708. editor.textarea = holder;
  17709. editor.textarea.style.display = 'none';
  17710. } else {
  17711. holder.parentNode.removeChild(holder);
  17712. holder.id && (newDiv.id = holder.id);
  17713. }
  17714. holder = newDiv;
  17715. holder.innerHTML = '';
  17716. }
  17717. }
  17718. domUtils.addClass(holder, "edui-" + editor.options.theme);
  17719. editor.ui.render(holder);
  17720. var iframeholder = editor.ui.getDom('iframeholder');
  17721. //给实例添加一个编辑器的容器引用
  17722. editor.container = editor.ui.getDom();
  17723. var width = editor.options.initialFrameWidth;
  17724. if (!/%/g.test(width)) width += "px";
  17725. editor.container.style.cssText = "z-index:" + editor.options.zIndex + ";width:" + width;
  17726. oldRender.call(editor, iframeholder);
  17727. }
  17728. })
  17729. };
  17730. return editor;
  17731. };
  17732. /**
  17733. * @file
  17734. * @name UE
  17735. * @short UE
  17736. * @desc UEditor的顶部命名空间
  17737. */
  17738. /**
  17739. * @name getEditor
  17740. * @since 1.2.4+
  17741. * @grammar UE.getEditor(id,[opt]) => Editor实例
  17742. * @desc 提供一个全局的方法得到编辑器实例
  17743. *
  17744. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  17745. * * ''opt'' 编辑器的可选参数
  17746. * @example
  17747. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  17748. * this.setContent('hello')
  17749. * }});
  17750. * UE.getEditor('containerId'); //返回刚创建的实例
  17751. *
  17752. */
  17753. UE.getEditor = function (id, opt) {
  17754. var editor = instances[id];
  17755. if (!editor) {
  17756. editor = instances[id] = new UE.ui.Editor(opt);
  17757. editor.render(id);
  17758. }
  17759. return editor;
  17760. };
  17761. UE.delEditor = function (id) {
  17762. var editor;
  17763. if (editor = instances[id]) {
  17764. editor.key && editor.destroy();
  17765. delete instances[id]
  17766. }
  17767. }
  17768. })();
  17769. ///import core
  17770. ///import uicore
  17771. ///commands 表情
  17772. (function(){
  17773. var utils = baidu.editor.utils,
  17774. Popup = baidu.editor.ui.Popup,
  17775. SplitButton = baidu.editor.ui.SplitButton,
  17776. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  17777. this.initOptions(options);
  17778. this.initMultiMenu();
  17779. };
  17780. MultiMenuPop.prototype = {
  17781. initMultiMenu: function (){
  17782. var me = this;
  17783. this.popup = new Popup({
  17784. content: '',
  17785. editor : me.editor,
  17786. iframe_rendered: false,
  17787. onshow: function (){
  17788. if (!this.iframe_rendered) {
  17789. this.iframe_rendered = true;
  17790. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  17791. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  17792. }
  17793. }
  17794. // canSideUp:false,
  17795. // canSideLeft:false
  17796. });
  17797. this.onbuttonclick = function(){
  17798. this.showPopup();
  17799. };
  17800. this.initSplitButton();
  17801. }
  17802. };
  17803. utils.inherits(MultiMenuPop, SplitButton);
  17804. })();
  17805. })();