editor_all.js 821 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202
  1. (function(){
  2. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  3. var baidu = window.baidu || {};
  4. window.baidu = baidu;
  5. window.UE = baidu.editor = {};
  6. UE.plugins = {};
  7. UE.commands = {};
  8. UE.instants = {};
  9. UE.I18N = {};
  10. UE.version = "1.2.6.0";
  11. var dom = UE.dom = {};/**
  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. extend2:function (t) {
  228. var a = arguments;
  229. for (var i = 1; i < a.length; i++) {
  230. var x = a[i];
  231. for (var k in x) {
  232. if (!t.hasOwnProperty(k)) {
  233. t[k] = x[k];
  234. }
  235. }
  236. }
  237. return t;
  238. },
  239. /**
  240. * 模拟继承机制,subClass继承superClass
  241. * @name inherits
  242. * @grammar UE.utils.inherits(subClass,superClass) => subClass
  243. * @example
  244. * function SuperClass(){
  245. * this.name = "小李";
  246. * }
  247. * SuperClass.prototype = {
  248. * hello:function(str){
  249. * console.log(this.name + str);
  250. * }
  251. * }
  252. * function SubClass(){
  253. * this.name = "小张";
  254. * }
  255. * UE.utils.inherits(SubClass,SuperClass);
  256. * var sub = new SubClass();
  257. * sub.hello("早上好!"); ==> "小张早上好!"
  258. */
  259. inherits:function (subClass, superClass) {
  260. var oldP = subClass.prototype,
  261. newP = utils.makeInstance(superClass.prototype);
  262. utils.extend(newP, oldP, true);
  263. subClass.prototype = newP;
  264. return (newP.constructor = subClass);
  265. },
  266. /**
  267. * 用指定的context作为fn上下文,也就是this
  268. * @name bind
  269. * @grammar UE.utils.bind(fn,context) => fn
  270. */
  271. bind:function (fn, context) {
  272. return function () {
  273. return fn.apply(context, arguments);
  274. };
  275. },
  276. /**
  277. * 创建延迟delay执行的函数fn
  278. * @name defer
  279. * @grammar UE.utils.defer(fn,delay) =>fn //延迟delay毫秒执行fn,返回fn
  280. * @grammar UE.utils.defer(fn,delay,exclusion) =>fn //延迟delay毫秒执行fn,若exclusion为真,则互斥执行fn
  281. * @example
  282. * function test(){
  283. * console.log("延迟输出!");
  284. * }
  285. * //非互斥延迟执行
  286. * var testDefer = UE.utils.defer(test,1000);
  287. * testDefer(); => "延迟输出!";
  288. * testDefer(); => "延迟输出!";
  289. * //互斥延迟执行
  290. * var testDefer1 = UE.utils.defer(test,1000,true);
  291. * testDefer1(); => //本次不执行
  292. * testDefer1(); => "延迟输出!";
  293. */
  294. defer:function (fn, delay, exclusion) {
  295. var timerID;
  296. return function () {
  297. if (exclusion) {
  298. clearTimeout(timerID);
  299. }
  300. timerID = setTimeout(fn, delay);
  301. };
  302. },
  303. /**
  304. * 查找元素item在数组array中的索引, 若找不到返回-1
  305. * @name indexOf
  306. * @grammar UE.utils.indexOf(array,item) => index|-1 //默认从数组开头部开始搜索
  307. * @grammar UE.utils.indexOf(array,item,start) => index|-1 //start指定开始查找的位置
  308. */
  309. indexOf:function (array, item, start) {
  310. var index = -1;
  311. start = this.isNumber(start) ? start : 0;
  312. this.each(array, function (v, i) {
  313. if (i >= start && v === item) {
  314. index = i;
  315. return false;
  316. }
  317. });
  318. return index;
  319. },
  320. /**
  321. * 移除数组array中的元素item
  322. * @name removeItem
  323. * @grammar UE.utils.removeItem(array,item)
  324. */
  325. removeItem:function (array, item) {
  326. for (var i = 0, l = array.length; i < l; i++) {
  327. if (array[i] === item) {
  328. array.splice(i, 1);
  329. i--;
  330. }
  331. }
  332. },
  333. /**
  334. * 删除字符串str的首尾空格
  335. * @name trim
  336. * @grammar UE.utils.trim(str) => String
  337. */
  338. trim:function (str) {
  339. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  340. },
  341. /**
  342. * 将字符串list(以','分隔)或者数组list转成哈希对象
  343. * @name listToMap
  344. * @grammar UE.utils.listToMap(list) => Object //Object形如{test:1,br:1,textarea:1}
  345. */
  346. listToMap:function (list) {
  347. if (!list)return {};
  348. list = utils.isArray(list) ? list : list.split(',');
  349. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  350. obj[ci.toUpperCase()] = obj[ci] = 1;
  351. }
  352. return obj;
  353. },
  354. /**
  355. * 将str中的html符号转义,默认将转义''&<">''四个字符,可自定义reg来确定需要转义的字符
  356. * @name unhtml
  357. * @grammar UE.utils.unhtml(str); => String
  358. * @grammar UE.utils.unhtml(str,reg) => String
  359. * @example
  360. * var html = '<body>You say:"你好!Baidu & UEditor!"</body>';
  361. * UE.utils.unhtml(html); ==> &lt;body&gt;You say:&quot;你好!Baidu &amp; UEditor!&quot;&lt;/body&gt;
  362. * UE.utils.unhtml(html,/[<>]/g) ==> &lt;body&gt;You say:"你好!Baidu & UEditor!"&lt;/body&gt;
  363. */
  364. unhtml:function (str, reg) {
  365. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) {
  366. if (b) {
  367. return a;
  368. } else {
  369. return {
  370. '<':'&lt;',
  371. '&':'&amp;',
  372. '"':'&quot;',
  373. '>':'&gt;',
  374. "'":'&#39;'
  375. }[a]
  376. }
  377. }) : '';
  378. },
  379. /**
  380. * 将str中的转义字符还原成html字符
  381. * @name html
  382. * @grammar UE.utils.html(str) => String //详细参见<code><a href = '#unhtml'>unhtml</a></code>
  383. */
  384. html:function (str) {
  385. return str ? str.replace(/&((g|l|quo)t|amp|#39);/g, function (m) {
  386. return {
  387. '&lt;':'<',
  388. '&amp;':'&',
  389. '&quot;':'"',
  390. '&gt;':'>',
  391. '&#39;':"'"
  392. }[m]
  393. }) : '';
  394. },
  395. /**
  396. * 将css样式转换为驼峰的形式。如font-size => fontSize
  397. * @name cssStyleToDomStyle
  398. * @grammar UE.utils.cssStyleToDomStyle(cssName) => String
  399. */
  400. cssStyleToDomStyle:function () {
  401. var test = document.createElement('div').style,
  402. cache = {
  403. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  404. };
  405. return function (cssName) {
  406. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  407. return match.charAt(1).toUpperCase();
  408. }));
  409. };
  410. }(),
  411. /**
  412. * 动态加载文件到doc中,并依据obj来设置属性,加载成功后执行回调函数fn
  413. * @name loadFile
  414. * @grammar UE.utils.loadFile(doc,obj)
  415. * @grammar UE.utils.loadFile(doc,obj,fn)
  416. * @example
  417. * //指定加载到当前document中一个script文件,加载成功后执行function
  418. * utils.loadFile( document, {
  419. * src:"test.js",
  420. * tag:"script",
  421. * type:"text/javascript",
  422. * defer:"defer"
  423. * }, function () {
  424. * console.log('加载成功!')
  425. * });
  426. */
  427. loadFile:function () {
  428. var tmpList = [];
  429. function getItem(doc, obj) {
  430. try {
  431. for (var i = 0, ci; ci = tmpList[i++];) {
  432. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  433. return ci;
  434. }
  435. }
  436. } catch (e) {
  437. return null;
  438. }
  439. }
  440. return function (doc, obj, fn) {
  441. var item = getItem(doc, obj);
  442. if (item) {
  443. if (item.ready) {
  444. fn && fn();
  445. } else {
  446. item.funs.push(fn)
  447. }
  448. return;
  449. }
  450. tmpList.push({
  451. doc:doc,
  452. url:obj.src || obj.href,
  453. funs:[fn]
  454. });
  455. if (!doc.body) {
  456. var html = [];
  457. for (var p in obj) {
  458. if (p == 'tag')continue;
  459. html.push(p + '="' + obj[p] + '"')
  460. }
  461. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  462. return;
  463. }
  464. if (obj.id && doc.getElementById(obj.id)) {
  465. return;
  466. }
  467. var element = doc.createElement(obj.tag);
  468. delete obj.tag;
  469. for (var p in obj) {
  470. element.setAttribute(p, obj[p]);
  471. }
  472. element.onload = element.onreadystatechange = function () {
  473. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  474. item = getItem(doc, obj);
  475. if (item.funs.length > 0) {
  476. item.ready = 1;
  477. for (var fi; fi = item.funs.pop();) {
  478. fi();
  479. }
  480. }
  481. element.onload = element.onreadystatechange = null;
  482. }
  483. };
  484. element.onerror = function () {
  485. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  486. };
  487. doc.getElementsByTagName("head")[0].appendChild(element);
  488. }
  489. }(),
  490. /**
  491. * 判断obj对象是否为空
  492. * @name isEmptyObject
  493. * @grammar UE.utils.isEmptyObject(obj) => true|false
  494. * @example
  495. * UE.utils.isEmptyObject({}) ==>true
  496. * UE.utils.isEmptyObject([]) ==>true
  497. * UE.utils.isEmptyObject("") ==>true
  498. */
  499. isEmptyObject:function (obj) {
  500. if (obj == null) return true;
  501. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  502. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  503. return true;
  504. },
  505. /**
  506. * 统一将颜色值使用16进制形式表示
  507. * @name fixColor
  508. * @grammar UE.utils.fixColor(name,value) => value
  509. * @example
  510. * rgb(255,255,255) => "#ffffff"
  511. */
  512. fixColor:function (name, value) {
  513. if (/color/i.test(name) && /rgba?/.test(value)) {
  514. var array = value.split(",");
  515. if (array.length > 3)
  516. return "";
  517. value = "#";
  518. for (var i = 0, color; color = array[i++];) {
  519. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  520. value += color.length == 1 ? "0" + color : color;
  521. }
  522. value = value.toUpperCase();
  523. }
  524. return value;
  525. },
  526. /**
  527. * 只针对border,padding,margin做了处理,因为性能问题
  528. * @public
  529. * @function
  530. * @param {String} val style字符串
  531. */
  532. optCss:function (val) {
  533. var padding, margin, border;
  534. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  535. if (val.split(' ').length == 1) {
  536. switch (key) {
  537. case 'padding':
  538. !padding && (padding = {});
  539. padding[name] = val;
  540. return '';
  541. case 'margin':
  542. !margin && (margin = {});
  543. margin[name] = val;
  544. return '';
  545. case 'border':
  546. return val == 'initial' ? '' : str;
  547. }
  548. }
  549. return str;
  550. });
  551. function opt(obj, name) {
  552. if (!obj) {
  553. return '';
  554. }
  555. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  556. if (!t || !l || !b || !r) {
  557. for (var p in obj) {
  558. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  559. }
  560. } else {
  561. val += ';' + name + ':' +
  562. (t == b && b == l && l == r ? t :
  563. t == b && l == r ? (t + ' ' + l) :
  564. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  565. }
  566. return val;
  567. }
  568. val += opt(padding, 'padding') + opt(margin, 'margin');
  569. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  570. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  571. return b ? b + ";;" : ';'
  572. });
  573. },
  574. /**
  575. * 深度克隆对象,从source到target
  576. * @name clone
  577. * @grammar UE.utils.clone(source) => anthorObj 新的对象是完整的source的副本
  578. * @grammar UE.utils.clone(source,target) => target包含了source的所有内容,重名会覆盖
  579. */
  580. clone:function (source, target) {
  581. var tmp;
  582. target = target || {};
  583. for (var i in source) {
  584. if (source.hasOwnProperty(i)) {
  585. tmp = source[i];
  586. if (typeof tmp == 'object') {
  587. target[i] = utils.isArray(tmp) ? [] : {};
  588. utils.clone(source[i], target[i])
  589. } else {
  590. target[i] = tmp;
  591. }
  592. }
  593. }
  594. return target;
  595. },
  596. /**
  597. * 转换cm/pt到px
  598. * @name transUnitToPx
  599. * @grammar UE.utils.transUnitToPx('20pt') => '27px'
  600. * @grammar UE.utils.transUnitToPx('0pt') => '0'
  601. */
  602. transUnitToPx:function (val) {
  603. if (!/(pt|cm)/.test(val)) {
  604. return val
  605. }
  606. var unit;
  607. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  608. val = v;
  609. unit = u;
  610. });
  611. switch (unit) {
  612. case 'cm':
  613. val = parseFloat(val) * 25;
  614. break;
  615. case 'pt':
  616. val = Math.round(parseFloat(val) * 96 / 72);
  617. }
  618. return val + (val ? 'px' : '');
  619. },
  620. /**
  621. * DomReady方法,回调函数将在dom树ready完成后执行
  622. * @name domReady
  623. * @grammar UE.utils.domReady(fn) => fn //返回一个延迟执行的方法
  624. */
  625. domReady:function () {
  626. var fnArr = [];
  627. function doReady(doc) {
  628. //确保onready只执行一次
  629. doc.isReady = true;
  630. for (var ci; ci = fnArr.pop(); ci()) {
  631. }
  632. }
  633. return function (onready, win) {
  634. win = win || window;
  635. var doc = win.document;
  636. onready && fnArr.push(onready);
  637. if (doc.readyState === "complete") {
  638. doReady(doc);
  639. } else {
  640. doc.isReady && doReady(doc);
  641. if (browser.ie) {
  642. (function () {
  643. if (doc.isReady) return;
  644. try {
  645. doc.documentElement.doScroll("left");
  646. } catch (error) {
  647. setTimeout(arguments.callee, 0);
  648. return;
  649. }
  650. doReady(doc);
  651. })();
  652. win.attachEvent('onload', function () {
  653. doReady(doc)
  654. });
  655. } else {
  656. doc.addEventListener("DOMContentLoaded", function () {
  657. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  658. doReady(doc);
  659. }, false);
  660. win.addEventListener('load', function () {
  661. doReady(doc)
  662. }, false);
  663. }
  664. }
  665. }
  666. }(),
  667. /**
  668. * 动态添加css样式
  669. * @name cssRule
  670. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  671. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  672. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  673. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  674. */
  675. cssRule:browser.ie ? function (key, style, doc) {
  676. var indexList, index;
  677. doc = doc || document;
  678. if (doc.indexList) {
  679. indexList = doc.indexList;
  680. } else {
  681. indexList = doc.indexList = {};
  682. }
  683. var sheetStyle;
  684. if (!indexList[key]) {
  685. if (style === undefined) {
  686. return ''
  687. }
  688. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  689. indexList[key] = index;
  690. } else {
  691. sheetStyle = doc.styleSheets[indexList[key]];
  692. }
  693. if (style === undefined) {
  694. return sheetStyle.cssText
  695. }
  696. sheetStyle.cssText = style || ''
  697. } : function (key, style, doc) {
  698. doc = doc || document;
  699. var head = doc.getElementsByTagName('head')[0], node;
  700. if (!(node = doc.getElementById(key))) {
  701. if (style === undefined) {
  702. return ''
  703. }
  704. node = doc.createElement('style');
  705. node.id = key;
  706. head.appendChild(node)
  707. }
  708. if (style === undefined) {
  709. return node.innerHTML
  710. }
  711. if (style !== '') {
  712. node.innerHTML = style;
  713. } else {
  714. head.removeChild(node)
  715. }
  716. },
  717. sort:function(array,compareFn){
  718. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  719. for(var i= 0,len = array.length; i<len; i++){
  720. for(var j = i,length = array.length; j<length; j++){
  721. if(compareFn(array[i], array[j]) > 0){
  722. var t = array[i];
  723. array[i] = array[j];
  724. array[j] = t;
  725. }
  726. }
  727. }
  728. return array;
  729. }
  730. };
  731. /**
  732. * 判断str是否为字符串
  733. * @name isString
  734. * @grammar UE.utils.isString(str) => true|false
  735. */
  736. /**
  737. * 判断array是否为数组
  738. * @name isArray
  739. * @grammar UE.utils.isArray(obj) => true|false
  740. */
  741. /**
  742. * 判断obj对象是否为方法
  743. * @name isFunction
  744. * @grammar UE.utils.isFunction(obj) => true|false
  745. */
  746. /**
  747. * 判断obj对象是否为数字
  748. * @name isNumber
  749. * @grammar UE.utils.isNumber(obj) => true|false
  750. */
  751. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'], function (v) {
  752. UE.utils['is' + v] = function (obj) {
  753. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  754. }
  755. });
  756. /**
  757. * @file
  758. * @name UE.EventBase
  759. * @short EventBase
  760. * @import editor.js,core/utils.js
  761. * @desc UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  762. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  763. */
  764. var EventBase = UE.EventBase = function () {};
  765. EventBase.prototype = {
  766. /**
  767. * 注册事件监听器
  768. * @name addListener
  769. * @grammar editor.addListener(types,fn) //types为事件名称,多个可用空格分隔
  770. * @example
  771. * editor.addListener('selectionchange',function(){
  772. * console.log("选区已经变化!");
  773. * })
  774. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  775. * if(type == 'beforegetcontent'){
  776. * //do something
  777. * }else{
  778. * //do something
  779. * }
  780. * console.log(this.getContent) // this是注册的事件的编辑器实例
  781. * })
  782. */
  783. addListener:function (types, listener) {
  784. types = utils.trim(types).split(' ');
  785. for (var i = 0, ti; ti = types[i++];) {
  786. getListener(this, ti, true).push(listener);
  787. }
  788. },
  789. /**
  790. * 移除事件监听器
  791. * @name removeListener
  792. * @grammar editor.removeListener(types,fn) //types为事件名称,多个可用空格分隔
  793. * @example
  794. * //changeCallback为方法体
  795. * editor.removeListener("selectionchange",changeCallback);
  796. */
  797. removeListener:function (types, listener) {
  798. types = utils.trim(types).split(' ');
  799. for (var i = 0, ti; ti = types[i++];) {
  800. utils.removeItem(getListener(this, ti) || [], listener);
  801. }
  802. },
  803. /**
  804. * 触发事件
  805. * @name fireEvent
  806. * @grammar editor.fireEvent(types) //types为事件名称,多个可用空格分隔
  807. * @example
  808. * editor.fireEvent("selectionchange");
  809. */
  810. fireEvent:function () {
  811. var types = arguments[0];
  812. types = utils.trim(types).split(' ');
  813. for (var i = 0, ti; ti = types[i++];) {
  814. var listeners = getListener(this, ti),
  815. r, t, k;
  816. if (listeners) {
  817. k = listeners.length;
  818. while (k--) {
  819. if(!listeners[k])continue;
  820. t = listeners[k].apply(this, arguments);
  821. if(t === true){
  822. return t;
  823. }
  824. if (t !== undefined) {
  825. r = t;
  826. }
  827. }
  828. }
  829. if (t = this['on' + ti.toLowerCase()]) {
  830. r = t.apply(this, arguments);
  831. }
  832. }
  833. return r;
  834. }
  835. };
  836. /**
  837. * 获得对象所拥有监听类型的所有监听器
  838. * @public
  839. * @function
  840. * @param {Object} obj 查询监听器的对象
  841. * @param {String} type 事件类型
  842. * @param {Boolean} force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  843. * @returns {Array} 监听器数组
  844. */
  845. function getListener(obj, type, force) {
  846. var allListeners;
  847. type = type.toLowerCase();
  848. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  849. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  850. }
  851. ///import editor.js
  852. ///import core/dom/dom.js
  853. ///import core/utils.js
  854. /**
  855. * dtd html语义化的体现类
  856. * @constructor
  857. * @namespace dtd
  858. */
  859. var dtd = dom.dtd = (function() {
  860. function _( s ) {
  861. for (var k in s) {
  862. s[k.toUpperCase()] = s[k];
  863. }
  864. return s;
  865. }
  866. var X = utils.extend2;
  867. var A = _({isindex:1,fieldset:1}),
  868. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  869. C = X( _({a:1}), B ),
  870. D = X( {iframe:1}, C ),
  871. 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}),
  872. F = _({ins:1,del:1,script:1,style:1}),
  873. 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 ),
  874. 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 ),
  875. I = X( _({p:1}), H ),
  876. J = X( _({iframe:1}), H, B ),
  877. 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}),
  878. L = X( _({a:0}), J ),//a不能被切开,所以把他
  879. M = _({tr:1}),
  880. N = _({'#':1}),
  881. O = X( _({param:1}), K ),
  882. P = X( _({form:1}), A, D, E, I ),
  883. Q = _({li:1,ol:1,ul:1}),
  884. R = _({style:1,script:1}),
  885. S = _({base:1,link:1,meta:1,title:1}),
  886. T = X( S, R ),
  887. U = _({head:1,body:1}),
  888. V = _({html:1});
  889. 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}),
  890. empty = _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1});
  891. return _({
  892. // $ 表示自定的属性
  893. // body外的元素列表.
  894. $nonBodyContent: X( V, U, S ),
  895. //块结构元素列表
  896. $block : block,
  897. //内联元素列表
  898. $inline : L,
  899. $inlineWithA : X(_({a:1}),L),
  900. $body : X( _({script:1,style:1}), block ),
  901. $cdata : _({script:1,style:1}),
  902. //自闭和元素
  903. $empty : empty,
  904. //不是自闭合,但不能让range选中里边
  905. $nonChild : _({iframe:1,textarea:1}),
  906. //列表元素列表
  907. $listItem : _({dd:1,dt:1,li:1}),
  908. //列表根元素列表
  909. $list: _({ul:1,ol:1,dl:1}),
  910. //不能认为是空的元素
  911. $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}),
  912. //如果没有子节点就可以删除的元素列表,像span,a
  913. $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}),
  914. $removeEmptyBlock : _({'p':1,'div':1}),
  915. //在table元素里的元素列表
  916. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  917. //不转换的标签
  918. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  919. html: U,
  920. head: T,
  921. style: N,
  922. script: N,
  923. body: P,
  924. base: {},
  925. link: {},
  926. meta: {},
  927. title: N,
  928. col : {},
  929. tr : _({td:1,th:1}),
  930. img : {},
  931. embed: {},
  932. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  933. noscript : P,
  934. td : P,
  935. br : {},
  936. th : P,
  937. center : P,
  938. kbd : L,
  939. button : X( I, E ),
  940. basefont : {},
  941. h5 : L,
  942. h4 : L,
  943. samp : L,
  944. h6 : L,
  945. ol : Q,
  946. h1 : L,
  947. h3 : L,
  948. option : N,
  949. h2 : L,
  950. form : X( A, D, E, I ),
  951. select : _({optgroup:1,option:1}),
  952. font : L,
  953. ins : L,
  954. menu : Q,
  955. abbr : L,
  956. label : L,
  957. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  958. code : L,
  959. tfoot : M,
  960. cite : L,
  961. li : P,
  962. input : {},
  963. iframe : P,
  964. strong : L,
  965. textarea : N,
  966. noframes : P,
  967. big : L,
  968. small : L,
  969. span :_({'#':1,br:1}),
  970. hr : L,
  971. dt : L,
  972. sub : L,
  973. optgroup : _({option:1}),
  974. param : {},
  975. bdo : L,
  976. 'var' : L,
  977. div : P,
  978. object : O,
  979. sup : L,
  980. dd : P,
  981. strike : L,
  982. area : {},
  983. dir : Q,
  984. map : X( _({area:1,form:1,p:1}), A, F, E ),
  985. applet : O,
  986. dl : _({dt:1,dd:1}),
  987. del : L,
  988. isindex : {},
  989. fieldset : X( _({legend:1}), K ),
  990. thead : M,
  991. ul : Q,
  992. acronym : L,
  993. b : L,
  994. a : X( _({a:1}), J ),
  995. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  996. caption : L,
  997. i : L,
  998. u : L,
  999. tbody : M,
  1000. s : L,
  1001. address : X( D, I ),
  1002. tt : L,
  1003. legend : L,
  1004. q : L,
  1005. pre : X( G, C ),
  1006. p : X(_({'a':1}),L),
  1007. em :L,
  1008. dfn : L
  1009. });
  1010. })();
  1011. /**
  1012. * @file
  1013. * @name UE.dom.domUtils
  1014. * @short DomUtils
  1015. * @import editor.js, core/utils.js,core/browser.js,core/dom/dtd.js
  1016. * @desc UEditor封装的底层dom操作库
  1017. */
  1018. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1019. var tmpNode = startFromChild && node[start],
  1020. parent;
  1021. !tmpNode && (tmpNode = node[ltr]);
  1022. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1023. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1024. return null;
  1025. }
  1026. tmpNode = parent[ltr];
  1027. }
  1028. if (tmpNode && fn && !fn(tmpNode)) {
  1029. return getDomNode(tmpNode, start, ltr, false, fn);
  1030. }
  1031. return tmpNode;
  1032. }
  1033. var attrFix = ie && browser.version < 9 ? {
  1034. tabindex:"tabIndex",
  1035. readonly:"readOnly",
  1036. "for":"htmlFor",
  1037. "class":"className",
  1038. maxlength:"maxLength",
  1039. cellspacing:"cellSpacing",
  1040. cellpadding:"cellPadding",
  1041. rowspan:"rowSpan",
  1042. colspan:"colSpan",
  1043. usemap:"useMap",
  1044. frameborder:"frameBorder"
  1045. } : {
  1046. tabindex:"tabIndex",
  1047. readonly:"readOnly"
  1048. },
  1049. styleBlock = utils.listToMap([
  1050. '-webkit-box', '-moz-box', 'block' ,
  1051. 'list-item' , 'table' , 'table-row-group' ,
  1052. 'table-header-group', 'table-footer-group' ,
  1053. 'table-row' , 'table-column-group' , 'table-column' ,
  1054. 'table-cell' , 'table-caption'
  1055. ]);
  1056. var domUtils = dom.domUtils = {
  1057. //节点常量
  1058. NODE_ELEMENT:1,
  1059. NODE_DOCUMENT:9,
  1060. NODE_TEXT:3,
  1061. NODE_COMMENT:8,
  1062. NODE_DOCUMENT_FRAGMENT:11,
  1063. //位置关系
  1064. POSITION_IDENTICAL:0,
  1065. POSITION_DISCONNECTED:1,
  1066. POSITION_FOLLOWING:2,
  1067. POSITION_PRECEDING:4,
  1068. POSITION_IS_CONTAINED:8,
  1069. POSITION_CONTAINS:16,
  1070. //ie6使用其他的会有一段空白出现
  1071. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1072. //-------------------------Node部分--------------------------------
  1073. keys:{
  1074. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1075. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1076. 37:1, 38:1, 39:1, 40:1,
  1077. 13:1 /*enter*/
  1078. },
  1079. /**
  1080. * 获取节点A相对于节点B的位置关系
  1081. * @name getPosition
  1082. * @grammar UE.dom.domUtils.getPosition(nodeA,nodeB) => Number
  1083. * @example
  1084. * switch (returnValue) {
  1085. * case 0: //相等,同一节点
  1086. * case 1: //无关,节点不相连
  1087. * case 2: //跟随,即节点A头部位于节点B头部的后面
  1088. * case 4: //前置,即节点A头部位于节点B头部的前面
  1089. * case 8: //被包含,即节点A被节点B包含
  1090. * case 10://组合类型,即节点A满足跟随节点B且被节点B包含。实际上,如果被包含,必定跟随,所以returnValue事实上不会存在8的情况。
  1091. * case 16://包含,即节点A包含节点B
  1092. * case 20://组合类型,即节点A满足前置节点A且包含节点B。同样,如果包含,必定前置,所以returnValue事实上也不会存在16的情况
  1093. * }
  1094. */
  1095. getPosition:function (nodeA, nodeB) {
  1096. // 如果两个节点是同一个节点
  1097. if (nodeA === nodeB) {
  1098. // domUtils.POSITION_IDENTICAL
  1099. return 0;
  1100. }
  1101. var node,
  1102. parentsA = [nodeA],
  1103. parentsB = [nodeB];
  1104. node = nodeA;
  1105. while (node = node.parentNode) {
  1106. // 如果nodeB是nodeA的祖先节点
  1107. if (node === nodeB) {
  1108. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1109. return 10;
  1110. }
  1111. parentsA.push(node);
  1112. }
  1113. node = nodeB;
  1114. while (node = node.parentNode) {
  1115. // 如果nodeA是nodeB的祖先节点
  1116. if (node === nodeA) {
  1117. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1118. return 20;
  1119. }
  1120. parentsB.push(node);
  1121. }
  1122. parentsA.reverse();
  1123. parentsB.reverse();
  1124. if (parentsA[0] !== parentsB[0]) {
  1125. // domUtils.POSITION_DISCONNECTED
  1126. return 1;
  1127. }
  1128. var i = -1;
  1129. while (i++, parentsA[i] === parentsB[i]) {
  1130. }
  1131. nodeA = parentsA[i];
  1132. nodeB = parentsB[i];
  1133. while (nodeA = nodeA.nextSibling) {
  1134. if (nodeA === nodeB) {
  1135. // domUtils.POSITION_PRECEDING
  1136. return 4
  1137. }
  1138. }
  1139. // domUtils.POSITION_FOLLOWING
  1140. return 2;
  1141. },
  1142. /**
  1143. * 返回节点node在父节点中的索引位置
  1144. * @name getNodeIndex
  1145. * @grammar UE.dom.domUtils.getNodeIndex(node) => Number //索引值从0开始
  1146. */
  1147. getNodeIndex:function (node, ignoreTextNode) {
  1148. var preNode = node,
  1149. i = 0;
  1150. while (preNode = preNode.previousSibling) {
  1151. if (ignoreTextNode && preNode.nodeType == 3) {
  1152. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1153. i++;
  1154. }
  1155. continue;
  1156. }
  1157. i++;
  1158. }
  1159. return i;
  1160. },
  1161. /**
  1162. * 检测节点node是否在节点doc的树上,实质上是检测是否被doc包含
  1163. * @name inDoc
  1164. * @grammar UE.dom.domUtils.inDoc(node,doc) => true|false
  1165. */
  1166. inDoc:function (node, doc) {
  1167. return domUtils.getPosition(node, doc) == 10;
  1168. },
  1169. /**
  1170. * 查找node节点的祖先节点
  1171. * @name findParent
  1172. * @grammar UE.dom.domUtils.findParent(node) => Element // 直接返回node节点的父节点
  1173. * @grammar UE.dom.domUtils.findParent(node,filterFn) => Element //filterFn为过滤函数,node作为参数,返回true时才会将node作为符合要求的节点返回
  1174. * @grammar UE.dom.domUtils.findParent(node,filterFn,includeSelf) => Element //includeSelf指定是否包含自身
  1175. */
  1176. findParent:function (node, filterFn, includeSelf) {
  1177. if (node && !domUtils.isBody(node)) {
  1178. node = includeSelf ? node : node.parentNode;
  1179. while (node) {
  1180. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1181. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1182. }
  1183. node = node.parentNode;
  1184. }
  1185. }
  1186. return null;
  1187. },
  1188. /**
  1189. * 通过tagName查找node节点的祖先节点
  1190. * @name findParentByTagName
  1191. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames) => Element //tagNames支持数组,区分大小写
  1192. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf) => Element //includeSelf指定是否包含自身
  1193. * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf,excludeFn) => Element //excludeFn指定例外过滤条件,返回true时忽略该节点
  1194. */
  1195. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  1196. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  1197. return domUtils.findParent(node, function (node) {
  1198. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  1199. }, includeSelf);
  1200. },
  1201. /**
  1202. * 查找节点node的祖先节点集合
  1203. * @name findParents
  1204. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  1205. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  1206. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  1207. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  1208. */
  1209. findParents:function (node, includeSelf, filterFn, closerFirst) {
  1210. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  1211. while (node = domUtils.findParent(node, filterFn)) {
  1212. parents.push(node);
  1213. }
  1214. return closerFirst ? parents : parents.reverse();
  1215. },
  1216. /**
  1217. * 在节点node后面插入新节点newNode
  1218. * @name insertAfter
  1219. * @grammar UE.dom.domUtils.insertAfter(node,newNode) => newNode
  1220. */
  1221. insertAfter:function (node, newNode) {
  1222. return node.parentNode.insertBefore(newNode, node.nextSibling);
  1223. },
  1224. /**
  1225. * 删除节点node,并根据keepChildren指定是否保留子节点
  1226. * @name remove
  1227. * @grammar UE.dom.domUtils.remove(node) => node
  1228. * @grammar UE.dom.domUtils.remove(node,keepChildren) => node
  1229. */
  1230. remove:function (node, keepChildren) {
  1231. var parent = node.parentNode,
  1232. child;
  1233. if (parent) {
  1234. if (keepChildren && node.hasChildNodes()) {
  1235. while (child = node.firstChild) {
  1236. parent.insertBefore(child, node);
  1237. }
  1238. }
  1239. parent.removeChild(node);
  1240. }
  1241. return node;
  1242. },
  1243. /**
  1244. * 取得node节点在dom树上的下一个节点,即多叉树遍历
  1245. * @name getNextDomNode
  1246. * @grammar UE.dom.domUtils.getNextDomNode(node) => Element
  1247. * @example
  1248. */
  1249. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  1250. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  1251. },
  1252. /**
  1253. * 检测节点node是否属于bookmark节点
  1254. * @name isBookmarkNode
  1255. * @grammar UE.dom.domUtils.isBookmarkNode(node) => true|false
  1256. */
  1257. isBookmarkNode:function (node) {
  1258. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  1259. },
  1260. /**
  1261. * 获取节点node所在的window对象
  1262. * @name getWindow
  1263. * @grammar UE.dom.domUtils.getWindow(node) => window对象
  1264. */
  1265. getWindow:function (node) {
  1266. var doc = node.ownerDocument || node;
  1267. return doc.defaultView || doc.parentWindow;
  1268. },
  1269. /**
  1270. * 得到nodeA与nodeB公共的祖先节点
  1271. * @name getCommonAncestor
  1272. * @grammar UE.dom.domUtils.getCommonAncestor(nodeA,nodeB) => Element
  1273. */
  1274. getCommonAncestor:function (nodeA, nodeB) {
  1275. if (nodeA === nodeB)
  1276. return nodeA;
  1277. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  1278. while (parent = parent.parentNode) {
  1279. if (parent === nodeB) {
  1280. return parent;
  1281. }
  1282. parentsA.push(parent);
  1283. }
  1284. parent = nodeB;
  1285. while (parent = parent.parentNode) {
  1286. if (parent === nodeA)
  1287. return parent;
  1288. parentsB.push(parent);
  1289. }
  1290. parentsA.reverse();
  1291. parentsB.reverse();
  1292. while (i++, parentsA[i] === parentsB[i]) {
  1293. }
  1294. return i == 0 ? null : parentsA[i - 1];
  1295. },
  1296. /**
  1297. * 清除node节点左右兄弟为空的inline节点
  1298. * @name clearEmptySibling
  1299. * @grammar UE.dom.domUtils.clearEmptySibling(node)
  1300. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  1301. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  1302. * @example
  1303. * <b></b><i></i>xxxx<b>bb</b> --> xxxx<b>bb</b>
  1304. */
  1305. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  1306. function clear(next, dir) {
  1307. var tmpNode;
  1308. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  1309. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  1310. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  1311. tmpNode = next[dir];
  1312. domUtils.remove(next);
  1313. next = tmpNode;
  1314. }
  1315. }
  1316. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  1317. !ignorePre && clear(node.previousSibling, 'previousSibling');
  1318. },
  1319. /**
  1320. * 将一个文本节点node拆分成两个文本节点,offset指定拆分位置
  1321. * @name split
  1322. * @grammar UE.dom.domUtils.split(node,offset) => TextNode //返回从切分位置开始的后一个文本节点
  1323. */
  1324. split:function (node, offset) {
  1325. var doc = node.ownerDocument;
  1326. if (browser.ie && offset == node.nodeValue.length) {
  1327. var next = doc.createTextNode('');
  1328. return domUtils.insertAfter(node, next);
  1329. }
  1330. var retval = node.splitText(offset);
  1331. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  1332. if (browser.ie8) {
  1333. var tmpNode = doc.createTextNode('');
  1334. domUtils.insertAfter(retval, tmpNode);
  1335. domUtils.remove(tmpNode);
  1336. }
  1337. return retval;
  1338. },
  1339. /**
  1340. * 检测节点node是否为空节点(包括空格、换行、占位符等字符)
  1341. * @name isWhitespace
  1342. * @grammar UE.dom.domUtils.isWhitespace(node) => true|false
  1343. */
  1344. isWhitespace:function (node) {
  1345. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  1346. },
  1347. /**
  1348. * 获取元素element相对于viewport的位置坐标
  1349. * @name getXY
  1350. * @grammar UE.dom.domUtils.getXY(element) => Object //返回坐标对象{x:left,y:top}
  1351. */
  1352. getXY:function (element) {
  1353. var x = 0, y = 0;
  1354. while (element.offsetParent) {
  1355. y += element.offsetTop;
  1356. x += element.offsetLeft;
  1357. element = element.offsetParent;
  1358. }
  1359. return { 'x':x, 'y':y};
  1360. },
  1361. /**
  1362. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  1363. * @name on
  1364. * @grammar UE.dom.domUtils.on(element,type,handler) //type支持数组传入
  1365. * @example
  1366. * UE.dom.domUtils.on(document.body,"click",function(e){
  1367. * //e为事件对象,this为被点击元素对戏那个
  1368. * })
  1369. * @example
  1370. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  1371. * //evt为事件对象,this为被点击元素对象
  1372. * })
  1373. */
  1374. on:function (element, type, handler) {
  1375. var types = utils.isArray(type) ? type : [type],
  1376. k = types.length;
  1377. if (k) while (k--) {
  1378. type = types[k];
  1379. if (element.addEventListener) {
  1380. element.addEventListener(type, handler, false);
  1381. } else {
  1382. if (!handler._d) {
  1383. handler._d = {
  1384. els : []
  1385. };
  1386. }
  1387. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  1388. if (!handler._d[key] || index == -1) {
  1389. if(index == -1){
  1390. handler._d.els.push(element);
  1391. }
  1392. if(!handler._d[key]){
  1393. handler._d[key] = function (evt) {
  1394. return handler.call(evt.srcElement, evt || window.event);
  1395. };
  1396. }
  1397. element.attachEvent('on' + type, handler._d[key]);
  1398. }
  1399. }
  1400. }
  1401. element = null;
  1402. },
  1403. /**
  1404. * 解除原生DOM事件绑定
  1405. * @name un
  1406. * @grammar UE.dom.donUtils.un(element,type,handler) //参见<code><a href="#on">on</a></code>
  1407. */
  1408. un:function (element, type, handler) {
  1409. var types = utils.isArray(type) ? type : [type],
  1410. k = types.length;
  1411. if (k) while (k--) {
  1412. type = types[k];
  1413. if (element.removeEventListener) {
  1414. element.removeEventListener(type, handler, false);
  1415. } else {
  1416. var key = type + handler.toString();
  1417. try{
  1418. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  1419. }catch(e){}
  1420. if (handler._d && handler._d[key]) {
  1421. var index = utils.indexOf(handler._d.els,element);
  1422. if(index!=-1){
  1423. handler._d.els.splice(index,1);
  1424. }
  1425. handler._d.els.length == 0 && delete handler._d[key];
  1426. }
  1427. }
  1428. }
  1429. },
  1430. /**
  1431. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  1432. * @name isSameElement
  1433. * @grammar UE.dom.domUtils.isSameElement(nodeA,nodeB) => true|false
  1434. * @example
  1435. * <span style="font-size:12px">ssss</span> and <span style="font-size:12px">bbbbb</span> => true
  1436. * <span style="font-size:13px">ssss</span> and <span style="font-size:12px">bbbbb</span> => false
  1437. */
  1438. isSameElement:function (nodeA, nodeB) {
  1439. if (nodeA.tagName != nodeB.tagName) {
  1440. return false;
  1441. }
  1442. var thisAttrs = nodeA.attributes,
  1443. otherAttrs = nodeB.attributes;
  1444. if (!ie && thisAttrs.length != otherAttrs.length) {
  1445. return false;
  1446. }
  1447. var attrA, attrB, al = 0, bl = 0;
  1448. for (var i = 0; attrA = thisAttrs[i++];) {
  1449. if (attrA.nodeName == 'style') {
  1450. if (attrA.specified) {
  1451. al++;
  1452. }
  1453. if (domUtils.isSameStyle(nodeA, nodeB)) {
  1454. continue;
  1455. } else {
  1456. return false;
  1457. }
  1458. }
  1459. if (ie) {
  1460. if (attrA.specified) {
  1461. al++;
  1462. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  1463. } else {
  1464. continue;
  1465. }
  1466. } else {
  1467. attrB = nodeB.attributes[attrA.nodeName];
  1468. }
  1469. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  1470. return false;
  1471. }
  1472. }
  1473. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  1474. if (ie) {
  1475. for (i = 0; attrB = otherAttrs[i++];) {
  1476. if (attrB.specified) {
  1477. bl++;
  1478. }
  1479. }
  1480. if (al != bl) {
  1481. return false;
  1482. }
  1483. }
  1484. return true;
  1485. },
  1486. /**
  1487. * 判断节点nodeA与节点nodeB的元素属性是否一致
  1488. * @name isSameStyle
  1489. * @grammar UE.dom.domUtils.isSameStyle(nodeA,nodeB) => true|false
  1490. */
  1491. isSameStyle:function (nodeA, nodeB) {
  1492. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  1493. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  1494. if (browser.opera) {
  1495. styleA = nodeA.style;
  1496. styleB = nodeB.style;
  1497. if (styleA.length != styleB.length)
  1498. return false;
  1499. for (var p in styleA) {
  1500. if (/^(\d+|csstext)$/i.test(p)) {
  1501. continue;
  1502. }
  1503. if (styleA[p] != styleB[p]) {
  1504. return false;
  1505. }
  1506. }
  1507. return true;
  1508. }
  1509. if (!styleA || !styleB) {
  1510. return styleA == styleB;
  1511. }
  1512. styleA = styleA.split(';');
  1513. styleB = styleB.split(';');
  1514. if (styleA.length != styleB.length) {
  1515. return false;
  1516. }
  1517. for (var i = 0, ci; ci = styleA[i++];) {
  1518. if (utils.indexOf(styleB, ci) == -1) {
  1519. return false;
  1520. }
  1521. }
  1522. return true;
  1523. },
  1524. /**
  1525. * 检查节点node是否为块元素
  1526. * @name isBlockElm
  1527. * @grammar UE.dom.domUtils.isBlockElm(node) => true|false
  1528. */
  1529. isBlockElm:function (node) {
  1530. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  1531. },
  1532. /**
  1533. * 检测node节点是否为body节点
  1534. * @name isBody
  1535. * @grammar UE.dom.domUtils.isBody(node) => true|false
  1536. */
  1537. isBody:function (node) {
  1538. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  1539. },
  1540. /**
  1541. * 以node节点为中心,将该节点的指定祖先节点parent拆分成2块
  1542. * @name breakParent
  1543. * @grammar UE.dom.domUtils.breakParent(node,parent) => node
  1544. * @desc
  1545. * <code type="html"><b>ooo</b>是node节点
  1546. * <p>xxxx<b>ooo</b>xxx</p> ==> <p>xxx</p><b>ooo</b><p>xxx</p>
  1547. * <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>
  1548. */
  1549. breakParent:function (node, parent) {
  1550. var tmpNode,
  1551. parentClone = node,
  1552. clone = node,
  1553. leftNodes,
  1554. rightNodes;
  1555. do {
  1556. parentClone = parentClone.parentNode;
  1557. if (leftNodes) {
  1558. tmpNode = parentClone.cloneNode(false);
  1559. tmpNode.appendChild(leftNodes);
  1560. leftNodes = tmpNode;
  1561. tmpNode = parentClone.cloneNode(false);
  1562. tmpNode.appendChild(rightNodes);
  1563. rightNodes = tmpNode;
  1564. } else {
  1565. leftNodes = parentClone.cloneNode(false);
  1566. rightNodes = leftNodes.cloneNode(false);
  1567. }
  1568. while (tmpNode = clone.previousSibling) {
  1569. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  1570. }
  1571. while (tmpNode = clone.nextSibling) {
  1572. rightNodes.appendChild(tmpNode);
  1573. }
  1574. clone = parentClone;
  1575. } while (parent !== parentClone);
  1576. tmpNode = parent.parentNode;
  1577. tmpNode.insertBefore(leftNodes, parent);
  1578. tmpNode.insertBefore(rightNodes, parent);
  1579. tmpNode.insertBefore(node, rightNodes);
  1580. domUtils.remove(parent);
  1581. return node;
  1582. },
  1583. /**
  1584. * 检查节点node是否是空inline节点
  1585. * @name isEmptyInlineElement
  1586. * @grammar UE.dom.domUtils.isEmptyInlineElement(node) => 1|0
  1587. * @example
  1588. * <b><i></i></b> => 1
  1589. * <b><i></i><u></u></b> => 1
  1590. * <b></b> => 1
  1591. * <b>xx<i></i></b> => 0
  1592. */
  1593. isEmptyInlineElement:function (node) {
  1594. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  1595. return 0;
  1596. }
  1597. node = node.firstChild;
  1598. while (node) {
  1599. //如果是创建的bookmark就跳过
  1600. if (domUtils.isBookmarkNode(node)) {
  1601. return 0;
  1602. }
  1603. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  1604. node.nodeType == 3 && !domUtils.isWhitespace(node)
  1605. ) {
  1606. return 0;
  1607. }
  1608. node = node.nextSibling;
  1609. }
  1610. return 1;
  1611. },
  1612. /**
  1613. * 删除node节点下的左右空白文本子节点
  1614. * @name trimWhiteTextNode
  1615. * @grammar UE.dom.domUtils.trimWhiteTextNode(node)
  1616. */
  1617. trimWhiteTextNode:function (node) {
  1618. function remove(dir) {
  1619. var child;
  1620. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  1621. node.removeChild(child);
  1622. }
  1623. }
  1624. remove('firstChild');
  1625. remove('lastChild');
  1626. },
  1627. /**
  1628. * 合并node节点下相同的子节点
  1629. * @name mergeChild
  1630. * @desc
  1631. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  1632. * @example
  1633. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  1634. * ==> UE.dom.domUtils.mergeChild(node,'span')
  1635. * <p><span style="font-size:12px;">xxaaxx</span></p>
  1636. */
  1637. mergeChild:function (node, tagName, attrs) {
  1638. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  1639. for (var i = 0, ci; ci = list[i++];) {
  1640. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  1641. continue;
  1642. }
  1643. //span单独处理
  1644. if (ci.tagName.toLowerCase() == 'span') {
  1645. if (node === ci.parentNode) {
  1646. domUtils.trimWhiteTextNode(node);
  1647. if (node.childNodes.length == 1) {
  1648. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  1649. domUtils.remove(ci, true);
  1650. continue;
  1651. }
  1652. }
  1653. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  1654. if (attrs) {
  1655. var style = attrs.style;
  1656. if (style) {
  1657. style = style.split(';');
  1658. for (var j = 0, s; s = style[j++];) {
  1659. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  1660. }
  1661. }
  1662. }
  1663. if (domUtils.isSameStyle(ci, node)) {
  1664. domUtils.remove(ci, true);
  1665. }
  1666. continue;
  1667. }
  1668. if (domUtils.isSameElement(node, ci)) {
  1669. domUtils.remove(ci, true);
  1670. }
  1671. }
  1672. },
  1673. /**
  1674. * 原生方法getElementsByTagName的封装
  1675. * @name getElementsByTagName
  1676. * @grammar UE.dom.domUtils.getElementsByTagName(node,tagName) => Array //节点集合数组
  1677. */
  1678. getElementsByTagName:function (node, name,filter) {
  1679. if(filter && utils.isString(filter)){
  1680. var className = filter;
  1681. filter = function(node){return domUtils.hasClass(node,className)}
  1682. }
  1683. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  1684. var arr = [];
  1685. for(var n = 0,ni;ni=name[n++];){
  1686. var list = node.getElementsByTagName(ni);
  1687. for (var i = 0, ci; ci = list[i++];) {
  1688. if(!filter || filter(ci))
  1689. arr.push(ci);
  1690. }
  1691. }
  1692. return arr;
  1693. },
  1694. /**
  1695. * 将节点node合并到父节点上
  1696. * @name mergeToParent
  1697. * @grammar UE.dom.domUtils.mergeToParent(node)
  1698. * @example
  1699. * <span style="color:#fff"><span style="font-size:12px">xxx</span></span> ==> <span style="color:#fff;font-size:12px">xxx</span>
  1700. */
  1701. mergeToParent:function (node) {
  1702. var parent = node.parentNode;
  1703. while (parent && dtd.$removeEmpty[parent.tagName]) {
  1704. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  1705. domUtils.trimWhiteTextNode(parent);
  1706. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  1707. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  1708. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  1709. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  1710. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  1711. parent = parent.parentNode;
  1712. continue;
  1713. } else {
  1714. parent.style.cssText += ";" + node.style.cssText;
  1715. //trace:952 a标签要保持下划线
  1716. if (parent.tagName == 'A') {
  1717. parent.style.textDecoration = 'underline';
  1718. }
  1719. }
  1720. }
  1721. if (parent.tagName != 'A') {
  1722. parent === node.parentNode && domUtils.remove(node, true);
  1723. break;
  1724. }
  1725. }
  1726. parent = parent.parentNode;
  1727. }
  1728. },
  1729. /**
  1730. * 合并节点node的左右兄弟节点
  1731. * @name mergeSibling
  1732. * @grammar UE.dom.domUtils.mergeSibling(node)
  1733. * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre) //ignorePre指定是否忽略左兄弟
  1734. * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre,ignoreNext) //ignoreNext指定是否忽略右兄弟
  1735. * @example
  1736. * <b>xxxx</b><b>ooo</b><b>xxxx</b> ==> <b>xxxxoooxxxx</b>
  1737. */
  1738. mergeSibling:function (node, ignorePre, ignoreNext) {
  1739. function merge(rtl, start, node) {
  1740. var next;
  1741. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  1742. while (next.firstChild) {
  1743. if (start == 'firstChild') {
  1744. node.insertBefore(next.lastChild, node.firstChild);
  1745. } else {
  1746. node.appendChild(next.firstChild);
  1747. }
  1748. }
  1749. domUtils.remove(next);
  1750. }
  1751. }
  1752. !ignorePre && merge('previousSibling', 'firstChild', node);
  1753. !ignoreNext && merge('nextSibling', 'lastChild', node);
  1754. },
  1755. /**
  1756. * 设置节点node及其子节点不会被选中
  1757. * @name unSelectable
  1758. * @grammar UE.dom.domUtils.unSelectable(node)
  1759. */
  1760. unSelectable:ie || browser.opera ? function (node) {
  1761. //for ie9
  1762. node.onselectstart = function () {
  1763. return false;
  1764. };
  1765. node.onclick = node.onkeyup = node.onkeydown = function () {
  1766. return false;
  1767. };
  1768. node.unselectable = 'on';
  1769. node.setAttribute("unselectable", "on");
  1770. for (var i = 0, ci; ci = node.all[i++];) {
  1771. switch (ci.tagName.toLowerCase()) {
  1772. case 'iframe' :
  1773. case 'textarea' :
  1774. case 'input' :
  1775. case 'select' :
  1776. break;
  1777. default :
  1778. ci.unselectable = 'on';
  1779. node.setAttribute("unselectable", "on");
  1780. }
  1781. }
  1782. } : function (node) {
  1783. node.style.MozUserSelect =
  1784. node.style.webkitUserSelect =
  1785. node.style.KhtmlUserSelect = 'none';
  1786. },
  1787. /**
  1788. * 删除节点node上的属性attrNames,attrNames为属性名称数组
  1789. * @name removeAttributes
  1790. * @grammar UE.dom.domUtils.removeAttributes(node,attrNames)
  1791. * @example
  1792. * //Before remove
  1793. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  1794. * //Remove
  1795. * UE.dom.domUtils.removeAttributes(node,["id","name"]);
  1796. * //After remove
  1797. * <span style="font-size:14px;">xxxxx</span>
  1798. */
  1799. removeAttributes:function (node, attrNames) {
  1800. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  1801. for (var i = 0, ci; ci = attrNames[i++];) {
  1802. ci = attrFix[ci] || ci;
  1803. switch (ci) {
  1804. case 'className':
  1805. node[ci] = '';
  1806. break;
  1807. case 'style':
  1808. node.style.cssText = '';
  1809. !browser.ie && node.removeAttributeNode(node.getAttributeNode('style'))
  1810. }
  1811. node.removeAttribute(ci);
  1812. }
  1813. },
  1814. /**
  1815. * 在doc下创建一个标签名为tag,属性为attrs的元素
  1816. * @name createElement
  1817. * @grammar UE.dom.domUtils.createElement(doc,tag,attrs) => Node //返回创建的节点
  1818. */
  1819. createElement:function (doc, tag, attrs) {
  1820. return domUtils.setAttributes(doc.createElement(tag), attrs)
  1821. },
  1822. /**
  1823. * 为节点node添加属性attrs,attrs为属性键值对
  1824. * @name setAttributes
  1825. * @grammar UE.dom.domUtils.setAttributes(node,attrs) => node
  1826. */
  1827. setAttributes:function (node, attrs) {
  1828. for (var attr in attrs) {
  1829. if(attrs.hasOwnProperty(attr)){
  1830. var value = attrs[attr];
  1831. switch (attr) {
  1832. case 'class':
  1833. //ie下要这样赋值,setAttribute不起作用
  1834. node.className = value;
  1835. break;
  1836. case 'style' :
  1837. node.style.cssText = node.style.cssText + ";" + value;
  1838. break;
  1839. case 'innerHTML':
  1840. node[attr] = value;
  1841. break;
  1842. case 'value':
  1843. node.value = value;
  1844. break;
  1845. default:
  1846. node.setAttribute(attrFix[attr] || attr, value);
  1847. }
  1848. }
  1849. }
  1850. return node;
  1851. },
  1852. /**
  1853. * 获取元素element的计算样式
  1854. * @name getComputedStyle
  1855. * @grammar UE.dom.domUtils.getComputedStyle(element,styleName) => String //返回对应样式名称的样式值
  1856. * @example
  1857. * getComputedStyle(document.body,"font-size") => "15px"
  1858. * getComputedStyle(form,"color") => "#ffccdd"
  1859. */
  1860. getComputedStyle:function (element, styleName) {
  1861. //一下的属性单独处理
  1862. var pros = 'width height top left';
  1863. if(pros.indexOf(styleName) > -1){
  1864. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  1865. }
  1866. //忽略文本节点
  1867. if (element.nodeType == 3) {
  1868. element = element.parentNode;
  1869. }
  1870. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  1871. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  1872. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  1873. var span = element.ownerDocument.createElement('span');
  1874. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  1875. span.innerHTML = '.';
  1876. element.appendChild(span);
  1877. var result = span.offsetHeight;
  1878. element.removeChild(span);
  1879. span = null;
  1880. return result + 'px';
  1881. }
  1882. try {
  1883. var value = domUtils.getStyle(element, styleName) ||
  1884. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  1885. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  1886. } catch (e) {
  1887. return "";
  1888. }
  1889. return utils.transUnitToPx(utils.fixColor(styleName, value));
  1890. },
  1891. /**
  1892. * 在元素element上删除classNames,支持同时删除多个
  1893. * @name removeClasses
  1894. * @grammar UE.dom.domUtils.removeClasses(element,classNames)
  1895. * @example
  1896. * //执行方法前的dom结构
  1897. * <span class="test1 test2 test3">xxx</span>
  1898. * //执行方法
  1899. * UE.dom.domUtils.removeClasses(element,["test1","test3"])
  1900. * //执行方法后的dom结构
  1901. * <span class="test2">xxx</span>
  1902. */
  1903. removeClasses:function (elm, classNames) {
  1904. classNames = utils.isArray(classNames) ? classNames :
  1905. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  1906. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  1907. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  1908. }
  1909. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  1910. if(cls){
  1911. elm.className = cls;
  1912. }else{
  1913. domUtils.removeAttributes(elm,['class']);
  1914. }
  1915. },
  1916. /**
  1917. * 在元素element上增加一个样式类className,支持以空格分开的多个类名
  1918. * 如果相同的类名将不会添加
  1919. * @name addClass
  1920. * @grammar UE.dom.domUtils.addClass(element,classNames)
  1921. */
  1922. addClass:function (elm, classNames) {
  1923. if(!elm)return;
  1924. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  1925. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  1926. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  1927. elm.className += ' ' + ci;
  1928. }
  1929. }
  1930. },
  1931. /**
  1932. * 判断元素element是否包含样式类名className,支持以空格分开的多个类名,多个类名顺序不同也可以比较
  1933. * @name hasClass
  1934. * @grammar UE.dom.domUtils.hasClass(element,className) =>true|false
  1935. */
  1936. hasClass:function (element, className) {
  1937. if(utils.isRegExp(className)){
  1938. return className.test(element.className)
  1939. }
  1940. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  1941. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  1942. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  1943. return false;
  1944. }
  1945. }
  1946. return i - 1 == className.length;
  1947. },
  1948. /**
  1949. * 阻止事件默认行为
  1950. * @param {Event} evt 需要组织的事件对象
  1951. */
  1952. preventDefault:function (evt) {
  1953. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  1954. },
  1955. /**
  1956. * 删除元素element的样式
  1957. * @grammar UE.dom.domUtils.removeStyle(element,name) 删除的样式名称
  1958. */
  1959. removeStyle:function (element, name) {
  1960. if(browser.ie ){
  1961. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  1962. }else{
  1963. if (element.style.removeProperty) {
  1964. element.style.removeProperty (name);
  1965. }else {
  1966. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  1967. }
  1968. }
  1969. if (!element.style.cssText) {
  1970. domUtils.removeAttributes(element, ['style']);
  1971. }
  1972. },
  1973. /**
  1974. * 获取元素element的某个样式值
  1975. * @name getStyle
  1976. * @grammar UE.dom.domUtils.getStyle(element,name) => String
  1977. */
  1978. getStyle:function (element, name) {
  1979. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  1980. return utils.fixColor(name, value);
  1981. },
  1982. /**
  1983. * 为元素element设置样式属性值
  1984. * @name setStyle
  1985. * @grammar UE.dom.domUtils.setStyle(element,name,value)
  1986. */
  1987. setStyle:function (element, name, value) {
  1988. element.style[utils.cssStyleToDomStyle(name)] = value;
  1989. if(!utils.trim(element.style.cssText)){
  1990. this.removeAttributes(element,'style')
  1991. }
  1992. },
  1993. /**
  1994. * 为元素element设置样式属性值
  1995. * @name setStyles
  1996. * @grammar UE.dom.domUtils.setStyle(element,styles) //styles为样式键值对
  1997. */
  1998. setStyles:function (element, styles) {
  1999. for (var name in styles) {
  2000. if (styles.hasOwnProperty(name)) {
  2001. domUtils.setStyle(element, name, styles[name]);
  2002. }
  2003. }
  2004. },
  2005. /**
  2006. * 删除_moz_dirty属性
  2007. * @function
  2008. */
  2009. removeDirtyAttr:function (node) {
  2010. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  2011. ci.removeAttribute('_moz_dirty');
  2012. }
  2013. node.removeAttribute('_moz_dirty');
  2014. },
  2015. /**
  2016. * 返回子节点的数量
  2017. * @function
  2018. * @param {Node} node 父节点
  2019. * @param {Function} fn 过滤子节点的规则,若为空,则得到所有子节点的数量
  2020. * @return {Number} 符合条件子节点的数量
  2021. */
  2022. getChildCount:function (node, fn) {
  2023. var count = 0, first = node.firstChild;
  2024. fn = fn || function () {
  2025. return 1;
  2026. };
  2027. while (first) {
  2028. if (fn(first)) {
  2029. count++;
  2030. }
  2031. first = first.nextSibling;
  2032. }
  2033. return count;
  2034. },
  2035. /**
  2036. * 判断是否为空节点
  2037. * @function
  2038. * @param {Node} node 节点
  2039. * @return {Boolean} 是否为空节点
  2040. */
  2041. isEmptyNode:function (node) {
  2042. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  2043. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  2044. }) == 0
  2045. },
  2046. /**
  2047. * 清空节点所有的className
  2048. * @function
  2049. * @param {Array} nodes 节点数组
  2050. */
  2051. clearSelectedArr:function (nodes) {
  2052. var node;
  2053. while (node = nodes.pop()) {
  2054. domUtils.removeAttributes(node, ['class']);
  2055. }
  2056. },
  2057. /**
  2058. * 将显示区域滚动到显示节点的位置
  2059. * @function
  2060. * @param {Node} node 节点
  2061. * @param {window} win window对象
  2062. * @param {Number} offsetTop 距离上方的偏移量
  2063. */
  2064. scrollToView:function (node, win, offsetTop) {
  2065. var getViewPaneSize = function () {
  2066. var doc = win.document,
  2067. mode = doc.compatMode == 'CSS1Compat';
  2068. return {
  2069. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  2070. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  2071. };
  2072. },
  2073. getScrollPosition = function (win) {
  2074. if ('pageXOffset' in win) {
  2075. return {
  2076. x:win.pageXOffset || 0,
  2077. y:win.pageYOffset || 0
  2078. };
  2079. }
  2080. else {
  2081. var doc = win.document;
  2082. return {
  2083. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  2084. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  2085. };
  2086. }
  2087. };
  2088. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  2089. offset += (node.offsetHeight || 0);
  2090. var elementPosition = domUtils.getXY(node);
  2091. offset += elementPosition.y;
  2092. var currentScroll = getScrollPosition(win).y;
  2093. // offset += 50;
  2094. if (offset > currentScroll || offset < currentScroll - winHeight) {
  2095. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  2096. }
  2097. },
  2098. /**
  2099. * 判断节点是否为br
  2100. * @function
  2101. * @param {Node} node 节点
  2102. */
  2103. isBr:function (node) {
  2104. return node.nodeType == 1 && node.tagName == 'BR';
  2105. },
  2106. isFillChar:function (node,isInStart) {
  2107. return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length
  2108. },
  2109. isStartInblock:function (range) {
  2110. var tmpRange = range.cloneRange(),
  2111. flag = 0,
  2112. start = tmpRange.startContainer,
  2113. tmp;
  2114. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  2115. start = start.childNodes[tmpRange.startOffset];
  2116. var pre = start.previousSibling;
  2117. while(pre && domUtils.isFillChar(pre)){
  2118. start = pre;
  2119. pre = pre.previousSibling;
  2120. }
  2121. }
  2122. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  2123. tmpRange.setStartBefore(start);
  2124. start = tmpRange.startContainer;
  2125. }
  2126. while (start && domUtils.isFillChar(start)) {
  2127. tmp = start;
  2128. start = start.previousSibling
  2129. }
  2130. if (tmp) {
  2131. tmpRange.setStartBefore(tmp);
  2132. start = tmpRange.startContainer;
  2133. }
  2134. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  2135. tmpRange.setStart(start, 0).collapse(true);
  2136. }
  2137. while (!tmpRange.startOffset) {
  2138. start = tmpRange.startContainer;
  2139. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  2140. flag = 1;
  2141. break;
  2142. }
  2143. var pre = tmpRange.startContainer.previousSibling,
  2144. tmpNode;
  2145. if (!pre) {
  2146. tmpRange.setStartBefore(tmpRange.startContainer);
  2147. } else {
  2148. while (pre && domUtils.isFillChar(pre)) {
  2149. tmpNode = pre;
  2150. pre = pre.previousSibling;
  2151. }
  2152. if (tmpNode) {
  2153. tmpRange.setStartBefore(tmpNode);
  2154. } else {
  2155. tmpRange.setStartBefore(tmpRange.startContainer);
  2156. }
  2157. }
  2158. }
  2159. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  2160. },
  2161. isEmptyBlock:function (node,reg) {
  2162. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  2163. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  2164. return 0;
  2165. }
  2166. for (var n in dtd.$isNotEmpty) {
  2167. if (node.getElementsByTagName(n).length) {
  2168. return 0;
  2169. }
  2170. }
  2171. return 1;
  2172. },
  2173. setViewportOffset:function (element, offset) {
  2174. var left = parseInt(element.style.left) | 0;
  2175. var top = parseInt(element.style.top) | 0;
  2176. var rect = element.getBoundingClientRect();
  2177. var offsetLeft = offset.left - rect.left;
  2178. var offsetTop = offset.top - rect.top;
  2179. if (offsetLeft) {
  2180. element.style.left = left + offsetLeft + 'px';
  2181. }
  2182. if (offsetTop) {
  2183. element.style.top = top + offsetTop + 'px';
  2184. }
  2185. },
  2186. fillNode:function (doc, node) {
  2187. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  2188. node.innerHTML = '';
  2189. node.appendChild(tmpNode);
  2190. },
  2191. moveChild:function (src, tag, dir) {
  2192. while (src.firstChild) {
  2193. if (dir && tag.firstChild) {
  2194. tag.insertBefore(src.lastChild, tag.firstChild);
  2195. } else {
  2196. tag.appendChild(src.firstChild);
  2197. }
  2198. }
  2199. },
  2200. //判断是否有额外属性
  2201. hasNoAttributes:function (node) {
  2202. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  2203. },
  2204. //判断是否是编辑器自定义的参数
  2205. isCustomeNode:function (node) {
  2206. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  2207. },
  2208. isTagNode:function (node, tagName) {
  2209. return node.nodeType == 1 && new RegExp(node.tagName,'i').test(tagName)
  2210. },
  2211. /**
  2212. * 对于nodelist用filter进行过滤
  2213. * @name filterNodeList
  2214. * @since 1.2.4+
  2215. * @grammar UE.dom.domUtils.filterNodeList(nodelist,filter,onlyFirst) => 节点
  2216. * @example
  2217. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'div p') //返回第一个是div或者p的节点
  2218. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),function(n){return n.getAttribute('src')})
  2219. * //返回第一个带src属性的节点
  2220. * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'i',true) //返回数组,里边都是i节点
  2221. */
  2222. filterNodeList : function(nodelist,filter,forAll){
  2223. var results = [];
  2224. if(!utils .isFunction(filter)){
  2225. var str = filter;
  2226. filter = function(n){
  2227. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  2228. };
  2229. }
  2230. utils.each(nodelist,function(n){
  2231. filter(n) && results.push(n)
  2232. });
  2233. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  2234. },
  2235. isInNodeEndBoundary : function (rng,node){
  2236. var start = rng.startContainer;
  2237. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  2238. return 0;
  2239. }
  2240. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  2241. return 0;
  2242. }
  2243. while(start !== node){
  2244. if(start.nextSibling){
  2245. return 0
  2246. };
  2247. start = start.parentNode;
  2248. }
  2249. return 1;
  2250. },
  2251. isBoundaryNode : function (node,dir){
  2252. var tmp;
  2253. while(!domUtils.isBody(node)){
  2254. tmp = node;
  2255. node = node.parentNode;
  2256. if(tmp !== node[dir]){
  2257. return false;
  2258. }
  2259. }
  2260. return true;
  2261. }
  2262. };
  2263. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  2264. ///import editor.js
  2265. ///import core/utils.js
  2266. ///import core/browser.js
  2267. ///import core/dom/dom.js
  2268. ///import core/dom/dtd.js
  2269. ///import core/dom/domUtils.js
  2270. /**
  2271. * @file
  2272. * @name UE.dom.Range
  2273. * @anthor zhanyi
  2274. * @short Range
  2275. * @import editor.js,core/utils.js,core/browser.js,core/dom/domUtils.js,core/dom/dtd.js
  2276. * @desc Range范围实现类,本类是UEditor底层核心类,统一w3cRange和ieRange之间的差异,包括接口和属性
  2277. */
  2278. (function () {
  2279. var guid = 0,
  2280. fillChar = domUtils.fillChar,
  2281. fillData;
  2282. /**
  2283. * 更新range的collapse状态
  2284. * @param {Range} range range对象
  2285. */
  2286. function updateCollapse(range) {
  2287. range.collapsed =
  2288. range.startContainer && range.endContainer &&
  2289. range.startContainer === range.endContainer &&
  2290. range.startOffset == range.endOffset;
  2291. }
  2292. function selectOneNode(rng){
  2293. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  2294. }
  2295. function setEndPoint(toStart, node, offset, range) {
  2296. //如果node是自闭合标签要处理
  2297. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  2298. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  2299. node = node.parentNode;
  2300. }
  2301. if (toStart) {
  2302. range.startContainer = node;
  2303. range.startOffset = offset;
  2304. if (!range.endContainer) {
  2305. range.collapse(true);
  2306. }
  2307. } else {
  2308. range.endContainer = node;
  2309. range.endOffset = offset;
  2310. if (!range.startContainer) {
  2311. range.collapse(false);
  2312. }
  2313. }
  2314. updateCollapse(range);
  2315. return range;
  2316. }
  2317. function execContentsAction(range, action) {
  2318. //调整边界
  2319. //range.includeBookmark();
  2320. var start = range.startContainer,
  2321. end = range.endContainer,
  2322. startOffset = range.startOffset,
  2323. endOffset = range.endOffset,
  2324. doc = range.document,
  2325. frag = doc.createDocumentFragment(),
  2326. tmpStart, tmpEnd;
  2327. if (start.nodeType == 1) {
  2328. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  2329. }
  2330. if (end.nodeType == 1) {
  2331. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  2332. }
  2333. if (start === end && start.nodeType == 3) {
  2334. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  2335. //is not clone
  2336. if (action) {
  2337. start.deleteData(startOffset, endOffset - startOffset);
  2338. range.collapse(true);
  2339. }
  2340. return frag;
  2341. }
  2342. var current, currentLevel, clone = frag,
  2343. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  2344. for (var i = 0; startParents[i] == endParents[i];) {
  2345. i++;
  2346. }
  2347. for (var j = i, si; si = startParents[j]; j++) {
  2348. current = si.nextSibling;
  2349. if (si == start) {
  2350. if (!tmpStart) {
  2351. if (range.startContainer.nodeType == 3) {
  2352. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  2353. //is not clone
  2354. if (action) {
  2355. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  2356. }
  2357. } else {
  2358. clone.appendChild(!action ? start.cloneNode(true) : start);
  2359. }
  2360. }
  2361. } else {
  2362. currentLevel = si.cloneNode(false);
  2363. clone.appendChild(currentLevel);
  2364. }
  2365. while (current) {
  2366. if (current === end || current === endParents[j]) {
  2367. break;
  2368. }
  2369. si = current.nextSibling;
  2370. clone.appendChild(!action ? current.cloneNode(true) : current);
  2371. current = si;
  2372. }
  2373. clone = currentLevel;
  2374. }
  2375. clone = frag;
  2376. if (!startParents[i]) {
  2377. clone.appendChild(startParents[i - 1].cloneNode(false));
  2378. clone = clone.firstChild;
  2379. }
  2380. for (var j = i, ei; ei = endParents[j]; j++) {
  2381. current = ei.previousSibling;
  2382. if (ei == end) {
  2383. if (!tmpEnd && range.endContainer.nodeType == 3) {
  2384. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  2385. //is not clone
  2386. if (action) {
  2387. end.deleteData(0, endOffset);
  2388. }
  2389. }
  2390. } else {
  2391. currentLevel = ei.cloneNode(false);
  2392. clone.appendChild(currentLevel);
  2393. }
  2394. //如果两端同级,右边第一次已经被开始做了
  2395. if (j != i || !startParents[i]) {
  2396. while (current) {
  2397. if (current === start) {
  2398. break;
  2399. }
  2400. ei = current.previousSibling;
  2401. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  2402. current = ei;
  2403. }
  2404. }
  2405. clone = currentLevel;
  2406. }
  2407. if (action) {
  2408. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  2409. }
  2410. tmpStart && domUtils.remove(tmpStart);
  2411. tmpEnd && domUtils.remove(tmpEnd);
  2412. return frag;
  2413. }
  2414. /**
  2415. * @name Range
  2416. * @grammar new UE.dom.Range(document) => Range 实例
  2417. * @desc 创建一个跟document绑定的空的Range实例
  2418. * - ***startContainer*** 开始边界的容器节点,可以是elementNode或者是textNode
  2419. * - ***startOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  2420. * - ***endContainer*** 结束边界的容器节点,可以是elementNode或者是textNode
  2421. * - ***endOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  2422. * - ***document*** 跟range关联的document对象
  2423. * - ***collapsed*** 是否是闭合状态
  2424. */
  2425. var Range = dom.Range = function (document) {
  2426. var me = this;
  2427. me.startContainer =
  2428. me.startOffset =
  2429. me.endContainer =
  2430. me.endOffset = null;
  2431. me.document = document;
  2432. me.collapsed = true;
  2433. };
  2434. /**
  2435. * 删除fillData
  2436. * @param doc
  2437. * @param excludeNode
  2438. */
  2439. function removeFillData(doc, excludeNode) {
  2440. try {
  2441. if (fillData && domUtils.inDoc(fillData, doc)) {
  2442. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  2443. var tmpNode = fillData.parentNode;
  2444. domUtils.remove(fillData);
  2445. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  2446. //safari的contains有bug
  2447. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  2448. ) {
  2449. fillData = tmpNode.parentNode;
  2450. domUtils.remove(tmpNode);
  2451. tmpNode = fillData;
  2452. }
  2453. } else {
  2454. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  2455. }
  2456. }
  2457. } catch (e) {
  2458. }
  2459. }
  2460. /**
  2461. *
  2462. * @param node
  2463. * @param dir
  2464. */
  2465. function mergeSibling(node, dir) {
  2466. var tmpNode;
  2467. node = node[dir];
  2468. while (node && domUtils.isFillChar(node)) {
  2469. tmpNode = node[dir];
  2470. domUtils.remove(node);
  2471. node = tmpNode;
  2472. }
  2473. }
  2474. Range.prototype = {
  2475. /**
  2476. * @name cloneContents
  2477. * @grammar range.cloneContents() => DocumentFragment
  2478. * @desc 克隆选中的内容到一个fragment里,如果选区是空的将返回null
  2479. */
  2480. cloneContents:function () {
  2481. return this.collapsed ? null : execContentsAction(this, 0);
  2482. },
  2483. /**
  2484. * @name deleteContents
  2485. * @grammar range.deleteContents() => Range
  2486. * @desc 删除当前选区范围中的所有内容并返回range实例,这时的range已经变成了闭合状态
  2487. * @example
  2488. * DOM Element :
  2489. * <b>x<i>x[x<i>xx]x</b>
  2490. * //执行方法后
  2491. * <b>x<i>x<i>|x</b>
  2492. * 注意range改变了
  2493. * range.startContainer => b
  2494. * range.startOffset => 2
  2495. * range.endContainer => b
  2496. * range.endOffset => 2
  2497. * range.collapsed => true
  2498. */
  2499. deleteContents:function () {
  2500. var txt;
  2501. if (!this.collapsed) {
  2502. execContentsAction(this, 1);
  2503. }
  2504. if (browser.webkit) {
  2505. txt = this.startContainer;
  2506. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  2507. this.setStartBefore(txt).collapse(true);
  2508. domUtils.remove(txt);
  2509. }
  2510. }
  2511. return this;
  2512. },
  2513. /**
  2514. * @name extractContents
  2515. * @grammar range.extractContents() => DocumentFragment
  2516. * @desc 将当前的内容放到一个fragment里并返回这个fragment,这时的range已经变成了闭合状态
  2517. * @example
  2518. * DOM Element :
  2519. * <b>x<i>x[x<i>xx]x</b>
  2520. * //执行方法后
  2521. * 返回的fragment里的 dom结构是
  2522. * <i>x<i>xx
  2523. * dom树上的结构是
  2524. * <b>x<i>x<i>|x</b>
  2525. * 注意range改变了
  2526. * range.startContainer => b
  2527. * range.startOffset => 2
  2528. * range.endContainer => b
  2529. * range.endOffset => 2
  2530. * range.collapsed => true
  2531. */
  2532. extractContents:function () {
  2533. return this.collapsed ? null : execContentsAction(this, 2);
  2534. },
  2535. /**
  2536. * @name setStart
  2537. * @grammar range.setStart(node,offset) => Range
  2538. * @desc 设置range的开始位置位于node节点内,偏移量为offset
  2539. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2540. */
  2541. setStart:function (node, offset) {
  2542. return setEndPoint(true, node, offset, this);
  2543. },
  2544. /**
  2545. * 设置range的结束位置位于node节点,偏移量为offset
  2546. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2547. * @name setEnd
  2548. * @grammar range.setEnd(node,offset) => Range
  2549. */
  2550. setEnd:function (node, offset) {
  2551. return setEndPoint(false, node, offset, this);
  2552. },
  2553. /**
  2554. * 将Range开始位置设置到node节点之后
  2555. * @name setStartAfter
  2556. * @grammar range.setStartAfter(node) => Range
  2557. * @example
  2558. * <b>xx<i>x|x</i>x</b>
  2559. * 执行setStartAfter(i)后
  2560. * range.startContainer =>b
  2561. * range.startOffset =>2
  2562. */
  2563. setStartAfter:function (node) {
  2564. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2565. },
  2566. /**
  2567. * 将Range开始位置设置到node节点之前
  2568. * @name setStartBefore
  2569. * @grammar range.setStartBefore(node) => Range
  2570. * @example
  2571. * <b>xx<i>x|x</i>x</b>
  2572. * 执行setStartBefore(i)后
  2573. * range.startContainer =>b
  2574. * range.startOffset =>1
  2575. */
  2576. setStartBefore:function (node) {
  2577. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  2578. },
  2579. /**
  2580. * 将Range结束位置设置到node节点之后
  2581. * @name setEndAfter
  2582. * @grammar range.setEndAfter(node) => Range
  2583. * @example
  2584. * <b>xx<i>x|x</i>x</b>
  2585. * setEndAfter(i)后
  2586. * range.endContainer =>b
  2587. * range.endtOffset =>2
  2588. */
  2589. setEndAfter:function (node) {
  2590. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2591. },
  2592. /**
  2593. * 将Range结束位置设置到node节点之前
  2594. * @name setEndBefore
  2595. * @grammar range.setEndBefore(node) => Range
  2596. * @example
  2597. * <b>xx<i>x|x</i>x</b>
  2598. * 执行setEndBefore(i)后
  2599. * range.endContainer =>b
  2600. * range.endtOffset =>1
  2601. */
  2602. setEndBefore:function (node) {
  2603. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  2604. },
  2605. /**
  2606. * 将Range开始位置设置到node节点内的开始位置
  2607. * @name setStartAtFirst
  2608. * @grammar range.setStartAtFirst(node) => Range
  2609. */
  2610. setStartAtFirst:function (node) {
  2611. return this.setStart(node, 0);
  2612. },
  2613. /**
  2614. * 将Range开始位置设置到node节点内的结束位置
  2615. * @name setStartAtLast
  2616. * @grammar range.setStartAtLast(node) => Range
  2617. */
  2618. setStartAtLast:function (node) {
  2619. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2620. },
  2621. /**
  2622. * 将Range结束位置设置到node节点内的开始位置
  2623. * @name setEndAtFirst
  2624. * @grammar range.setEndAtFirst(node) => Range
  2625. */
  2626. setEndAtFirst:function (node) {
  2627. return this.setEnd(node, 0);
  2628. },
  2629. /**
  2630. * 将Range结束位置设置到node节点内的结束位置
  2631. * @name setEndAtLast
  2632. * @grammar range.setEndAtLast(node) => Range
  2633. */
  2634. setEndAtLast:function (node) {
  2635. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2636. },
  2637. /**
  2638. * 选中完整的指定节点,并返回包含该节点的range
  2639. * @name selectNode
  2640. * @grammar range.selectNode(node) => Range
  2641. */
  2642. selectNode:function (node) {
  2643. return this.setStartBefore(node).setEndAfter(node);
  2644. },
  2645. /**
  2646. * 选中node内部的所有节点,并返回对应的range
  2647. * @name selectNodeContents
  2648. * @grammar range.selectNodeContents(node) => Range
  2649. * @example
  2650. * <b>xx[x<i>xxx</i>]xxx</b>
  2651. * 执行后
  2652. * <b>[xxx<i>xxx</i>xxx]</b>
  2653. * range.startContainer =>b
  2654. * range.startOffset =>0
  2655. * range.endContainer =>b
  2656. * range.endOffset =>3
  2657. */
  2658. selectNodeContents:function (node) {
  2659. return this.setStart(node, 0).setEndAtLast(node);
  2660. },
  2661. /**
  2662. * 克隆一个新的range对象
  2663. * @name cloneRange
  2664. * @grammar range.cloneRange() => Range
  2665. */
  2666. cloneRange:function () {
  2667. var me = this;
  2668. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  2669. },
  2670. /**
  2671. * 让选区闭合到尾部,若toStart为真,则闭合到头部
  2672. * @name collapse
  2673. * @grammar range.collapse() => Range
  2674. * @grammar range.collapse(true) => Range //闭合选区到头部
  2675. */
  2676. collapse:function (toStart) {
  2677. var me = this;
  2678. if (toStart) {
  2679. me.endContainer = me.startContainer;
  2680. me.endOffset = me.startOffset;
  2681. } else {
  2682. me.startContainer = me.endContainer;
  2683. me.startOffset = me.endOffset;
  2684. }
  2685. me.collapsed = true;
  2686. return me;
  2687. },
  2688. /**
  2689. * 调整range的边界,使其"收缩"到最小的位置
  2690. * @name shrinkBoundary
  2691. * @grammar range.shrinkBoundary() => Range //range开始位置和结束位置都调整,参见<code><a href="#adjustmentboundary">adjustmentBoundary</a></code>
  2692. * @grammar range.shrinkBoundary(true) => Range //仅调整开始位置,忽略结束位置
  2693. * @example
  2694. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  2695. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx]</b><i>xxx</i>
  2696. * [<b><i>xxxx</i>xxxxxxx</b>] ==> <b><i>[xxxx</i>xxxxxxx]</b>
  2697. */
  2698. shrinkBoundary:function (ignoreEnd) {
  2699. var me = this, child,
  2700. collapsed = me.collapsed;
  2701. function check(node){
  2702. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  2703. }
  2704. while (me.startContainer.nodeType == 1 //是element
  2705. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  2706. && check(child)) {
  2707. me.setStart(child, 0);
  2708. }
  2709. if (collapsed) {
  2710. return me.collapse(true);
  2711. }
  2712. if (!ignoreEnd) {
  2713. while (me.endContainer.nodeType == 1//是element
  2714. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  2715. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  2716. && check(child)) {
  2717. me.setEnd(child, child.childNodes.length);
  2718. }
  2719. }
  2720. return me;
  2721. },
  2722. /**
  2723. * 获取当前range所在位置的公共祖先节点,当前range位置可以位于文本节点内,也可以包含整个元素节点,也可以位于两个节点之间
  2724. * @name getCommonAncestor
  2725. * @grammar range.getCommonAncestor([includeSelf, ignoreTextNode]) => Element
  2726. * @example
  2727. * <b>xx[xx<i>xx]x</i>xxx</b> ==>getCommonAncestor() ==> b
  2728. * <b>[<img/>]</b>
  2729. * range.startContainer ==> b
  2730. * range.startOffset ==> 0
  2731. * range.endContainer ==> b
  2732. * range.endOffset ==> 1
  2733. * range.getCommonAncestor() ==> b
  2734. * range.getCommonAncestor(true) ==> img
  2735. * <b>xxx|xx</b>
  2736. * range.startContainer ==> textNode
  2737. * range.startOffset ==> 3
  2738. * range.endContainer ==> textNode
  2739. * range.endOffset ==> 3
  2740. * range.getCommonAncestor() ==> textNode
  2741. * range.getCommonAncestor(null,true) ==> b
  2742. */
  2743. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  2744. var me = this,
  2745. start = me.startContainer,
  2746. end = me.endContainer;
  2747. if (start === end) {
  2748. if (includeSelf && selectOneNode(this)) {
  2749. start = start.childNodes[me.startOffset];
  2750. if(start.nodeType == 1)
  2751. return start;
  2752. }
  2753. //只有在上来就相等的情况下才会出现是文本的情况
  2754. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  2755. }
  2756. return domUtils.getCommonAncestor(start, end);
  2757. },
  2758. /**
  2759. * 调整边界容器,如果是textNode,就调整到elementNode上
  2760. * @name trimBoundary
  2761. * @grammar range.trimBoundary([ignoreEnd]) => Range //true忽略结束边界
  2762. * @example
  2763. * DOM Element :
  2764. * <b>|xxx</b>
  2765. * startContainer = xxx; startOffset = 0
  2766. * //执行后本方法后
  2767. * startContainer = <b>; startOffset = 0
  2768. * @example
  2769. * Dom Element :
  2770. * <b>xx|x</b>
  2771. * startContainer = xxx; startOffset = 2
  2772. * //执行本方法后,xxx被实实在在地切分成两个TextNode
  2773. * startContainer = <b>; startOffset = 1
  2774. */
  2775. trimBoundary:function (ignoreEnd) {
  2776. this.txtToElmBoundary();
  2777. var start = this.startContainer,
  2778. offset = this.startOffset,
  2779. collapsed = this.collapsed,
  2780. end = this.endContainer;
  2781. if (start.nodeType == 3) {
  2782. if (offset == 0) {
  2783. this.setStartBefore(start);
  2784. } else {
  2785. if (offset >= start.nodeValue.length) {
  2786. this.setStartAfter(start);
  2787. } else {
  2788. var textNode = domUtils.split(start, offset);
  2789. //跟新结束边界
  2790. if (start === end) {
  2791. this.setEnd(textNode, this.endOffset - offset);
  2792. } else if (start.parentNode === end) {
  2793. this.endOffset += 1;
  2794. }
  2795. this.setStartBefore(textNode);
  2796. }
  2797. }
  2798. if (collapsed) {
  2799. return this.collapse(true);
  2800. }
  2801. }
  2802. if (!ignoreEnd) {
  2803. offset = this.endOffset;
  2804. end = this.endContainer;
  2805. if (end.nodeType == 3) {
  2806. if (offset == 0) {
  2807. this.setEndBefore(end);
  2808. } else {
  2809. offset < end.nodeValue.length && domUtils.split(end, offset);
  2810. this.setEndAfter(end);
  2811. }
  2812. }
  2813. }
  2814. return this;
  2815. },
  2816. /**
  2817. * 如果选区在文本的边界上,就扩展选区到文本的父节点上
  2818. * @name txtToElmBoundary
  2819. * @example
  2820. * Dom Element :
  2821. * <b> |xxx</b>
  2822. * startContainer = xxx; startOffset = 0
  2823. * //本方法执行后
  2824. * startContainer = <b>; startOffset = 0
  2825. * @example
  2826. * Dom Element :
  2827. * <b> xxx| </b>
  2828. * startContainer = xxx; startOffset = 3
  2829. * //本方法执行后
  2830. * startContainer = <b>; startOffset = 1
  2831. */
  2832. txtToElmBoundary:function () {
  2833. function adjust(r, c) {
  2834. var container = r[c + 'Container'],
  2835. offset = r[c + 'Offset'];
  2836. if (container.nodeType == 3) {
  2837. if (!offset) {
  2838. r['set' + c.replace(/(\w)/, function (a) {
  2839. return a.toUpperCase();
  2840. }) + 'Before'](container);
  2841. } else if (offset >= container.nodeValue.length) {
  2842. r['set' + c.replace(/(\w)/, function (a) {
  2843. return a.toUpperCase();
  2844. }) + 'After' ](container);
  2845. }
  2846. }
  2847. }
  2848. if (!this.collapsed) {
  2849. adjust(this, 'start');
  2850. adjust(this, 'end');
  2851. }
  2852. return this;
  2853. },
  2854. /**
  2855. * 在当前选区的开始位置前插入一个节点或者fragment,range的开始位置会在插入节点的前边
  2856. * @name insertNode
  2857. * @grammar range.insertNode(node) => Range //node可以是textNode,elementNode,fragment
  2858. * @example
  2859. * Range :
  2860. * xxx[x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2861. * 待插入Node :
  2862. * <p>ssss</p>
  2863. * 执行本方法后的Range :
  2864. * xxx[<p>ssss</p>x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2865. */
  2866. insertNode:function (node) {
  2867. var first = node, length = 1;
  2868. if (node.nodeType == 11) {
  2869. first = node.firstChild;
  2870. length = node.childNodes.length;
  2871. }
  2872. this.trimBoundary(true);
  2873. var start = this.startContainer,
  2874. offset = this.startOffset;
  2875. var nextNode = start.childNodes[ offset ];
  2876. if (nextNode) {
  2877. start.insertBefore(node, nextNode);
  2878. } else {
  2879. start.appendChild(node);
  2880. }
  2881. if (first.parentNode === this.endContainer) {
  2882. this.endOffset = this.endOffset + length;
  2883. }
  2884. return this.setStartBefore(first);
  2885. },
  2886. /**
  2887. * 设置光标闭合位置,toEnd设置为true时光标将闭合到选区的结尾
  2888. * @name setCursor
  2889. * @grammar range.setCursor([toEnd]) => Range //toEnd为true时,光标闭合到选区的末尾
  2890. */
  2891. setCursor:function (toEnd, noFillData) {
  2892. return this.collapse(!toEnd).select(noFillData);
  2893. },
  2894. /**
  2895. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  2896. * @name createBookmark
  2897. * @grammar range.createBookmark([serialize]) => Object //{start:开始标记,end:结束标记,id:serialize} serialize为真时,开始结束标记是插入节点的id,否则是插入节点的引用
  2898. */
  2899. createBookmark:function (serialize, same) {
  2900. var endNode,
  2901. startNode = this.document.createElement('span');
  2902. startNode.style.cssText = 'display:none;line-height:0px;';
  2903. startNode.appendChild(this.document.createTextNode('\u200D'));
  2904. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  2905. if (!this.collapsed) {
  2906. endNode = startNode.cloneNode(true);
  2907. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  2908. }
  2909. this.insertNode(startNode);
  2910. if (endNode) {
  2911. this.collapse().insertNode(endNode).setEndBefore(endNode);
  2912. }
  2913. this.setStartAfter(startNode);
  2914. return {
  2915. start:serialize ? startNode.id : startNode,
  2916. end:endNode ? serialize ? endNode.id : endNode : null,
  2917. id:serialize
  2918. }
  2919. },
  2920. /**
  2921. * 移动边界到书签位置,并删除插入的书签节点
  2922. * @name moveToBookmark
  2923. * @grammar range.moveToBookmark(bookmark) => Range //让当前的range选到给定bookmark的位置,bookmark对象是由range.createBookmark创建的
  2924. */
  2925. moveToBookmark:function (bookmark) {
  2926. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  2927. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  2928. this.setStartBefore(start);
  2929. domUtils.remove(start);
  2930. if (end) {
  2931. this.setEndBefore(end);
  2932. domUtils.remove(end);
  2933. } else {
  2934. this.collapse(true);
  2935. }
  2936. return this;
  2937. },
  2938. /**
  2939. * 调整range的边界,使其"放大"到最近的父block节点
  2940. * @name enlarge
  2941. * @grammar range.enlarge() => Range
  2942. * @example
  2943. * <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>
  2944. */
  2945. enlarge:function (toBlock, stopFn) {
  2946. var isBody = domUtils.isBody,
  2947. pre, node, tmp = this.document.createTextNode('');
  2948. if (toBlock) {
  2949. node = this.startContainer;
  2950. if (node.nodeType == 1) {
  2951. if (node.childNodes[this.startOffset]) {
  2952. pre = node = node.childNodes[this.startOffset]
  2953. } else {
  2954. node.appendChild(tmp);
  2955. pre = node = tmp;
  2956. }
  2957. } else {
  2958. pre = node;
  2959. }
  2960. while (1) {
  2961. if (domUtils.isBlockElm(node)) {
  2962. node = pre;
  2963. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  2964. node = pre;
  2965. }
  2966. this.setStartBefore(node);
  2967. break;
  2968. }
  2969. pre = node;
  2970. node = node.parentNode;
  2971. }
  2972. node = this.endContainer;
  2973. if (node.nodeType == 1) {
  2974. if (pre = node.childNodes[this.endOffset]) {
  2975. node.insertBefore(tmp, pre);
  2976. } else {
  2977. node.appendChild(tmp);
  2978. }
  2979. pre = node = tmp;
  2980. } else {
  2981. pre = node;
  2982. }
  2983. while (1) {
  2984. if (domUtils.isBlockElm(node)) {
  2985. node = pre;
  2986. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  2987. node = pre;
  2988. }
  2989. this.setEndAfter(node);
  2990. break;
  2991. }
  2992. pre = node;
  2993. node = node.parentNode;
  2994. }
  2995. if (tmp.parentNode === this.endContainer) {
  2996. this.endOffset--;
  2997. }
  2998. domUtils.remove(tmp);
  2999. }
  3000. // 扩展边界到最大
  3001. if (!this.collapsed) {
  3002. while (this.startOffset == 0) {
  3003. if (stopFn && stopFn(this.startContainer)) {
  3004. break;
  3005. }
  3006. if (isBody(this.startContainer)) {
  3007. break;
  3008. }
  3009. this.setStartBefore(this.startContainer);
  3010. }
  3011. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  3012. if (stopFn && stopFn(this.endContainer)) {
  3013. break;
  3014. }
  3015. if (isBody(this.endContainer)) {
  3016. break;
  3017. }
  3018. this.setEndAfter(this.endContainer);
  3019. }
  3020. }
  3021. return this;
  3022. },
  3023. /**
  3024. * 调整Range的边界,使其"缩小"到最合适的位置
  3025. * @name adjustmentBoundary
  3026. * @grammar range.adjustmentBoundary() => Range //参见<code><a href="#shrinkboundary">shrinkBoundary</a></code>
  3027. * @example
  3028. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  3029. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx</b>]<i>xxx</i>
  3030. */
  3031. adjustmentBoundary:function () {
  3032. if (!this.collapsed) {
  3033. while (!domUtils.isBody(this.startContainer) &&
  3034. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  3035. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  3036. ) {
  3037. this.setStartAfter(this.startContainer);
  3038. }
  3039. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  3040. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  3041. ) {
  3042. this.setEndBefore(this.endContainer);
  3043. }
  3044. }
  3045. return this;
  3046. },
  3047. /**
  3048. * 给range选区中的内容添加给定的标签,主要用于inline标签
  3049. * @name applyInlineStyle
  3050. * @grammar range.applyInlineStyle(tagName) => Range //tagName为需要添加的样式标签名
  3051. * @grammar range.applyInlineStyle(tagName,attrs) => Range //attrs为属性json对象
  3052. * @desc
  3053. * <code type="html"><p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  3054. * <p>xx[dd<strong>yyyy</strong>]x</p> ==> range.applyInlineStyle("strong") ==> <p>xx[<strong>ddyyyy</strong>]x</p>
  3055. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong",{"style":"font-size:12px"}) ==> <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p></code>
  3056. */
  3057. applyInlineStyle:function (tagName, attrs, list) {
  3058. if (this.collapsed)return this;
  3059. this.trimBoundary().enlarge(false,
  3060. function (node) {
  3061. return node.nodeType == 1 && domUtils.isBlockElm(node)
  3062. }).adjustmentBoundary();
  3063. var bookmark = this.createBookmark(),
  3064. end = bookmark.end,
  3065. filterFn = function (node) {
  3066. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  3067. },
  3068. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  3069. node,
  3070. pre,
  3071. range = this.cloneRange();
  3072. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  3073. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  3074. range.setStartBefore(current);
  3075. node = current;
  3076. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  3077. pre = node;
  3078. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  3079. return dtd[tagName][parent.tagName];
  3080. });
  3081. }
  3082. var frag = range.setEndAfter(pre).extractContents(), elm;
  3083. if (list && list.length > 0) {
  3084. var level, top;
  3085. top = level = list[0].cloneNode(false);
  3086. for (var i = 1, ci; ci = list[i++];) {
  3087. level.appendChild(ci.cloneNode(false));
  3088. level = level.firstChild;
  3089. }
  3090. elm = level;
  3091. } else {
  3092. elm = range.document.createElement(tagName);
  3093. }
  3094. if (attrs) {
  3095. domUtils.setAttributes(elm, attrs);
  3096. }
  3097. elm.appendChild(frag);
  3098. range.insertNode(list ? top : elm);
  3099. //处理下滑线在a上的情况
  3100. var aNode;
  3101. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  3102. domUtils.setAttributes(aNode, attrs);
  3103. domUtils.remove(elm, true);
  3104. elm = aNode;
  3105. } else {
  3106. domUtils.mergeSibling(elm);
  3107. domUtils.clearEmptySibling(elm);
  3108. }
  3109. //去除子节点相同的
  3110. domUtils.mergeChild(elm, attrs);
  3111. current = domUtils.getNextDomNode(elm, false, filterFn);
  3112. domUtils.mergeToParent(elm);
  3113. if (node === end) {
  3114. break;
  3115. }
  3116. } else {
  3117. current = domUtils.getNextDomNode(current, true, filterFn);
  3118. }
  3119. }
  3120. return this.moveToBookmark(bookmark);
  3121. },
  3122. /**
  3123. * 对当前range选中的节点,去掉给定的标签节点,但标签中的内容保留,主要用于处理inline元素
  3124. * @name removeInlineStyle
  3125. * @grammar range.removeInlineStyle(tagNames) => Range //tagNames 为需要去掉的样式标签名,支持"b"或者["b","i","u"]
  3126. * @desc
  3127. * <code type="html">xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span></code>
  3128. */
  3129. removeInlineStyle:function (tagNames) {
  3130. if (this.collapsed)return this;
  3131. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  3132. this.shrinkBoundary().adjustmentBoundary();
  3133. var start = this.startContainer, end = this.endContainer;
  3134. while (1) {
  3135. if (start.nodeType == 1) {
  3136. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  3137. break;
  3138. }
  3139. if (start.tagName.toLowerCase() == 'body') {
  3140. start = null;
  3141. break;
  3142. }
  3143. }
  3144. start = start.parentNode;
  3145. }
  3146. while (1) {
  3147. if (end.nodeType == 1) {
  3148. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  3149. break;
  3150. }
  3151. if (end.tagName.toLowerCase() == 'body') {
  3152. end = null;
  3153. break;
  3154. }
  3155. }
  3156. end = end.parentNode;
  3157. }
  3158. var bookmark = this.createBookmark(),
  3159. frag,
  3160. tmpRange;
  3161. if (start) {
  3162. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  3163. frag = tmpRange.extractContents();
  3164. tmpRange.insertNode(frag);
  3165. domUtils.clearEmptySibling(start, true);
  3166. start.parentNode.insertBefore(bookmark.start, start);
  3167. }
  3168. if (end) {
  3169. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  3170. frag = tmpRange.extractContents();
  3171. tmpRange.insertNode(frag);
  3172. domUtils.clearEmptySibling(end, false, true);
  3173. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  3174. }
  3175. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  3176. return node.nodeType == 1;
  3177. }), next;
  3178. while (current && current !== bookmark.end) {
  3179. next = domUtils.getNextDomNode(current, true, function (node) {
  3180. return node.nodeType == 1;
  3181. });
  3182. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  3183. domUtils.remove(current, true);
  3184. }
  3185. current = next;
  3186. }
  3187. return this.moveToBookmark(bookmark);
  3188. },
  3189. /**
  3190. * 得到一个自闭合的节点,常用于获取自闭和的节点,例如图片节点
  3191. * @name getClosedNode
  3192. * @grammar range.getClosedNode() => node|null
  3193. * @example
  3194. * <b>xxxx[<img />]xxx</b>
  3195. */
  3196. getClosedNode:function () {
  3197. var node;
  3198. if (!this.collapsed) {
  3199. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  3200. if (selectOneNode(range)) {
  3201. var child = range.startContainer.childNodes[range.startOffset];
  3202. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  3203. node = child;
  3204. }
  3205. }
  3206. }
  3207. return node;
  3208. },
  3209. /**
  3210. * 根据当前range选中内容节点(在页面上表现为反白显示)
  3211. * @name select
  3212. * @grammar range.select(); => Range
  3213. */
  3214. select:browser.ie ? function (noFillData, textRange) {
  3215. var nativeRange;
  3216. if (!this.collapsed)
  3217. this.shrinkBoundary();
  3218. var node = this.getClosedNode();
  3219. if (node && !textRange) {
  3220. try {
  3221. nativeRange = this.document.body.createControlRange();
  3222. nativeRange.addElement(node);
  3223. nativeRange.select();
  3224. } catch (e) {}
  3225. return this;
  3226. }
  3227. var bookmark = this.createBookmark(),
  3228. start = bookmark.start,
  3229. end;
  3230. nativeRange = this.document.body.createTextRange();
  3231. nativeRange.moveToElementText(start);
  3232. nativeRange.moveStart('character', 1);
  3233. if (!this.collapsed) {
  3234. var nativeRangeEnd = this.document.body.createTextRange();
  3235. end = bookmark.end;
  3236. nativeRangeEnd.moveToElementText(end);
  3237. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  3238. } else {
  3239. if (!noFillData && this.startContainer.nodeType != 3) {
  3240. //使用<span>|x<span>固定住光标
  3241. var tmpText = this.document.createTextNode(fillChar),
  3242. tmp = this.document.createElement('span');
  3243. tmp.appendChild(this.document.createTextNode(fillChar));
  3244. start.parentNode.insertBefore(tmp, start);
  3245. start.parentNode.insertBefore(tmpText, start);
  3246. //当点b,i,u时,不能清除i上边的b
  3247. removeFillData(this.document, tmpText);
  3248. fillData = tmpText;
  3249. mergeSibling(tmp, 'previousSibling');
  3250. mergeSibling(start, 'nextSibling');
  3251. nativeRange.moveStart('character', -1);
  3252. nativeRange.collapse(true);
  3253. }
  3254. }
  3255. this.moveToBookmark(bookmark);
  3256. tmp && domUtils.remove(tmp);
  3257. //IE在隐藏状态下不支持range操作,catch一下
  3258. try {
  3259. nativeRange.select();
  3260. } catch (e) {
  3261. }
  3262. return this;
  3263. } : function (notInsertFillData) {
  3264. function checkOffset(rng){
  3265. function check(node,offset,dir){
  3266. if(node.nodeType == 3 && node.nodeValue.length < offset){
  3267. rng[dir + 'Offset'] = node.nodeValue.length
  3268. }
  3269. }
  3270. check(rng.startContainer,rng.startOffset,'start');
  3271. check(rng.endContainer,rng.endOffset,'end');
  3272. }
  3273. var win = domUtils.getWindow(this.document),
  3274. sel = win.getSelection(),
  3275. txtNode;
  3276. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  3277. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  3278. browser.gecko ? this.document.body.focus() : win.focus();
  3279. if (sel) {
  3280. sel.removeAllRanges();
  3281. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  3282. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  3283. if (this.collapsed && !notInsertFillData) {
  3284. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  3285. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  3286. // var tmp = this.document.createTextNode('');
  3287. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  3288. // }
  3289. //
  3290. //处理光标落在文本节点的情况
  3291. //处理以下的情况
  3292. //<b>|xxxx</b>
  3293. //<b>xxxx</b>|xxxx
  3294. //xxxx<b>|</b>
  3295. var start = this.startContainer,child = start;
  3296. if(start.nodeType == 1){
  3297. child = start.childNodes[this.startOffset];
  3298. }
  3299. if( !(start.nodeType == 3 && this.startOffset) &&
  3300. (child ?
  3301. (!child.previousSibling || child.previousSibling.nodeType != 3)
  3302. :
  3303. (!start.lastChild || start.lastChild.nodeType != 3)
  3304. )
  3305. ){
  3306. txtNode = this.document.createTextNode(fillChar);
  3307. //跟着前边走
  3308. this.insertNode(txtNode);
  3309. removeFillData(this.document, txtNode);
  3310. mergeSibling(txtNode, 'previousSibling');
  3311. mergeSibling(txtNode, 'nextSibling');
  3312. fillData = txtNode;
  3313. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  3314. }
  3315. }
  3316. var nativeRange = this.document.createRange();
  3317. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  3318. var child = this.startContainer.childNodes[this.startOffset];
  3319. if(!child){
  3320. //往前靠拢
  3321. child = this.startContainer.lastChild;
  3322. if( child && domUtils.isBr(child)){
  3323. this.setStartBefore(child).collapse(true);
  3324. }
  3325. }else{
  3326. //向后靠拢
  3327. while(child && domUtils.isBlockElm(child)){
  3328. if(child.nodeType == 1 && child.childNodes[0]){
  3329. child = child.childNodes[0]
  3330. }else{
  3331. break;
  3332. }
  3333. }
  3334. child && this.setStartBefore(child).collapse(true)
  3335. }
  3336. }
  3337. //是createAddress最后一位算的不准,现在这里进行微调
  3338. checkOffset(this);
  3339. nativeRange.setStart(this.startContainer, this.startOffset);
  3340. nativeRange.setEnd(this.endContainer, this.endOffset);
  3341. sel.addRange(nativeRange);
  3342. }
  3343. return this;
  3344. },
  3345. /**
  3346. * 滚动条跳到当然range开始的位置
  3347. * @name scrollToView
  3348. * @grammar range.scrollToView([win,offset]) => Range //针对window对象,若不指定,将以编辑区域的窗口为准,offset偏移量
  3349. */
  3350. scrollToView:function (win, offset) {
  3351. win = win ? window : domUtils.getWindow(this.document);
  3352. var me = this,
  3353. span = me.document.createElement('span');
  3354. //trace:717
  3355. span.innerHTML = '&nbsp;';
  3356. me.cloneRange().insertNode(span);
  3357. domUtils.scrollToView(span, win, offset);
  3358. domUtils.remove(span);
  3359. return me;
  3360. },
  3361. inFillChar : function(){
  3362. var start = this.startContainer;
  3363. if(this.collapsed && start.nodeType == 3
  3364. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  3365. ){
  3366. return true;
  3367. }
  3368. return false;
  3369. },
  3370. createAddress : function(ignoreEnd,ignoreTxt){
  3371. var addr = {},me = this;
  3372. function getAddress(isStart){
  3373. var node = isStart ? me.startContainer : me.endContainer;
  3374. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  3375. addrs = [];
  3376. for(var i = 0,ci;ci = parents[i++];){
  3377. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  3378. }
  3379. var firstIndex = 0;
  3380. if(ignoreTxt){
  3381. if(node.nodeType == 3){
  3382. var tmpNode = node.previousSibling;
  3383. while(tmpNode && tmpNode.nodeType == 3){
  3384. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  3385. tmpNode = tmpNode.previousSibling;
  3386. }
  3387. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  3388. }else{
  3389. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  3390. if(node){
  3391. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  3392. }else{
  3393. node = isStart ? me.startContainer : me.endContainer;
  3394. var first = node.firstChild;
  3395. while(first){
  3396. if(domUtils.isFillChar(first)){
  3397. first = first.nextSibling;
  3398. continue;
  3399. }
  3400. firstIndex++;
  3401. if(first.nodeType == 3){
  3402. while( first && first.nodeType == 3){
  3403. first = first.nextSibling;
  3404. }
  3405. }else{
  3406. first = first.nextSibling;
  3407. }
  3408. }
  3409. }
  3410. }
  3411. }else{
  3412. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  3413. }
  3414. if(firstIndex < 0){
  3415. firstIndex = 0;
  3416. }
  3417. addrs.push(firstIndex);
  3418. return addrs;
  3419. }
  3420. addr.startAddress = getAddress(true);
  3421. if(!ignoreEnd){
  3422. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  3423. }
  3424. return addr;
  3425. },
  3426. moveToAddress : function(addr,ignoreEnd){
  3427. var me = this;
  3428. function getNode(address,isStart){
  3429. var tmpNode = me.document.body,
  3430. parentNode,offset;
  3431. for(var i= 0,ci,l=address.length;i<l;i++){
  3432. ci = address[i];
  3433. parentNode = tmpNode;
  3434. tmpNode = tmpNode.childNodes[ci];
  3435. if(!tmpNode){
  3436. offset = ci;
  3437. break;
  3438. }
  3439. }
  3440. if(isStart){
  3441. if(tmpNode){
  3442. me.setStartBefore(tmpNode)
  3443. }else{
  3444. me.setStart(parentNode,offset)
  3445. }
  3446. }else{
  3447. if(tmpNode){
  3448. me.setEndBefore(tmpNode)
  3449. }else{
  3450. me.setEnd(parentNode,offset)
  3451. }
  3452. }
  3453. }
  3454. getNode(addr.startAddress,true);
  3455. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  3456. return me;
  3457. },
  3458. equals : function(rng){
  3459. for(var p in this){
  3460. if(this.hasOwnProperty(p)){
  3461. if(this[p] !== rng[p])
  3462. return false
  3463. }
  3464. }
  3465. return true;
  3466. },
  3467. traversal:function(doFn,filterFn){
  3468. if (this.collapsed)
  3469. return this;
  3470. var bookmark = this.createBookmark(),
  3471. end = bookmark.end,
  3472. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  3473. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  3474. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  3475. doFn(current);
  3476. current = tmpNode;
  3477. }
  3478. return this.moveToBookmark(bookmark);
  3479. }
  3480. };
  3481. })();
  3482. ///import editor.js
  3483. ///import core/browser.js
  3484. ///import core/dom/dom.js
  3485. ///import core/dom/dtd.js
  3486. ///import core/dom/domUtils.js
  3487. ///import core/dom/Range.js
  3488. /**
  3489. * @class baidu.editor.dom.Selection Selection类
  3490. */
  3491. (function () {
  3492. function getBoundaryInformation( range, start ) {
  3493. var getIndex = domUtils.getNodeIndex;
  3494. range = range.duplicate();
  3495. range.collapse( start );
  3496. var parent = range.parentElement();
  3497. //如果节点里没有子节点,直接退出
  3498. if ( !parent.hasChildNodes() ) {
  3499. return {container:parent, offset:0};
  3500. }
  3501. var siblings = parent.children,
  3502. child,
  3503. testRange = range.duplicate(),
  3504. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  3505. distance;
  3506. while ( startIndex <= endIndex ) {
  3507. index = Math.floor( (startIndex + endIndex) / 2 );
  3508. child = siblings[index];
  3509. testRange.moveToElementText( child );
  3510. var position = testRange.compareEndPoints( 'StartToStart', range );
  3511. if ( position > 0 ) {
  3512. endIndex = index - 1;
  3513. } else if ( position < 0 ) {
  3514. startIndex = index + 1;
  3515. } else {
  3516. //trace:1043
  3517. return {container:parent, offset:getIndex( child )};
  3518. }
  3519. }
  3520. if ( index == -1 ) {
  3521. testRange.moveToElementText( parent );
  3522. testRange.setEndPoint( 'StartToStart', range );
  3523. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  3524. siblings = parent.childNodes;
  3525. if ( !distance ) {
  3526. child = siblings[siblings.length - 1];
  3527. return {container:child, offset:child.nodeValue.length};
  3528. }
  3529. var i = siblings.length;
  3530. while ( distance > 0 ){
  3531. distance -= siblings[ --i ].nodeValue.length;
  3532. }
  3533. return {container:siblings[i], offset:-distance};
  3534. }
  3535. testRange.collapse( position > 0 );
  3536. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  3537. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  3538. if ( !distance ) {
  3539. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  3540. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  3541. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  3542. }
  3543. while ( distance > 0 ) {
  3544. try {
  3545. var pre = child;
  3546. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  3547. distance -= child.nodeValue.length;
  3548. } catch ( e ) {
  3549. return {container:parent, offset:getIndex( pre )};
  3550. }
  3551. }
  3552. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  3553. }
  3554. /**
  3555. * 将ieRange转换为Range对象
  3556. * @param {Range} ieRange ieRange对象
  3557. * @param {Range} range Range对象
  3558. * @return {Range} range 返回转换后的Range对象
  3559. */
  3560. function transformIERangeToRange( ieRange, range ) {
  3561. if ( ieRange.item ) {
  3562. range.selectNode( ieRange.item( 0 ) );
  3563. } else {
  3564. var bi = getBoundaryInformation( ieRange, true );
  3565. range.setStart( bi.container, bi.offset );
  3566. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  3567. bi = getBoundaryInformation( ieRange, false );
  3568. range.setEnd( bi.container, bi.offset );
  3569. }
  3570. }
  3571. return range;
  3572. }
  3573. /**
  3574. * 获得ieRange
  3575. * @param {Selection} sel Selection对象
  3576. * @return {ieRange} 得到ieRange
  3577. */
  3578. function _getIERange( sel ) {
  3579. var ieRange;
  3580. //ie下有可能报错
  3581. try {
  3582. ieRange = sel.getNative().createRange();
  3583. } catch ( e ) {
  3584. return null;
  3585. }
  3586. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  3587. if ( ( el.ownerDocument || el ) === sel.document ) {
  3588. return ieRange;
  3589. }
  3590. return null;
  3591. }
  3592. var Selection = dom.Selection = function ( doc ) {
  3593. var me = this, iframe;
  3594. me.document = doc;
  3595. if ( ie ) {
  3596. iframe = domUtils.getWindow( doc ).frameElement;
  3597. domUtils.on( iframe, 'beforedeactivate', function () {
  3598. me._bakIERange = me.getIERange();
  3599. } );
  3600. domUtils.on( iframe, 'activate', function () {
  3601. try {
  3602. if ( !_getIERange( me ) && me._bakIERange ) {
  3603. me._bakIERange.select();
  3604. }
  3605. } catch ( ex ) {
  3606. }
  3607. me._bakIERange = null;
  3608. } );
  3609. }
  3610. iframe = doc = null;
  3611. };
  3612. Selection.prototype = {
  3613. /**
  3614. * 获取原生seleciton对象
  3615. * @public
  3616. * @function
  3617. * @name baidu.editor.dom.Selection.getNative
  3618. * @return {Selection} 获得selection对象
  3619. */
  3620. getNative:function () {
  3621. var doc = this.document;
  3622. try {
  3623. return !doc ? null : ie ? doc.selection : domUtils.getWindow( doc ).getSelection();
  3624. } catch ( e ) {
  3625. return null;
  3626. }
  3627. },
  3628. /**
  3629. * 获得ieRange
  3630. * @public
  3631. * @function
  3632. * @name baidu.editor.dom.Selection.getIERange
  3633. * @return {ieRange} 返回ie原生的Range
  3634. */
  3635. getIERange:function () {
  3636. var ieRange = _getIERange( this );
  3637. if ( !ieRange ) {
  3638. if ( this._bakIERange ) {
  3639. return this._bakIERange;
  3640. }
  3641. }
  3642. return ieRange;
  3643. },
  3644. /**
  3645. * 缓存当前选区的range和选区的开始节点
  3646. * @public
  3647. * @function
  3648. * @name baidu.editor.dom.Selection.cache
  3649. */
  3650. cache:function () {
  3651. this.clear();
  3652. this._cachedRange = this.getRange();
  3653. this._cachedStartElement = this.getStart();
  3654. this._cachedStartElementPath = this.getStartElementPath();
  3655. },
  3656. getStartElementPath:function () {
  3657. if ( this._cachedStartElementPath ) {
  3658. return this._cachedStartElementPath;
  3659. }
  3660. var start = this.getStart();
  3661. if ( start ) {
  3662. return domUtils.findParents( start, true, null, true )
  3663. }
  3664. return [];
  3665. },
  3666. /**
  3667. * 清空缓存
  3668. * @public
  3669. * @function
  3670. * @name baidu.editor.dom.Selection.clear
  3671. */
  3672. clear:function () {
  3673. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  3674. },
  3675. /**
  3676. * 编辑器是否得到了选区
  3677. */
  3678. isFocus:function () {
  3679. try {
  3680. return browser.ie && _getIERange( this ) || !browser.ie && this.getNative().rangeCount ? true : false;
  3681. } catch ( e ) {
  3682. return false;
  3683. }
  3684. },
  3685. /**
  3686. * 获取选区对应的Range
  3687. * @public
  3688. * @function
  3689. * @name baidu.editor.dom.Selection.getRange
  3690. * @returns {baidu.editor.dom.Range} 得到Range对象
  3691. */
  3692. getRange:function () {
  3693. var me = this;
  3694. function optimze( range ) {
  3695. var child = me.document.body.firstChild,
  3696. collapsed = range.collapsed;
  3697. while ( child && child.firstChild ) {
  3698. range.setStart( child, 0 );
  3699. child = child.firstChild;
  3700. }
  3701. if ( !range.startContainer ) {
  3702. range.setStart( me.document.body, 0 )
  3703. }
  3704. if ( collapsed ) {
  3705. range.collapse( true );
  3706. }
  3707. }
  3708. if ( me._cachedRange != null ) {
  3709. return this._cachedRange;
  3710. }
  3711. var range = new baidu.editor.dom.Range( me.document );
  3712. if ( ie ) {
  3713. var nativeRange = me.getIERange();
  3714. if ( nativeRange ) {
  3715. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  3716. try{
  3717. transformIERangeToRange( nativeRange, range );
  3718. }catch(e){
  3719. optimze( range );
  3720. }
  3721. } else {
  3722. optimze( range );
  3723. }
  3724. } else {
  3725. var sel = me.getNative();
  3726. if ( sel && sel.rangeCount ) {
  3727. var firstRange = sel.getRangeAt( 0 );
  3728. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  3729. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  3730. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  3731. optimze( range );
  3732. }
  3733. } else {
  3734. //trace:1734 有可能已经不在dom树上了,标识的节点
  3735. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  3736. return this._bakRange;
  3737. }
  3738. optimze( range );
  3739. }
  3740. }
  3741. return this._bakRange = range;
  3742. },
  3743. /**
  3744. * 获取开始元素,用于状态反射
  3745. * @public
  3746. * @function
  3747. * @name baidu.editor.dom.Selection.getStart
  3748. * @return {Element} 获得开始元素
  3749. */
  3750. getStart:function () {
  3751. if ( this._cachedStartElement ) {
  3752. return this._cachedStartElement;
  3753. }
  3754. var range = ie ? this.getIERange() : this.getRange(),
  3755. tmpRange,
  3756. start, tmp, parent;
  3757. if ( ie ) {
  3758. if ( !range ) {
  3759. //todo 给第一个值可能会有问题
  3760. return this.document.body.firstChild;
  3761. }
  3762. //control元素
  3763. if ( range.item ){
  3764. return range.item( 0 );
  3765. }
  3766. tmpRange = range.duplicate();
  3767. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  3768. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  3769. tmpRange.collapse( 1 );
  3770. start = tmpRange.parentElement();
  3771. parent = tmp = range.parentElement();
  3772. while ( tmp = tmp.parentNode ) {
  3773. if ( tmp == start ) {
  3774. start = parent;
  3775. break;
  3776. }
  3777. }
  3778. } else {
  3779. range.shrinkBoundary();
  3780. start = range.startContainer;
  3781. if ( start.nodeType == 1 && start.hasChildNodes() ){
  3782. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  3783. }
  3784. if ( start.nodeType == 3 ){
  3785. return start.parentNode;
  3786. }
  3787. }
  3788. return start;
  3789. },
  3790. /**
  3791. * 得到选区中的文本
  3792. * @public
  3793. * @function
  3794. * @name baidu.editor.dom.Selection.getText
  3795. * @return {String} 选区中包含的文本
  3796. */
  3797. getText:function () {
  3798. var nativeSel, nativeRange;
  3799. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  3800. nativeRange = browser.ie ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  3801. return browser.ie ? nativeRange.text : nativeRange.toString();
  3802. }
  3803. return '';
  3804. },
  3805. clearRange : function(){
  3806. this.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  3807. }
  3808. };
  3809. })();
  3810. /**
  3811. * @file
  3812. * @name UE.Editor
  3813. * @short Editor
  3814. * @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
  3815. * @desc 编辑器主类,包含编辑器提供的大部分公用接口
  3816. */
  3817. (function () {
  3818. var uid = 0, _selectionChangeTimer;
  3819. /**
  3820. * @private
  3821. * @ignore
  3822. * @param form 编辑器所在的form元素
  3823. * @param editor 编辑器实例对象
  3824. */
  3825. function setValue(form, editor) {
  3826. var textarea;
  3827. if (editor.textarea) {
  3828. if (utils.isString(editor.textarea)) {
  3829. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  3830. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  3831. textarea = ti;
  3832. break;
  3833. }
  3834. }
  3835. } else {
  3836. textarea = editor.textarea;
  3837. }
  3838. }
  3839. if (!textarea) {
  3840. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  3841. 'name': editor.options.textarea,
  3842. 'id': 'ueditor_textarea_' + editor.options.textarea,
  3843. 'style': "display:none"
  3844. }));
  3845. //不要产生多个textarea
  3846. editor.textarea = textarea;
  3847. }
  3848. textarea.value = editor.hasContents() ?
  3849. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  3850. ''
  3851. }
  3852. /**
  3853. * UEditor编辑器类
  3854. * @name Editor
  3855. * @desc 创建一个跟编辑器实例
  3856. * - ***container*** 编辑器容器对象
  3857. * - ***iframe*** 编辑区域所在的iframe对象
  3858. * - ***window*** 编辑区域所在的window
  3859. * - ***document*** 编辑区域所在的document对象
  3860. * - ***body*** 编辑区域所在的body对象
  3861. * - ***selection*** 编辑区域的选区对象
  3862. */
  3863. var Editor = UE.Editor = function (options) {
  3864. var me = this;
  3865. me.uid = uid++;
  3866. EventBase.call(me);
  3867. me.commands = {};
  3868. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  3869. me.shortcutkeys = {};
  3870. me.inputRules = [];
  3871. me.outputRules = [];
  3872. //设置默认的常用属性
  3873. me.setOpt({
  3874. isShow: true,
  3875. initialContent: '',
  3876. initialStyle:'',
  3877. autoClearinitialContent: false,
  3878. iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css',
  3879. textarea: 'editorValue',
  3880. focus: false,
  3881. focusInEnd: true,
  3882. autoClearEmptyNode: true,
  3883. fullscreen: false,
  3884. readonly: false,
  3885. zIndex: 999,
  3886. imagePopup: true,
  3887. enterTag: 'p',
  3888. customDomain: false,
  3889. lang: 'zh-cn',
  3890. langPath: me.options.UEDITOR_HOME_URL + 'lang/',
  3891. theme: 'default',
  3892. themePath: me.options.UEDITOR_HOME_URL + 'themes/',
  3893. allHtmlEnabled: false,
  3894. scaleEnabled: false,
  3895. tableNativeEditInFF: false,
  3896. autoSyncData : true
  3897. });
  3898. utils.loadFile(document, {
  3899. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  3900. tag: "script",
  3901. type: "text/javascript",
  3902. defer: "defer"
  3903. }, function () {
  3904. //初始化插件
  3905. for (var pi in UE.plugins) {
  3906. UE.plugins[pi].call(me);
  3907. }
  3908. me.langIsReady = true;
  3909. me.fireEvent("langReady");
  3910. });
  3911. UE.instants['ueditorInstant' + me.uid] = me;
  3912. };
  3913. Editor.prototype = {
  3914. /**
  3915. * 当编辑器ready后执行传入的fn,如果编辑器已经完成ready,就马上执行fn,fn的中的this是编辑器实例。
  3916. * 大部分的实例接口都需要放在该方法内部执行,否则在IE下可能会报错。
  3917. * @name ready
  3918. * @grammar editor.ready(fn) fn是当编辑器渲染好后执行的function
  3919. * @example
  3920. * var editor = new UE.ui.Editor();
  3921. * editor.render("myEditor");
  3922. * editor.ready(function(){
  3923. * editor.setContent("欢迎使用UEditor!");
  3924. * })
  3925. */
  3926. ready: function (fn) {
  3927. var me = this;
  3928. if (fn) {
  3929. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  3930. }
  3931. },
  3932. /**
  3933. * 为编辑器设置默认参数值。若用户配置为空,则以默认配置为准
  3934. * @grammar editor.setOpt(key,value); //传入一个键、值对
  3935. * @grammar editor.setOpt({ key:value}); //传入一个json对象
  3936. */
  3937. setOpt: function (key, val) {
  3938. var obj = {};
  3939. if (utils.isString(key)) {
  3940. obj[key] = val
  3941. } else {
  3942. obj = key;
  3943. }
  3944. utils.extend(this.options, obj, true);
  3945. },
  3946. /**
  3947. * 销毁编辑器实例对象
  3948. * @name destroy
  3949. * @grammar editor.destroy();
  3950. */
  3951. destroy: function () {
  3952. var me = this;
  3953. me.fireEvent('destroy');
  3954. var container = me.container.parentNode;
  3955. var textarea = me.textarea;
  3956. if (!textarea) {
  3957. textarea = document.createElement('textarea');
  3958. container.parentNode.insertBefore(textarea, container);
  3959. } else {
  3960. textarea.style.display = ''
  3961. }
  3962. textarea.style.width = me.iframe.offsetWidth + 'px';
  3963. textarea.style.height = me.iframe.offsetHeight + 'px';
  3964. textarea.value = me.getContent();
  3965. textarea.id = me.key;
  3966. container.innerHTML = '';
  3967. domUtils.remove(container);
  3968. var key = me.key;
  3969. //trace:2004
  3970. for (var p in me) {
  3971. if (me.hasOwnProperty(p)) {
  3972. delete this[p];
  3973. }
  3974. }
  3975. UE.delEditor(key);
  3976. },
  3977. /**
  3978. * 渲染编辑器的DOM到指定容器,必须且只能调用一次
  3979. * @name render
  3980. * @grammar editor.render(containerId); //可以指定一个容器ID
  3981. * @grammar editor.render(containerDom); //也可以直接指定容器对象
  3982. */
  3983. render: function (container,holder) {
  3984. var me = this, options = me.options;
  3985. if (utils.isString(container)) {
  3986. container = document.getElementById(container);
  3987. }
  3988. if (container) {
  3989. var useBodyAsViewport = ie && browser.version < 9,
  3990. html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  3991. '<html xmlns=\'http://www.w3.org/1999/xhtml\'' + (!useBodyAsViewport ? ' class=\'view\'' : '') + '><head>' +
  3992. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  3993. '<style type=\'text/css\'>' +
  3994. //设置四周的留边
  3995. '.view{padding:0;word-wrap:break-word;cursor:text;height:100%;}\n' +
  3996. //设置默认字体和字号
  3997. //font-family不能呢随便改,在safari下fillchar会有解析问题
  3998. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  3999. //设置段落间距
  4000. 'p{margin:5px 0;}'
  4001. + ( options.initialStyle || '' ) +
  4002. '</style></head><body' + (useBodyAsViewport ? ' class=\'view\'' : '') + '></body>';
  4003. if (options.customDomain && document.domain != location.hostname) {
  4004. html += '<script>window.parent.UE.instants[\'ueditorInstant' + me.uid + '\']._setup(document);</script></html>';
  4005. container.appendChild(domUtils.createElement(document, 'iframe', {
  4006. id: 'ueditor_' + me.uid,
  4007. width: "100%",
  4008. height: "100%",
  4009. frameborder: "0",
  4010. src: 'javascript:void(function(){document.open();document.domain="' + document.domain + '";' +
  4011. 'document.write("' + html + '");document.close();}())'
  4012. }));
  4013. } else {
  4014. if(options.initialFrameWidth){
  4015. options.minFrameWidth = options.initialFrameWidth
  4016. }else{
  4017. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  4018. }
  4019. if(options.initialFrameHeight){
  4020. options.minFrameHeight = options.initialFrameHeight
  4021. }else{
  4022. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  4023. }
  4024. container.style.width = options.initialFrameWidth+ 'px';
  4025. container.style.height = options.initialFrameHeight + 'px';
  4026. container.style.zIndex = options.zIndex;
  4027. container.innerHTML = '<iframe id="' + 'ueditor_' + this.uid + '"' + 'width="100%" height="100%" scroll="no" frameborder="0" ></iframe>';
  4028. var doc = container.firstChild.contentWindow.document;
  4029. //去掉了原来的判断!browser.webkit,因为会导致onload注册的事件不触发
  4030. doc.open();
  4031. doc.write(html + '</html>');
  4032. doc.close();
  4033. me._setup(doc);
  4034. }
  4035. container.style.overflow = 'hidden';
  4036. }
  4037. },
  4038. /**
  4039. * 编辑器初始化
  4040. * @private
  4041. * @ignore
  4042. * @param {Element} doc 编辑器Iframe中的文档对象
  4043. */
  4044. _setup: function (doc) {
  4045. var me = this,
  4046. options = me.options;
  4047. if (ie) {
  4048. doc.body.disabled = true;
  4049. doc.body.contentEditable = true;
  4050. doc.body.disabled = false;
  4051. } else {
  4052. doc.body.contentEditable = true;
  4053. doc.body.spellcheck = false;
  4054. }
  4055. me.document = doc;
  4056. me.window = doc.defaultView || doc.parentWindow;
  4057. me.iframe = me.window.frameElement;
  4058. me.body = doc.body;
  4059. me.selection = new dom.Selection(doc);
  4060. //gecko初始化就能得到range,无法判断isFocus了
  4061. var geckoSel;
  4062. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  4063. geckoSel.removeAllRanges();
  4064. }
  4065. this._initEvents();
  4066. //为form提交提供一个隐藏的textarea
  4067. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  4068. if (form.tagName == 'FORM') {
  4069. me.form = form;
  4070. if(me.options.autoSyncData){
  4071. domUtils.on(me.window,'blur',function(){
  4072. setValue(form,me);
  4073. });
  4074. }else{
  4075. domUtils.on(form, 'submit', function () {
  4076. setValue(this, me);
  4077. });
  4078. }
  4079. break;
  4080. }
  4081. }
  4082. if (options.initialContent) {
  4083. if (options.autoClearinitialContent) {
  4084. var oldExecCommand = me.execCommand;
  4085. me.execCommand = function () {
  4086. me.fireEvent('firstBeforeExecCommand');
  4087. return oldExecCommand.apply(me, arguments);
  4088. };
  4089. this._setDefaultContent(options.initialContent);
  4090. } else
  4091. this.setContent(options.initialContent, false, true);
  4092. }
  4093. //编辑器不能为空内容
  4094. if (domUtils.isEmptyNode(me.body)) {
  4095. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  4096. }
  4097. //如果要求focus, 就把光标定位到内容开始
  4098. if (options.focus) {
  4099. setTimeout(function () {
  4100. me.focus(me.options.focusInEnd);
  4101. //如果自动清除开着,就不需要做selectionchange;
  4102. !me.options.autoClearinitialContent && me._selectionChange();
  4103. }, 0);
  4104. }
  4105. if (!me.container) {
  4106. me.container = this.iframe.parentNode;
  4107. }
  4108. if (options.fullscreen && me.ui) {
  4109. me.ui.setFullScreen(true);
  4110. }
  4111. try {
  4112. me.document.execCommand('2D-position', false, false);
  4113. } catch (e) {
  4114. }
  4115. try {
  4116. me.document.execCommand('enableInlineTableEditing', false, false);
  4117. } catch (e) {
  4118. }
  4119. try {
  4120. me.document.execCommand('enableObjectResizing', false, false);
  4121. } catch (e) {
  4122. // domUtils.on(me.body,browser.ie ? 'resizestart' : 'resize', function( evt ) {
  4123. // domUtils.preventDefault(evt)
  4124. // });
  4125. }
  4126. me._bindshortcutKeys();
  4127. me.isReady = 1;
  4128. //console.log(me.__allListeners["ready"][11]);
  4129. me.__allListeners["ready"].splice(11,1); //清除toolbar持续显示
  4130. me.fireEvent('ready');
  4131. options.onready && options.onready.call(me);
  4132. if (!browser.ie) {
  4133. if(browser.gecko){
  4134. return;
  4135. }
  4136. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  4137. //chrome下会出现alt+tab切换时,导致选区位置不对
  4138. if (e.type == 'blur') {
  4139. me._bakRange = me.selection.getRange();
  4140. try {
  4141. me.selection.getNative().removeAllRanges();
  4142. } catch (e) {
  4143. }
  4144. } else {
  4145. try {
  4146. me._bakRange && me._bakRange.select();
  4147. } catch (e) {
  4148. }
  4149. }
  4150. });
  4151. }
  4152. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  4153. if (browser.gecko && browser.version <= 10902) {
  4154. //修复ff3.6初始化进来,不能点击获得焦点
  4155. me.body.contentEditable = false;
  4156. setTimeout(function () {
  4157. me.body.contentEditable = true;
  4158. }, 100);
  4159. setInterval(function () {
  4160. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  4161. }, 100)
  4162. }
  4163. !options.isShow && me.setHide();
  4164. options.readonly && me.setDisabled();
  4165. },
  4166. /**
  4167. * 同步编辑器的数据,为提交数据做准备,主要用于你是手动提交的情况
  4168. * @name sync
  4169. * @grammar editor.sync(); //从编辑器的容器向上查找,如果找到就同步数据
  4170. * @grammar editor.sync(formID); //formID制定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  4171. * @desc
  4172. * 后台取得数据得键值使用你容器上得''name''属性,如果没有就使用参数传入的''textarea''
  4173. * @example
  4174. * editor.sync();
  4175. * form.sumbit(); //form变量已经指向了form元素
  4176. *
  4177. */
  4178. sync: function (formId) {
  4179. var me = this,
  4180. form = formId ? document.getElementById(formId) :
  4181. domUtils.findParent(me.iframe.parentNode, function (node) {
  4182. return node.tagName == 'FORM'
  4183. }, true);
  4184. form && setValue(form, me);
  4185. },
  4186. /**
  4187. * 设置编辑器高度
  4188. * @name setHeight
  4189. * @grammar editor.setHeight(number); //纯数值,不带单位
  4190. */
  4191. setHeight: function (height) {
  4192. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  4193. this.iframe.parentNode.style.height = height + 'px';
  4194. }
  4195. this.document.body.style.height = height - 20 + 'px';
  4196. },
  4197. addshortcutkey: function (cmd, keys) {
  4198. var obj = {};
  4199. if (keys) {
  4200. obj[cmd] = keys
  4201. } else {
  4202. obj = cmd;
  4203. }
  4204. utils.extend(this.shortcutkeys, obj)
  4205. },
  4206. _bindshortcutKeys: function () {
  4207. var me = this, shortcutkeys = this.shortcutkeys;
  4208. me.addListener('keydown', function (type, e) {
  4209. var keyCode = e.keyCode || e.which;
  4210. for (var i in shortcutkeys) {
  4211. var tmp = shortcutkeys[i].split(',');
  4212. for (var t = 0, ti; ti = tmp[t++];) {
  4213. ti = ti.split(':');
  4214. var key = ti[0], param = ti[1];
  4215. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  4216. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  4217. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  4218. && keyCode == RegExp.$3
  4219. ) ||
  4220. keyCode == RegExp.$1
  4221. ) {
  4222. if (me.queryCommandState(i,param) != -1)
  4223. me.execCommand(i, param);
  4224. domUtils.preventDefault(e);
  4225. }
  4226. }
  4227. }
  4228. }
  4229. });
  4230. },
  4231. /**
  4232. * 获取编辑器内容
  4233. * @name getContent
  4234. * @grammar editor.getContent() => String //若编辑器中只包含字符"&lt;p&gt;&lt;br /&gt;&lt;/p/&gt;"会返回空。
  4235. * @grammar editor.getContent(fn) => String
  4236. * @example
  4237. * getContent默认是会现调用hasContents来判断编辑器是否为空,如果是,就直接返回空字符串
  4238. * 你也可以传入一个fn来接替hasContents的工作,定制判断的规则
  4239. * editor.getContent(function(){
  4240. * return false //编辑器没有内容 ,getContent直接返回空
  4241. * })
  4242. */
  4243. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  4244. var me = this;
  4245. if (cmd && utils.isFunction(cmd)) {
  4246. fn = cmd;
  4247. cmd = '';
  4248. }
  4249. if (fn ? !fn() : !this.hasContents()) {
  4250. return '';
  4251. }
  4252. me.fireEvent('beforegetcontent');
  4253. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  4254. me.filterOutputRule(root);
  4255. me.fireEvent('aftergetcontent', cmd);
  4256. var content = root.toHtml(formatter);
  4257. return content;
  4258. },
  4259. /**
  4260. * 取得完整的html代码,可以直接显示成完整的html文档
  4261. * @name getAllHtml
  4262. * @grammar editor.getAllHtml() => String
  4263. */
  4264. getAllHtml: function () {
  4265. var me = this,
  4266. headHtml = [],
  4267. html = '';
  4268. me.fireEvent('getAllHtml', headHtml);
  4269. if (browser.ie && browser.version > 8) {
  4270. var headHtmlForIE9 = '';
  4271. utils.each(me.document.styleSheets, function (si) {
  4272. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  4273. });
  4274. utils.each(me.document.getElementsByTagName('script'), function (si) {
  4275. headHtmlForIE9 += si.outerHTML;
  4276. });
  4277. }
  4278. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  4279. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  4280. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  4281. },
  4282. /**
  4283. * 得到编辑器的纯文本内容,但会保留段落格式
  4284. * @name getPlainTxt
  4285. * @grammar editor.getPlainTxt() => String
  4286. */
  4287. getPlainTxt: function () {
  4288. var reg = new RegExp(domUtils.fillChar, 'g'),
  4289. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  4290. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  4291. .replace(/<br\/?>/gi, '\n')
  4292. .replace(/<[^>/]+>/g, '')
  4293. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  4294. return dtd.$block[c] ? '\n' : b ? b : '';
  4295. });
  4296. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  4297. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  4298. },
  4299. /**
  4300. * 获取编辑器中的纯文本内容,没有段落格式
  4301. * @name getContentTxt
  4302. * @grammar editor.getContentTxt() => String
  4303. */
  4304. getContentTxt: function () {
  4305. var reg = new RegExp(domUtils.fillChar, 'g');
  4306. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  4307. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  4308. },
  4309. /**
  4310. * 将html设置到编辑器中, 如果是用于初始化时给编辑器赋初值,则必须放在ready方法内部执行
  4311. * @name setContent
  4312. * @grammar editor.setContent(html)
  4313. * @example
  4314. * var editor = new UE.ui.Editor()
  4315. * editor.ready(function(){
  4316. * //需要ready后执行,否则可能报错
  4317. * editor.setContent("欢迎使用UEditor!");
  4318. * })
  4319. */
  4320. setContent: function (html, isAppendTo, notFireSelectionchange) {
  4321. var me = this;
  4322. me.fireEvent('beforesetcontent', html);
  4323. var root = UE.htmlparser(html);
  4324. me.filterInputRule(root);
  4325. //html = root.toHtml();
  4326. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  4327. function isCdataDiv(node){
  4328. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  4329. }
  4330. //给文本或者inline节点套p标签
  4331. if (me.options.enterTag == 'p') {
  4332. var child = this.body.firstChild, tmpNode;
  4333. if (!child || child.nodeType == 1 &&
  4334. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  4335. domUtils.isCustomeNode(child)
  4336. )
  4337. && child === this.body.lastChild) {
  4338. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  4339. } else {
  4340. var p = me.document.createElement('p');
  4341. while (child) {
  4342. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  4343. tmpNode = child.nextSibling;
  4344. p.appendChild(child);
  4345. child = tmpNode;
  4346. }
  4347. if (p.firstChild) {
  4348. if (!child) {
  4349. me.body.appendChild(p);
  4350. break;
  4351. } else {
  4352. child.parentNode.insertBefore(p, child);
  4353. p = me.document.createElement('p');
  4354. }
  4355. }
  4356. child = child.nextSibling;
  4357. }
  4358. }
  4359. }
  4360. me.fireEvent('aftersetcontent');
  4361. me.fireEvent('contentchange');
  4362. !notFireSelectionchange && me._selectionChange();
  4363. //清除保存的选区
  4364. me._bakRange = me._bakIERange = null;
  4365. //trace:1742 setContent后gecko能得到焦点问题
  4366. var geckoSel;
  4367. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  4368. geckoSel.removeAllRanges();
  4369. }
  4370. if(me.options.autoSyncData){
  4371. me.form && setValue(me.form,me);
  4372. }
  4373. },
  4374. /**
  4375. * 让编辑器获得焦点,toEnd确定focus位置
  4376. * @name focus
  4377. * @grammar editor.focus([toEnd]) //默认focus到编辑器头部,toEnd为true时focus到内容尾部
  4378. */
  4379. focus: function (toEnd) {
  4380. try {
  4381. var me = this,
  4382. rng = me.selection.getRange();
  4383. if (toEnd) {
  4384. rng.setStartAtLast(me.body.lastChild).setCursor(false, true);
  4385. } else {
  4386. rng.select(true);
  4387. }
  4388. this.fireEvent('focus');
  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.apply(me,arguments) != -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. me.addListener('firstBeforeExecCommand focus', clear);
  4704. }
  4705. }(),
  4706. /**
  4707. * show方法的兼容版本
  4708. * @private
  4709. * @ignore
  4710. */
  4711. setShow: function () {
  4712. var me = this, range = me.selection.getRange();
  4713. if (me.container.style.display == 'none') {
  4714. //有可能内容丢失了
  4715. try {
  4716. range.moveToBookmark(me.lastBk);
  4717. delete me.lastBk
  4718. } catch (e) {
  4719. range.setStartAtFirst(me.body).collapse(true)
  4720. }
  4721. //ie下focus实效,所以做了个延迟
  4722. setTimeout(function () {
  4723. range.select(true);
  4724. }, 100);
  4725. me.container.style.display = '';
  4726. }
  4727. },
  4728. /**
  4729. * 显示编辑器
  4730. * @name show
  4731. * @grammar editor.show()
  4732. */
  4733. show: function () {
  4734. return this.setShow();
  4735. },
  4736. /**
  4737. * hide方法的兼容版本
  4738. * @private
  4739. * @ignore
  4740. */
  4741. setHide: function () {
  4742. var me = this;
  4743. if (!me.lastBk) {
  4744. me.lastBk = me.selection.getRange().createBookmark(true);
  4745. }
  4746. me.container.style.display = 'none'
  4747. },
  4748. /**
  4749. * 隐藏编辑器
  4750. * @name hide
  4751. * @grammar editor.hide()
  4752. */
  4753. hide: function () {
  4754. return this.setHide();
  4755. },
  4756. /**
  4757. * 根据制定的路径,获取对应的语言资源
  4758. * @name getLang
  4759. * @grammar editor.getLang(path) => (JSON|String) 路径根据的是lang目录下的语言文件的路径结构
  4760. * @example
  4761. * editor.getLang('contextMenu.delete') //如果当前是中文,那返回是的是删除
  4762. */
  4763. getLang: function (path) {
  4764. var lang = UE.I18N[this.options.lang];
  4765. if (!lang) {
  4766. throw Error("not import language file");
  4767. }
  4768. path = (path || "").split(".");
  4769. for (var i = 0, ci; ci = path[i++];) {
  4770. lang = lang[ci];
  4771. if (!lang)break;
  4772. }
  4773. return lang;
  4774. },
  4775. /**
  4776. * 计算编辑器当前内容的长度
  4777. * @name getContentLength
  4778. * @grammar editor.getContentLength(ingoneHtml,tagNames) =>
  4779. * @example
  4780. * editor.getLang(true)
  4781. */
  4782. getContentLength: function (ingoneHtml, tagNames) {
  4783. var count = this.getContent(false,false,true).length;
  4784. if (ingoneHtml) {
  4785. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  4786. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  4787. for (var i = 0, ci; ci = tagNames[i++];) {
  4788. count += this.document.getElementsByTagName(ci).length;
  4789. }
  4790. }
  4791. return count;
  4792. },
  4793. addInputRule: function (rule) {
  4794. this.inputRules.push(rule);
  4795. },
  4796. filterInputRule: function (root) {
  4797. for (var i = 0, ci; ci = this.inputRules[i++];) {
  4798. ci.call(this, root)
  4799. }
  4800. },
  4801. addOutputRule: function (rule) {
  4802. this.outputRules.push(rule)
  4803. },
  4804. filterOutputRule: function (root) {
  4805. for (var i = 0, ci; ci = this.outputRules[i++];) {
  4806. ci.call(this, root)
  4807. }
  4808. }
  4809. /**
  4810. * 得到dialog实例对象
  4811. * @name getDialog
  4812. * @grammar editor.getDialog(dialogName) => Object
  4813. * @example
  4814. * var dialog = editor.getDialog("insertimage");
  4815. * dialog.open(); //打开dialog
  4816. * dialog.close(); //关闭dialog
  4817. */
  4818. };
  4819. utils.inherits(Editor, EventBase);
  4820. })();
  4821. /**
  4822. * @file
  4823. * @name UE.ajax
  4824. * @short Ajax
  4825. * @desc UEditor内置的ajax请求模块
  4826. * @import core/utils.js
  4827. * @user: taoqili
  4828. * @date: 11-8-18
  4829. * @time: 下午3:18
  4830. */
  4831. UE.ajax = function() {
  4832. /**
  4833. * 创建一个ajaxRequest对象
  4834. */
  4835. var fnStr = 'XMLHttpRequest()';
  4836. try {
  4837. new ActiveXObject("Msxml2.XMLHTTP");
  4838. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  4839. } catch (e) {
  4840. try {
  4841. new ActiveXObject("Microsoft.XMLHTTP");
  4842. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  4843. } catch (e) {
  4844. }
  4845. }
  4846. var creatAjaxRequest = new Function('return new ' + fnStr);
  4847. /**
  4848. * 将json参数转化成适合ajax提交的参数列表
  4849. * @param json
  4850. */
  4851. function json2str(json) {
  4852. var strArr = [];
  4853. for (var i in json) {
  4854. //忽略默认的几个参数
  4855. if(i=="method" || i=="timeout" || i=="async") continue;
  4856. //传递过来的对象和函数不在提交之列
  4857. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  4858. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  4859. }
  4860. }
  4861. return strArr.join("&");
  4862. }
  4863. return {
  4864. /**
  4865. * @name request
  4866. * @desc 发出ajax请求,ajaxOpt中默认包含method,timeout,async,data,onsuccess以及onerror等六个,支持自定义添加参数
  4867. * @grammar UE.ajax.request(url,ajaxOpt);
  4868. * @example
  4869. * UE.ajax.request('http://www.xxxx.com/test.php',{
  4870. * //可省略,默认POST
  4871. * method:'POST',
  4872. * //可以自定义参数
  4873. * content:'这里是提交的内容',
  4874. * //也可以直接传json,但是只能命名为data,否则当做一般字符串处理
  4875. * data:{
  4876. * name:'UEditor',
  4877. * age:'1'
  4878. * }
  4879. * onsuccess:function(xhr){
  4880. * console.log(xhr.responseText);
  4881. * },
  4882. * onerror:function(xhr){
  4883. * console.log(xhr.responseText);
  4884. * }
  4885. * })
  4886. * @param ajaxOptions
  4887. */
  4888. request:function(url, ajaxOptions) {
  4889. var ajaxRequest = creatAjaxRequest(),
  4890. //是否超时
  4891. timeIsOut = false,
  4892. //默认参数
  4893. defaultAjaxOptions = {
  4894. method:"POST",
  4895. timeout:5000,
  4896. async:true,
  4897. data:{},//需要传递对象的话只能覆盖
  4898. onsuccess:function() {
  4899. },
  4900. onerror:function() {
  4901. }
  4902. };
  4903. if (typeof url === "object") {
  4904. ajaxOptions = url;
  4905. url = ajaxOptions.url;
  4906. }
  4907. if (!ajaxRequest || !url) return;
  4908. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  4909. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  4910. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  4911. if (!utils.isEmptyObject(ajaxOpts.data)){
  4912. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  4913. }
  4914. //超时检测
  4915. var timerID = setTimeout(function() {
  4916. if (ajaxRequest.readyState != 4) {
  4917. timeIsOut = true;
  4918. ajaxRequest.abort();
  4919. clearTimeout(timerID);
  4920. }
  4921. }, ajaxOpts.timeout);
  4922. var method = ajaxOpts.method.toUpperCase();
  4923. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  4924. ajaxRequest.open(method, str, ajaxOpts.async);
  4925. ajaxRequest.onreadystatechange = function() {
  4926. if (ajaxRequest.readyState == 4) {
  4927. if (!timeIsOut && ajaxRequest.status == 200) {
  4928. ajaxOpts.onsuccess(ajaxRequest);
  4929. } else {
  4930. ajaxOpts.onerror(ajaxRequest);
  4931. }
  4932. }
  4933. };
  4934. if (method == "POST") {
  4935. ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4936. ajaxRequest.send(submitStr);
  4937. } else {
  4938. ajaxRequest.send(null);
  4939. }
  4940. }
  4941. };
  4942. }();
  4943. /**
  4944. * @file
  4945. * @name UE.filterWord
  4946. * @short filterWord
  4947. * @desc 用来过滤word粘贴过来的字符串
  4948. * @import editor.js,core/utils.js
  4949. * @anthor zhanyi
  4950. */
  4951. var filterWord = UE.filterWord = function () {
  4952. //是否是word过来的内容
  4953. function isWordDocument( str ) {
  4954. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<v:)/ig.test( str );
  4955. }
  4956. //去掉小数
  4957. function transUnit( v ) {
  4958. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  4959. return utils.transUnitToPx(m);
  4960. } );
  4961. return v;
  4962. }
  4963. function filterPasteWord( str ) {
  4964. return str.replace( /[\t\r\n]+/g, "" )
  4965. .replace( /<!--[\s\S]*?-->/ig, "" )
  4966. //转换图片
  4967. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  4968. //opera能自己解析出image所这里直接返回空
  4969. if(browser.opera){
  4970. return '';
  4971. }
  4972. try{
  4973. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  4974. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  4975. src = str.match(/src=\s*"([^"]*)"/i)[1];
  4976. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  4977. } catch(e){
  4978. return '';
  4979. }
  4980. })
  4981. //针对wps添加的多余标签处理
  4982. .replace(/<\/?div[^>]*>/g,'')
  4983. //去掉多余的属性
  4984. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  4985. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  4986. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  4987. //去掉多余的属性
  4988. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  4989. //保留list的标示
  4990. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  4991. })
  4992. //清除多余的font/span不能匹配&nbsp;有可能是空格
  4993. .replace( /<(font|span)[^>]*>\s*<\/\1>/gi, '' )
  4994. //处理style的问题
  4995. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  4996. var n = [],
  4997. s = style.replace( /^\s+|\s+$/, '' )
  4998. .replace(/&#39;/g,'\'')
  4999. .replace( /&quot;/gi, "'" )
  5000. .split( /;\s*/g );
  5001. for ( var i = 0,v; v = s[i];i++ ) {
  5002. var name, value,
  5003. parts = v.split( ":" );
  5004. if ( parts.length == 2 ) {
  5005. name = parts[0].toLowerCase();
  5006. value = parts[1].toLowerCase();
  5007. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  5008. ||
  5009. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  5010. ){
  5011. continue;
  5012. }
  5013. switch ( name ) {
  5014. case "mso-padding-alt":
  5015. case "mso-padding-top-alt":
  5016. case "mso-padding-right-alt":
  5017. case "mso-padding-bottom-alt":
  5018. case "mso-padding-left-alt":
  5019. case "mso-margin-alt":
  5020. case "mso-margin-top-alt":
  5021. case "mso-margin-right-alt":
  5022. case "mso-margin-bottom-alt":
  5023. case "mso-margin-left-alt":
  5024. //ie下会出现挤到一起的情况
  5025. //case "mso-table-layout-alt":
  5026. case "mso-height":
  5027. case "mso-width":
  5028. case "mso-vertical-align-alt":
  5029. //trace:1819 ff下会解析出padding在table上
  5030. if(!/<table/.test(tag))
  5031. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  5032. continue;
  5033. case "horiz-align":
  5034. n[i] = "text-align:" + value;
  5035. continue;
  5036. case "vert-align":
  5037. n[i] = "vertical-align:" + value;
  5038. continue;
  5039. case "font-color":
  5040. case "mso-foreground":
  5041. n[i] = "color:" + value;
  5042. continue;
  5043. case "mso-background":
  5044. case "mso-highlight":
  5045. n[i] = "background:" + value;
  5046. continue;
  5047. case "mso-default-height":
  5048. n[i] = "min-height:" + transUnit( value );
  5049. continue;
  5050. case "mso-default-width":
  5051. n[i] = "min-width:" + transUnit( value );
  5052. continue;
  5053. case "mso-padding-between-alt":
  5054. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  5055. continue;
  5056. case "text-line-through":
  5057. if ( (value == "single") || (value == "double") ) {
  5058. n[i] = "text-decoration:line-through";
  5059. }
  5060. continue;
  5061. case "mso-zero-height":
  5062. if ( value == "yes" ) {
  5063. n[i] = "display:none";
  5064. }
  5065. continue;
  5066. case 'background':
  5067. break;
  5068. case 'margin':
  5069. if ( !/[1-9]/.test( value ) ) {
  5070. continue;
  5071. }
  5072. }
  5073. 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 )
  5074. ||
  5075. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  5076. ) {
  5077. continue;
  5078. }
  5079. n[i] = name + ":" + parts[1];
  5080. }
  5081. }
  5082. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  5083. })
  5084. .replace(/("data:image[^"]+)cm([^"]*")/g,function(a,b,c){
  5085. return a.replace(/cm/g,"c========m");
  5086. })
  5087. .replace(/("data:image[^"]+)pt([^"]*")/g,function(a,b,c){
  5088. return a.replace(/pt/g,"p========t");
  5089. })
  5090. .replace(/[\d.]+(cm|pt)/g,function(str){
  5091. return utils.transUnitToPx(str)
  5092. }).replace(/c========m/g,"cm").replace(/p========t/g,"pt")
  5093. }
  5094. return function ( html ) {
  5095. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  5096. };
  5097. }();
  5098. ///import editor.js
  5099. ///import core/utils.js
  5100. ///import core/dom/dom.js
  5101. ///import core/dom/dtd.js
  5102. ///import core/htmlparser.js
  5103. //模拟的节点类
  5104. //by zhanyi
  5105. (function () {
  5106. var uNode = UE.uNode = function (obj) {
  5107. this.type = obj.type;
  5108. this.data = obj.data;
  5109. this.tagName = obj.tagName;
  5110. this.parentNode = obj.parentNode;
  5111. this.attrs = obj.attrs || {};
  5112. this.children = obj.children;
  5113. };
  5114. var indentChar = ' ',
  5115. breakChar = '\n';
  5116. function insertLine(arr, current, begin) {
  5117. arr.push(breakChar);
  5118. return current + (begin ? 1 : -1);
  5119. }
  5120. function insertIndent(arr, current) {
  5121. //插入缩进
  5122. for (var i = 0; i < current; i++) {
  5123. arr.push(indentChar);
  5124. }
  5125. }
  5126. //创建uNode的静态方法
  5127. //支持标签和html
  5128. uNode.createElement = function (html) {
  5129. if (/[<>]/.test(html)) {
  5130. return UE.htmlparser(html).children[0]
  5131. } else {
  5132. return new uNode({
  5133. type:'element',
  5134. children:[],
  5135. tagName:html
  5136. })
  5137. }
  5138. };
  5139. uNode.createText = function (data) {
  5140. return new UE.uNode({
  5141. type:'text',
  5142. 'data':utils.unhtml(data || '')
  5143. })
  5144. };
  5145. function nodeToHtml(node, arr, formatter, current) {
  5146. switch (node.type) {
  5147. case 'root':
  5148. for (var i = 0, ci; ci = node.children[i++];) {
  5149. //插入新行
  5150. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  5151. insertLine(arr, current, true);
  5152. insertIndent(arr, current)
  5153. }
  5154. nodeToHtml(ci, arr, formatter, current)
  5155. }
  5156. break;
  5157. case 'text':
  5158. isText(node, arr);
  5159. break;
  5160. case 'element':
  5161. isElement(node, arr, formatter, current);
  5162. break;
  5163. case 'comment':
  5164. isComment(node, arr, formatter);
  5165. }
  5166. return arr;
  5167. }
  5168. function isText(node, arr) {
  5169. arr.push(node.parentNode.tagName == 'pre' ? node.data : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  5170. }
  5171. function isElement(node, arr, formatter, current) {
  5172. var attrhtml = '';
  5173. if (node.attrs) {
  5174. attrhtml = [];
  5175. var attrs = node.attrs;
  5176. for (var a in attrs) {
  5177. attrhtml.push(a + (attrs[a] !== undefined ? '="' + utils.unhtml(attrs[a]) + '"' : ''))
  5178. }
  5179. attrhtml = attrhtml.join(' ');
  5180. }
  5181. arr.push('<' + node.tagName +
  5182. (attrhtml ? ' ' + attrhtml : '') +
  5183. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  5184. );
  5185. //插入新行
  5186. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  5187. if(node.children && node.children.length){
  5188. current = insertLine(arr, current, true);
  5189. insertIndent(arr, current)
  5190. }
  5191. }
  5192. if (node.children && node.children.length) {
  5193. for (var i = 0, ci; ci = node.children[i++];) {
  5194. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  5195. insertLine(arr, current);
  5196. insertIndent(arr, current)
  5197. }
  5198. nodeToHtml(ci, arr, formatter, current)
  5199. }
  5200. }
  5201. if (!dtd.$empty[node.tagName]) {
  5202. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  5203. if(node.children && node.children.length){
  5204. current = insertLine(arr, current);
  5205. insertIndent(arr, current)
  5206. }
  5207. }
  5208. arr.push('<\/' + node.tagName + '>');
  5209. }
  5210. }
  5211. function isComment(node, arr) {
  5212. arr.push('<!--' + node.data + '-->');
  5213. }
  5214. function getNodeById(root, id) {
  5215. var node;
  5216. if (root.type == 'element' && root.getAttr('id') == id) {
  5217. return root;
  5218. }
  5219. if (root.children && root.children.length) {
  5220. for (var i = 0, ci; ci = root.children[i++];) {
  5221. if (node = getNodeById(ci, id)) {
  5222. return node;
  5223. }
  5224. }
  5225. }
  5226. }
  5227. function getNodesByTagName(node, tagName, arr) {
  5228. if (node.type == 'element' && node.tagName == tagName) {
  5229. arr.push(node);
  5230. }
  5231. if (node.children && node.children.length) {
  5232. for (var i = 0, ci; ci = node.children[i++];) {
  5233. getNodesByTagName(ci, tagName, arr)
  5234. }
  5235. }
  5236. }
  5237. function nodeTraversal(root,fn){
  5238. if(root.children && root.children.length){
  5239. for(var i= 0,ci;ci=root.children[i];){
  5240. nodeTraversal(ci,fn);
  5241. //ci被替换的情况,这里就不再走 fn了
  5242. if(ci.parentNode ){
  5243. if(ci.children && ci.children.length){
  5244. fn(ci)
  5245. }
  5246. if(ci.parentNode) i++
  5247. }
  5248. }
  5249. }else{
  5250. fn(root)
  5251. }
  5252. }
  5253. uNode.prototype = {
  5254. toHtml:function (formatter) {
  5255. var arr = [];
  5256. nodeToHtml(this, arr, formatter, 0);
  5257. return arr.join('')
  5258. },
  5259. innerHTML:function (htmlstr) {
  5260. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  5261. return this;
  5262. }
  5263. if (utils.isString(htmlstr)) {
  5264. if(this.children){
  5265. for (var i = 0, ci; ci = this.children[i++];) {
  5266. ci.parentNode = null;
  5267. }
  5268. }
  5269. this.children = [];
  5270. var tmpRoot = UE.htmlparser(htmlstr);
  5271. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  5272. this.children.push(ci);
  5273. ci.parentNode = this;
  5274. }
  5275. return this;
  5276. } else {
  5277. var tmpRoot = new UE.uNode({
  5278. type:'root',
  5279. children:this.children
  5280. });
  5281. return tmpRoot.toHtml();
  5282. }
  5283. },
  5284. innerText:function (textStr) {
  5285. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  5286. return this;
  5287. }
  5288. if (textStr) {
  5289. if(this.children){
  5290. for (var i = 0, ci; ci = this.children[i++];) {
  5291. ci.parentNode = null;
  5292. }
  5293. }
  5294. this.children = [];
  5295. this.appendChild(uNode.createText(textStr));
  5296. return this;
  5297. } else {
  5298. return this.toHtml().replace(/<[^>]+>/g, '');
  5299. }
  5300. },
  5301. getData:function () {
  5302. if (this.type == 'element')
  5303. return '';
  5304. return this.data
  5305. },
  5306. firstChild:function () {
  5307. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  5308. // return this;
  5309. // }
  5310. return this.children ? this.children[0] : null;
  5311. },
  5312. lastChild:function () {
  5313. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  5314. // return this;
  5315. // }
  5316. return this.children ? this.children[this.children.length - 1] : null;
  5317. },
  5318. previousSibling : function(){
  5319. var parent = this.parentNode;
  5320. for (var i = 0, ci; ci = parent.children[i]; i++) {
  5321. if (ci === this) {
  5322. return i == 0 ? null : parent.children[i-1];
  5323. }
  5324. }
  5325. },
  5326. nextSibling : function(){
  5327. var parent = this.parentNode;
  5328. for (var i = 0, ci; ci = parent.children[i++];) {
  5329. if (ci === this) {
  5330. return parent.children[i];
  5331. }
  5332. }
  5333. },
  5334. replaceChild:function (target, source) {
  5335. if (this.children) {
  5336. if(target.parentNode){
  5337. target.parentNode.removeChild(target);
  5338. }
  5339. for (var i = 0, ci; ci = this.children[i]; i++) {
  5340. if (ci === source) {
  5341. this.children.splice(i, 1, target);
  5342. source.parentNode = null;
  5343. target.parentNode = this;
  5344. return target;
  5345. }
  5346. }
  5347. }
  5348. },
  5349. appendChild:function (node) {
  5350. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  5351. if (!this.children) {
  5352. this.children = []
  5353. }
  5354. if(node.parentNode){
  5355. node.parentNode.removeChild(node);
  5356. }
  5357. for (var i = 0, ci; ci = this.children[i]; i++) {
  5358. if (ci === node) {
  5359. this.children.splice(i, 1);
  5360. break;
  5361. }
  5362. }
  5363. this.children.push(node);
  5364. node.parentNode = this;
  5365. return node;
  5366. }
  5367. },
  5368. insertBefore:function (target, source) {
  5369. if (this.children) {
  5370. if(target.parentNode){
  5371. target.parentNode.removeChild(target);
  5372. }
  5373. for (var i = 0, ci; ci = this.children[i]; i++) {
  5374. if (ci === source) {
  5375. this.children.splice(i, 0, target);
  5376. target.parentNode = this;
  5377. return target;
  5378. }
  5379. }
  5380. }
  5381. },
  5382. insertAfter:function (target, source) {
  5383. if (this.children) {
  5384. if(target.parentNode){
  5385. target.parentNode.removeChild(target);
  5386. }
  5387. for (var i = 0, ci; ci = this.children[i]; i++) {
  5388. if (ci === source) {
  5389. this.children.splice(i + 1, 0, target);
  5390. target.parentNode = this;
  5391. return target;
  5392. }
  5393. }
  5394. }
  5395. },
  5396. removeChild:function (node,keepChildren) {
  5397. if (this.children) {
  5398. for (var i = 0, ci; ci = this.children[i]; i++) {
  5399. if (ci === node) {
  5400. this.children.splice(i, 1);
  5401. ci.parentNode = null;
  5402. if(keepChildren && ci.children && ci.children.length){
  5403. for(var j= 0,cj;cj=ci.children[j];j++){
  5404. this.children.splice(i+j,0,cj);
  5405. cj.parentNode = this;
  5406. }
  5407. }
  5408. return ci;
  5409. }
  5410. }
  5411. }
  5412. },
  5413. getAttr:function (attrName) {
  5414. return this.attrs && this.attrs[attrName.toLowerCase()]
  5415. },
  5416. setAttr:function (attrName, attrVal) {
  5417. if (!attrName) {
  5418. delete this.attrs;
  5419. return;
  5420. }
  5421. if(!this.attrs){
  5422. this.attrs = {};
  5423. }
  5424. if (utils.isObject(attrName)) {
  5425. for (var a in attrName) {
  5426. if (!attrName[a]) {
  5427. delete this.attrs[a]
  5428. } else {
  5429. this.attrs[a.toLowerCase()] = attrName[a];
  5430. }
  5431. }
  5432. } else {
  5433. if (!attrVal) {
  5434. delete this.attrs[attrName]
  5435. } else {
  5436. this.attrs[attrName.toLowerCase()] = attrVal;
  5437. }
  5438. }
  5439. },
  5440. getIndex:function(){
  5441. var parent = this.parentNode;
  5442. for(var i= 0,ci;ci=parent.children[i];i++){
  5443. if(ci === this){
  5444. return i;
  5445. }
  5446. }
  5447. return -1;
  5448. },
  5449. getNodeById:function (id) {
  5450. var node;
  5451. if (this.children && this.children.length) {
  5452. for (var i = 0, ci; ci = this.children[i++];) {
  5453. if (node = getNodeById(ci, id)) {
  5454. return node;
  5455. }
  5456. }
  5457. }
  5458. },
  5459. getNodesByTagName:function (tagNames) {
  5460. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  5461. var arr = [], me = this;
  5462. utils.each(tagNames, function (tagName) {
  5463. if (me.children && me.children.length) {
  5464. for (var i = 0, ci; ci = me.children[i++];) {
  5465. getNodesByTagName(ci, tagName, arr)
  5466. }
  5467. }
  5468. });
  5469. return arr;
  5470. },
  5471. getStyle:function (name) {
  5472. var cssStyle = this.getAttr('style');
  5473. if (!cssStyle) {
  5474. return ''
  5475. }
  5476. var reg = new RegExp(name + ':([^;]+)','i');
  5477. var match = cssStyle.match(reg);
  5478. if (match && match[0]) {
  5479. return match[1]
  5480. }
  5481. return '';
  5482. },
  5483. setStyle:function (name, val) {
  5484. function exec(name, val) {
  5485. var reg = new RegExp(name + ':([^;]+;?)', 'gi');
  5486. cssStyle = cssStyle.replace(reg, '');
  5487. if (val) {
  5488. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  5489. }
  5490. }
  5491. var cssStyle = this.getAttr('style');
  5492. if (!cssStyle) {
  5493. cssStyle = '';
  5494. }
  5495. if (utils.isObject(name)) {
  5496. for (var a in name) {
  5497. exec(a, name[a])
  5498. }
  5499. } else {
  5500. exec(name, val)
  5501. }
  5502. this.setAttr('style', cssStyle)
  5503. },
  5504. traversal:function(fn){
  5505. if(this.children && this.children.length){
  5506. nodeTraversal(this,fn);
  5507. }
  5508. return this;
  5509. }
  5510. }
  5511. })();
  5512. //html字符串转换成uNode节点
  5513. //by zhanyi
  5514. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  5515. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  5516. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  5517. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  5518. var allowEmptyTags = {
  5519. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  5520. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  5521. };
  5522. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  5523. if(!ignoreBlank){
  5524. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  5525. //br暂时单独处理
  5526. if(b && allowEmptyTags[b.toLowerCase()]){
  5527. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  5528. }
  5529. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  5530. });
  5531. }
  5532. var uNode = UE.uNode,
  5533. needParentNode = {
  5534. 'td':'tr',
  5535. 'tr':['tbody','thead','tfoot'],
  5536. 'tbody':'table',
  5537. 'th':'tr',
  5538. 'thead':'table',
  5539. 'tfoot':'table',
  5540. 'caption':'table',
  5541. 'li':['ul', 'ol'],
  5542. 'dt':'dl',
  5543. 'dd':'dl',
  5544. 'option':'select'
  5545. },
  5546. needChild = {
  5547. 'ol':'li',
  5548. 'ul':'li'
  5549. };
  5550. function text(parent, data) {
  5551. if(needChild[parent.tagName]){
  5552. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  5553. parent.appendChild(tmpNode);
  5554. tmpNode.appendChild(uNode.createText(data));
  5555. parent = tmpNode;
  5556. }else{
  5557. parent.appendChild(uNode.createText(data));
  5558. }
  5559. }
  5560. function element(parent, tagName, htmlattr) {
  5561. var needParentTag;
  5562. if (needParentTag = needParentNode[tagName]) {
  5563. var tmpParent = parent,hasParent;
  5564. while(tmpParent.type != 'root'){
  5565. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  5566. parent = tmpParent;
  5567. hasParent = true;
  5568. break;
  5569. }
  5570. tmpParent = tmpParent.parentNode;
  5571. }
  5572. if(!hasParent){
  5573. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  5574. }
  5575. }
  5576. //按dtd处理嵌套
  5577. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  5578. // parent = parent.parentNode;
  5579. var elm = new uNode({
  5580. parentNode:parent,
  5581. type:'element',
  5582. tagName:tagName.toLowerCase(),
  5583. //是自闭合的处理一下
  5584. children:dtd.$empty[tagName] ? null : []
  5585. });
  5586. //如果属性存在,处理属性
  5587. if (htmlattr) {
  5588. var attrs = {}, match;
  5589. while (match = re_attr.exec(htmlattr)) {
  5590. attrs[match[1].toLowerCase()] = utils.unhtml(match[2] || match[3] || match[4])
  5591. }
  5592. elm.attrs = attrs;
  5593. }
  5594. parent.children.push(elm);
  5595. //如果是自闭合节点返回父亲节点
  5596. return dtd.$empty[tagName] ? parent : elm
  5597. }
  5598. function comment(parent, data) {
  5599. parent.children.push(new uNode({
  5600. type:'comment',
  5601. data:data,
  5602. parentNode:parent
  5603. }));
  5604. }
  5605. var match, currentIndex = 0, nextIndex = 0;
  5606. //设置根节点
  5607. var root = new uNode({
  5608. type:'root',
  5609. children:[]
  5610. });
  5611. var currentParent = root;
  5612. while (match = re_tag.exec(htmlstr)) {
  5613. currentIndex = match.index;
  5614. try{
  5615. if (currentIndex > nextIndex) {
  5616. //text node
  5617. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  5618. }
  5619. if (match[3]) {
  5620. //start tag
  5621. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  5622. } else if (match[1]) {
  5623. if(currentParent.type != 'root'){
  5624. var tmpParent = currentParent;
  5625. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  5626. currentParent = currentParent.parentNode;
  5627. if(currentParent.type == 'root'){
  5628. currentParent = tmpParent;
  5629. throw 'break'
  5630. }
  5631. }
  5632. //end tag
  5633. currentParent = currentParent.parentNode;
  5634. }
  5635. } else if (match[2]) {
  5636. //comment
  5637. comment(currentParent, match[2])
  5638. }
  5639. }catch(e){}
  5640. nextIndex = re_tag.lastIndex;
  5641. }
  5642. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  5643. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  5644. if (nextIndex < htmlstr.length) {
  5645. text(currentParent, htmlstr.slice(nextIndex));
  5646. }
  5647. return root;
  5648. };
  5649. /**
  5650. * @file
  5651. * @name UE.filterNode
  5652. * @short filterNode
  5653. * @desc 根据给定的规则过滤节点
  5654. * @import editor.js,core/utils.js
  5655. * @anthor zhanyi
  5656. */
  5657. var filterNode = UE.filterNode = function () {
  5658. function filterNode(node,rules){
  5659. switch (node.type) {
  5660. case 'text':
  5661. break;
  5662. case 'element':
  5663. var val;
  5664. if(val = rules[node.tagName]){
  5665. if(val === '-'){
  5666. node.parentNode.removeChild(node)
  5667. }else if(utils.isFunction(val)){
  5668. var parentNode = node.parentNode,
  5669. index = node.getIndex();
  5670. val(node);
  5671. if(node.parentNode){
  5672. if(node.children){
  5673. for(var i = 0,ci;ci=node.children[i];){
  5674. filterNode(ci,rules);
  5675. if(ci.parentNode){
  5676. i++;
  5677. }
  5678. }
  5679. }
  5680. }else{
  5681. for(var i = index,ci;ci=parentNode.children[i];){
  5682. filterNode(ci,rules);
  5683. if(ci.parentNode){
  5684. i++;
  5685. }
  5686. }
  5687. }
  5688. }else{
  5689. var attrs = val['$'];
  5690. if(attrs && node.attrs){
  5691. var tmpAttrs = {},tmpVal;
  5692. for(var a in attrs){
  5693. tmpVal = node.getAttr(a);
  5694. //todo 只先对style单独处理
  5695. if(a == 'style' && utils.isArray(attrs[a])){
  5696. var tmpCssStyle = [];
  5697. utils.each(attrs[a],function(v){
  5698. var tmp;
  5699. if(tmp = node.getStyle(v)){
  5700. tmpCssStyle.push(v + ':' + tmp);
  5701. }
  5702. });
  5703. tmpVal = tmpCssStyle.join(';')
  5704. }
  5705. if(tmpVal){
  5706. tmpAttrs[a] = tmpVal;
  5707. }
  5708. }
  5709. node.attrs = tmpAttrs;
  5710. }
  5711. if(node.children){
  5712. for(var i = 0,ci;ci=node.children[i];){
  5713. filterNode(ci,rules);
  5714. if(ci.parentNode){
  5715. i++;
  5716. }
  5717. }
  5718. }
  5719. }
  5720. }else{
  5721. //如果不在名单里扣出子节点并删除该节点,cdata除外
  5722. if(dtd.$cdata[node.tagName]){
  5723. node.parentNode.removeChild(node)
  5724. }else{
  5725. var parentNode = node.parentNode,
  5726. index = node.getIndex();
  5727. node.parentNode.removeChild(node,true);
  5728. for(var i = index,ci;ci=parentNode.children[i];){
  5729. filterNode(ci,rules);
  5730. if(ci.parentNode){
  5731. i++;
  5732. }
  5733. }
  5734. }
  5735. }
  5736. break;
  5737. case 'comment':
  5738. node.parentNode.removeChild(node)
  5739. }
  5740. }
  5741. return function(root,rules){
  5742. if(utils.isEmptyObject(rules)){
  5743. return root;
  5744. }
  5745. var val;
  5746. if(val = rules['-']){
  5747. utils.each(val.split(' '),function(k){
  5748. rules[k] = '-'
  5749. })
  5750. }
  5751. for(var i= 0,ci;ci=root.children[i];){
  5752. filterNode(ci,rules);
  5753. if(ci.parentNode){
  5754. i++;
  5755. }
  5756. }
  5757. return root;
  5758. }
  5759. }();
  5760. ///import core
  5761. ///plugin 编辑器默认的过滤转换机制
  5762. UE.plugins['defaultfilter'] = function () {
  5763. var me = this;
  5764. //默认的过滤处理
  5765. //进入编辑器的内容处理
  5766. me.addInputRule(function (root) {
  5767. var val;
  5768. //进行默认的处理
  5769. root.traversal(function (node) {
  5770. if (node.type == 'element') {
  5771. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5772. if (!node.firstChild()) node.parentNode.removeChild(node);
  5773. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5774. node.parentNode.removeChild(node, true)
  5775. }
  5776. return;
  5777. }
  5778. switch (node.tagName) {
  5779. case 'style':
  5780. case 'script':
  5781. node.setAttr({
  5782. cdata_tag: node.tagName,
  5783. cdata_data: encodeURIComponent(node.innerText() || '')
  5784. });
  5785. node.tagName = 'div';
  5786. node.removeChild(node.firstChild());
  5787. break;
  5788. case 'a':
  5789. if (val = node.getAttr('href')) {
  5790. node.setAttr('_href', val)
  5791. }
  5792. break;
  5793. case 'img':
  5794. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  5795. /*if (val = node.getAttr('src')) {
  5796. if (/^data:/.test(val)) {
  5797. node.parentNode.removeChild(node);
  5798. break;
  5799. }
  5800. }*/
  5801. node.setAttr('_src', node.getAttr('src'));
  5802. break;
  5803. case 'span':
  5804. if (browser.webkit && (val = node.getStyle('white-space'))) {
  5805. if (/nowrap|normal/.test(val)) {
  5806. node.setStyle('white-space', '');
  5807. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  5808. node.parentNode.removeChild(node, true)
  5809. }
  5810. }
  5811. }
  5812. break;
  5813. case 'p':
  5814. if (val = node.getAttr('align')) {
  5815. node.setAttr('align');
  5816. node.setStyle('text-align', val)
  5817. }
  5818. var cssStyle = node.getAttr('style');
  5819. if (cssStyle) {
  5820. cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  5821. node.setAttr('style', cssStyle)
  5822. }
  5823. if (!node.firstChild()) {
  5824. node.innerHTML(UE.browser.ie ? '&nbsp;' : '<br>')
  5825. }
  5826. break;
  5827. case 'div':
  5828. if(node.getAttr('cdata_tag')){
  5829. break;
  5830. }
  5831. //针对代码这里不处理插入代码的div
  5832. val = node.getAttr('class');
  5833. if(val && /^line number\d+/.test(val)){
  5834. break;
  5835. }
  5836. var tmpNode, p = UE.uNode.createElement('p');
  5837. while (tmpNode = node.firstChild()) {
  5838. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  5839. p.appendChild(tmpNode);
  5840. } else {
  5841. if (p.firstChild()) {
  5842. node.parentNode.insertBefore(p, node);
  5843. p = UE.uNode.createElement('p');
  5844. } else {
  5845. node.parentNode.insertBefore(tmpNode, node);
  5846. }
  5847. }
  5848. }
  5849. if (p.firstChild()) {
  5850. node.parentNode.insertBefore(p, node);
  5851. }
  5852. node.parentNode.removeChild(node);
  5853. break;
  5854. case 'dl':
  5855. node.tagName = 'ul';
  5856. break;
  5857. case 'dt':
  5858. case 'dd':
  5859. node.tagName = 'li';
  5860. break;
  5861. case 'li':
  5862. var className = node.getAttr('class');
  5863. if (!className || !/list\-/.test(className)) {
  5864. node.setAttr()
  5865. }
  5866. var tmpNodes = node.getNodesByTagName('ol ul');
  5867. UE.utils.each(tmpNodes, function (n) {
  5868. node.parentNode.insertAfter(n, node);
  5869. });
  5870. break;
  5871. case 'td':
  5872. case 'th':
  5873. case 'caption':
  5874. if(!node.children || !node.children.length){
  5875. node.appendChild(browser.ie ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  5876. }
  5877. }
  5878. }
  5879. if(node.type == 'comment'){
  5880. node.parentNode.removeChild(node);
  5881. }
  5882. })
  5883. });
  5884. //从编辑器出去的内容处理
  5885. me.addOutputRule(function (root) {
  5886. var val;
  5887. root.traversal(function (node) {
  5888. if (node.type == 'element') {
  5889. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5890. if (!node.firstChild()) node.parentNode.removeChild(node);
  5891. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  5892. node.parentNode.removeChild(node, true)
  5893. }
  5894. return;
  5895. }
  5896. switch (node.tagName) {
  5897. case 'div':
  5898. if (val = node.getAttr('cdata_tag')) {
  5899. node.tagName = val;
  5900. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  5901. node.setAttr({cdata_tag: '', cdata_data: ''});
  5902. }
  5903. break;
  5904. case 'a':
  5905. if (val = node.getAttr('_href')) {
  5906. node.setAttr({
  5907. 'href': val,
  5908. '_href': ''
  5909. })
  5910. }
  5911. break;
  5912. case 'img':
  5913. if (val = node.getAttr('_src')) {
  5914. node.setAttr({
  5915. 'src': node.getAttr('_src'),
  5916. '_src': ''
  5917. })
  5918. }
  5919. }
  5920. }
  5921. })
  5922. });
  5923. };
  5924. ///import core
  5925. /**
  5926. * @description 插入内容
  5927. * @name baidu.editor.execCommand
  5928. * @param {String} cmdName inserthtml插入内容的命令
  5929. * @param {String} html 要插入的内容
  5930. * @author zhanyi
  5931. */
  5932. UE.commands['inserthtml'] = {
  5933. execCommand: function (command,html,notNeedFilter){
  5934. var me = this,
  5935. range,
  5936. div;
  5937. if(!html){
  5938. return;
  5939. }
  5940. if(me.fireEvent('beforeinserthtml',html) === true){
  5941. return;
  5942. }
  5943. range = me.selection.getRange();
  5944. div = range.document.createElement( 'div' );
  5945. div.style.display = 'inline';
  5946. if (!notNeedFilter) {
  5947. var root = UE.htmlparser(html);
  5948. //如果给了过滤规则就先进行过滤
  5949. if(me.options.filterRules){
  5950. UE.filterNode(root,me.options.filterRules);
  5951. }
  5952. //执行默认的处理
  5953. me.filterInputRule(root);
  5954. html = root.toHtml()
  5955. }
  5956. div.innerHTML = utils.trim( html );
  5957. if ( !range.collapsed ) {
  5958. var tmpNode = range.startContainer;
  5959. if(domUtils.isFillChar(tmpNode)){
  5960. range.setStartBefore(tmpNode)
  5961. }
  5962. tmpNode = range.endContainer;
  5963. if(domUtils.isFillChar(tmpNode)){
  5964. range.setEndAfter(tmpNode)
  5965. }
  5966. range.txtToElmBoundary();
  5967. //结束边界可能放到了br的前边,要把br包含进来
  5968. // x[xxx]<br/>
  5969. if(range.endContainer && range.endContainer.nodeType == 1){
  5970. tmpNode = range.endContainer.childNodes[range.endOffset];
  5971. if(tmpNode && domUtils.isBr(tmpNode)){
  5972. range.setEndAfter(tmpNode);
  5973. }
  5974. }
  5975. if(range.startOffset == 0){
  5976. tmpNode = range.startContainer;
  5977. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  5978. tmpNode = range.endContainer;
  5979. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  5980. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  5981. range.setStart(me.body.firstChild,0).collapse(true)
  5982. }
  5983. }
  5984. }
  5985. !range.collapsed && range.deleteContents();
  5986. if(range.startContainer.nodeType == 1){
  5987. var child = range.startContainer.childNodes[range.startOffset],pre;
  5988. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  5989. range.setEnd(pre,pre.childNodes.length).collapse();
  5990. while(child.firstChild){
  5991. pre.appendChild(child.firstChild);
  5992. }
  5993. domUtils.remove(child);
  5994. }
  5995. }
  5996. }
  5997. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  5998. //如果当前位置选中了fillchar要干掉,要不会产生空行
  5999. if(range.inFillChar()){
  6000. child = range.startContainer;
  6001. if(domUtils.isFillChar(child)){
  6002. range.setStartBefore(child).collapse(true);
  6003. domUtils.remove(child);
  6004. }else if(domUtils.isFillChar(child,true)){
  6005. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  6006. range.startOffset--;
  6007. range.collapsed && range.collapse(true)
  6008. }
  6009. }
  6010. //列表单独处理
  6011. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  6012. if(li){
  6013. var next,last;
  6014. while(child = div.firstChild){
  6015. //针对hr单独处理一下先
  6016. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  6017. next = child.nextSibling;
  6018. range.insertNode( child).collapse();
  6019. last = child;
  6020. child = next;
  6021. }
  6022. if(child){
  6023. if(/^(ol|ul)$/i.test(child.tagName)){
  6024. while(child.firstChild){
  6025. last = child.firstChild;
  6026. domUtils.insertAfter(li,child.firstChild);
  6027. li = li.nextSibling;
  6028. }
  6029. domUtils.remove(child)
  6030. }else{
  6031. var tmpLi;
  6032. next = child.nextSibling;
  6033. tmpLi = me.document.createElement('li');
  6034. domUtils.insertAfter(li,tmpLi);
  6035. tmpLi.appendChild(child);
  6036. last = child;
  6037. child = next;
  6038. li = tmpLi;
  6039. }
  6040. }
  6041. }
  6042. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  6043. if(domUtils.isEmptyBlock(li)){
  6044. domUtils.remove(li)
  6045. }
  6046. if(last){
  6047. range.setStartAfter(last).collapse(true).select(true)
  6048. }
  6049. }else{
  6050. while ( child = div.firstChild ) {
  6051. if(hadBreak){
  6052. var p = me.document.createElement('p');
  6053. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  6054. nextNode = child.nextSibling;
  6055. p.appendChild(child);
  6056. child = nextNode;
  6057. }
  6058. if(p.firstChild){
  6059. child = p
  6060. }
  6061. }
  6062. range.insertNode( child );
  6063. nextNode = child.nextSibling;
  6064. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  6065. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  6066. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  6067. if(!dtd[parent.tagName][child.nodeName]){
  6068. pre = parent;
  6069. }else{
  6070. tmp = child.parentNode;
  6071. while (tmp !== parent){
  6072. pre = tmp;
  6073. tmp = tmp.parentNode;
  6074. }
  6075. }
  6076. domUtils.breakParent( child, pre || tmp );
  6077. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  6078. var pre = child.previousSibling;
  6079. domUtils.trimWhiteTextNode(pre);
  6080. if(!pre.childNodes.length){
  6081. domUtils.remove(pre);
  6082. }
  6083. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  6084. if(!browser.ie &&
  6085. (next = child.nextSibling) &&
  6086. domUtils.isBlockElm(next) &&
  6087. next.lastChild &&
  6088. !domUtils.isBr(next.lastChild)){
  6089. next.appendChild(me.document.createElement('br'));
  6090. }
  6091. hadBreak = 1;
  6092. }
  6093. }
  6094. var next = child.nextSibling;
  6095. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  6096. range.setStart(next,0).collapse(true);
  6097. break;
  6098. }
  6099. range.setEndAfter( child ).collapse();
  6100. }
  6101. child = range.startContainer;
  6102. if(nextNode && domUtils.isBr(nextNode)){
  6103. domUtils.remove(nextNode)
  6104. }
  6105. //用chrome可能有空白展位符
  6106. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  6107. if(nextNode = child.nextSibling){
  6108. domUtils.remove(child);
  6109. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  6110. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  6111. }
  6112. }else{
  6113. try{
  6114. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  6115. }catch(e){
  6116. range.setStartBefore(child);
  6117. domUtils.remove(child)
  6118. }
  6119. }
  6120. }
  6121. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  6122. try{
  6123. range.select(true);
  6124. }catch(e){}
  6125. }
  6126. setTimeout(function(){
  6127. range = me.selection.getRange();
  6128. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  6129. me.fireEvent('afterinserthtml');
  6130. },200);
  6131. }
  6132. };
  6133. ///import core
  6134. ///commands 自动排版
  6135. ///commandsName autotypeset
  6136. ///commandsTitle 自动排版
  6137. /**
  6138. * 自动排版
  6139. * @function
  6140. * @name baidu.editor.execCommands
  6141. */
  6142. UE.plugins['autotypeset'] = function(){
  6143. this.setOpt({'autotypeset':{
  6144. mergeEmptyline : true, //合并空行
  6145. removeClass : true, //去掉冗余的class
  6146. removeEmptyline : false, //去掉空行
  6147. textAlign : "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  6148. imageBlockLine : 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  6149. pasteFilter : false, //根据规则过滤没事粘贴进来的内容
  6150. clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号
  6151. clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体
  6152. removeEmptyNode : false, // 去掉空节点
  6153. //可以去掉的标签
  6154. removeTagNames : utils.extend({div:1},dtd.$removeEmpty),
  6155. indent : false, // 行首缩进
  6156. indentValue : '2em' //行首缩进的大小
  6157. }});
  6158. var me = this,
  6159. opt = me.options.autotypeset,
  6160. remainClass = {
  6161. 'selectTdClass':1,
  6162. 'pagebreak':1,
  6163. 'anchorclass':1
  6164. },
  6165. remainTag = {
  6166. 'li':1
  6167. },
  6168. tags = {
  6169. div:1,
  6170. p:1,
  6171. //trace:2183 这些也认为是行
  6172. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  6173. span:1
  6174. },
  6175. highlightCont;
  6176. //升级了版本,但配置项目里没有autotypeset
  6177. if(!opt){
  6178. return;
  6179. }
  6180. function isLine(node,notEmpty){
  6181. if(!node || node.nodeType == 3)
  6182. return 0;
  6183. if(domUtils.isBr(node))
  6184. return 1;
  6185. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  6186. if(highlightCont && highlightCont.contains(node)
  6187. ||
  6188. node.getAttribute('pagebreak')
  6189. ){
  6190. return 0;
  6191. }
  6192. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  6193. +']','g'));
  6194. }
  6195. }
  6196. function removeNotAttributeSpan(node){
  6197. if(!node.style.cssText){
  6198. domUtils.removeAttributes(node,['style']);
  6199. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  6200. domUtils.remove(node,true);
  6201. }
  6202. }
  6203. }
  6204. function autotype(type,html){
  6205. var me = this,cont;
  6206. if(html){
  6207. if(!opt.pasteFilter){
  6208. return;
  6209. }
  6210. cont = me.document.createElement('div');
  6211. cont.innerHTML = html.html;
  6212. }else{
  6213. cont = me.document.body;
  6214. }
  6215. var nodes = domUtils.getElementsByTagName(cont,'*');
  6216. // 行首缩进,段落方向,段间距,段内间距
  6217. for(var i=0,ci;ci=nodes[i++];){
  6218. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  6219. continue;
  6220. }
  6221. //font-size
  6222. if(opt.clearFontSize && ci.style.fontSize){
  6223. domUtils.removeStyle(ci,'font-size');
  6224. removeNotAttributeSpan(ci);
  6225. }
  6226. //font-family
  6227. if(opt.clearFontFamily && ci.style.fontFamily){
  6228. domUtils.removeStyle(ci,'font-family');
  6229. removeNotAttributeSpan(ci);
  6230. }
  6231. if(isLine(ci)){
  6232. //合并空行
  6233. if(opt.mergeEmptyline ){
  6234. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  6235. while(isLine(next)){
  6236. tmpNode = next;
  6237. next = tmpNode.nextSibling;
  6238. if(isBr && (!next || next && !domUtils.isBr(next))){
  6239. break;
  6240. }
  6241. domUtils.remove(tmpNode);
  6242. }
  6243. }
  6244. //去掉空行,保留占位的空行
  6245. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  6246. if(domUtils.isBr(ci)){
  6247. next = ci.nextSibling;
  6248. if(next && !domUtils.isBr(next)){
  6249. continue;
  6250. }
  6251. }
  6252. domUtils.remove(ci);
  6253. continue;
  6254. }
  6255. }
  6256. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  6257. if(opt.indent){
  6258. ci.style.textIndent = opt.indentValue;
  6259. }
  6260. if(opt.textAlign){
  6261. ci.style.textAlign = opt.textAlign;
  6262. }
  6263. // if(opt.lineHeight)
  6264. // ci.style.lineHeight = opt.lineHeight + 'cm';
  6265. }
  6266. //去掉class,保留的class不去掉
  6267. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  6268. if(highlightCont && highlightCont.contains(ci)){
  6269. continue;
  6270. }
  6271. domUtils.removeAttributes(ci,['class']);
  6272. }
  6273. //表情不处理
  6274. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  6275. if(html){
  6276. var img = ci;
  6277. switch (opt.imageBlockLine){
  6278. case 'left':
  6279. case 'right':
  6280. case 'none':
  6281. var pN = img.parentNode,tmpNode,pre,next;
  6282. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  6283. pN = pN.parentNode;
  6284. }
  6285. tmpNode = pN;
  6286. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  6287. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  6288. pre = tmpNode.previousSibling;
  6289. next = tmpNode.nextSibling;
  6290. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  6291. pre.appendChild(tmpNode.firstChild);
  6292. while(next.firstChild){
  6293. pre.appendChild(next.firstChild);
  6294. }
  6295. domUtils.remove(tmpNode);
  6296. domUtils.remove(next);
  6297. }else{
  6298. domUtils.setStyle(tmpNode,'text-align','');
  6299. }
  6300. }
  6301. }
  6302. domUtils.setStyle(img,'float',opt.imageBlockLine);
  6303. break;
  6304. case 'center':
  6305. if(me.queryCommandValue('imagefloat') != 'center'){
  6306. pN = img.parentNode;
  6307. domUtils.setStyle(img,'float','none');
  6308. tmpNode = img;
  6309. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  6310. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  6311. tmpNode = pN;
  6312. pN = pN.parentNode;
  6313. }
  6314. var pNode = me.document.createElement('p');
  6315. domUtils.setAttributes(pNode,{
  6316. style:'text-align:center'
  6317. });
  6318. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  6319. pNode.appendChild(tmpNode);
  6320. domUtils.setStyle(tmpNode,'float','');
  6321. }
  6322. }
  6323. }else{
  6324. var range = me.selection.getRange();
  6325. range.selectNode(ci).select();
  6326. me.execCommand('imagefloat',opt.imageBlockLine);
  6327. }
  6328. }
  6329. //去掉冗余的标签
  6330. if(opt.removeEmptyNode){
  6331. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  6332. domUtils.remove(ci);
  6333. }
  6334. }
  6335. }
  6336. if(html){
  6337. html.html = cont.innerHTML;
  6338. }
  6339. }
  6340. if(opt.pasteFilter){
  6341. me.addListener('beforepaste',autotype);
  6342. }
  6343. me.commands['autotypeset'] = {
  6344. execCommand:function () {
  6345. me.removeListener('beforepaste',autotype);
  6346. if(opt.pasteFilter){
  6347. me.addListener('beforepaste',autotype);
  6348. }
  6349. autotype.call(me)
  6350. }
  6351. };
  6352. };
  6353. ///import core
  6354. ///commands 自动提交
  6355. ///commandsName autosubmit
  6356. ///commandsTitle 自动提交
  6357. UE.plugins['autosubmit'] = function(){
  6358. var me = this;
  6359. me.commands['autosubmit'] = {
  6360. execCommand:function () {
  6361. var me=this,
  6362. form = domUtils.findParentByTagName(me.iframe,"form", false);
  6363. if (form) {
  6364. if(me.fireEvent("beforesubmit")===false){
  6365. return;
  6366. }
  6367. me.sync();
  6368. form.submit();
  6369. }
  6370. }
  6371. };
  6372. //快捷键
  6373. me.addshortcutkey({
  6374. "autosubmit" : "ctrl+13" //手动提交
  6375. });
  6376. };
  6377. ///import core
  6378. ///commands 插入背景
  6379. ///commandsName background
  6380. ///commandsTitle 插入背景
  6381. ///commandsDialog dialogs\background
  6382. UE.plugins['background'] = function(){
  6383. var me = this;
  6384. me.addListener("getAllHtml",function(type,headHtml){
  6385. var body = this.body,
  6386. su = domUtils.getComputedStyle(body,"background-image"),
  6387. url="";
  6388. if(su.indexOf(me.options.imagePath)>0){
  6389. url = su.substring(su.indexOf(me.options.imagePath),su.length-1).replace(/"|\(|\)/ig,"");
  6390. }else{
  6391. url = su!="none" ? su.replace(/url\("?|"?\)/ig,""):"";
  6392. }
  6393. var html = '<style type="text/css">body{';
  6394. var bgObj = {
  6395. "background-color" : domUtils.getComputedStyle(body,"background-color")||"#ffffff",
  6396. 'background-image' : url ? 'url('+url+')' : '',
  6397. 'background-repeat':domUtils.getComputedStyle(body,"background-repeat")||"",
  6398. 'background-position': browser.ie?(domUtils.getComputedStyle(body,"background-position-x")+" "+domUtils.getComputedStyle(body,"background-position-y")):domUtils.getComputedStyle(body,"background-position"),
  6399. 'height':domUtils.getComputedStyle(body,"height")
  6400. };
  6401. for ( var name in bgObj ) {
  6402. if ( bgObj.hasOwnProperty( name ) ) {
  6403. html += name+":"+bgObj[name]+";";
  6404. }
  6405. }
  6406. html += '}</style> ';
  6407. headHtml.push(html);
  6408. });
  6409. }
  6410. ///import core
  6411. ///import plugins\inserthtml.js
  6412. ///commands 插入图片,操作图片的对齐方式
  6413. ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter
  6414. ///commandsTitle 图片,默认,居左,居右,居中
  6415. ///commandsDialog dialogs\image
  6416. /**
  6417. * Created by .
  6418. * User: zhanyi
  6419. * for image
  6420. */
  6421. UE.commands['imagefloat'] = {
  6422. execCommand:function (cmd, align) {
  6423. var me = this,
  6424. range = me.selection.getRange();
  6425. if (!range.collapsed) {
  6426. var img = range.getClosedNode();
  6427. if (img && img.tagName == 'IMG') {
  6428. switch (align) {
  6429. case 'left':
  6430. case 'right':
  6431. case 'none':
  6432. var pN = img.parentNode, tmpNode, pre, next;
  6433. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  6434. pN = pN.parentNode;
  6435. }
  6436. tmpNode = pN;
  6437. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  6438. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  6439. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  6440. }) == 1) {
  6441. pre = tmpNode.previousSibling;
  6442. next = tmpNode.nextSibling;
  6443. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  6444. pre.appendChild(tmpNode.firstChild);
  6445. while (next.firstChild) {
  6446. pre.appendChild(next.firstChild);
  6447. }
  6448. domUtils.remove(tmpNode);
  6449. domUtils.remove(next);
  6450. } else {
  6451. domUtils.setStyle(tmpNode, 'text-align', '');
  6452. }
  6453. }
  6454. range.selectNode(img).select();
  6455. }
  6456. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  6457. if(align == 'none'){
  6458. domUtils.removeAttributes(img,'align');
  6459. }
  6460. break;
  6461. case 'center':
  6462. if (me.queryCommandValue('imagefloat') != 'center') {
  6463. pN = img.parentNode;
  6464. domUtils.setStyle(img, 'float', '');
  6465. domUtils.removeAttributes(img,'align');
  6466. tmpNode = img;
  6467. while (pN && domUtils.getChildCount(pN, function (node) {
  6468. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  6469. }) == 1
  6470. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  6471. tmpNode = pN;
  6472. pN = pN.parentNode;
  6473. }
  6474. range.setStartBefore(tmpNode).setCursor(false);
  6475. pN = me.document.createElement('div');
  6476. pN.appendChild(tmpNode);
  6477. domUtils.setStyle(tmpNode, 'float', '');
  6478. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  6479. tmpNode = me.document.getElementById('_img_parent_tmp');
  6480. tmpNode.removeAttribute('id');
  6481. tmpNode = tmpNode.firstChild;
  6482. range.selectNode(tmpNode).select();
  6483. //去掉后边多余的元素
  6484. next = tmpNode.parentNode.nextSibling;
  6485. if (next && domUtils.isEmptyNode(next)) {
  6486. domUtils.remove(next);
  6487. }
  6488. }
  6489. break;
  6490. }
  6491. }
  6492. }
  6493. },
  6494. queryCommandValue:function () {
  6495. var range = this.selection.getRange(),
  6496. startNode, floatStyle;
  6497. if (range.collapsed) {
  6498. return 'none';
  6499. }
  6500. startNode = range.getClosedNode();
  6501. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  6502. floatStyle = startNode.getAttribute('align')||domUtils.getComputedStyle(startNode, 'float');
  6503. if (floatStyle == 'none') {
  6504. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  6505. }
  6506. return {
  6507. left:1,
  6508. right:1,
  6509. center:1
  6510. }[floatStyle] ? floatStyle : 'none';
  6511. }
  6512. return 'none';
  6513. },
  6514. queryCommandState:function () {
  6515. var range = this.selection.getRange(),
  6516. startNode;
  6517. if (range.collapsed) return -1;
  6518. startNode = range.getClosedNode();
  6519. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  6520. return 0;
  6521. }
  6522. return -1;
  6523. }
  6524. };
  6525. UE.commands['insertimage'] = {
  6526. execCommand:function (cmd, opt) {
  6527. opt = utils.isArray(opt) ? opt : [opt];
  6528. if (!opt.length) {
  6529. return;
  6530. }
  6531. var me = this,
  6532. range = me.selection.getRange(),
  6533. img = range.getClosedNode();
  6534. if (img && /img/i.test(img.tagName) && img.className != "edui-faked-video" && !img.getAttribute("word_img")) {
  6535. var first = opt.shift();
  6536. var floatStyle = first['floatStyle'];
  6537. delete first['floatStyle'];
  6538. //// img.style.border = (first.border||0) +"px solid #000";
  6539. //// img.style.margin = (first.margin||0) +"px";
  6540. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  6541. domUtils.setAttributes(img, first);
  6542. me.execCommand('imagefloat', floatStyle);
  6543. if (opt.length > 0) {
  6544. range.setStartAfter(img).setCursor(false, true);
  6545. me.execCommand('insertimage', opt);
  6546. }
  6547. } else {
  6548. var setImgSize = function(ci){
  6549. var tmpImg = new Image();
  6550. tmpImg.src = ci.src;
  6551. if(tmpImg.width>480){
  6552. ci.width = 480;
  6553. }else{
  6554. if(tmpImg.width==0){
  6555. ci.width = 480;
  6556. $("<img src='"+ci.src+"'/>").bind("load",function(){
  6557. if(this.width<480){
  6558. $(me.body).find("img[src='"+ci.src+"']").attr({
  6559. width : this.width
  6560. });
  6561. }
  6562. });
  6563. }else{
  6564. ci.width = tmpImg.width;
  6565. }
  6566. }
  6567. }
  6568. var html = [], str = '', ci;
  6569. ci = opt[0];
  6570. if (opt.length == 1) {
  6571. setImgSize(ci);
  6572. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  6573. (ci.width ? 'width="' + ci.width + '" ' : '') +
  6574. (ci.height ? ' height="' + ci.height + '" ' : '') +
  6575. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  6576. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  6577. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  6578. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  6579. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  6580. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  6581. if (ci['floatStyle'] == 'center') {
  6582. str = '<p style="text-align: center">' + str + '</p>';
  6583. }
  6584. html.push(str);
  6585. } else {
  6586. for (var i = 0; ci = opt[i++];) {
  6587. setImgSize(ci);
  6588. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  6589. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  6590. (ci.height ? ' height="' + ci.height + '" ' : '') +
  6591. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  6592. (ci.border || '') + '" ' +
  6593. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  6594. html.push(str);
  6595. }
  6596. }
  6597. me.execCommand('insertHtml', html.join(''));
  6598. }
  6599. }
  6600. };
  6601. ///import core
  6602. ///commands 段落格式,居左,居右,居中,两端对齐
  6603. ///commandsName JustifyLeft,JustifyCenter,JustifyRight,JustifyJustify
  6604. ///commandsTitle 居左对齐,居中对齐,居右对齐,两端对齐
  6605. /**
  6606. * @description 居左右中
  6607. * @name baidu.editor.execCommand
  6608. * @param {String} cmdName justify执行对齐方式的命令
  6609. * @param {String} align 对齐方式:left居左,right居右,center居中,justify两端对齐
  6610. * @author zhanyi
  6611. */
  6612. UE.plugins['justify']=function(){
  6613. var me=this,
  6614. block = domUtils.isBlockElm,
  6615. defaultValue = {
  6616. left:1,
  6617. right:1,
  6618. center:1,
  6619. justify:1
  6620. },
  6621. doJustify = function (range, style) {
  6622. var bookmark = range.createBookmark(),
  6623. filterFn = function (node) {
  6624. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  6625. };
  6626. range.enlarge(true);
  6627. var bookmark2 = range.createBookmark(),
  6628. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  6629. tmpRange = range.cloneRange(),
  6630. tmpNode;
  6631. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  6632. if (current.nodeType == 3 || !block(current)) {
  6633. tmpRange.setStartBefore(current);
  6634. while (current && current !== bookmark2.end && !block(current)) {
  6635. tmpNode = current;
  6636. current = domUtils.getNextDomNode(current, false, null, function (node) {
  6637. return !block(node);
  6638. });
  6639. }
  6640. tmpRange.setEndAfter(tmpNode);
  6641. var common = tmpRange.getCommonAncestor();
  6642. if (!domUtils.isBody(common) && block(common)) {
  6643. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  6644. current = common;
  6645. } else {
  6646. var p = range.document.createElement('p');
  6647. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  6648. var frag = tmpRange.extractContents();
  6649. p.appendChild(frag);
  6650. tmpRange.insertNode(p);
  6651. current = p;
  6652. }
  6653. current = domUtils.getNextDomNode(current, false, filterFn);
  6654. } else {
  6655. current = domUtils.getNextDomNode(current, true, filterFn);
  6656. }
  6657. }
  6658. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  6659. };
  6660. UE.commands['justify'] = {
  6661. execCommand:function (cmdName, align) {
  6662. var range = this.selection.getRange(),
  6663. txt;
  6664. //闭合时单独处理
  6665. if (range.collapsed) {
  6666. txt = this.document.createTextNode('p');
  6667. range.insertNode(txt);
  6668. }
  6669. doJustify(range, align);
  6670. if (txt) {
  6671. range.setStartBefore(txt).collapse(true);
  6672. domUtils.remove(txt);
  6673. }
  6674. range.select();
  6675. return true;
  6676. },
  6677. queryCommandValue:function () {
  6678. var startNode = this.selection.getStart(),
  6679. value = domUtils.getComputedStyle(startNode, 'text-align');
  6680. return defaultValue[value] ? value : 'left';
  6681. },
  6682. queryCommandState:function () {
  6683. var start = this.selection.getStart(),
  6684. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  6685. return cell? -1:0;
  6686. }
  6687. };
  6688. };
  6689. ///import core
  6690. ///import plugins\removeformat.js
  6691. ///commands 字体颜色,背景色,字号,字体,下划线,删除线
  6692. ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough
  6693. ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线
  6694. /**
  6695. * @description 字体
  6696. * @name baidu.editor.execCommand
  6697. * @param {String} cmdName 执行的功能名称
  6698. * @param {String} value 传入的值
  6699. */
  6700. UE.plugins['font'] = function() {
  6701. var me = this,
  6702. fonts = {
  6703. 'forecolor':'color',
  6704. 'backcolor':'background-color',
  6705. 'fontsize':'font-size',
  6706. 'fontfamily':'font-family',
  6707. 'underline':'text-decoration',
  6708. 'strikethrough':'text-decoration',
  6709. 'fontborder':'border'
  6710. },
  6711. needCmd = {'underline':1,'strikethrough':1,'fontborder':1};
  6712. me.setOpt({
  6713. 'fontfamily':[
  6714. { name:'songti',val:'宋体,SimSun'},
  6715. { name:'yahei',val:'微软雅黑,Microsoft YaHei'},
  6716. { name:'kaiti',val:'楷体,楷体_GB2312, SimKai'},
  6717. { name:'heiti',val:'黑体, SimHei'},
  6718. { name:'lishu',val:'隶书, SimLi'},
  6719. { name:'andaleMono',val:'andale mono'},
  6720. { name:'arial',val:'arial, helvetica,sans-serif'},
  6721. { name:'arialBlack',val:'arial black,avant garde'},
  6722. { name:'comicSansMs',val:'comic sans ms'},
  6723. { name:'impact',val:'impact,chicago'},
  6724. { name:'timesNewRoman',val:'times new roman'}
  6725. ],
  6726. 'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36]
  6727. });
  6728. // function mergesibling(range,me){
  6729. // var collapsed = range.collapsed,
  6730. // bk = range.createBookmark(),common;
  6731. // if(collapsed){
  6732. // common = bk.start.parentNode;
  6733. // while(dtd.$inline[common.tagName]){
  6734. // common = common.parentNode;
  6735. // }
  6736. // }else{
  6737. //
  6738. // common = domUtils.getCommonAncestor(bk.start,bk.end);
  6739. // }
  6740. //
  6741. // utils.each(domUtils.getElementsByTagName(common,'span'),function(node){
  6742. // if(!node.parentNode){
  6743. // return;
  6744. // }
  6745. // function isBorder(n){
  6746. // if(!n)
  6747. // return false;
  6748. // if(n.tagName != 'SPAN')
  6749. // return false;
  6750. // var val;
  6751. // if(val = domUtils.getComputedStyle( n, 'border' )){
  6752. // if(/1px/.test(val) && /solid/.test(val)){
  6753. // return true;
  6754. // }
  6755. // }
  6756. // return false;
  6757. // }
  6758. // function nextSibling(node){
  6759. // var next = node.nextSibling;
  6760. // if(next && domUtils.isBookmarkNode(next)){
  6761. // next = next.nextSibling;
  6762. // }
  6763. // return next;
  6764. // }
  6765. //
  6766. // var span = me.document.createElement('span');
  6767. // span.style.cssText = 'border:1px solid #000';
  6768. // node.parentNode.insertBefore(span,node);
  6769. // while(isBorder(node) && isBorder(nextSibling(node))){
  6770. // var val = utils.trim(node.style.cssText.replace(/border[^:]+:[^;]+;?/gi,''));
  6771. // node.style.cssText = val;
  6772. // var tmp = node.nextSibling;
  6773. // if(!val){
  6774. // while(node.firstChild){
  6775. // if(isBorder(node.firstChild)){
  6776. // node.firstChild.style.cssText = node.firstChild.style.cssText.replace(/border[^:]+:[^;]+;?/gi,'');
  6777. // }
  6778. // span.appendChild(node.firstChild)
  6779. // }
  6780. // domUtils.remove(node)
  6781. // }else{
  6782. // span.appendChild(node);
  6783. // }
  6784. // if(domUtils.isBookmarkNode(tmp)){
  6785. // node = tmp.nextSibling;
  6786. // span.appendChild(tmp)
  6787. // }else{
  6788. // node = tmp;
  6789. // }
  6790. // }
  6791. // if(!span.firstChild){
  6792. // domUtils.remove(span)
  6793. // }else{
  6794. // if(isBorder(span) && isBorder(nextSibling(span))){
  6795. // node = span.nextSibling;
  6796. // var val = utils.trim(node.style.cssText.replace(/border[^:]+:[^;]+;?/gi,''));
  6797. // node.style.cssText = val;
  6798. //
  6799. // if(!val){
  6800. // while(node.firstChild){
  6801. // if(isBorder(node.firstChild)){
  6802. // node.firstChild.style.cssText = node.firstChild.style.cssText.replace(/border[^:]+:[^;];?/,'');
  6803. // }
  6804. // span.appendChild(node.firstChild)
  6805. // }
  6806. // domUtils.remove(node)
  6807. // }else{
  6808. // span.appendChild(node);
  6809. // }
  6810. // }
  6811. // }
  6812. // if(isBorder(node)){
  6813. // var tmpParent = node.parentNode;
  6814. // while(dtd.$inline[tmpParent.tagName]){
  6815. // if(isBorder(tmpParent)){
  6816. // var val = utils.trim(node.style.cssText.replace(/border[^:]+:[^;]+;?/gi,''));
  6817. // node.style.cssText = val;
  6818. // if(!val){
  6819. // domUtils.remove(node,true)
  6820. // }
  6821. // break;
  6822. // }
  6823. // tmpParent = tmpParent.parentNode;
  6824. //
  6825. // }
  6826. //
  6827. // }
  6828. //
  6829. // });
  6830. // range.moveToBookmark(bk);
  6831. // }
  6832. function mergesibling(rng){
  6833. var collapsed = rng.collapsed,
  6834. bk = rng.createBookmark(),common;
  6835. if(collapsed){
  6836. common = bk.start.parentNode;
  6837. while(dtd.$inline[common.tagName]){
  6838. common = common.parentNode;
  6839. }
  6840. }else{
  6841. common = domUtils.getCommonAncestor(bk.start,bk.end);
  6842. }
  6843. utils.each(domUtils.getElementsByTagName(common,'span'),function(span){
  6844. if(!span.parentNode || domUtils.isBookmarkNode(span))return;
  6845. if(/^\s*border\s*:\s*none;\s*/i.test(span.style.cssText)){
  6846. domUtils.remove(span,true);
  6847. return
  6848. }
  6849. if(/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)){
  6850. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi,'');
  6851. }
  6852. var next = span.nextSibling;
  6853. while(next && next.nodeType == 1 && next.tagName == 'SPAN'){
  6854. if(domUtils.isBookmarkNode(next)){
  6855. span.appendChild(next);
  6856. }else{
  6857. if(next.style.cssText == span.style.cssText){
  6858. domUtils.moveChild(next,span);
  6859. domUtils.remove(next);
  6860. }
  6861. }
  6862. if(span.nextSibling === next)
  6863. break;
  6864. next = span.nextSibling;
  6865. }
  6866. });
  6867. rng.moveToBookmark(bk);
  6868. }
  6869. me.addInputRule(function(root){
  6870. utils.each(root.getNodesByTagName('u s del font'),function(node){
  6871. if(node.tagName == 'font'){
  6872. var cssStyle = [];
  6873. for(var p in node.attrs){
  6874. switch (p){
  6875. case 'size':
  6876. cssStyle.push('font-size:' + node.attrs[p] + 'px');
  6877. break;
  6878. case 'color':
  6879. cssStyle.push('color:'+ node.attrs[p]);
  6880. break;
  6881. case 'face':
  6882. cssStyle.push('font-family:'+ node.attrs[p]);
  6883. break;
  6884. case 'style':
  6885. cssStyle.push(node.attrs[p]);
  6886. }
  6887. }
  6888. node.attrs = {
  6889. 'style' : cssStyle.join(';')
  6890. };
  6891. }else{
  6892. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  6893. node.attrs = {
  6894. 'style' : (node.getAttr('style') || '') + 'text-decoration:'+val+';'
  6895. }
  6896. }
  6897. node.tagName = 'span';
  6898. });
  6899. });
  6900. for ( var p in fonts ) {
  6901. (function( cmd, style ) {
  6902. UE.commands[cmd] = {
  6903. execCommand : function( cmdName, value ) {
  6904. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  6905. cmdName == 'fontborder' ? '1px solid #000' :
  6906. 'line-through');
  6907. var me = this,
  6908. range = this.selection.getRange(),
  6909. text;
  6910. if ( value == 'default' ) {
  6911. if(range.collapsed){
  6912. text = me.document.createTextNode('font');
  6913. range.insertNode(text).select();
  6914. }
  6915. me.execCommand( 'removeFormat', 'span,a', style);
  6916. if(text){
  6917. range.setStartBefore(text).setCursor();
  6918. domUtils.remove(text);
  6919. }
  6920. } else {
  6921. if ( !range.collapsed ) {
  6922. if(needCmd[cmd] && me.queryCommandValue(cmd)){
  6923. me.execCommand( 'removeFormat', 'span,a', style );
  6924. }
  6925. range = me.selection.getRange();
  6926. range.applyInlineStyle( 'span', {'style':style + ':' + value} );
  6927. mergesibling(range,me);
  6928. range.select();
  6929. } else {
  6930. var span = domUtils.findParentByTagName(range.startContainer,'span',true);
  6931. text = me.document.createTextNode('font');
  6932. if(span && !span.children.length && !span[browser.ie ? 'innerText':'textContent'].replace(fillCharReg,'').length){
  6933. //for ie hack when enter
  6934. range.insertNode(text);
  6935. if(needCmd[cmd]){
  6936. range.selectNode(text).select();
  6937. me.execCommand( 'removeFormat','span,a', style, null );
  6938. span = domUtils.findParentByTagName(text,'span',true);
  6939. range.setStartBefore(text);
  6940. }
  6941. span && (span.style.cssText += ';' + style + ':' + value);
  6942. range.collapse(true).select();
  6943. }else{
  6944. range.insertNode(text);
  6945. range.selectNode(text).select();
  6946. span = range.document.createElement( 'span' );
  6947. if(needCmd[cmd]){
  6948. //a标签内的不处理跳过
  6949. if(domUtils.findParentByTagName(text,'a',true)){
  6950. range.setStartBefore(text).setCursor();
  6951. domUtils.remove(text);
  6952. return;
  6953. }
  6954. me.execCommand( 'removeFormat','span,a', style );
  6955. }
  6956. span.style.cssText = style + ':' + value;
  6957. text.parentNode.insertBefore(span,text);
  6958. //修复,span套span 但样式不继承的问题
  6959. if(!browser.ie || browser.ie && browser.version == 9){
  6960. var spanParent = span.parentNode;
  6961. while(!domUtils.isBlockElm(spanParent)){
  6962. if(spanParent.tagName == 'SPAN'){
  6963. //opera合并style不会加入";"
  6964. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  6965. }
  6966. spanParent = spanParent.parentNode;
  6967. }
  6968. }
  6969. if(opera){
  6970. setTimeout(function(){
  6971. range.setStart(span,0).collapse(true);
  6972. mergesibling(range,me);
  6973. range.select();
  6974. });
  6975. }else{
  6976. range.setStart(span,0).collapse(true);
  6977. mergesibling(range,me);
  6978. range.select();
  6979. }
  6980. //trace:981
  6981. //domUtils.mergeToParent(span)
  6982. }
  6983. domUtils.remove(text);
  6984. }
  6985. }
  6986. return true;
  6987. },
  6988. queryCommandValue : function (cmdName) {
  6989. var startNode = this.selection.getStart();
  6990. //trace:946
  6991. if(cmdName == 'underline'||cmdName=='strikethrough' ){
  6992. var tmpNode = startNode,value;
  6993. while(tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)){
  6994. if(tmpNode.nodeType == 1){
  6995. value = domUtils.getComputedStyle( tmpNode, style );
  6996. if(value != 'none'){
  6997. return value;
  6998. }
  6999. }
  7000. tmpNode = tmpNode.parentNode;
  7001. }
  7002. return 'none';
  7003. }
  7004. if(cmdName == 'fontborder'){
  7005. var tmp = startNode,val;
  7006. while(tmp && dtd.$inline[tmp.tagName]){
  7007. if(val = domUtils.getComputedStyle( tmp, 'border' )){
  7008. if( /1px/.test(val) && /solid/.test(val)){
  7009. return val;
  7010. }
  7011. }
  7012. tmp = tmp.parentNode;
  7013. }
  7014. return ''
  7015. }
  7016. return domUtils.getComputedStyle( startNode, style );
  7017. },
  7018. queryCommandState : function(cmdName){
  7019. if(!needCmd[cmdName])
  7020. return 0;
  7021. var val = this.queryCommandValue(cmdName);
  7022. if(cmdName == 'fontborder'){
  7023. return /1px/.test(val) && /solid/.test(val)
  7024. }else{
  7025. return val == (cmdName == 'underline' ?
  7026. 'underline' : 'line-through');
  7027. }
  7028. }
  7029. };
  7030. })( p, fonts[p] );
  7031. }
  7032. };
  7033. ///import core
  7034. ///commands 超链接,取消链接
  7035. ///commandsName Link,Unlink
  7036. ///commandsTitle 超链接,取消链接
  7037. ///commandsDialog dialogs\link
  7038. /**
  7039. * 超链接
  7040. * @function
  7041. * @name baidu.editor.execCommand
  7042. * @param {String} cmdName link插入超链接
  7043. * @param {Object} options url地址,title标题,target是否打开新页
  7044. * @author zhanyi
  7045. */
  7046. /**
  7047. * 取消链接
  7048. * @function
  7049. * @name baidu.editor.execCommand
  7050. * @param {String} cmdName unlink取消链接
  7051. * @author zhanyi
  7052. */
  7053. UE.plugins['link'] = function(){
  7054. function optimize( range ) {
  7055. var start = range.startContainer,end = range.endContainer;
  7056. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  7057. range.setStartBefore( start );
  7058. }
  7059. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  7060. range.setEndAfter( end );
  7061. }
  7062. }
  7063. UE.commands['unlink'] = {
  7064. execCommand : function() {
  7065. var range = this.selection.getRange(),
  7066. bookmark;
  7067. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  7068. return;
  7069. }
  7070. bookmark = range.createBookmark();
  7071. optimize( range );
  7072. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  7073. },
  7074. queryCommandState : function(){
  7075. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  7076. }
  7077. };
  7078. function doLink(range,opt,me){
  7079. var rngClone = range.cloneRange(),
  7080. link = me.queryCommandValue('link');
  7081. optimize( range = range.adjustmentBoundary() );
  7082. var start = range.startContainer;
  7083. if(start.nodeType == 1 && link){
  7084. start = start.childNodes[range.startOffset];
  7085. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  7086. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  7087. }
  7088. }
  7089. if( !rngClone.collapsed || link){
  7090. range.removeInlineStyle( 'a' );
  7091. rngClone = range.cloneRange();
  7092. }
  7093. if ( rngClone.collapsed ) {
  7094. var a = range.document.createElement( 'a'),
  7095. text = '';
  7096. if(opt.textValue){
  7097. text = utils.html(opt.textValue);
  7098. delete opt.textValue;
  7099. }else{
  7100. text = utils.html(opt.href);
  7101. }
  7102. domUtils.setAttributes( a, opt );
  7103. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  7104. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  7105. range.setStartAfter(start).collapse(true);
  7106. }
  7107. a[browser.ie ? 'innerText' : 'textContent'] = text;
  7108. range.insertNode(a).selectNode( a );
  7109. } else {
  7110. range.applyInlineStyle( 'a', opt );
  7111. }
  7112. }
  7113. UE.commands['link'] = {
  7114. execCommand : function( cmdName, opt ) {
  7115. var range;
  7116. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  7117. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  7118. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  7119. doLink(range=this.selection.getRange(),opt,this);
  7120. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  7121. range.collapse().select(true);
  7122. },
  7123. queryCommandValue : function() {
  7124. var range = this.selection.getRange(),
  7125. node;
  7126. if ( range.collapsed ) {
  7127. // node = this.selection.getStart();
  7128. //在ie下getstart()取值偏上了
  7129. node = range.startContainer;
  7130. node = node.nodeType == 1 ? node : node.parentNode;
  7131. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  7132. return node;
  7133. }
  7134. } else {
  7135. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  7136. range.shrinkBoundary();
  7137. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  7138. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  7139. common = range.getCommonAncestor();
  7140. node = domUtils.findParentByTagName( common, 'a', true );
  7141. if ( !node && common.nodeType == 1){
  7142. var as = common.getElementsByTagName( 'a' ),
  7143. ps,pe;
  7144. for ( var i = 0,ci; ci = as[i++]; ) {
  7145. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  7146. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  7147. &&
  7148. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  7149. ) {
  7150. node = ci;
  7151. break;
  7152. }
  7153. }
  7154. }
  7155. return node;
  7156. }
  7157. },
  7158. queryCommandState : function() {
  7159. //判断如果是视频的话连接不可用
  7160. //fix 853
  7161. var img = this.selection.getRange().getClosedNode(),
  7162. flag = img && (img.className == "edui-faked-video");
  7163. return flag ? -1 : 0;
  7164. }
  7165. };
  7166. };
  7167. ///import core
  7168. ///import plugins\inserthtml.js
  7169. ///commands 插入框架
  7170. ///commandsName InsertFrame
  7171. ///commandsTitle 插入Iframe
  7172. ///commandsDialog dialogs\insertframe
  7173. UE.plugins['insertframe'] = function() {
  7174. var me =this;
  7175. function deleteIframe(){
  7176. me._iframe && delete me._iframe;
  7177. }
  7178. me.addListener("selectionchange",function(){
  7179. deleteIframe();
  7180. });
  7181. };
  7182. ///import core
  7183. ///commands 涂鸦
  7184. ///commandsName Scrawl
  7185. ///commandsTitle 涂鸦
  7186. ///commandsDialog dialogs\scrawl
  7187. UE.commands['scrawl'] = {
  7188. queryCommandState : function(){
  7189. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  7190. }
  7191. };
  7192. ///import core
  7193. ///commands 清除格式
  7194. ///commandsName RemoveFormat
  7195. ///commandsTitle 清除格式
  7196. /**
  7197. * @description 清除格式
  7198. * @name baidu.editor.execCommand
  7199. * @param {String} cmdName removeformat清除格式命令
  7200. * @param {String} tags 以逗号隔开的标签。如:span,a
  7201. * @param {String} style 样式
  7202. * @param {String} attrs 属性
  7203. * @param {String} notIncluedA 是否把a标签切开
  7204. * @author zhanyi
  7205. */
  7206. UE.plugins['removeformat'] = function(){
  7207. var me = this;
  7208. me.setOpt({
  7209. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  7210. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  7211. });
  7212. me.commands['removeformat'] = {
  7213. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  7214. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  7215. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  7216. range = new dom.Range( this.document ),
  7217. bookmark,node,parent,
  7218. filter = function( node ) {
  7219. return node.nodeType == 1;
  7220. };
  7221. function isRedundantSpan (node) {
  7222. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  7223. return 0;
  7224. }
  7225. if (browser.ie) {
  7226. //ie 下判断实效,所以只能简单用style来判断
  7227. //return node.style.cssText == '' ? 1 : 0;
  7228. var attrs = node.attributes;
  7229. if ( attrs.length ) {
  7230. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  7231. if ( attrs[i].specified ) {
  7232. return 0;
  7233. }
  7234. }
  7235. return 1;
  7236. }
  7237. }
  7238. return !node.attributes.length;
  7239. }
  7240. function doRemove( range ) {
  7241. var bookmark1 = range.createBookmark();
  7242. if ( range.collapsed ) {
  7243. range.enlarge( true );
  7244. }
  7245. //不能把a标签切了
  7246. if(!notIncludeA){
  7247. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  7248. if(aNode){
  7249. range.setStartBefore(aNode);
  7250. }
  7251. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  7252. if(aNode){
  7253. range.setEndAfter(aNode);
  7254. }
  7255. }
  7256. bookmark = range.createBookmark();
  7257. node = bookmark.start;
  7258. //切开始
  7259. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7260. domUtils.breakParent( node, parent );
  7261. domUtils.clearEmptySibling( node );
  7262. }
  7263. if ( bookmark.end ) {
  7264. //切结束
  7265. node = bookmark.end;
  7266. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7267. domUtils.breakParent( node, parent );
  7268. domUtils.clearEmptySibling( node );
  7269. }
  7270. //开始去除样式
  7271. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  7272. next;
  7273. while ( current ) {
  7274. if ( current == bookmark.end ) {
  7275. break;
  7276. }
  7277. next = domUtils.getNextDomNode( current, true, filter );
  7278. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  7279. if ( tagReg.test( current.tagName ) ) {
  7280. if ( style ) {
  7281. domUtils.removeStyle( current, style );
  7282. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  7283. domUtils.remove( current, true );
  7284. }
  7285. } else {
  7286. domUtils.remove( current, true );
  7287. }
  7288. } else {
  7289. //trace:939 不能把list上的样式去掉
  7290. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  7291. domUtils.removeAttributes( current, removeFormatAttributes );
  7292. if ( isRedundantSpan( current ) ){
  7293. domUtils.remove( current, true );
  7294. }
  7295. }
  7296. }
  7297. }
  7298. current = next;
  7299. }
  7300. }
  7301. //trace:1035
  7302. //trace:1096 不能把td上的样式去掉,比如边框
  7303. var pN = bookmark.start.parentNode;
  7304. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  7305. domUtils.removeAttributes( pN,removeFormatAttributes );
  7306. }
  7307. pN = bookmark.end.parentNode;
  7308. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  7309. domUtils.removeAttributes( pN,removeFormatAttributes );
  7310. }
  7311. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  7312. //清除冗余的代码 <b><bookmark></b>
  7313. var node = range.startContainer,
  7314. tmp,
  7315. collapsed = range.collapsed;
  7316. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7317. tmp = node.parentNode;
  7318. range.setStartBefore(node);
  7319. //trace:937
  7320. //更新结束边界
  7321. if(range.startContainer === range.endContainer){
  7322. range.endOffset--;
  7323. }
  7324. domUtils.remove(node);
  7325. node = tmp;
  7326. }
  7327. if(!collapsed){
  7328. node = range.endContainer;
  7329. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7330. tmp = node.parentNode;
  7331. range.setEndBefore(node);
  7332. domUtils.remove(node);
  7333. node = tmp;
  7334. }
  7335. }
  7336. }
  7337. range = this.selection.getRange();
  7338. doRemove( range );
  7339. range.select();
  7340. }
  7341. };
  7342. };
  7343. ///import core
  7344. ///commands 引用
  7345. ///commandsName BlockQuote
  7346. ///commandsTitle 引用
  7347. /**
  7348. *
  7349. * 引用模块实现
  7350. * @function
  7351. * @name baidu.editor.execCommand
  7352. * @param {String} cmdName blockquote引用
  7353. */
  7354. UE.plugins['blockquote'] = function(){
  7355. var me = this;
  7356. function getObj(editor){
  7357. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  7358. }
  7359. me.commands['blockquote'] = {
  7360. execCommand : function( cmdName, attrs ) {
  7361. var range = this.selection.getRange(),
  7362. obj = getObj(this),
  7363. blockquote = dtd.blockquote,
  7364. bookmark = range.createBookmark();
  7365. if ( obj ) {
  7366. var start = range.startContainer,
  7367. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  7368. end = range.endContainer,
  7369. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  7370. //处理一下li
  7371. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  7372. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  7373. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  7374. domUtils.remove(obj,true);
  7375. }else{
  7376. domUtils.breakParent(startBlock,obj);
  7377. }
  7378. if(startBlock !== endBlock){
  7379. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  7380. if(obj){
  7381. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  7382. obj.parentNode && domUtils.remove(obj,true);
  7383. }else{
  7384. domUtils.breakParent(endBlock,obj);
  7385. }
  7386. }
  7387. }
  7388. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  7389. for(var i=0,bi;bi=blockquotes[i++];){
  7390. if(!bi.childNodes.length){
  7391. domUtils.remove(bi);
  7392. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  7393. domUtils.remove(bi,true);
  7394. }
  7395. }
  7396. } else {
  7397. var tmpRange = range.cloneRange(),
  7398. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  7399. preNode = node,
  7400. doEnd = 1;
  7401. //调整开始
  7402. while ( 1 ) {
  7403. if ( domUtils.isBody(node) ) {
  7404. if ( preNode !== node ) {
  7405. if ( range.collapsed ) {
  7406. tmpRange.selectNode( preNode );
  7407. doEnd = 0;
  7408. } else {
  7409. tmpRange.setStartBefore( preNode );
  7410. }
  7411. }else{
  7412. tmpRange.setStart(node,0);
  7413. }
  7414. break;
  7415. }
  7416. if ( !blockquote[node.tagName] ) {
  7417. if ( range.collapsed ) {
  7418. tmpRange.selectNode( preNode );
  7419. } else{
  7420. tmpRange.setStartBefore( preNode);
  7421. }
  7422. break;
  7423. }
  7424. preNode = node;
  7425. node = node.parentNode;
  7426. }
  7427. //调整结束
  7428. if ( doEnd ) {
  7429. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  7430. while ( 1 ) {
  7431. if ( domUtils.isBody( node ) ) {
  7432. if ( preNode !== node ) {
  7433. tmpRange.setEndAfter( preNode );
  7434. } else {
  7435. tmpRange.setEnd( node, node.childNodes.length );
  7436. }
  7437. break;
  7438. }
  7439. if ( !blockquote[node.tagName] ) {
  7440. tmpRange.setEndAfter( preNode );
  7441. break;
  7442. }
  7443. preNode = node;
  7444. node = node.parentNode;
  7445. }
  7446. }
  7447. node = range.document.createElement( 'blockquote' );
  7448. domUtils.setAttributes( node, attrs );
  7449. node.appendChild( tmpRange.extractContents() );
  7450. tmpRange.insertNode( node );
  7451. //去除重复的
  7452. var childs = domUtils.getElementsByTagName(node,'blockquote');
  7453. for(var i=0,ci;ci=childs[i++];){
  7454. if(ci.parentNode){
  7455. domUtils.remove(ci,true);
  7456. }
  7457. }
  7458. }
  7459. range.moveToBookmark( bookmark ).select();
  7460. },
  7461. queryCommandState : function() {
  7462. return getObj(this) ? 1 : 0;
  7463. }
  7464. };
  7465. };
  7466. ///import core
  7467. ///commands 大小写转换
  7468. ///commandsName touppercase,tolowercase
  7469. ///commandsTitle 大写,小写
  7470. /**
  7471. * 大小写转换
  7472. * @function
  7473. * @name baidu.editor.execCommands
  7474. * @param {String} cmdName cmdName="convertcase"
  7475. */
  7476. UE.commands['touppercase'] =
  7477. UE.commands['tolowercase'] = {
  7478. execCommand:function (cmd) {
  7479. var me = this;
  7480. var rng = me.selection.getRange();
  7481. if(rng.collapsed){
  7482. return rng;
  7483. }
  7484. var bk = rng.createBookmark(),
  7485. bkEnd = bk.end,
  7486. filterFn = function( node ) {
  7487. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  7488. },
  7489. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  7490. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  7491. if ( curNode.nodeType == 3 ) {
  7492. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  7493. }
  7494. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  7495. if(curNode === bkEnd){
  7496. break;
  7497. }
  7498. }
  7499. rng.moveToBookmark(bk).select();
  7500. }
  7501. };
  7502. ///import core
  7503. ///import plugins\paragraph.js
  7504. ///commands 首行缩进
  7505. ///commandsName Outdent,Indent
  7506. ///commandsTitle 取消缩进,首行缩进
  7507. /**
  7508. * 首行缩进
  7509. * @function
  7510. * @name baidu.editor.execCommand
  7511. * @param {String} cmdName outdent取消缩进,indent缩进
  7512. */
  7513. UE.commands['indent'] = {
  7514. execCommand : function() {
  7515. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  7516. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  7517. },
  7518. queryCommandState : function() {
  7519. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  7520. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  7521. }
  7522. };
  7523. ///import core
  7524. ///commands 打印
  7525. ///commandsName Print
  7526. ///commandsTitle 打印
  7527. /**
  7528. * @description 打印
  7529. * @name baidu.editor.execCommand
  7530. * @param {String} cmdName print打印编辑器内容
  7531. * @author zhanyi
  7532. */
  7533. UE.commands['print'] = {
  7534. execCommand : function(){
  7535. this.window.print();
  7536. },
  7537. notNeedUndo : 1
  7538. };
  7539. ///import core
  7540. ///commands 预览
  7541. ///commandsName Preview
  7542. ///commandsTitle 预览
  7543. /**
  7544. * 预览
  7545. * @function
  7546. * @name baidu.editor.execCommand
  7547. * @param {String} cmdName preview预览编辑器内容
  7548. */
  7549. UE.commands['preview'] = {
  7550. execCommand : function(){
  7551. var w = window.open('', '_blank', ''),
  7552. d = w.document;
  7553. d.open();
  7554. d.write('<html><head><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  7555. "setTimeout(function(){uParse('div',{" +
  7556. " 'highlightJsUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCore.js'," +
  7557. " 'highlightCssUrl':'"+this.options.UEDITOR_HOME_URL+"third-party/SyntaxHighlighter/shCoreDefault.css'" +
  7558. "})},300)" +
  7559. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  7560. d.close();
  7561. },
  7562. notNeedUndo : 1
  7563. };
  7564. ///import core
  7565. ///commands 全选
  7566. ///commandsName SelectAll
  7567. ///commandsTitle 全选
  7568. /**
  7569. * 选中所有
  7570. * @function
  7571. * @name baidu.editor.execCommand
  7572. * @param {String} cmdName selectall选中编辑器里的所有内容
  7573. * @author zhanyi
  7574. */
  7575. UE.plugins['selectall'] = function(){
  7576. var me = this;
  7577. me.commands['selectall'] = {
  7578. execCommand : function(){
  7579. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  7580. var me = this,body = me.body,
  7581. range = me.selection.getRange();
  7582. range.selectNodeContents(body);
  7583. if(domUtils.isEmptyBlock(body)){
  7584. //opera不能自动合并到元素的里边,要手动处理一下
  7585. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  7586. range.setStartAtFirst(body.firstChild);
  7587. }
  7588. range.collapse(true);
  7589. }
  7590. range.select(true);
  7591. },
  7592. notNeedUndo : 1
  7593. };
  7594. //快捷键
  7595. me.addshortcutkey({
  7596. "selectAll" : "ctrl+65"
  7597. });
  7598. };
  7599. ///import core
  7600. ///commands 格式
  7601. ///commandsName Paragraph
  7602. ///commandsTitle 段落格式
  7603. /**
  7604. * 段落样式
  7605. * @function
  7606. * @name baidu.editor.execCommand
  7607. * @param {String} cmdName paragraph插入段落执行命令
  7608. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  7609. * @param {String} attrs 标签的属性
  7610. * @author zhanyi
  7611. */
  7612. UE.plugins['paragraph'] = function() {
  7613. var me = this,
  7614. block = domUtils.isBlockElm,
  7615. notExchange = ['TD','LI','PRE'],
  7616. doParagraph = function(range,style,attrs,sourceCmdName){
  7617. var bookmark = range.createBookmark(),
  7618. filterFn = function( node ) {
  7619. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  7620. },
  7621. para;
  7622. range.enlarge( true );
  7623. var bookmark2 = range.createBookmark(),
  7624. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  7625. tmpRange = range.cloneRange(),
  7626. tmpNode;
  7627. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  7628. if ( current.nodeType == 3 || !block( current ) ) {
  7629. tmpRange.setStartBefore( current );
  7630. while ( current && current !== bookmark2.end && !block( current ) ) {
  7631. tmpNode = current;
  7632. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  7633. return !block( node );
  7634. } );
  7635. }
  7636. tmpRange.setEndAfter( tmpNode );
  7637. para = range.document.createElement( style );
  7638. if(attrs){
  7639. domUtils.setAttributes(para,attrs);
  7640. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  7641. para.style.cssText = attrs.style;
  7642. }
  7643. }
  7644. para.appendChild( tmpRange.extractContents() );
  7645. //需要内容占位
  7646. if(domUtils.isEmptyNode(para)){
  7647. domUtils.fillChar(range.document,para);
  7648. }
  7649. tmpRange.insertNode( para );
  7650. var parent = para.parentNode;
  7651. //如果para上一级是一个block元素且不是body,td就删除它
  7652. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  7653. //存储dir,style
  7654. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  7655. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  7656. //trace:1070
  7657. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  7658. //trace:1030
  7659. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  7660. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  7661. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  7662. }
  7663. //trace:1706 选择的就是h1-6要删除
  7664. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  7665. domUtils.setAttributes(parent,attrs);
  7666. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  7667. parent.style.cssText = attrs.style;
  7668. }
  7669. domUtils.remove(para,true);
  7670. para = parent;
  7671. }else{
  7672. domUtils.remove( para.parentNode, true );
  7673. }
  7674. }
  7675. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  7676. current = parent;
  7677. }else{
  7678. current = para;
  7679. }
  7680. current = domUtils.getNextDomNode( current, false, filterFn );
  7681. } else {
  7682. current = domUtils.getNextDomNode( current, true, filterFn );
  7683. }
  7684. }
  7685. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  7686. };
  7687. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  7688. me.commands['paragraph'] = {
  7689. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  7690. var range = this.selection.getRange();
  7691. //闭合时单独处理
  7692. if(range.collapsed){
  7693. var txt = this.document.createTextNode('p');
  7694. range.insertNode(txt);
  7695. //去掉冗余的fillchar
  7696. if(browser.ie){
  7697. var node = txt.previousSibling;
  7698. if(node && domUtils.isWhitespace(node)){
  7699. domUtils.remove(node);
  7700. }
  7701. node = txt.nextSibling;
  7702. if(node && domUtils.isWhitespace(node)){
  7703. domUtils.remove(node);
  7704. }
  7705. }
  7706. }
  7707. range = doParagraph(range,style,attrs,sourceCmdName);
  7708. if(txt){
  7709. range.setStartBefore(txt).collapse(true);
  7710. pN = txt.parentNode;
  7711. domUtils.remove(txt);
  7712. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  7713. domUtils.fillNode(this.document,pN);
  7714. }
  7715. }
  7716. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  7717. var child = range.startContainer.childNodes[range.startOffset];
  7718. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  7719. range.setStart(child,0).collapse(true);
  7720. }
  7721. }
  7722. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  7723. range.select();
  7724. return true;
  7725. },
  7726. queryCommandValue : function() {
  7727. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  7728. return node ? node.tagName.toLowerCase() : '';
  7729. }
  7730. };
  7731. };
  7732. ///import core
  7733. ///commands 输入的方向
  7734. ///commandsName DirectionalityLtr,DirectionalityRtl
  7735. ///commandsTitle 从左向右输入,从右向左输入
  7736. /**
  7737. * 输入的方向
  7738. * @function
  7739. * @name baidu.editor.execCommand
  7740. * @param {String} cmdName directionality执行函数的参数
  7741. * @param {String} forward ltr从左向右输入,rtl从右向左输入
  7742. */
  7743. (function() {
  7744. var block = domUtils.isBlockElm ,
  7745. getObj = function(editor){
  7746. // var startNode = editor.selection.getStart(),
  7747. // parents;
  7748. // if ( startNode ) {
  7749. // //查找所有的是block的父亲节点
  7750. // parents = domUtils.findParents( startNode, true, block, true );
  7751. // for ( var i = 0,ci; ci = parents[i++]; ) {
  7752. // if ( ci.getAttribute( 'dir' ) ) {
  7753. // return ci;
  7754. // }
  7755. // }
  7756. // }
  7757. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n.getAttribute('dir')});
  7758. },
  7759. doDirectionality = function(range,editor,forward){
  7760. var bookmark,
  7761. filterFn = function( node ) {
  7762. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  7763. },
  7764. obj = getObj( editor );
  7765. if ( obj && range.collapsed ) {
  7766. obj.setAttribute( 'dir', forward );
  7767. return range;
  7768. }
  7769. bookmark = range.createBookmark();
  7770. range.enlarge( true );
  7771. var bookmark2 = range.createBookmark(),
  7772. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  7773. tmpRange = range.cloneRange(),
  7774. tmpNode;
  7775. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  7776. if ( current.nodeType == 3 || !block( current ) ) {
  7777. tmpRange.setStartBefore( current );
  7778. while ( current && current !== bookmark2.end && !block( current ) ) {
  7779. tmpNode = current;
  7780. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  7781. return !block( node );
  7782. } );
  7783. }
  7784. tmpRange.setEndAfter( tmpNode );
  7785. var common = tmpRange.getCommonAncestor();
  7786. if ( !domUtils.isBody( common ) && block( common ) ) {
  7787. //遍历到了block节点
  7788. common.setAttribute( 'dir', forward );
  7789. current = common;
  7790. } else {
  7791. //没有遍历到,添加一个block节点
  7792. var p = range.document.createElement( 'p' );
  7793. p.setAttribute( 'dir', forward );
  7794. var frag = tmpRange.extractContents();
  7795. p.appendChild( frag );
  7796. tmpRange.insertNode( p );
  7797. current = p;
  7798. }
  7799. current = domUtils.getNextDomNode( current, false, filterFn );
  7800. } else {
  7801. current = domUtils.getNextDomNode( current, true, filterFn );
  7802. }
  7803. }
  7804. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  7805. };
  7806. UE.commands['directionality'] = {
  7807. execCommand : function( cmdName,forward ) {
  7808. var range = this.selection.getRange();
  7809. //闭合时单独处理
  7810. if(range.collapsed){
  7811. var txt = this.document.createTextNode('d');
  7812. range.insertNode(txt);
  7813. }
  7814. doDirectionality(range,this,forward);
  7815. if(txt){
  7816. range.setStartBefore(txt).collapse(true);
  7817. domUtils.remove(txt);
  7818. }
  7819. range.select();
  7820. return true;
  7821. },
  7822. queryCommandValue : function() {
  7823. var node = getObj(this);
  7824. return node ? node.getAttribute('dir') : 'ltr';
  7825. }
  7826. };
  7827. })();
  7828. ///import core
  7829. ///import plugins\inserthtml.js
  7830. ///commands 分割线
  7831. ///commandsName Horizontal
  7832. ///commandsTitle 分隔线
  7833. /**
  7834. * 分割线
  7835. * @function
  7836. * @name baidu.editor.execCommand
  7837. * @param {String} cmdName horizontal插入分割线
  7838. */
  7839. UE.plugins['horizontal'] = function(){
  7840. var me = this;
  7841. me.commands['horizontal'] = {
  7842. execCommand : function( cmdName ) {
  7843. var me = this;
  7844. if(me.queryCommandState(cmdName)!==-1){
  7845. me.execCommand('insertHtml','<hr>');
  7846. var range = me.selection.getRange(),
  7847. start = range.startContainer;
  7848. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  7849. var tmp;
  7850. if(tmp = start.childNodes[range.startOffset - 1]){
  7851. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  7852. if(me.options.enterTag == 'p'){
  7853. tmp = me.document.createElement('p');
  7854. range.insertNode(tmp);
  7855. range.setStart(tmp,0).setCursor();
  7856. }else{
  7857. tmp = me.document.createElement('br');
  7858. range.insertNode(tmp);
  7859. range.setStartBefore(tmp).setCursor();
  7860. }
  7861. }
  7862. }
  7863. }
  7864. return true;
  7865. }
  7866. },
  7867. //边界在table里不能加分隔线
  7868. queryCommandState : function() {
  7869. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  7870. }
  7871. };
  7872. me.addListener('delkeyup',function(){
  7873. var rng = this.selection.getRange();
  7874. if(domUtils.isBody(rng.startContainer)){
  7875. var hr = rng.startContainer.childNodes[rng.startOffset -1];
  7876. if(hr && hr.nodeName == 'HR'){
  7877. domUtils.remove(hr)
  7878. }
  7879. }
  7880. })
  7881. };
  7882. ///import core
  7883. ///import plugins\inserthtml.js
  7884. ///commands 日期,时间
  7885. ///commandsName Date,Time
  7886. ///commandsTitle 日期,时间
  7887. /**
  7888. * 插入日期
  7889. * @function
  7890. * @name baidu.editor.execCommand
  7891. * @param {String} cmdName date插入日期
  7892. * @author zhuwenxuan
  7893. */
  7894. /**
  7895. * 插入时间
  7896. * @function
  7897. * @name baidu.editor.execCommand
  7898. * @param {String} cmdName time插入时间
  7899. * @author zhuwenxuan
  7900. */
  7901. UE.commands['time'] = UE.commands["date"] = {
  7902. execCommand : function(cmd){
  7903. var date = new Date;
  7904. this.execCommand('insertHtml',cmd == "time" ?
  7905. (date.getHours()+":"+ (date.getMinutes()<10 ? "0"+date.getMinutes() : date.getMinutes())+":"+(date.getSeconds()<10 ? "0"+date.getSeconds() : date.getSeconds())) :
  7906. (date.getFullYear()+"-"+((date.getMonth()+1)<10 ? "0"+(date.getMonth()+1) : date.getMonth()+1)+"-"+(date.getDate()<10?"0"+date.getDate():date.getDate())));
  7907. }
  7908. };
  7909. ///import core
  7910. ///import plugins\paragraph.js
  7911. ///commands 段间距
  7912. ///commandsName RowSpacingBottom,RowSpacingTop
  7913. ///commandsTitle 段间距
  7914. /**
  7915. * @description 设置段前距,段后距
  7916. * @name baidu.editor.execCommand
  7917. * @param {String} cmdName rowspacing设置段间距
  7918. * @param {String} value 值,以px为单位
  7919. * @param {String} dir top或bottom段前后段后
  7920. * @author zhanyi
  7921. */
  7922. UE.plugins['rowspacing'] = function(){
  7923. var me = this;
  7924. me.setOpt({
  7925. 'rowspacingtop':['5', '10', '15', '20', '25'],
  7926. 'rowspacingbottom':['5', '10', '15', '20', '25']
  7927. });
  7928. me.commands['rowspacing'] = {
  7929. execCommand : function( cmdName,value,dir ) {
  7930. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  7931. return true;
  7932. },
  7933. queryCommandValue : function(cmdName,dir) {
  7934. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  7935. value;
  7936. //trace:1026
  7937. if(pN){
  7938. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  7939. return !value ? 0 : value;
  7940. }
  7941. return 0;
  7942. }
  7943. };
  7944. };
  7945. ///import core
  7946. ///import plugins\paragraph.js
  7947. ///commands 行间距
  7948. ///commandsName LineHeight
  7949. ///commandsTitle 行间距
  7950. /**
  7951. * @description 设置行内间距
  7952. * @name baidu.editor.execCommand
  7953. * @param {String} cmdName lineheight设置行内间距
  7954. * @param {String} value 值
  7955. * @author zhuwenxuan
  7956. */
  7957. UE.plugins['lineheight'] = function(){
  7958. var me = this;
  7959. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  7960. me.commands['lineheight'] = {
  7961. execCommand : function( cmdName,value ) {
  7962. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  7963. return true;
  7964. },
  7965. queryCommandValue : function() {
  7966. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  7967. if(pN){
  7968. var value = domUtils.getComputedStyle(pN,'line-height');
  7969. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  7970. }
  7971. }
  7972. };
  7973. };
  7974. ///import core
  7975. ///import plugins/inserthtml.js
  7976. ///commands 插入代码
  7977. ///commandsName code
  7978. ///commandsTitle 插入代码
  7979. UE.plugins['insertcode'] = function() {
  7980. var me = this;
  7981. me.ready(function(){
  7982. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;line-height:1.5}',
  7983. me.document)
  7984. });
  7985. me.setOpt('insertcode',{
  7986. 'as3':'ActionScript3',
  7987. 'bash':'Bash/Shell',
  7988. 'cpp':'C/C++',
  7989. 'css':'Css',
  7990. 'cf':'CodeFunction',
  7991. 'c#':'C#',
  7992. 'delphi':'Delphi',
  7993. 'diff':'Diff',
  7994. 'erlang':'Erlang',
  7995. 'groovy':'Groovy',
  7996. 'html':'Html',
  7997. 'java':'Java',
  7998. 'jfx':'JavaFx',
  7999. 'js':'Javascript',
  8000. 'pl':'Perl',
  8001. 'php':'Php',
  8002. 'plain':'Plain Text',
  8003. 'ps':'PowerShell',
  8004. 'python':'Python',
  8005. 'ruby':'Ruby',
  8006. 'scala':'Scala',
  8007. 'sql':'Sql',
  8008. 'vb':'Vb',
  8009. 'xml':'Xml'
  8010. });
  8011. me.commands['insertcode'] = {
  8012. execCommand : function(cmd,lang){
  8013. var me = this,
  8014. rng = me.selection.getRange(),
  8015. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8016. if(pre){
  8017. pre.className = 'brush:'+lang+';toolbar:false;';
  8018. }else{
  8019. var code = '';
  8020. if(rng.collapsed){
  8021. code = browser.ie? (browser.version > 8 ? '' : '&nbsp;'):'<br/>';
  8022. }else{
  8023. var frag = rng.extractContents();
  8024. var div = me.document.createElement('div');
  8025. div.appendChild(frag);
  8026. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  8027. if(browser.ie && browser.version > 8){
  8028. if(node.type =='element'){
  8029. if(node.tagName == 'br'){
  8030. code += '\n'
  8031. }else if(!dtd.$empty[node.tagName]){
  8032. utils.each(node.children,function(cn){
  8033. if(cn.type =='element'){
  8034. if(cn.tagName == 'br'){
  8035. code += '\n'
  8036. }else if(!dtd.$empty[node.tagName]){
  8037. code += cn.innerText();
  8038. }
  8039. }else{
  8040. code += cn.data
  8041. }
  8042. })
  8043. if(!/\n$/.test(code)){
  8044. code += '\n';
  8045. }
  8046. }
  8047. }else{
  8048. code += node.data + '\n'
  8049. }
  8050. if(!node.nextSibling() && /\n$/.test(code)){
  8051. code = code.replace(/\n$/,'');
  8052. }
  8053. }else{
  8054. if(browser.ie){
  8055. if(node.type =='element'){
  8056. if(node.tagName == 'br'){
  8057. code += '<br>'
  8058. }else if(!dtd.$empty[node.tagName]){
  8059. utils.each(node.children,function(cn){
  8060. if(cn.type =='element'){
  8061. if(cn.tagName == 'br'){
  8062. code += '<br>'
  8063. }else if(!dtd.$empty[node.tagName]){
  8064. code += cn.innerText();
  8065. }
  8066. }else{
  8067. code += cn.data
  8068. }
  8069. })
  8070. if(!/br>$/.test(code)){
  8071. code += '<br>';
  8072. }
  8073. }
  8074. }else{
  8075. code += node.data + '<br>'
  8076. }
  8077. if(!node.nextSibling() && /<br>$/.test(code)){
  8078. code = code.replace(/<br>$/,'');
  8079. }
  8080. }else{
  8081. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  8082. if(!/br\/?\s*>$/.test(code)){
  8083. if(!node.nextSibling())
  8084. return;
  8085. code += '<br>'
  8086. }
  8087. }
  8088. }
  8089. });
  8090. }
  8091. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  8092. pre = me.document.getElementById('coder');
  8093. domUtils.removeAttributes(pre,'id');
  8094. var tmpNode = pre.previousSibling;
  8095. if(tmpNode && domUtils.isEmptyBlock(tmpNode)){
  8096. domUtils.remove(tmpNode)
  8097. }
  8098. var rng = me.selection.getRange();
  8099. if(domUtils.isEmptyBlock(pre)){
  8100. rng.setStart(pre,0).setCursor(false,true)
  8101. }else{
  8102. rng.selectNodeContents(pre).select()
  8103. }
  8104. }
  8105. },
  8106. queryCommandValue : function(){
  8107. var path = this.selection.getStartElementPath();
  8108. var lang = '';
  8109. utils.each(path,function(node){
  8110. if(node.nodeName =='PRE'){
  8111. var match = node.className.match(/brush:([^;]+)/);
  8112. lang = match && match[1] ? match[1] : '';
  8113. return false;
  8114. }
  8115. });
  8116. return lang;
  8117. }
  8118. };
  8119. me.addInputRule(function(root){
  8120. utils.each(root.getNodesByTagName('pre'),function(pre){
  8121. var brs = pre.getNodesByTagName('br');
  8122. if(brs.length){
  8123. browser.ie && browser.version > 8 && utils.each(brs,function(br){
  8124. var txt = UE.uNode.createText('\n');
  8125. br.parentNode.insertBefore(txt,br);
  8126. br.parentNode.removeChild(br);
  8127. });
  8128. return;
  8129. }
  8130. if(browser.ie && browser.version > 8)
  8131. return;
  8132. var code = pre.innerText().split(/\n/);
  8133. pre.innerHTML('');
  8134. utils.each(code,function(c){
  8135. if(c.length){
  8136. pre.appendChild(UE.uNode.createText(c));
  8137. }
  8138. pre.appendChild(UE.uNode.createElement('br'))
  8139. })
  8140. })
  8141. });
  8142. me.addOutputRule(function(root){
  8143. utils.each(root.getNodesByTagName('pre'),function(pre){
  8144. var code = '';
  8145. utils.each(pre.children,function(n){
  8146. if(n.type == 'text'){
  8147. code += n.data.replace(/[ ]/g,'&nbsp;');
  8148. }else{
  8149. code += '\n'
  8150. }
  8151. });
  8152. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  8153. })
  8154. });
  8155. //不需要判断highlight的command列表
  8156. me.notNeedCodeQuery ={
  8157. help:1,
  8158. undo:1,
  8159. redo:1,
  8160. source:1,
  8161. print:1,
  8162. searchreplace:1,
  8163. fullscreen:1,
  8164. preview:1,
  8165. insertparagraph:1,
  8166. elementpath:1,
  8167. highlightcode:1,
  8168. insertcode:1,
  8169. inserthtml:1,
  8170. selectall:1
  8171. };
  8172. //将queyCommamndState重置
  8173. var orgQuery = me.queryCommandState;
  8174. me.queryCommandState = function(cmd){
  8175. var me = this;
  8176. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  8177. return -1;
  8178. }
  8179. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  8180. };
  8181. me.addListener('beforeenterkeydown',function(){
  8182. var rng = me.selection.getRange();
  8183. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8184. if(pre){
  8185. me.fireEvent('saveScene');
  8186. if(!rng.collapsed){
  8187. rng.deleteContents();
  8188. }
  8189. if(!browser.ie ){
  8190. var tmpNode = me.document.createElement('br'),pre;
  8191. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  8192. var next = tmpNode.nextSibling;
  8193. if(!next){
  8194. rng.insertNode(tmpNode.cloneNode(false));
  8195. }else{
  8196. rng.setStartAfter(tmpNode);
  8197. }
  8198. pre = tmpNode.previousSibling;
  8199. var tmp;
  8200. while(pre ){
  8201. tmp = pre;
  8202. pre = pre.previousSibling;
  8203. if(!pre || pre.nodeName == 'BR'){
  8204. pre = tmp;
  8205. break;
  8206. }
  8207. }
  8208. if(pre){
  8209. var str = '';
  8210. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  8211. str += pre.nodeValue;
  8212. pre = pre.nextSibling;
  8213. }
  8214. if(pre.nodeName != 'BR'){
  8215. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  8216. if(match && match[1]){
  8217. str += match[1]
  8218. }
  8219. }
  8220. if(str){
  8221. str = me.document.createTextNode(str);
  8222. rng.insertNode(str).setStartAfter(str);
  8223. }
  8224. }
  8225. rng.collapse(true).select(true);
  8226. }else{
  8227. if(browser.version > 8){
  8228. var txt = me.document.createTextNode('\n');
  8229. var start = rng.startContainer;
  8230. if(rng.startOffset == 0){
  8231. var preNode = start.previousSibling;
  8232. if(preNode){
  8233. rng.insertNode(txt);
  8234. var fillchar = me.document.createTextNode(' ');
  8235. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  8236. }
  8237. }else{
  8238. rng.insertNode(txt).setStartAfter(txt);
  8239. var fillchar = me.document.createTextNode(' ');
  8240. start = rng.startContainer.childNodes[rng.startOffset];
  8241. if(start && !/^\n/.test(start.nodeValue)){
  8242. rng.setStartBefore(txt)
  8243. }
  8244. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  8245. }
  8246. }else{
  8247. var tmpNode = me.document.createElement('br');
  8248. rng.insertNode(tmpNode);
  8249. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  8250. rng.setStartAfter(tmpNode);
  8251. pre = tmpNode.previousSibling;
  8252. var tmp;
  8253. while(pre ){
  8254. tmp = pre;
  8255. pre = pre.previousSibling;
  8256. if(!pre || pre.nodeName == 'BR'){
  8257. pre = tmp;
  8258. break;
  8259. }
  8260. }
  8261. if(pre){
  8262. var str = '';
  8263. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  8264. str += pre.nodeValue;
  8265. pre = pre.nextSibling;
  8266. }
  8267. if(pre.nodeName != 'BR'){
  8268. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  8269. if(match && match[1]){
  8270. str += match[1]
  8271. }
  8272. }
  8273. str = me.document.createTextNode(str);
  8274. rng.insertNode(str).setStartAfter(str);
  8275. }
  8276. rng.collapse(true).select();
  8277. }
  8278. }
  8279. me.fireEvent('saveScene');
  8280. return true;
  8281. }
  8282. });
  8283. me.addListener('tabkeydown',function(cmd,evt){
  8284. var rng = me.selection.getRange();
  8285. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8286. if(pre){
  8287. me.fireEvent('saveScene');
  8288. if(evt.shiftKey){
  8289. // if(!rng.collapsed){
  8290. // var bk = rng.createBookmark();
  8291. // var start = bk.start.previousSibling;
  8292. // if(start === pre.firstChild){
  8293. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8294. // }else{
  8295. // while(start){
  8296. // if(domUtils.isBr(start)){
  8297. // start = start.nextSibling;
  8298. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8299. // break;
  8300. // }
  8301. // while(start.previousSibling && start.previousSibling.nodeType == 3){
  8302. // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue;
  8303. // domUtils.remove(start.previousSibling)
  8304. // }
  8305. // start = start.previousSibling;
  8306. // }
  8307. // }
  8308. //
  8309. // var end = bk.end;
  8310. // start = bk.start.nextSibling;
  8311. //
  8312. // while(start && start !== end){
  8313. // if(domUtils.isBr(start) && start.nextSibling){
  8314. // if(start.nextSibling === end){
  8315. // break;
  8316. // }
  8317. // start = start.nextSibling;
  8318. // while(start.nextSibling && start.nextSibling.nodeType == 3){
  8319. // start.nodeValue += start.nextSibling.nodeValue;
  8320. // domUtils.remove(start.nextSibling)
  8321. // }
  8322. //
  8323. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8324. // }
  8325. //
  8326. // start = start.nextSibling;
  8327. // }
  8328. // rng.moveToBookmark(bk).select();
  8329. // }else{
  8330. // var bk = rng.createBookmark();
  8331. // var start = bk.start.previousSibling;
  8332. // if(start === pre.firstChild){
  8333. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8334. // }else{
  8335. // while(start){
  8336. // if(domUtils.isBr(start)){
  8337. // start = start.nextSibling;
  8338. // start.nodeValue = start.nodeValue.replace(/^\s{4}/,'');
  8339. // break;
  8340. // }
  8341. // while(start.previousSibling && start.previousSibling.nodeType == 3){
  8342. // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue;
  8343. // domUtils.remove(start.previousSibling)
  8344. // }
  8345. // start = start.previousSibling;
  8346. // }
  8347. // }
  8348. // }
  8349. }else{
  8350. if(!rng.collapsed){
  8351. var bk = rng.createBookmark();
  8352. var start = bk.start.previousSibling;
  8353. while(start){
  8354. if(pre.firstChild === start && !domUtils.isBr(start)){
  8355. pre.insertBefore(me.document.createTextNode(' '),start);
  8356. break;
  8357. }
  8358. if(domUtils.isBr(start)){
  8359. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  8360. break;
  8361. }
  8362. start = start.previousSibling;
  8363. }
  8364. var end = bk.end;
  8365. start = bk.start.nextSibling;
  8366. if(pre.firstChild === bk.start){
  8367. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  8368. }
  8369. while(start && start !== end){
  8370. if(domUtils.isBr(start) && start.nextSibling){
  8371. if(start.nextSibling === end){
  8372. break;
  8373. }
  8374. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  8375. }
  8376. start = start.nextSibling;
  8377. }
  8378. rng.moveToBookmark(bk).select();
  8379. }else{
  8380. var tmpNode = me.document.createTextNode(' ');
  8381. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  8382. }
  8383. }
  8384. me.fireEvent('saveScene');
  8385. return true;
  8386. }
  8387. });
  8388. me.addListener('beforeinserthtml',function(evtName,html){
  8389. var me = this,
  8390. rng = me.selection.getRange(),
  8391. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  8392. if(pre){
  8393. if(!rng.collapsed){
  8394. rng.deleteContents()
  8395. }
  8396. var htmlstr = '';
  8397. if(browser.ie && browser.version > 8){
  8398. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  8399. if(node.type =='element'){
  8400. if(node.tagName == 'br'){
  8401. htmlstr += '\n'
  8402. }else if(!dtd.$empty[node.tagName]){
  8403. utils.each(node.children,function(cn){
  8404. if(cn.type =='element'){
  8405. if(cn.tagName == 'br'){
  8406. htmlstr += '\n'
  8407. }else if(!dtd.$empty[node.tagName]){
  8408. htmlstr += cn.innerText();
  8409. }
  8410. }else{
  8411. htmlstr += cn.data
  8412. }
  8413. })
  8414. if(!/\n$/.test(htmlstr)){
  8415. htmlstr += '\n';
  8416. }
  8417. }
  8418. }else{
  8419. htmlstr += node.data + '\n'
  8420. }
  8421. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  8422. htmlstr = htmlstr.replace(/\n$/,'');
  8423. }
  8424. });
  8425. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  8426. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  8427. }else{
  8428. var frag = me.document.createDocumentFragment();
  8429. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  8430. if(node.type =='element'){
  8431. if(node.tagName == 'br'){
  8432. frag.appendChild(me.document.createElement('br'))
  8433. }else if(!dtd.$empty[node.tagName]){
  8434. utils.each(node.children,function(cn){
  8435. if(cn.type =='element'){
  8436. if(cn.tagName == 'br'){
  8437. frag.appendChild(me.document.createElement('br'))
  8438. }else if(!dtd.$empty[node.tagName]){
  8439. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  8440. }
  8441. }else{
  8442. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  8443. }
  8444. })
  8445. if(frag.lastChild.nodeName != 'BR'){
  8446. frag.appendChild(me.document.createElement('br'))
  8447. }
  8448. }
  8449. }else{
  8450. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  8451. }
  8452. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  8453. frag.removeChild(frag.lastChild)
  8454. }
  8455. });
  8456. rng.insertNode(frag).select();
  8457. }
  8458. return true;
  8459. }
  8460. });
  8461. //方向键的处理
  8462. me.addListener('keydown',function(cmd,evt){
  8463. var me = this,keyCode = evt.keyCode || evt.which;
  8464. if(keyCode == 40){
  8465. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  8466. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  8467. var last = pre.lastChild
  8468. while(last && last.nodeName == 'BR'){
  8469. last = last.previousSibling;
  8470. }
  8471. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  8472. me.execCommand('insertparagraph');
  8473. domUtils.preventDefault(evt)
  8474. }
  8475. }
  8476. }
  8477. })
  8478. };
  8479. ///import core
  8480. ///commands 清空文档
  8481. ///commandsName ClearDoc
  8482. ///commandsTitle 清空文档
  8483. /**
  8484. *
  8485. * 清空文档
  8486. * @function
  8487. * @name baidu.editor.execCommand
  8488. * @param {String} cmdName cleardoc清空文档
  8489. */
  8490. UE.commands['cleardoc'] = {
  8491. execCommand : function( cmdName) {
  8492. var me = this,
  8493. enterTag = me.options.enterTag,
  8494. range = me.selection.getRange();
  8495. if(enterTag == "br"){
  8496. me.body.innerHTML = "<br/>";
  8497. range.setStart(me.body,0).setCursor();
  8498. }else{
  8499. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  8500. range.setStart(me.body.firstChild,0).setCursor(false,true);
  8501. }
  8502. setTimeout(function(){
  8503. me.fireEvent("clearDoc");
  8504. },0);
  8505. }
  8506. };
  8507. UE.commands['insertword'] = {
  8508. execCommand : function( cmdName) {
  8509. var ue = this;
  8510. var clickYes = function(call){
  8511. ue.execCommand("insertHtml",$("#pasteHtmlDiv").contents().find("body").html());
  8512. call(true);
  8513. uploadBase64Img(ue.iframe.contentWindow.document.body);
  8514. }
  8515. $.confirm("<div>将复制的word粘贴至此处</div><iframe src='about:blank' id='pasteHtmlDiv' style='border:1px solid #ddd;width:700px;height:400px' onload=\"insertwordInit(this)\"></iframe>",clickYes);
  8516. }
  8517. };
  8518. window.insertwordInit = function(obj){
  8519. var d = obj.contentWindow.document;
  8520. d.body.setAttribute('contenteditable','true');
  8521. d.onpaste = function(){
  8522. var body = this.body;
  8523. setTimeout(function(){
  8524. body.innerHTML = body.innerHTML.replace(/<[\/]?span[^>]*>/g,"").replace(/<[\/]?o:[^>]+>/g,"").replace(/style="[^"]+"/g,"").replace(/<table[^>]+>/g,"<table border=1 width=90% cellspacing=0 cellpadding=5>");
  8525. });
  8526. }
  8527. }
  8528. ///import core
  8529. ///commands 锚点
  8530. ///commandsName Anchor
  8531. ///commandsTitle 锚点
  8532. ///commandsDialog dialogs\anchor
  8533. /**
  8534. * 锚点
  8535. * @function
  8536. * @name baidu.editor.execCommands
  8537. * @param {String} cmdName cmdName="anchor"插入锚点
  8538. */
  8539. UE.plugins['anchor'] = function (){
  8540. var me = this;
  8541. me.ready(function(){
  8542. utils.cssRule('anchor',
  8543. '.anchorclass{background: url(\''
  8544. + me.options.UEDITOR_HOME_URL +
  8545. 'themes/default/images/anchor.gif\') no-repeat scroll left center transparent;border: 1px dotted #0000FF;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  8546. me.document)
  8547. });
  8548. me.addOutputRule(function(root){
  8549. utils.each(root.getNodesByTagName('img'),function(a){
  8550. var val;
  8551. if(val = a.getAttr('anchorname')){
  8552. a.tagName = 'a';
  8553. a.setAttr({
  8554. anchorname : '',
  8555. name : val,
  8556. 'class' : ''
  8557. })
  8558. }
  8559. })
  8560. });
  8561. me.addInputRule(function(root){
  8562. utils.each(root.getNodesByTagName('a'),function(a){
  8563. var val;
  8564. if((val = a.getAttr('name')) && !a.getAttr('href')){
  8565. a.tagName = 'img';
  8566. a.setAttr({
  8567. anchorname :a.getAttr('name'),
  8568. 'class' : 'anchorclass'
  8569. });
  8570. a.setAttr('name')
  8571. }
  8572. })
  8573. });
  8574. me.commands['anchor'] = {
  8575. execCommand:function (cmd, name) {
  8576. var range = this.selection.getRange(),img = range.getClosedNode();
  8577. if (img && img.getAttribute('anchorname')) {
  8578. if (name) {
  8579. img.setAttribute('anchorname', name);
  8580. } else {
  8581. range.setStartBefore(img).setCursor();
  8582. domUtils.remove(img);
  8583. }
  8584. } else {
  8585. if (name) {
  8586. //只在选区的开始插入
  8587. var anchor = this.document.createElement('img');
  8588. range.collapse(true);
  8589. domUtils.setAttributes(anchor,{
  8590. 'anchorname':name,
  8591. 'class':'anchorclass'
  8592. });
  8593. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  8594. }
  8595. }
  8596. }
  8597. };
  8598. };
  8599. ///import core
  8600. ///commands 字数统计
  8601. ///commandsName WordCount,wordCount
  8602. ///commandsTitle 字数统计
  8603. /**
  8604. * Created by JetBrains WebStorm.
  8605. * User: taoqili
  8606. * Date: 11-9-7
  8607. * Time: 下午8:18
  8608. * To change this template use File | Settings | File Templates.
  8609. */
  8610. UE.plugins['wordcount'] = function(){
  8611. var me = this;
  8612. me.addListener('contentchange',function(){
  8613. me.fireEvent('wordcount');
  8614. });
  8615. var timer;
  8616. me.addListener('ready',function(){
  8617. var me = this;
  8618. domUtils.on(me.body,"keyup",function(evt){
  8619. var code = evt.keyCode||evt.which,
  8620. //忽略的按键,ctr,alt,shift,方向键
  8621. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  8622. if(code in ignores) return;
  8623. clearTimeout(timer);
  8624. timer = setTimeout(function(){
  8625. me.fireEvent('wordcount');
  8626. },200)
  8627. })
  8628. });
  8629. };
  8630. ///import core
  8631. ///commands 添加分页功能
  8632. ///commandsName PageBreak
  8633. ///commandsTitle 分页
  8634. /**
  8635. * @description 添加分页功能
  8636. * @author zhanyi
  8637. */
  8638. UE.plugins['pagebreak'] = function () {
  8639. var me = this,
  8640. notBreakTags = ['td'];
  8641. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  8642. function fillNode(node){
  8643. if(domUtils.isEmptyBlock(node)){
  8644. var firstChild = node.firstChild,tmpNode;
  8645. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  8646. tmpNode = firstChild;
  8647. firstChild = firstChild.firstChild;
  8648. }
  8649. !tmpNode && (tmpNode = node);
  8650. domUtils.fillNode(me.document,tmpNode);
  8651. }
  8652. }
  8653. //分页符样式添加
  8654. me.ready(function(){
  8655. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  8656. });
  8657. function isHr(node){
  8658. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  8659. }
  8660. me.addInputRule(function(root){
  8661. root.traversal(function(node){
  8662. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  8663. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  8664. node.parentNode.insertBefore(hr,node);
  8665. node.parentNode.removeChild(node)
  8666. }
  8667. })
  8668. });
  8669. me.addOutputRule(function(node){
  8670. utils.each(node.getNodesByTagName('hr'),function(n){
  8671. if(n.getAttr('class') == 'pagebreak'){
  8672. var txt = UE.uNode.createText(me.options.pageBreakTag);
  8673. n.parentNode.insertBefore(txt,n);
  8674. n.parentNode.removeChild(n);
  8675. }
  8676. })
  8677. });
  8678. me.commands['pagebreak'] = {
  8679. execCommand:function () {
  8680. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  8681. domUtils.setAttributes(hr,{
  8682. 'class' : 'pagebreak',
  8683. noshade:"noshade",
  8684. size:"5"
  8685. });
  8686. domUtils.unSelectable(hr);
  8687. //table单独处理
  8688. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  8689. parents = [], pN;
  8690. if (node) {
  8691. switch (node.tagName) {
  8692. case 'TD':
  8693. pN = node.parentNode;
  8694. if (!pN.previousSibling) {
  8695. var table = domUtils.findParentByTagName(pN, 'table');
  8696. // var tableWrapDiv = table.parentNode;
  8697. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  8698. // && tableWrapDiv.tagName == 'DIV'
  8699. // && tableWrapDiv.getAttribute('dropdrag')
  8700. // ){
  8701. // domUtils.remove(tableWrapDiv,true);
  8702. // }
  8703. table.parentNode.insertBefore(hr, table);
  8704. parents = domUtils.findParents(hr, true);
  8705. } else {
  8706. pN.parentNode.insertBefore(hr, pN);
  8707. parents = domUtils.findParents(hr);
  8708. }
  8709. pN = parents[1];
  8710. if (hr !== pN) {
  8711. domUtils.breakParent(hr, pN);
  8712. }
  8713. //table要重写绑定一下拖拽
  8714. me.fireEvent('afteradjusttable',me.document);
  8715. }
  8716. } else {
  8717. if (!range.collapsed) {
  8718. range.deleteContents();
  8719. var start = range.startContainer;
  8720. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  8721. range.setStartBefore(start).collapse(true);
  8722. domUtils.remove(start);
  8723. start = range.startContainer;
  8724. }
  8725. }
  8726. range.insertNode(hr);
  8727. var pN = hr.parentNode, nextNode;
  8728. while (!domUtils.isBody(pN)) {
  8729. domUtils.breakParent(hr, pN);
  8730. nextNode = hr.nextSibling;
  8731. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  8732. domUtils.remove(nextNode);
  8733. }
  8734. pN = hr.parentNode;
  8735. }
  8736. nextNode = hr.nextSibling;
  8737. var pre = hr.previousSibling;
  8738. if(isHr(pre)){
  8739. domUtils.remove(pre);
  8740. }else{
  8741. pre && fillNode(pre);
  8742. }
  8743. if(!nextNode){
  8744. var p = me.document.createElement('p');
  8745. hr.parentNode.appendChild(p);
  8746. domUtils.fillNode(me.document,p);
  8747. range.setStart(p,0).collapse(true);
  8748. }else{
  8749. if(isHr(nextNode)){
  8750. domUtils.remove(nextNode);
  8751. }else{
  8752. fillNode(nextNode);
  8753. }
  8754. range.setEndAfter(hr).collapse(false);
  8755. }
  8756. range.select(true);
  8757. }
  8758. }
  8759. };
  8760. };
  8761. ///import core
  8762. ///commands 本地图片引导上传
  8763. ///commandsName WordImage
  8764. ///commandsTitle 本地图片引导上传
  8765. ///commandsDialog dialogs\wordimage
  8766. UE.plugins["wordimage"] = function () {
  8767. var me = this,
  8768. images;
  8769. me.addInputRule(function (root) {
  8770. utils.each(root.getNodesByTagName('img'), function (img) {
  8771. var attrs = img.attrs,
  8772. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  8773. opt = me.options,
  8774. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  8775. if (attrs['_src'] && attrs['_src'].indexOf("file:///")!==-1) {
  8776. img.setAttr({
  8777. width:attrs.width,
  8778. height:attrs.height,
  8779. alt:attrs.alt,
  8780. word_img:attrs._src,
  8781. src:src,
  8782. _src:src,
  8783. 'style':'background:url(' + ( flag ? opt.themePath + opt.theme + '/images/word.gif' : opt.langPath + opt.lang + '/images/localimage.png') + ') no-repeat center center;border:1px solid #ddd'
  8784. })
  8785. }
  8786. })
  8787. });
  8788. me.commands['wordimage'] = {
  8789. execCommand:function () {
  8790. images = domUtils.getElementsByTagName(me.document.body, "img");
  8791. var urlList = [];
  8792. for (var i = 0, ci; ci = images[i++];) {
  8793. var url = ci.getAttribute("word_img");
  8794. url && urlList.push(url);
  8795. }
  8796. if (images.length) {
  8797. this["word_img"] = urlList;
  8798. }
  8799. },
  8800. queryCommandState:function () {
  8801. images = domUtils.getElementsByTagName(me.document.body, "img");
  8802. for (var i = 0, ci; ci = images[i++];) {
  8803. if (ci.getAttribute("word_img")) {
  8804. return 1;
  8805. }
  8806. }
  8807. return -1;
  8808. }
  8809. };
  8810. };
  8811. UE.plugins['dragdrop'] = function (){
  8812. var me = this;
  8813. me.ready(function(){
  8814. domUtils.on(this.body,'dragend',function(){
  8815. var rng = me.selection.getRange();
  8816. var node = rng.getClosedNode()||me.selection.getStart();
  8817. if(node && node.tagName == 'IMG'){
  8818. var pre = node.previousSibling,next;
  8819. while(next = node.nextSibling){
  8820. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  8821. domUtils.remove(next)
  8822. }else{
  8823. break;
  8824. }
  8825. }
  8826. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  8827. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  8828. pre.appendChild(node);
  8829. domUtils.moveChild(next,pre);
  8830. domUtils.remove(next);
  8831. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  8832. next.insertBefore(node,next.firstChild);
  8833. }
  8834. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  8835. domUtils.remove(pre)
  8836. }
  8837. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  8838. domUtils.remove(next)
  8839. }
  8840. rng.selectNode(node).select();
  8841. me.fireEvent('saveScene');
  8842. }
  8843. }
  8844. })
  8845. });
  8846. me.addListener('keyup', function(type, evt) {
  8847. var keyCode = evt.keyCode || evt.which;
  8848. if (keyCode == 13) {
  8849. var rng = me.selection.getRange(),node;
  8850. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  8851. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  8852. domUtils.removeStyle(node,'text-align')
  8853. }
  8854. }
  8855. }
  8856. })
  8857. };
  8858. ///import core
  8859. ///commands 撤销和重做
  8860. ///commandsName Undo,Redo
  8861. ///commandsTitle 撤销,重做
  8862. /**
  8863. * @description 回退
  8864. * @author zhanyi
  8865. */
  8866. UE.plugins['undo'] = function () {
  8867. var saveSceneTimer;
  8868. var me = this,
  8869. maxUndoCount = me.options.maxUndoCount || 20,
  8870. maxInputCount = me.options.maxInputCount || 20,
  8871. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  8872. var noNeedFillCharTags = {
  8873. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  8874. };
  8875. var orgState = me.options.autoClearEmptyNode;
  8876. function compareAddr(indexA, indexB) {
  8877. if (indexA.length != indexB.length)
  8878. return 0;
  8879. for (var i = 0, l = indexA.length; i < l; i++) {
  8880. if (indexA[i] != indexB[i])
  8881. return 0
  8882. }
  8883. return 1;
  8884. }
  8885. function compareRangeAddress(rngAddrA, rngAddrB) {
  8886. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  8887. return 0;
  8888. }
  8889. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  8890. return 0;
  8891. }
  8892. return 1;
  8893. }
  8894. function UndoManager() {
  8895. this.list = [];
  8896. this.index = 0;
  8897. this.hasUndo = false;
  8898. this.hasRedo = false;
  8899. this.undo = function () {
  8900. if (this.hasUndo) {
  8901. if (!this.list[this.index - 1] && this.list.length == 1) {
  8902. this.reset();
  8903. return;
  8904. }
  8905. while (this.list[this.index].content == this.list[this.index - 1].content) {
  8906. this.index--;
  8907. if (this.index == 0) {
  8908. return this.restore(0);
  8909. }
  8910. }
  8911. this.restore(--this.index);
  8912. }
  8913. };
  8914. this.redo = function () {
  8915. if (this.hasRedo) {
  8916. while (this.list[this.index].content == this.list[this.index + 1].content) {
  8917. this.index++;
  8918. if (this.index == this.list.length - 1) {
  8919. return this.restore(this.index);
  8920. }
  8921. }
  8922. this.restore(++this.index);
  8923. }
  8924. };
  8925. this.restore = function () {
  8926. var me = this.editor;
  8927. var scene = this.list[this.index];
  8928. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  8929. me.options.autoClearEmptyNode = false;
  8930. me.filterInputRule(root);
  8931. me.options.autoClearEmptyNode = orgState;
  8932. //trace:873
  8933. //去掉展位符
  8934. me.document.body.innerHTML = root.toHtml();
  8935. me.fireEvent('afterscencerestore');
  8936. //处理undo后空格不展位的问题
  8937. if (browser.ie) {
  8938. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  8939. if(domUtils.isEmptyNode(node)){
  8940. domUtils.fillNode(me.document, node);
  8941. }
  8942. })
  8943. }
  8944. try{
  8945. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  8946. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  8947. }catch(e){}
  8948. this.update();
  8949. this.clearKey();
  8950. //不能把自己reset了
  8951. me.fireEvent('reset', true);
  8952. };
  8953. this.getScene = function (notSetCursor) {
  8954. var me = this.editor;
  8955. var rng = me.selection.getRange(),
  8956. // restoreAddress = rng.createAddress(),
  8957. rngAddress = rng.createAddress(false,true);
  8958. me.fireEvent('beforegetscene');
  8959. var root = UE.htmlparser(me.body.innerHTML,true);
  8960. me.options.autoClearEmptyNode = false;
  8961. me.filterOutputRule(root);
  8962. me.options.autoClearEmptyNode = orgState;
  8963. var cont = root.toHtml();
  8964. browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  8965. me.fireEvent('aftergetscene');
  8966. try{
  8967. // !notSetCursor && rng.moveToAddress(restoreAddress).select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  8968. }catch(e){}
  8969. return {
  8970. address:rngAddress,
  8971. content:cont
  8972. }
  8973. };
  8974. this.save = function (notCompareRange,notSetCursor) {
  8975. clearTimeout(saveSceneTimer);
  8976. var currentScene = this.getScene(notSetCursor),
  8977. lastScene = this.list[this.index];
  8978. //内容相同位置相同不存
  8979. if (lastScene && lastScene.content == currentScene.content &&
  8980. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  8981. ) {
  8982. return;
  8983. }
  8984. this.list = this.list.slice(0, this.index + 1);
  8985. this.list.push(currentScene);
  8986. //如果大于最大数量了,就把最前的剔除
  8987. if (this.list.length > maxUndoCount) {
  8988. this.list.shift();
  8989. }
  8990. this.index = this.list.length - 1;
  8991. this.clearKey();
  8992. //跟新undo/redo状态
  8993. this.update();
  8994. };
  8995. this.update = function () {
  8996. this.hasRedo = !!this.list[this.index + 1];
  8997. this.hasUndo = !!this.list[this.index - 1];
  8998. };
  8999. this.reset = function () {
  9000. this.list = [];
  9001. this.index = 0;
  9002. this.hasUndo = false;
  9003. this.hasRedo = false;
  9004. this.clearKey();
  9005. };
  9006. this.clearKey = function () {
  9007. keycont = 0;
  9008. lastKeyCode = null;
  9009. };
  9010. }
  9011. me.undoManger = new UndoManager();
  9012. me.undoManger.editor = me;
  9013. function saveScene() {
  9014. this.undoManger.save();
  9015. }
  9016. me.addListener('saveScene', function () {
  9017. var args = Array.prototype.splice.call(arguments,1);
  9018. this.undoManger.save.apply(this.undoManger,args);
  9019. });
  9020. me.addListener('beforeexeccommand', saveScene);
  9021. me.addListener('afterexeccommand', saveScene);
  9022. me.addListener('reset', function (type, exclude) {
  9023. if (!exclude) {
  9024. this.undoManger.reset();
  9025. }
  9026. });
  9027. me.commands['redo'] = me.commands['undo'] = {
  9028. execCommand:function (cmdName) {
  9029. this.undoManger[cmdName]();
  9030. },
  9031. queryCommandState:function (cmdName) {
  9032. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  9033. },
  9034. notNeedUndo:1
  9035. };
  9036. var keys = {
  9037. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  9038. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  9039. 37:1, 38:1, 39:1, 40:1
  9040. },
  9041. keycont = 0,
  9042. lastKeyCode;
  9043. //输入法状态下不计算字符数
  9044. var inputType = false;
  9045. me.addListener('ready', function () {
  9046. domUtils.on(this.body, 'compositionstart', function () {
  9047. inputType = true;
  9048. });
  9049. domUtils.on(this.body, 'compositionend', function () {
  9050. inputType = false;
  9051. })
  9052. });
  9053. //快捷键
  9054. me.addshortcutkey({
  9055. "Undo":"ctrl+90", //undo
  9056. "Redo":"ctrl+89" //redo
  9057. });
  9058. var isCollapsed = true;
  9059. me.addListener('keydown', function (type, evt) {
  9060. var me = this;
  9061. var keyCode = evt.keyCode || evt.which;
  9062. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  9063. if (inputType)
  9064. return;
  9065. if(!me.selection.getRange().collapsed){
  9066. me.undoManger.save(false,true);
  9067. isCollapsed = false;
  9068. return;
  9069. }
  9070. if (me.undoManger.list.length == 0) {
  9071. me.undoManger.save(true);
  9072. }
  9073. clearTimeout(saveSceneTimer);
  9074. function save(cont){
  9075. if (cont.selection.getRange().collapsed)
  9076. cont.fireEvent('contentchange');
  9077. cont.undoManger.save(false,true);
  9078. cont.fireEvent('selectionchange');
  9079. }
  9080. saveSceneTimer = setTimeout(function(){
  9081. if(inputType){
  9082. var interalTimer = setInterval(function(){
  9083. if(!inputType){
  9084. save(me);
  9085. clearInterval(interalTimer)
  9086. }
  9087. },300)
  9088. return;
  9089. }
  9090. save(me);
  9091. },200);
  9092. lastKeyCode = keyCode;
  9093. keycont++;
  9094. if (keycont >= maxInputCount ) {
  9095. save(me)
  9096. }
  9097. }
  9098. });
  9099. me.addListener('keyup', function (type, evt) {
  9100. var keyCode = evt.keyCode || evt.which;
  9101. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  9102. if (inputType)
  9103. return;
  9104. if(!isCollapsed){
  9105. this.undoManger.save(false,true);
  9106. isCollapsed = true;
  9107. }
  9108. }
  9109. });
  9110. };
  9111. ///import core
  9112. ///import plugins/inserthtml.js
  9113. ///import plugins/undo.js
  9114. ///import plugins/serialize.js
  9115. ///commands 粘贴
  9116. ///commandsName PastePlain
  9117. ///commandsTitle 纯文本粘贴模式
  9118. /*
  9119. ** @description 粘贴
  9120. * @author zhanyi
  9121. */
  9122. UE.plugins['paste'] = function () {
  9123. function getClipboardData(callback) {
  9124. var doc = this.document;
  9125. if (doc.getElementById('baidu_pastebin')) {
  9126. return;
  9127. }
  9128. var range = this.selection.getRange(),
  9129. bk = range.createBookmark(),
  9130. //创建剪贴的容器div
  9131. pastebin = doc.createElement('div');
  9132. pastebin.id = 'baidu_pastebin';
  9133. // Safari 要求div必须有内容,才能粘贴内容进来
  9134. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  9135. doc.body.appendChild(pastebin);
  9136. //trace:717 隐藏的span不能得到top
  9137. //bk.start.innerHTML = '&nbsp;';
  9138. bk.start.style.display = '';
  9139. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  9140. //要在现在光标平行的位置加入,否则会出现跳动的问题
  9141. domUtils.getXY(bk.start).y + 'px';
  9142. range.selectNodeContents(pastebin).select(true);
  9143. setTimeout(function () {
  9144. if (browser.webkit) {
  9145. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  9146. if (domUtils.isEmptyNode(pi)) {
  9147. domUtils.remove(pi);
  9148. } else {
  9149. pastebin = pi;
  9150. break;
  9151. }
  9152. }
  9153. }
  9154. try {
  9155. pastebin.parentNode.removeChild(pastebin);
  9156. } catch (e) {
  9157. }
  9158. range.moveToBookmark(bk).select(true);
  9159. callback(pastebin);
  9160. }, 0);
  9161. }
  9162. var me = this;
  9163. var txtContent, htmlContent, address;
  9164. function filter(div) {
  9165. var html;
  9166. if (div.firstChild) {
  9167. //去掉cut中添加的边界值
  9168. var nodes = domUtils.getElementsByTagName(div, 'span');
  9169. for (var i = 0, ni; ni = nodes[i++];) {
  9170. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  9171. domUtils.remove(ni);
  9172. }
  9173. }
  9174. if (browser.webkit) {
  9175. var brs = div.querySelectorAll('div br');
  9176. for (var i = 0, bi; bi = brs[i++];) {
  9177. var pN = bi.parentNode;
  9178. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  9179. pN.innerHTML = '<p><br/></p>';
  9180. domUtils.remove(pN);
  9181. }
  9182. }
  9183. var divs = div.querySelectorAll('#baidu_pastebin');
  9184. for (var i = 0, di; di = divs[i++];) {
  9185. var tmpP = me.document.createElement('p');
  9186. di.parentNode.insertBefore(tmpP, di);
  9187. while (di.firstChild) {
  9188. tmpP.appendChild(di.firstChild);
  9189. }
  9190. domUtils.remove(di);
  9191. }
  9192. var metas = div.querySelectorAll('meta');
  9193. for (var i = 0, ci; ci = metas[i++];) {
  9194. domUtils.remove(ci);
  9195. }
  9196. var brs = div.querySelectorAll('br');
  9197. for (i = 0; ci = brs[i++];) {
  9198. if (/^apple-/i.test(ci.className)) {
  9199. domUtils.remove(ci);
  9200. }
  9201. }
  9202. }
  9203. if (browser.gecko) {
  9204. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  9205. for (i = 0; ci = dirtyNodes[i++];) {
  9206. ci.removeAttribute('_moz_dirty');
  9207. }
  9208. }
  9209. if (!browser.ie) {
  9210. var spans = div.querySelectorAll('span.Apple-style-span');
  9211. for (var i = 0, ci; ci = spans[i++];) {
  9212. domUtils.remove(ci, true);
  9213. }
  9214. }
  9215. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  9216. html = div.innerHTML//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  9217. //过滤word粘贴过来的冗余属性
  9218. html = UE.filterWord(html);
  9219. var root = UE.htmlparser(html,true);
  9220. //如果给了过滤规则就先进行过滤
  9221. if (me.options.filterRules) {
  9222. UE.filterNode(root, me.options.filterRules);
  9223. }
  9224. //执行默认的处理
  9225. me.filterInputRule(root);
  9226. //针对chrome的处理
  9227. if (browser.webkit) {
  9228. var br = root.lastChild();
  9229. if (br && br.type == 'element' && br.tagName == 'br') {
  9230. root.removeChild(br)
  9231. }
  9232. utils.each(me.body.querySelectorAll('div'), function (node) {
  9233. if (domUtils.isEmptyBlock(node)) {
  9234. domUtils.remove(node)
  9235. }
  9236. })
  9237. }
  9238. html = {'html': root.toHtml()};
  9239. me.fireEvent('beforepaste', html, root);
  9240. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  9241. if(!html.html){
  9242. return;
  9243. }
  9244. root = UE.htmlparser(html.html,true);
  9245. //如果开启了纯文本模式
  9246. if (me.queryCommandState('pasteplain') === 1) {
  9247. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  9248. } else {
  9249. //文本模式
  9250. UE.filterNode(root, me.options.filterTxtRules);
  9251. txtContent = root.toHtml();
  9252. //完全模式
  9253. htmlContent = html.html;
  9254. address = me.selection.getRange().createAddress(true);
  9255. me.execCommand('insertHtml', htmlContent, true);
  9256. }
  9257. me.fireEvent("afterpaste", html);
  9258. }
  9259. }
  9260. me.addListener('pasteTransfer', function (cmd, plainType) {
  9261. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  9262. var range = me.selection.getRange();
  9263. range.moveToAddress(address, true);
  9264. if (!range.collapsed) {
  9265. while (!domUtils.isBody(range.startContainer)
  9266. ) {
  9267. var start = range.startContainer;
  9268. if(start.nodeType == 1){
  9269. start = start.childNodes[range.startOffset];
  9270. if(!start){
  9271. range.setStartBefore(range.startContainer);
  9272. continue;
  9273. }
  9274. var pre = start.previousSibling;
  9275. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  9276. range.setStartBefore(pre)
  9277. }
  9278. }
  9279. if(range.startOffset == 0){
  9280. range.setStartBefore(range.startContainer);
  9281. }else{
  9282. break;
  9283. }
  9284. }
  9285. while (!domUtils.isBody(range.endContainer)
  9286. ) {
  9287. var end = range.endContainer;
  9288. if(end.nodeType == 1){
  9289. end = end.childNodes[range.endOffset];
  9290. if(!end){
  9291. range.setEndAfter(range.endContainer);
  9292. continue;
  9293. }
  9294. var next = end.nextSibling;
  9295. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  9296. range.setEndAfter(next)
  9297. }
  9298. }
  9299. if(range.endOffset == range.endContainer.childNodes.length){
  9300. range.setEndAfter(range.endContainer);
  9301. }else{
  9302. break;
  9303. }
  9304. }
  9305. }
  9306. range.deleteContents();
  9307. range.select(true);
  9308. me.__hasEnterExecCommand = true;
  9309. var html = htmlContent;
  9310. if (plainType === 2) {
  9311. html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  9312. tagName = tagName.toLowerCase();
  9313. if ({img: 1}[tagName]) {
  9314. return a;
  9315. }
  9316. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  9317. if ({
  9318. 'src': 1,
  9319. 'href': 1,
  9320. 'name': 1
  9321. }[atr.toLowerCase()]) {
  9322. return atr + '=' + val + ' '
  9323. }
  9324. return ''
  9325. });
  9326. if ({
  9327. 'span': 1,
  9328. 'div': 1
  9329. }[tagName]) {
  9330. return ''
  9331. } else {
  9332. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  9333. }
  9334. });
  9335. } else if (plainType) {
  9336. html = txtContent;
  9337. }
  9338. me.execCommand('inserthtml', html, true);
  9339. me.__hasEnterExecCommand = false;
  9340. var tmpAddress = me.selection.getRange().createAddress(true);
  9341. address.endAddress = tmpAddress.startAddress;
  9342. }
  9343. });
  9344. me.addListener('ready', function () {
  9345. domUtils.on(me.body, 'cut', function () {
  9346. var range = me.selection.getRange();
  9347. if (!range.collapsed && me.undoManger) {
  9348. me.undoManger.save();
  9349. }
  9350. });
  9351. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  9352. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  9353. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  9354. return;
  9355. }
  9356. getClipboardData.call(me, function (div) {
  9357. filter(div);
  9358. });
  9359. });
  9360. });
  9361. };
  9362. ///import core
  9363. ///commands 有序列表,无序列表
  9364. ///commandsName InsertOrderedList,InsertUnorderedList
  9365. ///commandsTitle 有序列表,无序列表
  9366. /**
  9367. * 有序列表
  9368. * @function
  9369. * @name baidu.editor.execCommand
  9370. * @param {String} cmdName insertorderlist插入有序列表
  9371. * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman
  9372. * @author zhanyi
  9373. */
  9374. /**
  9375. * 无序链接
  9376. * @function
  9377. * @name baidu.editor.execCommand
  9378. * @param {String} cmdName insertunorderlist插入无序列表
  9379. * * @param {String} style 值为:circle,disc,square
  9380. * @author zhanyi
  9381. */
  9382. UE.plugins['list'] = function () {
  9383. var me = this,
  9384. notExchange = {
  9385. 'TD':1,
  9386. 'PRE':1,
  9387. 'BLOCKQUOTE':1
  9388. };
  9389. var customStyle = {
  9390. 'cn' : 'cn-1-',
  9391. 'cn1' : 'cn-2-',
  9392. 'cn2' : 'cn-3-',
  9393. 'num': 'num-1-',
  9394. 'num1' : 'num-2-',
  9395. 'num2' : 'num-3-',
  9396. 'dash' : 'dash',
  9397. 'dot':'dot'
  9398. };
  9399. me.setOpt( {
  9400. 'insertorderedlist':{
  9401. 'num':'',
  9402. 'num1':'',
  9403. 'num2':'',
  9404. 'cn':'',
  9405. 'cn1':'',
  9406. 'cn2':'',
  9407. 'decimal':'',
  9408. 'lower-alpha':'',
  9409. 'lower-roman':'',
  9410. 'upper-alpha':'',
  9411. 'upper-roman':''
  9412. },
  9413. 'insertunorderedlist':{
  9414. 'circle':'',
  9415. 'disc':'',
  9416. 'square':'',
  9417. 'dash' : '',
  9418. 'dot':''
  9419. },
  9420. listDefaultPaddingLeft : '30',
  9421. listiconpath : 'http://bs.baidu.com/listicon/',
  9422. maxListLevel : -1//-1不限制
  9423. } );
  9424. function listToArray(list){
  9425. var arr = [];
  9426. for(var p in list){
  9427. arr.push(p)
  9428. }
  9429. return arr;
  9430. }
  9431. var listStyle = {
  9432. 'OL':listToArray(me.options.insertorderedlist),
  9433. 'UL':listToArray(me.options.insertunorderedlist)
  9434. };
  9435. var liiconpath = me.options.listiconpath;
  9436. //根据用户配置,调整customStyle
  9437. for(var s in customStyle){
  9438. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  9439. delete customStyle[s];
  9440. }
  9441. }
  9442. me.ready(function () {
  9443. var customCss = [];
  9444. for(var p in customStyle){
  9445. if(p == 'dash' || p == 'dot'){
  9446. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  9447. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  9448. }else{
  9449. for(var i= 0;i<99;i++){
  9450. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  9451. }
  9452. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  9453. }
  9454. switch(p){
  9455. case 'cn':
  9456. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  9457. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  9458. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  9459. break;
  9460. case 'cn1':
  9461. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  9462. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  9463. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  9464. break;
  9465. case 'cn2':
  9466. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  9467. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  9468. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  9469. break;
  9470. case 'num':
  9471. case 'num1':
  9472. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  9473. break;
  9474. case 'num2':
  9475. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  9476. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  9477. break;
  9478. case 'dash':
  9479. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  9480. break;
  9481. case 'dot':
  9482. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  9483. }
  9484. }
  9485. customCss.push('.list-paddingleft-1{padding-left:0}');
  9486. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  9487. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  9488. //如果不给宽度会在自定应样式里出现滚动条
  9489. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  9490. });
  9491. //单独处理剪切的问题
  9492. me.ready(function(){
  9493. domUtils.on(me.body,'cut',function(){
  9494. setTimeout(function(){
  9495. var rng = me.selection.getRange(),li;
  9496. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  9497. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  9498. var pn = li.parentNode,node;
  9499. if(node = pn.previousSibling){
  9500. domUtils.remove(pn);
  9501. rng.setStartAtLast(node).collapse(true);
  9502. rng.select(true);
  9503. }else if(node = pn.nextSibling){
  9504. domUtils.remove(pn);
  9505. rng.setStartAtFirst(node).collapse(true);
  9506. rng.select(true);
  9507. }else{
  9508. var tmpNode = me.document.createElement('p');
  9509. domUtils.fillNode(me.document,tmpNode);
  9510. pn.parentNode.insertBefore(tmpNode,pn);
  9511. domUtils.remove(pn);
  9512. rng.setStart(tmpNode,0).collapse(true);
  9513. rng.select(true);
  9514. }
  9515. }
  9516. }
  9517. })
  9518. })
  9519. });
  9520. function getStyle(node){
  9521. var cls = node.className;
  9522. if(domUtils.hasClass(node,/custom_/)){
  9523. return cls.match(/custom_(\w+)/)[1]
  9524. }
  9525. return domUtils.getStyle(node, 'list-style-type')
  9526. }
  9527. me.addListener('beforepaste',function(type,html){
  9528. var me = this,
  9529. rng = me.selection.getRange(),li;
  9530. var root = UE.htmlparser(html.html,true);
  9531. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  9532. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  9533. utils.each(root.getNodesByTagName(tagName),function(n){
  9534. n.tagName = list.tagName;
  9535. n.setAttr();
  9536. if(n.parentNode === root){
  9537. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  9538. }else{
  9539. var className = n.parentNode.getAttr('class');
  9540. if(className && /custom_/.test(className)){
  9541. type = className.match(/custom_(\w+)/)[1]
  9542. }else{
  9543. type = n.parentNode.getStyle('list-style-type');
  9544. }
  9545. if(!type){
  9546. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  9547. }
  9548. }
  9549. var index = utils.indexOf(listStyle[list.tagName], type);
  9550. if(n.parentNode !== root)
  9551. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  9552. var currentStyle = listStyle[list.tagName][index];
  9553. if(customStyle[currentStyle]){
  9554. n.setAttr('class', 'custom_' + currentStyle)
  9555. }else{
  9556. n.setStyle('list-style-type',currentStyle)
  9557. }
  9558. })
  9559. }
  9560. html.html = root.toHtml();
  9561. });
  9562. //进入编辑器的li要套p标签
  9563. me.addInputRule(function(root){
  9564. utils.each(root.getNodesByTagName('li'),function(li){
  9565. var tmpP = UE.uNode.createElement('p');
  9566. for(var i= 0,ci;ci=li.children[i];){
  9567. if(ci.type == 'text' || dtd.p[ci.tagName]){
  9568. tmpP.appendChild(ci);
  9569. }else{
  9570. if(tmpP.firstChild()){
  9571. li.insertBefore(tmpP,ci);
  9572. tmpP = UE.uNode.createElement('p');
  9573. i = i + 2;
  9574. }else{
  9575. i++;
  9576. }
  9577. }
  9578. }
  9579. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  9580. li.appendChild(tmpP);
  9581. }
  9582. });
  9583. var orderlisttype = {
  9584. 'num1':/^\d+\)/,
  9585. 'decimal':/^\d+\./,
  9586. 'lower-alpha':/^[a-z]+\)/,
  9587. 'upper-alpha':/^[A-Z]+\./,
  9588. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  9589. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  9590. },
  9591. unorderlisttype = {
  9592. 'square':'n'
  9593. };
  9594. function checkListType(content,container){
  9595. var span = container.firstChild();
  9596. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  9597. for(var p in unorderlisttype){
  9598. if(unorderlisttype[p] == span.data){
  9599. return p
  9600. }
  9601. }
  9602. return 'disc'
  9603. }
  9604. for(var p in orderlisttype){
  9605. if(orderlisttype[p].test(content)){
  9606. return p;
  9607. }
  9608. }
  9609. }
  9610. utils.each(root.getNodesByTagName('p'),function(node){
  9611. if(node.getAttr('class') != 'MsoListParagraph'){
  9612. return
  9613. }
  9614. node.setAttr('class','');
  9615. function appendLi(list,p,type){
  9616. if(list.tagName == 'ol'){
  9617. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  9618. }else{
  9619. p.removeChild(p.firstChild())
  9620. }
  9621. var li = UE.uNode.createElement('li');
  9622. li.appendChild(p);
  9623. list.appendChild(li);
  9624. }
  9625. var tmp = node,type;
  9626. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  9627. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  9628. if(customStyle[type]){
  9629. list.setAttr('class','custom_'+type)
  9630. }else{
  9631. list.setStyle('list-style-type',type)
  9632. }
  9633. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  9634. tmp = node.nextSibling();
  9635. if(!tmp){
  9636. node.parentNode.insertBefore(list,node)
  9637. }
  9638. appendLi(list,node,type);
  9639. node = tmp;
  9640. }
  9641. if(!list.parentNode && node && node.parentNode){
  9642. node.parentNode.insertBefore(list,node)
  9643. }
  9644. }
  9645. })
  9646. });
  9647. //调整索引标签
  9648. me.addListener('contentchange',function(){
  9649. adjustListStyle(me.document)
  9650. });
  9651. function adjustListStyle(doc,ignore){
  9652. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  9653. if(!domUtils.inDoc(node,doc))
  9654. return;
  9655. var parent = node.parentNode;
  9656. if(parent.tagName == node.tagName){
  9657. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  9658. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  9659. if(nodeStyleType == parentStyleType){
  9660. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  9661. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  9662. setListStyle(node,listStyle[node.tagName][styleIndex])
  9663. }
  9664. }
  9665. var index = 0,type = 2;
  9666. if( domUtils.hasClass(node,/custom_/)){
  9667. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  9668. type = 1;
  9669. }
  9670. }else{
  9671. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  9672. type = 3;
  9673. }
  9674. }
  9675. var style = domUtils.getStyle(node, 'list-style-type');
  9676. style && (node.style.cssText = 'list-style-type:' + style);
  9677. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  9678. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  9679. li.style.cssText && (li.style.cssText = '');
  9680. if(!li.firstChild){
  9681. domUtils.remove(li);
  9682. return;
  9683. }
  9684. if(li.parentNode !== node){
  9685. return;
  9686. }
  9687. index++;
  9688. if(domUtils.hasClass(node,/custom_/) ){
  9689. var paddingLeft = 1,currentStyle = getStyle(node);
  9690. if(node.tagName == 'OL'){
  9691. if(currentStyle){
  9692. switch(currentStyle){
  9693. case 'cn' :
  9694. case 'cn1':
  9695. case 'cn2':
  9696. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  9697. paddingLeft = 2
  9698. }else if(index > 20){
  9699. paddingLeft = 3
  9700. }
  9701. break;
  9702. case 'num2' :
  9703. if(index > 9){
  9704. paddingLeft = 2
  9705. }
  9706. }
  9707. }
  9708. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  9709. }else{
  9710. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  9711. }
  9712. }else{
  9713. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  9714. }
  9715. var className = li.getAttribute('class');
  9716. if(className !== null && !className.replace(/\s/g,'')){
  9717. domUtils.removeAttributes(li,'class')
  9718. }
  9719. });
  9720. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  9721. })
  9722. }
  9723. function adjustList(list, tag, style,ignoreEmpty) {
  9724. var nextList = list.nextSibling;
  9725. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  9726. domUtils.moveChild(nextList, list);
  9727. if (nextList.childNodes.length == 0) {
  9728. domUtils.remove(nextList);
  9729. }
  9730. }
  9731. if(nextList && domUtils.isFillChar(nextList)){
  9732. domUtils.remove(nextList);
  9733. }
  9734. var preList = list.previousSibling;
  9735. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  9736. domUtils.moveChild(list, preList);
  9737. }
  9738. if(preList && domUtils.isFillChar(preList)){
  9739. domUtils.remove(preList);
  9740. }
  9741. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  9742. if(getStyle(list)){
  9743. adjustListStyle(list.ownerDocument,true)
  9744. }
  9745. }
  9746. function setListStyle(list,style){
  9747. if(customStyle[style]){
  9748. list.className = 'custom_' + style;
  9749. }
  9750. try{
  9751. domUtils.setStyle(list, 'list-style-type', style);
  9752. }catch(e){}
  9753. }
  9754. function clearEmptySibling(node) {
  9755. var tmpNode = node.previousSibling;
  9756. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  9757. domUtils.remove(tmpNode);
  9758. }
  9759. tmpNode = node.nextSibling;
  9760. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  9761. domUtils.remove(tmpNode);
  9762. }
  9763. }
  9764. me.addListener('keydown', function (type, evt) {
  9765. function preventAndSave() {
  9766. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  9767. me.fireEvent('contentchange');
  9768. me.undoManger && me.undoManger.save();
  9769. }
  9770. function findList(node,filterFn){
  9771. while(node && !domUtils.isBody(node)){
  9772. if(filterFn(node)){
  9773. return null
  9774. }
  9775. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  9776. return node;
  9777. }
  9778. node = node.parentNode;
  9779. }
  9780. return null;
  9781. }
  9782. return;
  9783. var keyCode = evt.keyCode || evt.which;
  9784. if (keyCode == 13 && !evt.shiftKey) {//回车
  9785. var rng = me.selection.getRange(),
  9786. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  9787. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  9788. if(parent && parent.tagName != 'PRE' && !li){
  9789. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  9790. if(/^\s*1\s*\.[^\d]/.test(html)){
  9791. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  9792. rng.setStartAtLast(parent).collapse(true).select();
  9793. me.__hasEnterExecCommand = true;
  9794. me.execCommand('insertorderedlist');
  9795. me.__hasEnterExecCommand = false;
  9796. }
  9797. }
  9798. var range = me.selection.getRange(),
  9799. start = findList(range.startContainer,function (node) {
  9800. return node.tagName == 'TABLE';
  9801. }),
  9802. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  9803. return node.tagName == 'TABLE';
  9804. });
  9805. if (start && end && start === end) {
  9806. if (!range.collapsed) {
  9807. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9808. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  9809. if (start && end && start === end) {
  9810. range.deleteContents();
  9811. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9812. if (li && domUtils.isEmptyBlock(li)) {
  9813. pre = li.previousSibling;
  9814. next = li.nextSibling;
  9815. p = me.document.createElement('p');
  9816. domUtils.fillNode(me.document, p);
  9817. parentList = li.parentNode;
  9818. if (pre && next) {
  9819. range.setStart(next, 0).collapse(true).select(true);
  9820. domUtils.remove(li);
  9821. } else {
  9822. if (!pre && !next || !pre) {
  9823. parentList.parentNode.insertBefore(p, parentList);
  9824. } else {
  9825. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  9826. }
  9827. domUtils.remove(li);
  9828. if (!parentList.firstChild) {
  9829. domUtils.remove(parentList);
  9830. }
  9831. range.setStart(p, 0).setCursor();
  9832. }
  9833. preventAndSave();
  9834. return;
  9835. }
  9836. } else {
  9837. var tmpRange = range.cloneRange(),
  9838. bk = tmpRange.collapse(false).createBookmark();
  9839. range.deleteContents();
  9840. tmpRange.moveToBookmark(bk);
  9841. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  9842. clearEmptySibling(li);
  9843. tmpRange.select();
  9844. preventAndSave();
  9845. return;
  9846. }
  9847. }
  9848. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9849. if (li) {
  9850. if (domUtils.isEmptyBlock(li)) {
  9851. bk = range.createBookmark();
  9852. var parentList = li.parentNode;
  9853. if (li !== parentList.lastChild) {
  9854. domUtils.breakParent(li, parentList);
  9855. clearEmptySibling(li);
  9856. } else {
  9857. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  9858. if (domUtils.isEmptyNode(parentList)) {
  9859. domUtils.remove(parentList);
  9860. }
  9861. }
  9862. //嵌套不处理
  9863. if (!dtd.$list[li.parentNode.tagName]) {
  9864. if (!domUtils.isBlockElm(li.firstChild)) {
  9865. p = me.document.createElement('p');
  9866. li.parentNode.insertBefore(p, li);
  9867. while (li.firstChild) {
  9868. p.appendChild(li.firstChild);
  9869. }
  9870. domUtils.remove(li);
  9871. } else {
  9872. domUtils.remove(li, true);
  9873. }
  9874. }
  9875. range.moveToBookmark(bk).select();
  9876. } else {
  9877. var first = li.firstChild;
  9878. if (!first || !domUtils.isBlockElm(first)) {
  9879. var p = me.document.createElement('p');
  9880. !li.firstChild && domUtils.fillNode(me.document, p);
  9881. while (li.firstChild) {
  9882. p.appendChild(li.firstChild);
  9883. }
  9884. li.appendChild(p);
  9885. first = p;
  9886. }
  9887. var span = me.document.createElement('span');
  9888. range.insertNode(span);
  9889. domUtils.breakParent(span, li);
  9890. var nextLi = span.nextSibling;
  9891. first = nextLi.firstChild;
  9892. if (!first) {
  9893. p = me.document.createElement('p');
  9894. domUtils.fillNode(me.document, p);
  9895. nextLi.appendChild(p);
  9896. first = p;
  9897. }
  9898. if (domUtils.isEmptyNode(first)) {
  9899. first.innerHTML = '';
  9900. domUtils.fillNode(me.document, first);
  9901. }
  9902. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  9903. domUtils.remove(span);
  9904. var pre = nextLi.previousSibling;
  9905. if (pre && domUtils.isEmptyBlock(pre)) {
  9906. pre.innerHTML = '<p></p>';
  9907. domUtils.fillNode(me.document, pre.firstChild);
  9908. }
  9909. }
  9910. // }
  9911. preventAndSave();
  9912. }
  9913. }
  9914. }
  9915. if (keyCode == 8) {
  9916. //修中ie中li下的问题
  9917. range = me.selection.getRange();
  9918. if (range.collapsed && domUtils.isStartInblock(range)) {
  9919. tmpRange = range.cloneRange().trimBoundary();
  9920. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  9921. //要在li的最左边,才能处理
  9922. if (li && domUtils.isStartInblock(tmpRange)) {
  9923. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  9924. if (start && start !== li.firstChild) {
  9925. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  9926. domUtils.breakParent(start,parentList);
  9927. clearEmptySibling(start);
  9928. me.fireEvent('contentchange');
  9929. range.setStart(start,0).setCursor(false,true);
  9930. me.fireEvent('saveScene');
  9931. domUtils.preventDefault(evt);
  9932. return;
  9933. }
  9934. if (li && (pre = li.previousSibling)) {
  9935. if (keyCode == 46 && li.childNodes.length) {
  9936. return;
  9937. }
  9938. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  9939. if (dtd.$list[pre.tagName]) {
  9940. pre = pre.lastChild;
  9941. }
  9942. me.undoManger && me.undoManger.save();
  9943. first = li.firstChild;
  9944. if (domUtils.isBlockElm(first)) {
  9945. if (domUtils.isEmptyNode(first)) {
  9946. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  9947. pre.appendChild(first);
  9948. range.setStart(first, 0).setCursor(false, true);
  9949. //first不是唯一的节点
  9950. while (li.firstChild) {
  9951. pre.appendChild(li.firstChild);
  9952. }
  9953. } else {
  9954. span = me.document.createElement('span');
  9955. range.insertNode(span);
  9956. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  9957. if (domUtils.isEmptyBlock(pre)) {
  9958. pre.innerHTML = '';
  9959. }
  9960. domUtils.moveChild(li, pre);
  9961. range.setStartBefore(span).collapse(true).select(true);
  9962. domUtils.remove(span);
  9963. }
  9964. } else {
  9965. if (domUtils.isEmptyNode(li)) {
  9966. var p = me.document.createElement('p');
  9967. pre.appendChild(p);
  9968. range.setStart(p, 0).setCursor();
  9969. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  9970. } else {
  9971. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  9972. while (li.firstChild) {
  9973. pre.appendChild(li.firstChild);
  9974. }
  9975. }
  9976. }
  9977. domUtils.remove(li);
  9978. me.fireEvent('contentchange');
  9979. me.fireEvent('saveScene');
  9980. domUtils.preventDefault(evt);
  9981. return;
  9982. }
  9983. //trace:980
  9984. if (li && !li.previousSibling) {
  9985. var parentList = li.parentNode;
  9986. var bk = range.createBookmark();
  9987. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  9988. parentList.parentNode.insertBefore(li,parentList);
  9989. if(domUtils.isEmptyNode(parentList)){
  9990. domUtils.remove(parentList)
  9991. }
  9992. }else{
  9993. while(li.firstChild){
  9994. parentList.parentNode.insertBefore(li.firstChild,parentList);
  9995. }
  9996. domUtils.remove(li);
  9997. if(domUtils.isEmptyNode(parentList)){
  9998. domUtils.remove(parentList)
  9999. }
  10000. }
  10001. range.moveToBookmark(bk).setCursor(false,true);
  10002. me.fireEvent('contentchange');
  10003. me.fireEvent('saveScene');
  10004. domUtils.preventDefault(evt);
  10005. return;
  10006. }
  10007. }
  10008. }
  10009. }
  10010. });
  10011. me.addListener('keyup',function(type, evt){
  10012. var keyCode = evt.keyCode || evt.which;
  10013. if (keyCode == 8) {
  10014. var rng = me.selection.getRange(),list;
  10015. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  10016. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  10017. }
  10018. }
  10019. });
  10020. //处理tab键
  10021. me.addListener('tabkeydown',function(){
  10022. var range = me.selection.getRange();
  10023. //控制级数
  10024. function checkLevel(li){
  10025. if(me.options.maxListLevel != -1){
  10026. var level = li.parentNode,levelNum = 0;
  10027. while(/[ou]l/i.test(level.tagName)){
  10028. levelNum++;
  10029. level = level.parentNode;
  10030. }
  10031. if(levelNum >= me.options.maxListLevel){
  10032. return true;
  10033. }
  10034. }
  10035. }
  10036. //只以开始为准
  10037. //todo 后续改进
  10038. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  10039. if(li){
  10040. var bk;
  10041. if(range.collapsed){
  10042. if(checkLevel(li))
  10043. return true;
  10044. var parentLi = li.parentNode,
  10045. list = me.document.createElement(parentLi.tagName),
  10046. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  10047. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  10048. var currentStyle = listStyle[list.tagName][index];
  10049. setListStyle(list,currentStyle);
  10050. if(domUtils.isStartInblock(range)){
  10051. me.fireEvent('saveScene');
  10052. bk = range.createBookmark();
  10053. parentLi.insertBefore(list, li);
  10054. list.appendChild(li);
  10055. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  10056. me.fireEvent('contentchange');
  10057. range.moveToBookmark(bk).select(true);
  10058. return true;
  10059. }
  10060. }else{
  10061. me.fireEvent('saveScene');
  10062. bk = range.createBookmark();
  10063. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  10064. if(domUtils.isTagNode(ci,'ol ul')){
  10065. closeList = ci;
  10066. break;
  10067. }
  10068. }
  10069. var current = li;
  10070. if(bk.end){
  10071. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  10072. if(checkLevel(current)){
  10073. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  10074. continue;
  10075. }
  10076. var parentLi = current.parentNode,
  10077. list = me.document.createElement(parentLi.tagName),
  10078. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  10079. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  10080. var currentStyle = listStyle[list.tagName][currentIndex];
  10081. setListStyle(list,currentStyle);
  10082. parentLi.insertBefore(list, current);
  10083. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  10084. li = current.nextSibling;
  10085. list.appendChild(current);
  10086. if(!li || domUtils.isTagNode(li,'ol ul')){
  10087. if(li){
  10088. while(li = li.firstChild){
  10089. if(li.tagName == 'LI'){
  10090. break;
  10091. }
  10092. }
  10093. }else{
  10094. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  10095. }
  10096. break;
  10097. }
  10098. current = li;
  10099. }
  10100. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  10101. current = li;
  10102. }
  10103. }
  10104. me.fireEvent('contentchange');
  10105. range.moveToBookmark(bk).select();
  10106. return true;
  10107. }
  10108. }
  10109. });
  10110. function getLi(start){
  10111. while(start && !domUtils.isBody(start)){
  10112. if(start.nodeName == 'TABLE'){
  10113. return null;
  10114. }
  10115. if(start.nodeName == 'LI'){
  10116. return start
  10117. }
  10118. start = start.parentNode;
  10119. }
  10120. }
  10121. me.commands['insertorderedlist'] =
  10122. me.commands['insertunorderedlist'] = {
  10123. execCommand:function (command, style) {
  10124. if (!style) {
  10125. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  10126. }
  10127. var me = this,
  10128. range = this.selection.getRange(),
  10129. filterFn = function (node) {
  10130. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  10131. },
  10132. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  10133. frag = me.document.createDocumentFragment();
  10134. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  10135. //range.shrinkBoundary();//.adjustmentBoundary();
  10136. range.adjustmentBoundary().shrinkBoundary();
  10137. var bko = range.createBookmark(true),
  10138. start = getLi(me.document.getElementById(bko.start)),
  10139. modifyStart = 0,
  10140. end = getLi(me.document.getElementById(bko.end)),
  10141. modifyEnd = 0,
  10142. startParent, endParent,
  10143. list, tmp;
  10144. if (start || end) {
  10145. start && (startParent = start.parentNode);
  10146. if (!bko.end) {
  10147. end = start;
  10148. }
  10149. end && (endParent = end.parentNode);
  10150. if (startParent === endParent) {
  10151. while (start !== end) {
  10152. tmp = start;
  10153. start = start.nextSibling;
  10154. if (!domUtils.isBlockElm(tmp.firstChild)) {
  10155. var p = me.document.createElement('p');
  10156. while (tmp.firstChild) {
  10157. p.appendChild(tmp.firstChild);
  10158. }
  10159. tmp.appendChild(p);
  10160. }
  10161. frag.appendChild(tmp);
  10162. }
  10163. tmp = me.document.createElement('span');
  10164. startParent.insertBefore(tmp, end);
  10165. if (!domUtils.isBlockElm(end.firstChild)) {
  10166. p = me.document.createElement('p');
  10167. while (end.firstChild) {
  10168. p.appendChild(end.firstChild);
  10169. }
  10170. end.appendChild(p);
  10171. }
  10172. frag.appendChild(end);
  10173. domUtils.breakParent(tmp, startParent);
  10174. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  10175. domUtils.remove(tmp.previousSibling);
  10176. }
  10177. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  10178. domUtils.remove(tmp.nextSibling)
  10179. }
  10180. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  10181. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  10182. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.childNodes[i++];) {
  10183. if(domUtils.isTagNode(ci,'ol ul')){
  10184. utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  10185. while(li.firstChild){
  10186. tmpFrag.appendChild(li.firstChild);
  10187. }
  10188. });
  10189. }else{
  10190. while (ci.firstChild) {
  10191. tmpFrag.appendChild(ci.firstChild);
  10192. }
  10193. }
  10194. }
  10195. tmp.parentNode.insertBefore(tmpFrag, tmp);
  10196. } else {
  10197. list = me.document.createElement(tag);
  10198. setListStyle(list,style);
  10199. list.appendChild(frag);
  10200. tmp.parentNode.insertBefore(list, tmp);
  10201. }
  10202. domUtils.remove(tmp);
  10203. list && adjustList(list, tag, style);
  10204. range.moveToBookmark(bko).select();
  10205. return;
  10206. }
  10207. //开始
  10208. if (start) {
  10209. while (start) {
  10210. tmp = start.nextSibling;
  10211. if (domUtils.isTagNode(start, 'ol ul')) {
  10212. frag.appendChild(start);
  10213. } else {
  10214. var tmpfrag = me.document.createDocumentFragment(),
  10215. hasBlock = 0;
  10216. while (start.firstChild) {
  10217. if (domUtils.isBlockElm(start.firstChild)) {
  10218. hasBlock = 1;
  10219. }
  10220. tmpfrag.appendChild(start.firstChild);
  10221. }
  10222. if (!hasBlock) {
  10223. var tmpP = me.document.createElement('p');
  10224. tmpP.appendChild(tmpfrag);
  10225. frag.appendChild(tmpP);
  10226. } else {
  10227. frag.appendChild(tmpfrag);
  10228. }
  10229. domUtils.remove(start);
  10230. }
  10231. start = tmp;
  10232. }
  10233. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  10234. if (domUtils.isEmptyNode(startParent)) {
  10235. range.setStartBefore(startParent);
  10236. domUtils.remove(startParent);
  10237. } else {
  10238. range.setStartAfter(startParent);
  10239. }
  10240. modifyStart = 1;
  10241. }
  10242. if (end && domUtils.inDoc(endParent, me.document)) {
  10243. //结束
  10244. start = endParent.firstChild;
  10245. while (start && start !== end) {
  10246. tmp = start.nextSibling;
  10247. if (domUtils.isTagNode(start, 'ol ul')) {
  10248. frag.appendChild(start);
  10249. } else {
  10250. tmpfrag = me.document.createDocumentFragment();
  10251. hasBlock = 0;
  10252. while (start.firstChild) {
  10253. if (domUtils.isBlockElm(start.firstChild)) {
  10254. hasBlock = 1;
  10255. }
  10256. tmpfrag.appendChild(start.firstChild);
  10257. }
  10258. if (!hasBlock) {
  10259. tmpP = me.document.createElement('p');
  10260. tmpP.appendChild(tmpfrag);
  10261. frag.appendChild(tmpP);
  10262. } else {
  10263. frag.appendChild(tmpfrag);
  10264. }
  10265. domUtils.remove(start);
  10266. }
  10267. start = tmp;
  10268. }
  10269. var tmpDiv = domUtils.createElement(me.document, 'div', {
  10270. 'tmpDiv':1
  10271. });
  10272. domUtils.moveChild(end, tmpDiv);
  10273. frag.appendChild(tmpDiv);
  10274. domUtils.remove(end);
  10275. endParent.parentNode.insertBefore(frag, endParent);
  10276. range.setEndBefore(endParent);
  10277. if (domUtils.isEmptyNode(endParent)) {
  10278. domUtils.remove(endParent);
  10279. }
  10280. modifyEnd = 1;
  10281. }
  10282. }
  10283. if (!modifyStart) {
  10284. range.setStartBefore(me.document.getElementById(bko.start));
  10285. }
  10286. if (bko.end && !modifyEnd) {
  10287. range.setEndAfter(me.document.getElementById(bko.end));
  10288. }
  10289. range.enlarge(true, function (node) {
  10290. return notExchange[node.tagName];
  10291. });
  10292. frag = me.document.createDocumentFragment();
  10293. var bk = range.createBookmark(),
  10294. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  10295. tmpRange = range.cloneRange(),
  10296. tmpNode,
  10297. block = domUtils.isBlockElm;
  10298. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  10299. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  10300. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  10301. while (current.firstChild) {
  10302. frag.appendChild(current.firstChild);
  10303. }
  10304. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  10305. domUtils.remove(current);
  10306. current = tmpNode;
  10307. continue;
  10308. }
  10309. tmpNode = current;
  10310. tmpRange.setStartBefore(current);
  10311. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  10312. tmpNode = current;
  10313. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10314. return !notExchange[node.tagName];
  10315. });
  10316. }
  10317. if (current && block(current)) {
  10318. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  10319. if (tmp && domUtils.isBookmarkNode(tmp)) {
  10320. current = domUtils.getNextDomNode(tmp, false, filterFn);
  10321. tmpNode = tmp;
  10322. }
  10323. }
  10324. tmpRange.setEndAfter(tmpNode);
  10325. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  10326. var li = range.document.createElement('li');
  10327. li.appendChild(tmpRange.extractContents());
  10328. if(domUtils.isEmptyNode(li)){
  10329. var tmpNode = range.document.createElement('p');
  10330. while(li.firstChild){
  10331. tmpNode.appendChild(li.firstChild)
  10332. }
  10333. li.appendChild(tmpNode);
  10334. }
  10335. frag.appendChild(li);
  10336. } else {
  10337. current = domUtils.getNextDomNode(current, true, filterFn);
  10338. }
  10339. }
  10340. range.moveToBookmark(bk).collapse(true);
  10341. list = me.document.createElement(tag);
  10342. setListStyle(list,style);
  10343. list.appendChild(frag);
  10344. range.insertNode(list);
  10345. //当前list上下看能否合并
  10346. adjustList(list, tag, style);
  10347. //去掉冗余的tmpDiv
  10348. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  10349. if (ci.getAttribute('tmpDiv')) {
  10350. domUtils.remove(ci, true)
  10351. }
  10352. }
  10353. range.moveToBookmark(bko).select();
  10354. },
  10355. queryCommandState:function (command) {
  10356. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  10357. var path = this.selection.getStartElementPath();
  10358. for(var i= 0,ci;ci = path[i++];){
  10359. if(ci.nodeName == 'TABLE'){
  10360. return 0
  10361. }
  10362. if(tag == ci.nodeName.toLowerCase()){
  10363. return 1
  10364. };
  10365. }
  10366. return 0;
  10367. },
  10368. queryCommandValue:function (command) {
  10369. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  10370. var path = this.selection.getStartElementPath(),
  10371. node;
  10372. for(var i= 0,ci;ci = path[i++];){
  10373. if(ci.nodeName == 'TABLE'){
  10374. node = null;
  10375. break;
  10376. }
  10377. if(tag == ci.nodeName.toLowerCase()){
  10378. node = ci;
  10379. break;
  10380. };
  10381. }
  10382. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  10383. }
  10384. };
  10385. };
  10386. ///import core
  10387. ///import plugins/serialize.js
  10388. ///import plugins/undo.js
  10389. ///commands 查看源码
  10390. ///commandsName Source
  10391. ///commandsTitle 查看源码
  10392. (function (){
  10393. var sourceEditors = {
  10394. textarea: function (editor, holder){
  10395. var textarea = holder.ownerDocument.createElement('textarea');
  10396. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  10397. // todo: IE下只有onresize属性可用... 很纠结
  10398. if (browser.ie && browser.version < 8) {
  10399. textarea.style.width = holder.offsetWidth + 'px';
  10400. textarea.style.height = holder.offsetHeight + 'px';
  10401. holder.onresize = function (){
  10402. textarea.style.width = holder.offsetWidth + 'px';
  10403. textarea.style.height = holder.offsetHeight + 'px';
  10404. };
  10405. }
  10406. holder.appendChild(textarea);
  10407. return {
  10408. setContent: function (content){
  10409. textarea.value = content;
  10410. },
  10411. getContent: function (){
  10412. return textarea.value;
  10413. },
  10414. select: function (){
  10415. var range;
  10416. if (browser.ie) {
  10417. range = textarea.createTextRange();
  10418. range.collapse(true);
  10419. range.select();
  10420. } else {
  10421. //todo: chrome下无法设置焦点
  10422. textarea.setSelectionRange(0, 0);
  10423. textarea.focus();
  10424. }
  10425. },
  10426. dispose: function (){
  10427. holder.removeChild(textarea);
  10428. // todo
  10429. holder.onresize = null;
  10430. textarea = null;
  10431. holder = null;
  10432. }
  10433. };
  10434. },
  10435. codemirror: function (editor, holder){
  10436. var codeEditor = window.CodeMirror(holder, {
  10437. mode: "text/html",
  10438. tabMode: "indent",
  10439. lineNumbers: true,
  10440. lineWrapping:true
  10441. });
  10442. var dom = codeEditor.getWrapperElement();
  10443. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  10444. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  10445. codeEditor.refresh();
  10446. return {
  10447. getCodeMirror:function(){
  10448. return codeEditor;
  10449. },
  10450. setContent: function (content){
  10451. codeEditor.setValue(content);
  10452. },
  10453. getContent: function (){
  10454. return codeEditor.getValue();
  10455. },
  10456. select: function (){
  10457. codeEditor.focus();
  10458. },
  10459. dispose: function (){
  10460. holder.removeChild(dom);
  10461. dom = null;
  10462. codeEditor = null;
  10463. }
  10464. };
  10465. }
  10466. };
  10467. UE.plugins['source'] = function (){
  10468. var me = this;
  10469. var opt = this.options;
  10470. var sourceMode = false;
  10471. var sourceEditor;
  10472. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  10473. me.setOpt({
  10474. sourceEditorFirst:false
  10475. });
  10476. function createSourceEditor(holder){
  10477. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  10478. }
  10479. var bakCssText;
  10480. //解决在源码模式下getContent不能得到最新的内容问题
  10481. var oldGetContent = me.getContent,
  10482. bakAddress;
  10483. me.commands['source'] = {
  10484. execCommand: function (){
  10485. sourceMode = !sourceMode;
  10486. if (sourceMode) {
  10487. bakAddress = me.selection.getRange().createAddress(false,true);
  10488. me.undoManger && me.undoManger.save(true);
  10489. if(browser.gecko){
  10490. me.body.contentEditable = false;
  10491. }
  10492. bakCssText = me.iframe.style.cssText;
  10493. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  10494. me.fireEvent('beforegetcontent');
  10495. var root = UE.htmlparser(me.body.innerHTML);
  10496. me.filterOutputRule(root);
  10497. root.traversal(function (node) {
  10498. if (node.type == 'element') {
  10499. switch (node.tagName) {
  10500. case 'td':
  10501. case 'th':
  10502. case 'caption':
  10503. if(node.children && node.children.length == 1){
  10504. if(node.firstChild().tagName == 'br' ){
  10505. node.removeChild(node.firstChild())
  10506. }
  10507. };
  10508. break;
  10509. case 'pre':
  10510. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  10511. }
  10512. }
  10513. });
  10514. me.fireEvent('aftergetcontent');
  10515. var content = root.toHtml(true);
  10516. sourceEditor = createSourceEditor(me.iframe.parentNode);
  10517. sourceEditor.setContent(content);
  10518. orgSetContent = me.setContent;
  10519. me.setContent = function(html){
  10520. //这里暂时不触发事件,防止报错
  10521. var root = UE.htmlparser(html);
  10522. me.filterInputRule(root);
  10523. html = root.toHtml();
  10524. sourceEditor.setContent(html);
  10525. };
  10526. setTimeout(function (){
  10527. sourceEditor.select();
  10528. me.addListener('fullscreenchanged', function(){
  10529. try{
  10530. sourceEditor.getCodeMirror().refresh()
  10531. }catch(e){}
  10532. });
  10533. });
  10534. //重置getContent,源码模式下取值也能是最新的数据
  10535. oldGetContent = me.getContent;
  10536. me.getContent = function (){
  10537. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  10538. };
  10539. } else {
  10540. me.iframe.style.cssText = bakCssText;
  10541. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  10542. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  10543. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  10544. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  10545. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  10546. }
  10547. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  10548. });
  10549. me.setContent = orgSetContent;
  10550. me.setContent(cont);
  10551. sourceEditor.dispose();
  10552. sourceEditor = null;
  10553. //还原getContent方法
  10554. me.getContent = oldGetContent;
  10555. var first = me.body.firstChild;
  10556. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  10557. if(!first){
  10558. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  10559. first = me.body.firstChild;
  10560. }
  10561. //要在ifm为显示时ff才能取到selection,否则报错
  10562. //这里不能比较位置了
  10563. me.undoManger && me.undoManger.save(true);
  10564. if(browser.gecko){
  10565. var input = document.createElement('input');
  10566. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  10567. document.body.appendChild(input);
  10568. me.body.contentEditable = false;
  10569. setTimeout(function(){
  10570. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  10571. input.focus();
  10572. setTimeout(function(){
  10573. me.body.contentEditable = true;
  10574. me.selection.getRange().moveToAddress(bakAddress).select(true);
  10575. domUtils.remove(input);
  10576. });
  10577. });
  10578. }else{
  10579. //ie下有可能报错,比如在代码顶头的情况
  10580. try{
  10581. me.selection.getRange().moveToAddress(bakAddress).select(true);
  10582. }catch(e){}
  10583. }
  10584. }
  10585. this.fireEvent('sourcemodechanged', sourceMode);
  10586. },
  10587. queryCommandState: function (){
  10588. return sourceMode|0;
  10589. },
  10590. notNeedUndo : 1
  10591. };
  10592. var oldQueryCommandState = me.queryCommandState;
  10593. me.queryCommandState = function (cmdName){
  10594. cmdName = cmdName.toLowerCase();
  10595. if (sourceMode) {
  10596. //源码模式下可以开启的命令
  10597. return cmdName in {
  10598. 'source' : 1,
  10599. 'fullscreen' : 1
  10600. } ? 1 : -1
  10601. }
  10602. return oldQueryCommandState.apply(this, arguments);
  10603. };
  10604. if(opt.sourceEditor == "codemirror"){
  10605. me.addListener("ready",function(){
  10606. utils.loadFile(document,{
  10607. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  10608. tag : "script",
  10609. type : "text/javascript",
  10610. defer : "defer"
  10611. },function(){
  10612. if(opt.sourceEditorFirst){
  10613. setTimeout(function(){
  10614. me.execCommand("source");
  10615. },0);
  10616. }
  10617. });
  10618. utils.loadFile(document,{
  10619. tag : "link",
  10620. rel : "stylesheet",
  10621. type : "text/css",
  10622. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  10623. });
  10624. });
  10625. }
  10626. };
  10627. })();
  10628. ///import core
  10629. ///import plugins/undo.js
  10630. ///commands 设置回车标签p或br
  10631. ///commandsName EnterKey
  10632. ///commandsTitle 设置回车标签p或br
  10633. /**
  10634. * @description 处理回车
  10635. * @author zhanyi
  10636. */
  10637. UE.plugins['enterkey'] = function() {
  10638. var hTag,
  10639. me = this,
  10640. tag = me.options.enterTag;
  10641. me.addListener('keyup', function(type, evt) {
  10642. var keyCode = evt.keyCode || evt.which;
  10643. if (keyCode == 13) {
  10644. var range = me.selection.getRange(),
  10645. start = range.startContainer,
  10646. doSave;
  10647. //修正在h1-h6里边回车后不能嵌套p的问题
  10648. if (!browser.ie) {
  10649. if (/h\d/i.test(hTag)) {
  10650. if (browser.gecko) {
  10651. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  10652. if (!h) {
  10653. me.document.execCommand('formatBlock', false, '<p>');
  10654. doSave = 1;
  10655. }
  10656. } else {
  10657. //chrome remove div
  10658. if (start.nodeType == 1) {
  10659. var tmp = me.document.createTextNode(''),div;
  10660. range.insertNode(tmp);
  10661. div = domUtils.findParentByTagName(tmp, 'div', true);
  10662. if (div) {
  10663. var p = me.document.createElement('p');
  10664. while (div.firstChild) {
  10665. p.appendChild(div.firstChild);
  10666. }
  10667. div.parentNode.insertBefore(p, div);
  10668. domUtils.remove(div);
  10669. range.setStartBefore(tmp).setCursor();
  10670. doSave = 1;
  10671. }
  10672. domUtils.remove(tmp);
  10673. }
  10674. }
  10675. if (me.undoManger && doSave) {
  10676. me.undoManger.save();
  10677. }
  10678. }
  10679. //没有站位符,会出现多行的问题
  10680. browser.opera && range.select();
  10681. }else{
  10682. me.fireEvent('saveScene',true,true)
  10683. }
  10684. }
  10685. });
  10686. me.addListener('keydown', function(type, evt) {
  10687. var keyCode = evt.keyCode || evt.which;
  10688. if (keyCode == 13) {//回车
  10689. if(me.fireEvent('beforeenterkeydown')){
  10690. domUtils.preventDefault(evt);
  10691. return;
  10692. }
  10693. me.fireEvent('saveScene',true,true);
  10694. hTag = '';
  10695. var range = me.selection.getRange();
  10696. if (!range.collapsed) {
  10697. //跨td不能删
  10698. var start = range.startContainer,
  10699. end = range.endContainer,
  10700. startTd = domUtils.findParentByTagName(start, 'td', true),
  10701. endTd = domUtils.findParentByTagName(end, 'td', true);
  10702. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  10703. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  10704. return;
  10705. }
  10706. }
  10707. if (tag == 'p') {
  10708. if (!browser.ie) {
  10709. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  10710. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  10711. //trace:2431
  10712. if (!start && !browser.opera) {
  10713. me.document.execCommand('formatBlock', false, '<p>');
  10714. if (browser.gecko) {
  10715. range = me.selection.getRange();
  10716. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  10717. start && domUtils.removeDirtyAttr(start);
  10718. }
  10719. } else {
  10720. hTag = start.tagName;
  10721. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  10722. }
  10723. }
  10724. } else {
  10725. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  10726. if (!range.collapsed) {
  10727. range.deleteContents();
  10728. start = range.startContainer;
  10729. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  10730. while (start.nodeType == 1) {
  10731. if (dtd.$empty[start.tagName]) {
  10732. range.setStartBefore(start).setCursor();
  10733. if (me.undoManger) {
  10734. me.undoManger.save();
  10735. }
  10736. return false;
  10737. }
  10738. if (!start.firstChild) {
  10739. var br = range.document.createElement('br');
  10740. start.appendChild(br);
  10741. range.setStart(start, 0).setCursor();
  10742. if (me.undoManger) {
  10743. me.undoManger.save();
  10744. }
  10745. return false;
  10746. }
  10747. start = start.firstChild;
  10748. }
  10749. if (start === range.startContainer.childNodes[range.startOffset]) {
  10750. br = range.document.createElement('br');
  10751. range.insertNode(br).setCursor();
  10752. } else {
  10753. range.setStart(start, 0).setCursor();
  10754. }
  10755. } else {
  10756. br = range.document.createElement('br');
  10757. range.insertNode(br).setStartAfter(br).setCursor();
  10758. }
  10759. } else {
  10760. br = range.document.createElement('br');
  10761. range.insertNode(br);
  10762. var parent = br.parentNode;
  10763. if (parent.lastChild === br) {
  10764. br.parentNode.insertBefore(br.cloneNode(true), br);
  10765. range.setStartBefore(br);
  10766. } else {
  10767. range.setStartAfter(br);
  10768. }
  10769. range.setCursor();
  10770. }
  10771. }
  10772. }
  10773. });
  10774. };
  10775. /*
  10776. * 处理特殊键的兼容性问题
  10777. */
  10778. UE.plugins['keystrokes'] = function() {
  10779. var me = this;
  10780. var collapsed = true;
  10781. me.addListener('keydown', function(type, evt) {
  10782. var keyCode = evt.keyCode || evt.which,
  10783. rng = me.selection.getRange();
  10784. //处理全选的情况
  10785. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  10786. || keyCode >= 48 && keyCode <= 57 ||
  10787. keyCode >= 96 && keyCode <= 111 || {
  10788. 13:1,
  10789. 8:1,
  10790. 46:1
  10791. }[keyCode])
  10792. ){
  10793. var tmpNode = rng.startContainer;
  10794. if(domUtils.isFillChar(tmpNode)){
  10795. rng.setStartBefore(tmpNode)
  10796. }
  10797. tmpNode = rng.endContainer;
  10798. if(domUtils.isFillChar(tmpNode)){
  10799. rng.setEndAfter(tmpNode)
  10800. }
  10801. rng.txtToElmBoundary();
  10802. //结束边界可能放到了br的前边,要把br包含进来
  10803. // x[xxx]<br/>
  10804. if(rng.endContainer && rng.endContainer.nodeType == 1){
  10805. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  10806. if(tmpNode && domUtils.isBr(tmpNode)){
  10807. rng.setEndAfter(tmpNode);
  10808. }
  10809. }
  10810. if(rng.startOffset == 0){
  10811. tmpNode = rng.startContainer;
  10812. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  10813. tmpNode = rng.endContainer;
  10814. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  10815. me.fireEvent('saveScene');
  10816. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  10817. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  10818. me._selectionChange();
  10819. return;
  10820. }
  10821. }
  10822. }
  10823. }
  10824. //处理backspace
  10825. if (keyCode == 8) {
  10826. rng = me.selection.getRange();
  10827. collapsed = rng.collapsed;
  10828. var start,end;
  10829. //避免按两次删除才能生效的问题
  10830. if(rng.collapsed && rng.inFillChar()){
  10831. start = rng.startContainer;
  10832. if(domUtils.isFillChar(start)){
  10833. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  10834. domUtils.remove(start)
  10835. }else{
  10836. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  10837. rng.startOffset--;
  10838. rng.collapse(true).select(true)
  10839. }
  10840. }
  10841. //解决选中control元素不能删除的问题
  10842. if (start = rng.getClosedNode()) {
  10843. me.fireEvent('saveScene');
  10844. rng.setStartBefore(start);
  10845. domUtils.remove(start);
  10846. rng.setCursor();
  10847. me.fireEvent('saveScene');
  10848. domUtils.preventDefault(evt);
  10849. return;
  10850. }
  10851. //阻止在table上的删除
  10852. if (!browser.ie) {
  10853. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  10854. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  10855. if (start && !end || !start && end || start !== end) {
  10856. evt.preventDefault();
  10857. return;
  10858. }
  10859. }
  10860. }
  10861. //处理tab键的逻辑
  10862. if (keyCode == 9) {
  10863. //不处理以下标签
  10864. var excludeTagNameForTabKey = {
  10865. 'ol' : 1,
  10866. 'ul' : 1,
  10867. 'table':1
  10868. };
  10869. //处理组件里的tab按下事件
  10870. if(me.fireEvent('tabkeydown',evt)){
  10871. domUtils.preventDefault(evt);
  10872. return;
  10873. }
  10874. var range = me.selection.getRange();
  10875. me.fireEvent('saveScene');
  10876. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  10877. txt += tabNode;
  10878. }
  10879. var span = me.document.createElement('span');
  10880. span.innerHTML = txt + domUtils.fillChar;
  10881. if (range.collapsed) {
  10882. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  10883. } else {
  10884. //普通的情况
  10885. start = domUtils.findParent(range.startContainer, filterFn);
  10886. end = domUtils.findParent(range.endContainer, filterFn);
  10887. if (start && end && start === end) {
  10888. range.deleteContents();
  10889. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  10890. } else {
  10891. var bookmark = range.createBookmark(),
  10892. filterFn = function(node) {
  10893. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  10894. };
  10895. range.enlarge(true);
  10896. var bookmark2 = range.createBookmark(),
  10897. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  10898. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10899. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  10900. current = domUtils.getNextDomNode(current, false, filterFn);
  10901. }
  10902. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  10903. }
  10904. }
  10905. domUtils.preventDefault(evt)
  10906. }
  10907. //trace:1634
  10908. //ff的del键在容器空的时候,也会删除
  10909. if(browser.gecko && keyCode == 46){
  10910. range = me.selection.getRange();
  10911. if(range.collapsed){
  10912. start = range.startContainer;
  10913. if(domUtils.isEmptyBlock(start)){
  10914. var parent = start.parentNode;
  10915. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  10916. start = parent;
  10917. parent = parent.parentNode;
  10918. }
  10919. if(start === parent.lastChild)
  10920. evt.preventDefault();
  10921. return;
  10922. }
  10923. }
  10924. }
  10925. });
  10926. me.addListener('keyup', function(type, evt) {
  10927. var keyCode = evt.keyCode || evt.which,
  10928. rng,me = this;
  10929. if(keyCode == 8){
  10930. if(me.fireEvent('delkeyup')){
  10931. return;
  10932. }
  10933. rng = me.selection.getRange();
  10934. if(rng.collapsed){
  10935. var tmpNode,
  10936. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  10937. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  10938. if(domUtils.isEmptyBlock(tmpNode)){
  10939. var pre = tmpNode.previousSibling;
  10940. if(pre && pre.nodeName != 'TABLE'){
  10941. domUtils.remove(tmpNode);
  10942. rng.setStartAtLast(pre).setCursor(false,true);
  10943. return;
  10944. }else{
  10945. var next = tmpNode.nextSibling;
  10946. if(next && next.nodeName != 'TABLE'){
  10947. domUtils.remove(tmpNode);
  10948. rng.setStartAtFirst(next).setCursor(false,true);
  10949. return;
  10950. }
  10951. }
  10952. }
  10953. }
  10954. //处理当删除到body时,要重新给p标签展位
  10955. if(domUtils.isBody(rng.startContainer)){
  10956. var tmpNode = domUtils.createElement(me.document,'p',{
  10957. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  10958. });
  10959. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  10960. }
  10961. }
  10962. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  10963. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  10964. if(browser.ie){
  10965. var span = rng.document.createElement('span');
  10966. rng.insertNode(span).setStartBefore(span).collapse(true);
  10967. rng.select();
  10968. domUtils.remove(span)
  10969. }else{
  10970. rng.select()
  10971. }
  10972. }
  10973. }
  10974. })
  10975. };
  10976. ///import core
  10977. ///commands 修复chrome下图片不能点击的问题
  10978. ///commandsName FixImgClick
  10979. ///commandsTitle 修复chrome下图片不能点击的问题
  10980. //修复chrome下图片不能点击的问题
  10981. //todo 可以改大小
  10982. UE.plugins['fiximgclick'] = function() {
  10983. var me = this;
  10984. if ( browser.webkit ) {
  10985. me.addListener( 'click', function( type, e ) {
  10986. if ( e.target.tagName == 'IMG' ) {
  10987. var range = new dom.Range( me.document );
  10988. range.selectNode( e.target ).select();
  10989. }
  10990. } );
  10991. }
  10992. };
  10993. ///import core
  10994. ///commands 为非ie浏览器自动添加a标签
  10995. ///commandsName AutoLink
  10996. ///commandsTitle 自动增加链接
  10997. /**
  10998. * @description 为非ie浏览器自动添加a标签
  10999. * @author zhanyi
  11000. */
  11001. UE.plugins['autolink'] = function() {
  11002. var cont = 0;
  11003. if (browser.ie) {
  11004. return;
  11005. }
  11006. var me = this;
  11007. me.addListener('reset',function(){
  11008. cont = 0;
  11009. });
  11010. me.addListener('keydown', function(type, evt) {
  11011. var keyCode = evt.keyCode || evt.which;
  11012. if (keyCode == 32 || keyCode == 13) {
  11013. var sel = me.selection.getNative(),
  11014. range = sel.getRangeAt(0).cloneRange(),
  11015. offset,
  11016. charCode;
  11017. var start = range.startContainer;
  11018. while (start.nodeType == 1 && range.startOffset > 0) {
  11019. start = range.startContainer.childNodes[range.startOffset - 1];
  11020. if (!start){
  11021. break;
  11022. }
  11023. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  11024. range.collapse(true);
  11025. start = range.startContainer;
  11026. }
  11027. do{
  11028. if (range.startOffset == 0) {
  11029. start = range.startContainer.previousSibling;
  11030. while (start && start.nodeType == 1) {
  11031. start = start.lastChild;
  11032. }
  11033. if (!start || domUtils.isFillChar(start)){
  11034. break;
  11035. }
  11036. offset = start.nodeValue.length;
  11037. } else {
  11038. start = range.startContainer;
  11039. offset = range.startOffset;
  11040. }
  11041. range.setStart(start, offset - 1);
  11042. charCode = range.toString().charCodeAt(0);
  11043. } while (charCode != 160 && charCode != 32);
  11044. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  11045. while(range.toString().length){
  11046. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  11047. break;
  11048. }
  11049. try{
  11050. range.setStart(range.startContainer,range.startOffset+1);
  11051. }catch(e){
  11052. //trace:2121
  11053. var start = range.startContainer;
  11054. while(!(next = start.nextSibling)){
  11055. if(domUtils.isBody(start)){
  11056. return;
  11057. }
  11058. start = start.parentNode;
  11059. }
  11060. range.setStart(next,0);
  11061. }
  11062. }
  11063. //range的开始边界已经在a标签里的不再处理
  11064. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  11065. return;
  11066. }
  11067. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  11068. me.undoManger && me.undoManger.save();
  11069. a.appendChild(range.extractContents());
  11070. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  11071. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  11072. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  11073. a.setAttribute('_src',utils.html(href));
  11074. a.href = utils.html(href);
  11075. range.insertNode(a);
  11076. a.parentNode.insertBefore(text, a.nextSibling);
  11077. range.setStart(text, 0);
  11078. range.collapse(true);
  11079. sel.removeAllRanges();
  11080. sel.addRange(range);
  11081. me.undoManger && me.undoManger.save();
  11082. }
  11083. }
  11084. });
  11085. };
  11086. ///import core
  11087. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  11088. ///commandsName AutoHeight,autoHeightEnabled
  11089. ///commandsTitle 自动增高
  11090. /**
  11091. * @description 自动伸展
  11092. * @author zhanyi
  11093. */
  11094. UE.plugins['autoheight'] = function () {
  11095. var me = this;
  11096. //提供开关,就算加载也可以关闭
  11097. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  11098. if (!me.autoHeightEnabled) {
  11099. return;
  11100. }
  11101. var bakOverflow,
  11102. span, tmpNode,
  11103. lastHeight = 0,
  11104. options = me.options,
  11105. currentHeight,
  11106. timer;
  11107. function adjustHeight() {
  11108. var me = this;
  11109. clearTimeout(timer);
  11110. if(isFullscreen)return;
  11111. timer = setTimeout(function () {
  11112. if (me.queryCommandState && me.queryCommandState('source') != 1) {
  11113. if (!span) {
  11114. span = me.document.createElement('span');
  11115. //trace:1764
  11116. span.style.cssText = 'display:block;width:0;margin:0;padding:0;border:0;clear:both;';
  11117. span.innerHTML = '.';
  11118. }
  11119. tmpNode = span.cloneNode(true);
  11120. me.body.appendChild(tmpNode);
  11121. currentHeight = Math.max(domUtils.getXY(tmpNode).y + tmpNode.offsetHeight,Math.max(options.minFrameHeight, options.initialFrameHeight));
  11122. if (currentHeight != lastHeight) {
  11123. me.setHeight(currentHeight);
  11124. lastHeight = currentHeight;
  11125. }
  11126. domUtils.remove(tmpNode);
  11127. }
  11128. }, 50);
  11129. }
  11130. var isFullscreen;
  11131. me.addListener('fullscreenchanged',function(cmd,f){
  11132. isFullscreen = f
  11133. });
  11134. me.addListener('destroy', function () {
  11135. me.removeListener('contentchange', adjustHeight);
  11136. me.removeListener('afterinserthtml',adjustHeight);
  11137. me.removeListener('keyup', adjustHeight);
  11138. me.removeListener('mouseup', adjustHeight);
  11139. });
  11140. me.enableAutoHeight = function () {
  11141. if (!me.autoHeightEnabled) {
  11142. return;
  11143. }
  11144. var doc = me.document;
  11145. me.autoHeightEnabled = true;
  11146. bakOverflow = doc.body.style.overflowY;
  11147. doc.body.style.overflowY = 'hidden';
  11148. me.addListener('contentchange', adjustHeight);
  11149. me.addListener('afterinserthtml',adjustHeight)
  11150. me.addListener('keyup', adjustHeight);
  11151. me.addListener('mouseup', adjustHeight);
  11152. //ff不给事件算得不对
  11153. setTimeout(function () {
  11154. adjustHeight.call(this);
  11155. }, browser.gecko ? 100 : 0);
  11156. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  11157. };
  11158. me.disableAutoHeight = function () {
  11159. me.body.style.overflowY = bakOverflow || '';
  11160. me.removeListener('contentchange', adjustHeight);
  11161. me.removeListener('keyup', adjustHeight);
  11162. me.removeListener('mouseup', adjustHeight);
  11163. me.autoHeightEnabled = false;
  11164. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  11165. };
  11166. me.addListener('ready', function () {
  11167. me.enableAutoHeight();
  11168. //trace:1764
  11169. var timer;
  11170. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  11171. clearTimeout(timer);
  11172. timer = setTimeout(function () {
  11173. adjustHeight.call(this);
  11174. }, 100);
  11175. });
  11176. });
  11177. };
  11178. ///import core
  11179. ///commands 悬浮工具栏
  11180. ///commandsName AutoFloat,autoFloatEnabled
  11181. ///commandsTitle 悬浮工具栏
  11182. /*
  11183. * modified by chengchao01
  11184. *
  11185. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  11186. */
  11187. UE.plugins['autofloat'] = function() {
  11188. var me = this,
  11189. lang = me.getLang();
  11190. me.setOpt({
  11191. topOffset:0
  11192. });
  11193. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  11194. topOffset = me.options.topOffset;
  11195. //如果不固定toolbar的位置,则直接退出
  11196. if(!optsAutoFloatEnabled){
  11197. return;
  11198. }
  11199. var uiUtils = UE.ui.uiUtils,
  11200. LteIE6 = browser.ie && browser.version <= 6,
  11201. quirks = browser.quirks;
  11202. function checkHasUI(editor){
  11203. if(!editor.ui){
  11204. alert(lang.autofloatMsg);
  11205. return 0;
  11206. }
  11207. return 1;
  11208. }
  11209. function fixIE6FixedPos(){
  11210. var docStyle = document.body.style;
  11211. docStyle.backgroundImage = 'url("about:blank")';
  11212. docStyle.backgroundAttachment = 'fixed';
  11213. }
  11214. var bakCssText,
  11215. placeHolder = document.createElement('div'),
  11216. toolbarBox,orgTop,
  11217. getPosition,
  11218. flag =true; //ie7模式下需要偏移
  11219. function setFloating(){
  11220. var toobarBoxPos = domUtils.getXY(toolbarBox),
  11221. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  11222. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  11223. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  11224. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  11225. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  11226. if (LteIE6 || (quirks && browser.ie)) {
  11227. if(toolbarBox.style.position != 'absolute'){
  11228. toolbarBox.style.position = 'absolute';
  11229. }
  11230. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  11231. } else {
  11232. if (browser.ie7Compat && flag) {
  11233. flag = false;
  11234. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  11235. }
  11236. if(toolbarBox.style.position != 'fixed'){
  11237. toolbarBox.style.position = 'fixed';
  11238. toolbarBox.style.top = topOffset +"px";
  11239. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  11240. }
  11241. }
  11242. }
  11243. function unsetFloating(){
  11244. flag = true;
  11245. if(placeHolder.parentNode){
  11246. placeHolder.parentNode.removeChild(placeHolder);
  11247. }
  11248. toolbarBox.style.cssText = bakCssText;
  11249. }
  11250. function updateFloating(){
  11251. var rect3 = getPosition(me.container);
  11252. var offset=me.options.toolbarTopOffset||0;
  11253. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  11254. setFloating();
  11255. }else{
  11256. unsetFloating();
  11257. }
  11258. }
  11259. var defer_updateFloating = utils.defer(function(){
  11260. updateFloating();
  11261. },browser.ie ? 200 : 100,true);
  11262. me.addListener('destroy',function(){
  11263. domUtils.un(window, ['scroll','resize'], updateFloating);
  11264. me.removeListener('keydown', defer_updateFloating);
  11265. });
  11266. me.addListener('ready', function(){
  11267. if(checkHasUI(me)){
  11268. getPosition = uiUtils.getClientRect;
  11269. toolbarBox = me.ui.getDom('toolbarbox');
  11270. orgTop = getPosition(toolbarBox).top;
  11271. bakCssText = toolbarBox.style.cssText;
  11272. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  11273. if(LteIE6){
  11274. fixIE6FixedPos();
  11275. }
  11276. //domUtils.on(window, ['scroll','resize'], updateFloating);
  11277. //me.addListener('keydown', defer_updateFloating);
  11278. me.addListener('beforefullscreenchange', function (t, enabled){
  11279. if (enabled) {
  11280. unsetFloating();
  11281. }
  11282. });
  11283. me.addListener('fullscreenchanged', function (t, enabled){
  11284. if (!enabled) {
  11285. updateFloating();
  11286. }
  11287. });
  11288. me.addListener('sourcemodechanged', function (t, enabled){
  11289. setTimeout(function (){
  11290. updateFloating();
  11291. },0);
  11292. });
  11293. me.addListener("clearDoc",function(){
  11294. setTimeout(function(){
  11295. updateFloating();
  11296. },0);
  11297. })
  11298. }
  11299. });
  11300. };
  11301. /**
  11302. * @description 纯文本粘贴
  11303. * @name puretxtpaste
  11304. * @author zhanyi
  11305. */
  11306. UE.plugins['pasteplain'] = function(){
  11307. var me = this;
  11308. me.setOpt({
  11309. 'pasteplain':false,
  11310. 'filterTxtRules' : function(){
  11311. function transP(node){
  11312. node.tagName = 'p';
  11313. node.setStyle();
  11314. }
  11315. return {
  11316. //直接删除及其字节点内容
  11317. '-' : 'script style object iframe embed input select',
  11318. 'p': {$:{}},
  11319. 'br':{$:{}},
  11320. div: function (node) {
  11321. var tmpNode, p = UE.uNode.createElement('p');
  11322. while (tmpNode = node.firstChild()) {
  11323. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  11324. p.appendChild(tmpNode);
  11325. } else {
  11326. if (p.firstChild()) {
  11327. node.parentNode.insertBefore(p, node);
  11328. p = UE.uNode.createElement('p');
  11329. } else {
  11330. node.parentNode.insertBefore(tmpNode, node);
  11331. }
  11332. }
  11333. }
  11334. if (p.firstChild()) {
  11335. node.parentNode.insertBefore(p, node);
  11336. }
  11337. node.parentNode.removeChild(node);
  11338. },
  11339. ol: function (node) {
  11340. node.parentNode.removeChild(node,true)
  11341. },
  11342. ul: function (node) {
  11343. node.parentNode.removeChild(node,true)
  11344. },
  11345. dl:function(node){
  11346. node.parentNode.removeChild(node,true)
  11347. },
  11348. dt:function(node){
  11349. node.parentNode.removeChild(node,true)
  11350. },
  11351. dd:function(node){
  11352. node.parentNode.removeChild(node,true)
  11353. },
  11354. 'li': function(node){
  11355. node.parentNode.removeChild(node,true)
  11356. },
  11357. 'caption':transP,
  11358. 'th':transP,
  11359. 'tr':transP,
  11360. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  11361. 'td':function(node){
  11362. //没有内容的td直接删掉
  11363. var txt = !!node.innerText();
  11364. if(txt){
  11365. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  11366. }
  11367. node.parentNode.removeChild(node,node.innerText())
  11368. }
  11369. }
  11370. }()
  11371. });
  11372. //暂时这里支持一下老版本的属性
  11373. var pasteplain = me.options.pasteplain;
  11374. me.commands['pasteplain'] = {
  11375. queryCommandState: function (){
  11376. return pasteplain ? 1 : 0;
  11377. },
  11378. execCommand: function (){
  11379. pasteplain = !pasteplain|0;
  11380. },
  11381. notNeedUndo : 1
  11382. };
  11383. };
  11384. ///import core
  11385. ///import plugins/inserthtml.js
  11386. ///commands 视频
  11387. ///commandsName InsertVideo
  11388. ///commandsTitle 插入视频
  11389. ///commandsDialog dialogs\video
  11390. UE.plugins['video'] = function (){
  11391. var me =this,
  11392. div;
  11393. /**
  11394. * 创建插入视频字符窜
  11395. * @param url 视频地址
  11396. * @param width 视频宽度
  11397. * @param height 视频高度
  11398. * @param align 视频对齐
  11399. * @param toEmbed 是否以flash代替显示
  11400. * @param addParagraph 是否需要添加P 标签
  11401. */
  11402. function creatInsertStr(url,width,height,id,align,toEmbed){
  11403. return !toEmbed ?
  11404. '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-video"' +
  11405. ' src="' + me.options.UEDITOR_HOME_URL+'themes/default/images/spacer.gif" style="background:url('+me.options.UEDITOR_HOME_URL+'themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;'+(align ? 'float:' + align + ';': '')+'" />'
  11406. :
  11407. '<embed type="application/x-shockwave-flash" class="edui-faked-video" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  11408. ' src="' + url + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  11409. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  11410. }
  11411. function switchImgAndEmbed(root,img2embed){
  11412. utils.each(root.getNodesByTagName(img2embed ? 'img' : 'embed'),function(node){
  11413. if(node.getAttr('class') == 'edui-faked-video'){
  11414. var html = creatInsertStr( img2embed ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',img2embed);
  11415. node.parentNode.replaceChild(UE.uNode.createElement(html),node)
  11416. }
  11417. })
  11418. }
  11419. me.addOutputRule(function(root){
  11420. switchImgAndEmbed(root,true)
  11421. });
  11422. me.addInputRule(function(root){
  11423. switchImgAndEmbed(root)
  11424. });
  11425. me.commands["insertvideo"] = {
  11426. execCommand: function (cmd, videoObjs){
  11427. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  11428. var html = [],id = 'tmpVedio';
  11429. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  11430. vi = videoObjs[i];
  11431. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i,null,false));
  11432. }
  11433. me.execCommand("inserthtml",html.join(""),true);
  11434. var rng = this.selection.getRange();
  11435. for(var i= 0,len=videoObjs.length;i<len;i++){
  11436. var img = this.document.getElementById('tmpVedio'+i);
  11437. domUtils.removeAttributes(img,'id');
  11438. rng.selectNode(img).select();
  11439. me.execCommand('imagefloat',videoObjs[i].align)
  11440. }
  11441. },
  11442. queryCommandState : function(){
  11443. var img = me.selection.getRange().getClosedNode(),
  11444. flag = img && (img.className == "edui-faked-video");
  11445. return flag ? 1 : 0;
  11446. }
  11447. };
  11448. };
  11449. /**
  11450. * Created with JetBrains WebStorm.
  11451. * User: taoqili
  11452. * Date: 13-1-18
  11453. * Time: 上午11:09
  11454. * To change this template use File | Settings | File Templates.
  11455. */
  11456. /**
  11457. * UE表格操作类
  11458. * @param table
  11459. * @constructor
  11460. */
  11461. (function () {
  11462. var UETable = UE.UETable = function (table) {
  11463. this.table = table;
  11464. this.indexTable = [];
  11465. this.selectedTds = [];
  11466. this.cellsRange = {};
  11467. this.update(table);
  11468. };
  11469. //===以下为静态工具方法===
  11470. UETable.removeSelectedClass = function (cells) {
  11471. utils.each(cells, function (cell) {
  11472. domUtils.removeClasses(cell, "selectTdClass");
  11473. })
  11474. };
  11475. UETable.addSelectedClass = function (cells) {
  11476. utils.each(cells, function (cell) {
  11477. domUtils.addClass(cell, "selectTdClass");
  11478. })
  11479. };
  11480. UETable.isEmptyBlock = function (node) {
  11481. var reg = new RegExp(domUtils.fillChar, 'g');
  11482. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  11483. return 0;
  11484. }
  11485. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  11486. if (node.getElementsByTagName(i).length) {
  11487. return 0;
  11488. }
  11489. }
  11490. return 1;
  11491. };
  11492. UETable.getWidth = function (cell) {
  11493. if (!cell)return 0;
  11494. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  11495. };
  11496. /**
  11497. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  11498. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  11499. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  11500. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  11501. */
  11502. UETable.getTableCellAlignState = function ( cells ) {
  11503. !utils.isArray( cells ) && ( cells = [cells] );
  11504. var result = {},
  11505. status = ['align', 'valign'],
  11506. tempStatus = null,
  11507. isSame = true;//状态是否相同
  11508. utils.each( cells, function( cellNode ){
  11509. utils.each( status, function( currentState ){
  11510. tempStatus = cellNode.getAttribute( currentState );
  11511. if( !result[ currentState ] && tempStatus ) {
  11512. result[ currentState ] = tempStatus;
  11513. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  11514. isSame = false;
  11515. return false;
  11516. }
  11517. } );
  11518. return isSame;
  11519. });
  11520. return isSame ? result : null;
  11521. };
  11522. /**
  11523. * 根据当前选区获取相关的table信息
  11524. * @return {Object}
  11525. */
  11526. UETable.getTableItemsByRange = function (editor) {
  11527. var start = editor.selection.getStart(),
  11528. //在table或者td边缘有可能存在选中tr的情况
  11529. cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  11530. tr = cell && cell.parentNode,
  11531. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  11532. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  11533. return {
  11534. cell:cell,
  11535. tr:tr,
  11536. table:table,
  11537. caption:caption
  11538. }
  11539. };
  11540. UETable.getUETableBySelected = function (editor) {
  11541. var table = UETable.getTableItemsByRange(editor).table;
  11542. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  11543. return table.ueTable;
  11544. }
  11545. return null;
  11546. };
  11547. UETable.getDefaultValue = function (editor, table) {
  11548. var borderMap = {
  11549. thin:'0px',
  11550. medium:'1px',
  11551. thick:'2px'
  11552. },
  11553. tableBorder, tdPadding, tdBorder, tmpValue;
  11554. if (!table) {
  11555. table = editor.document.createElement('table');
  11556. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  11557. editor.body.appendChild(table);
  11558. var td = table.getElementsByTagName('td')[0];
  11559. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  11560. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11561. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  11562. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11563. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  11564. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11565. domUtils.remove(table);
  11566. return {
  11567. tableBorder:tableBorder,
  11568. tdPadding:tdPadding,
  11569. tdBorder:tdBorder
  11570. };
  11571. } else {
  11572. td = table.getElementsByTagName('td')[0];
  11573. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  11574. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11575. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  11576. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11577. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  11578. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  11579. return {
  11580. tableBorder:tableBorder,
  11581. tdPadding:tdPadding,
  11582. tdBorder:tdBorder
  11583. };
  11584. }
  11585. };
  11586. /**
  11587. * 根据当前点击的td或者table获取索引对象
  11588. * @param tdOrTable
  11589. */
  11590. UETable.getUETable = function (tdOrTable) {
  11591. var tag = tdOrTable.tagName.toLowerCase();
  11592. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  11593. if (!tdOrTable.ueTable) {
  11594. tdOrTable.ueTable = new UETable(tdOrTable);
  11595. }
  11596. return tdOrTable.ueTable;
  11597. };
  11598. UETable.cloneCell = function(cell,ignoreMerge,ignoreWidth){
  11599. if (!cell || utils.isString(cell)) {
  11600. return this.table.ownerDocument.createElement(cell || 'td');
  11601. }
  11602. var flag = domUtils.hasClass(cell, "selectTdClass");
  11603. flag && domUtils.removeClasses(cell, "selectTdClass");
  11604. var tmpCell = cell.cloneNode(true);
  11605. if (ignoreMerge) {
  11606. tmpCell.rowSpan = tmpCell.colSpan = 1;
  11607. }
  11608. tmpCell.style.borderLeftStyle = "";
  11609. tmpCell.style.borderTopStyle = "";
  11610. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  11611. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  11612. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  11613. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  11614. flag && domUtils.addClass(cell, "selectTdClass");
  11615. ignoreWidth && domUtils.removeAttributes(tmpCell,'width height');
  11616. return tmpCell;
  11617. }
  11618. UETable.prototype = {
  11619. getMaxRows:function () {
  11620. var rows = this.table.rows, maxLen = 1;
  11621. for (var i = 0, row; row = rows[i]; i++) {
  11622. var currentMax = 1;
  11623. for (var j = 0, cj; cj = row.cells[j++];) {
  11624. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  11625. }
  11626. maxLen = Math.max(currentMax + i, maxLen);
  11627. }
  11628. return maxLen;
  11629. },
  11630. /**
  11631. * 获取当前表格的最大列数
  11632. */
  11633. getMaxCols:function () {
  11634. var rows = this.table.rows, maxLen = 0, cellRows = {};
  11635. for (var i = 0, row; row = rows[i]; i++) {
  11636. var cellsNum = 0;
  11637. for (var j = 0, cj; cj = row.cells[j++];) {
  11638. cellsNum += (cj.colSpan || 1);
  11639. if (cj.rowSpan && cj.rowSpan > 1) {
  11640. for (var k = 1; k < cj.rowSpan; k++) {
  11641. if (!cellRows['row_' + (i + k)]) {
  11642. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  11643. } else {
  11644. cellRows['row_' + (i + k)]++
  11645. }
  11646. }
  11647. }
  11648. }
  11649. cellsNum += cellRows['row_' + i] || 0;
  11650. maxLen = Math.max(cellsNum, maxLen);
  11651. }
  11652. return maxLen;
  11653. },
  11654. getCellColIndex:function (cell) {
  11655. },
  11656. /**
  11657. * 获取当前cell旁边的单元格,
  11658. * @param cell
  11659. * @param right
  11660. */
  11661. getHSideCell:function (cell, right) {
  11662. try {
  11663. var cellInfo = this.getCellInfo(cell),
  11664. previewRowIndex, previewColIndex;
  11665. var len = this.selectedTds.length,
  11666. range = this.cellsRange;
  11667. //首行或者首列没有前置单元格
  11668. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  11669. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  11670. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  11671. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  11672. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  11673. } catch (e) {
  11674. showError(e);
  11675. }
  11676. },
  11677. getTabNextCell:function (cell, preRowIndex) {
  11678. var cellInfo = this.getCellInfo(cell),
  11679. rowIndex = preRowIndex || cellInfo.rowIndex,
  11680. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  11681. nextCell;
  11682. try {
  11683. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  11684. } catch (e) {
  11685. try {
  11686. rowIndex = rowIndex * 1 + 1;
  11687. colIndex = 0;
  11688. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  11689. } catch (e) {
  11690. }
  11691. }
  11692. return nextCell;
  11693. },
  11694. /**
  11695. * 获取视觉上的后置单元格
  11696. * @param cell
  11697. * @param bottom
  11698. */
  11699. getVSideCell:function (cell, bottom, ignoreRange) {
  11700. try {
  11701. var cellInfo = this.getCellInfo(cell),
  11702. nextRowIndex, nextColIndex;
  11703. var len = this.selectedTds.length && !ignoreRange,
  11704. range = this.cellsRange;
  11705. //末行或者末列没有后置单元格
  11706. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  11707. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  11708. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  11709. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  11710. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  11711. } catch (e) {
  11712. showError(e);
  11713. }
  11714. },
  11715. /**
  11716. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  11717. */
  11718. getSameEndPosCells:function (cell, xOrY) {
  11719. try {
  11720. var flag = (xOrY.toLowerCase() === "x"),
  11721. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  11722. rows = this.table.rows,
  11723. cells = null, returns = [];
  11724. for (var i = 0; i < this.rowsNum; i++) {
  11725. cells = rows[i].cells;
  11726. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  11727. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  11728. //对应行的td已经被上面行rowSpan了
  11729. if (tmpEnd > end && flag) break;
  11730. if (cell == tmpCell || end == tmpEnd) {
  11731. //只获取单一的单元格
  11732. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  11733. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  11734. returns.push(tmpCell);
  11735. }
  11736. if (flag) break;
  11737. }
  11738. }
  11739. }
  11740. return returns;
  11741. } catch (e) {
  11742. showError(e);
  11743. }
  11744. },
  11745. setCellContent:function (cell, content) {
  11746. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  11747. },
  11748. cloneCell:UETable.cloneCell,
  11749. /**
  11750. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  11751. */
  11752. getSameStartPosXCells:function (cell) {
  11753. try {
  11754. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  11755. rows = this.table.rows, cells , returns = [];
  11756. for (var i = 0; i < this.rowsNum; i++) {
  11757. cells = rows[i].cells;
  11758. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  11759. var tmpStart = domUtils.getXY(tmpCell).x;
  11760. if (tmpStart > start) break;
  11761. if (tmpStart == start && tmpCell.colSpan == 1) {
  11762. returns.push(tmpCell);
  11763. break;
  11764. }
  11765. }
  11766. }
  11767. return returns;
  11768. } catch (e) {
  11769. showError(e);
  11770. }
  11771. },
  11772. /**
  11773. * 更新table对应的索引表
  11774. */
  11775. update:function (table) {
  11776. this.table = table || this.table;
  11777. this.selectedTds = [];
  11778. this.cellsRange = {};
  11779. this.indexTable = [];
  11780. var rows = this.table.rows,
  11781. rowsNum = this.getMaxRows(),
  11782. dNum = rowsNum - rows.length,
  11783. colsNum = this.getMaxCols();
  11784. while (dNum--) {
  11785. this.table.insertRow(rows.length);
  11786. }
  11787. this.rowsNum = rowsNum;
  11788. this.colsNum = colsNum;
  11789. for (var i = 0, len = rows.length; i < len; i++) {
  11790. this.indexTable[i] = new Array(colsNum);
  11791. }
  11792. //填充索引表
  11793. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  11794. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  11795. //修正整行被rowSpan时导致的行数计算错误
  11796. if (cell.rowSpan > rowsNum) {
  11797. cell.rowSpan = rowsNum;
  11798. }
  11799. var colIndex = cellIndex,
  11800. rowSpan = cell.rowSpan || 1,
  11801. colSpan = cell.colSpan || 1;
  11802. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  11803. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  11804. for (var j = 0; j < rowSpan; j++) {
  11805. for (var k = 0; k < colSpan; k++) {
  11806. this.indexTable[rowIndex + j][colIndex + k] = {
  11807. rowIndex:rowIndex,
  11808. cellIndex:cellIndex,
  11809. colIndex:colIndex,
  11810. rowSpan:rowSpan,
  11811. colSpan:colSpan
  11812. }
  11813. }
  11814. }
  11815. }
  11816. }
  11817. //修复残缺td
  11818. for (j = 0; j < rowsNum; j++) {
  11819. for (k = 0; k < colsNum; k++) {
  11820. if (this.indexTable[j][k] === undefined) {
  11821. row = rows[j];
  11822. cell = row.cells[row.cells.length - 1];
  11823. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  11824. this.setCellContent(cell);
  11825. if (cell.colSpan !== 1)cell.colSpan = 1;
  11826. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  11827. row.appendChild(cell);
  11828. this.indexTable[j][k] = {
  11829. rowIndex:j,
  11830. cellIndex:cell.cellIndex,
  11831. colIndex:k,
  11832. rowSpan:1,
  11833. colSpan:1
  11834. }
  11835. }
  11836. }
  11837. }
  11838. //当框选后删除行或者列后撤销,需要重建选区。
  11839. var tds = domUtils.getElementsByTagName(this.table, "td"),
  11840. selectTds = [];
  11841. utils.each(tds, function (td) {
  11842. if (domUtils.hasClass(td, "selectTdClass")) {
  11843. selectTds.push(td);
  11844. }
  11845. });
  11846. if (selectTds.length) {
  11847. var start = selectTds[0],
  11848. end = selectTds[selectTds.length - 1],
  11849. startInfo = this.getCellInfo(start),
  11850. endInfo = this.getCellInfo(end);
  11851. this.selectedTds = selectTds;
  11852. this.cellsRange = {
  11853. beginRowIndex:startInfo.rowIndex,
  11854. beginColIndex:startInfo.colIndex,
  11855. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  11856. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  11857. };
  11858. }
  11859. },
  11860. /**
  11861. * 获取单元格的索引信息
  11862. */
  11863. getCellInfo:function (cell) {
  11864. if (!cell) return;
  11865. var cellIndex = cell.cellIndex,
  11866. rowIndex = cell.parentNode.rowIndex,
  11867. rowInfo = this.indexTable[rowIndex],
  11868. numCols = this.colsNum;
  11869. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  11870. var cellInfo = rowInfo[colIndex];
  11871. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  11872. return cellInfo;
  11873. }
  11874. }
  11875. },
  11876. /**
  11877. * 根据行列号获取单元格
  11878. */
  11879. getCell:function (rowIndex, cellIndex) {
  11880. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  11881. },
  11882. /**
  11883. * 删除单元格
  11884. */
  11885. deleteCell:function (cell, rowIndex) {
  11886. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  11887. var row = this.table.rows[rowIndex];
  11888. row.deleteCell(cell.cellIndex);
  11889. },
  11890. /**
  11891. * 根据始末两个单元格获取被框选的所有单元格范围
  11892. */
  11893. getCellsRange:function (cellA, cellB) {
  11894. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  11895. var tmpBeginRowIndex = beginRowIndex,
  11896. tmpBeginColIndex = beginColIndex,
  11897. tmpEndRowIndex = endRowIndex,
  11898. tmpEndColIndex = endColIndex,
  11899. cellInfo, colIndex, rowIndex;
  11900. // 通过indexTable检查是否存在超出TableRange上边界的情况
  11901. if (beginRowIndex > 0) {
  11902. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  11903. cellInfo = me.indexTable[beginRowIndex][colIndex];
  11904. rowIndex = cellInfo.rowIndex;
  11905. if (rowIndex < beginRowIndex) {
  11906. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  11907. }
  11908. }
  11909. }
  11910. // 通过indexTable检查是否存在超出TableRange右边界的情况
  11911. if (endColIndex < me.colsNum) {
  11912. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  11913. cellInfo = me.indexTable[rowIndex][endColIndex];
  11914. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  11915. if (colIndex > endColIndex) {
  11916. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  11917. }
  11918. }
  11919. }
  11920. // 检查是否有超出TableRange下边界的情况
  11921. if (endRowIndex < me.rowsNum) {
  11922. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  11923. cellInfo = me.indexTable[endRowIndex][colIndex];
  11924. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  11925. if (rowIndex > endRowIndex) {
  11926. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  11927. }
  11928. }
  11929. }
  11930. // 检查是否有超出TableRange左边界的情况
  11931. if (beginColIndex > 0) {
  11932. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  11933. cellInfo = me.indexTable[rowIndex][beginColIndex];
  11934. colIndex = cellInfo.colIndex;
  11935. if (colIndex < beginColIndex) {
  11936. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  11937. }
  11938. }
  11939. }
  11940. //递归调用直至所有完成所有框选单元格的扩展
  11941. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  11942. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  11943. } else {
  11944. // 不需要扩展TableRange的情况
  11945. return {
  11946. beginRowIndex:beginRowIndex,
  11947. beginColIndex:beginColIndex,
  11948. endRowIndex:endRowIndex,
  11949. endColIndex:endColIndex
  11950. };
  11951. }
  11952. }
  11953. try {
  11954. var me = this,
  11955. cellAInfo = me.getCellInfo(cellA);
  11956. if (cellA === cellB) {
  11957. return {
  11958. beginRowIndex:cellAInfo.rowIndex,
  11959. beginColIndex:cellAInfo.colIndex,
  11960. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  11961. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  11962. };
  11963. }
  11964. var cellBInfo = me.getCellInfo(cellB);
  11965. // 计算TableRange的四个边
  11966. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  11967. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  11968. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  11969. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  11970. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  11971. } catch (e) {
  11972. if (debug) throw e;
  11973. }
  11974. },
  11975. /**
  11976. * 依据cellsRange获取对应的单元格集合
  11977. */
  11978. getCells:function (range) {
  11979. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  11980. this.clearSelected();
  11981. var beginRowIndex = range.beginRowIndex,
  11982. beginColIndex = range.beginColIndex,
  11983. endRowIndex = range.endRowIndex,
  11984. endColIndex = range.endColIndex,
  11985. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  11986. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  11987. for (var j = beginColIndex; j <= endColIndex; j++) {
  11988. cellInfo = this.indexTable[i][j];
  11989. rowIndex = cellInfo.rowIndex;
  11990. colIndex = cellInfo.colIndex;
  11991. // 如果Cells里已经包含了此Cell则跳过
  11992. var key = rowIndex + '|' + colIndex;
  11993. if (tdHash[key]) continue;
  11994. tdHash[key] = 1;
  11995. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  11996. return null;
  11997. }
  11998. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  11999. }
  12000. }
  12001. return returnTds;
  12002. },
  12003. /**
  12004. * 清理已经选中的单元格
  12005. */
  12006. clearSelected:function () {
  12007. UETable.removeSelectedClass(this.selectedTds);
  12008. this.selectedTds = [];
  12009. this.cellsRange = {};
  12010. },
  12011. /**
  12012. * 根据range设置已经选中的单元格
  12013. */
  12014. setSelected:function (range) {
  12015. var cells = this.getCells(range);
  12016. UETable.addSelectedClass(cells);
  12017. this.selectedTds = cells;
  12018. this.cellsRange = range;
  12019. },
  12020. isFullRow:function () {
  12021. var range = this.cellsRange;
  12022. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  12023. },
  12024. isFullCol:function () {
  12025. var range = this.cellsRange,
  12026. table = this.table,
  12027. ths = table.getElementsByTagName("th"),
  12028. rows = range.endRowIndex - range.beginRowIndex + 1;
  12029. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  12030. },
  12031. /**
  12032. * 获取视觉上的前置单元格,默认是左边,top传入时
  12033. * @param cell
  12034. * @param top
  12035. */
  12036. getNextCell:function (cell, bottom, ignoreRange) {
  12037. try {
  12038. var cellInfo = this.getCellInfo(cell),
  12039. nextRowIndex, nextColIndex;
  12040. var len = this.selectedTds.length && !ignoreRange,
  12041. range = this.cellsRange;
  12042. //末行或者末列没有后置单元格
  12043. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  12044. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  12045. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  12046. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  12047. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  12048. } catch (e) {
  12049. showError(e);
  12050. }
  12051. },
  12052. getPreviewCell:function (cell, top) {
  12053. try {
  12054. var cellInfo = this.getCellInfo(cell),
  12055. previewRowIndex, previewColIndex;
  12056. var len = this.selectedTds.length,
  12057. range = this.cellsRange;
  12058. //首行或者首列没有前置单元格
  12059. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  12060. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  12061. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  12062. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  12063. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  12064. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  12065. } catch (e) {
  12066. showError(e);
  12067. }
  12068. },
  12069. /**
  12070. * 移动单元格中的内容
  12071. */
  12072. moveContent:function (cellTo, cellFrom) {
  12073. if (UETable.isEmptyBlock(cellFrom)) return;
  12074. if (UETable.isEmptyBlock(cellTo)) {
  12075. cellTo.innerHTML = cellFrom.innerHTML;
  12076. return;
  12077. }
  12078. var child = cellTo.lastChild;
  12079. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  12080. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  12081. }
  12082. while (child = cellFrom.firstChild) {
  12083. cellTo.appendChild(child);
  12084. }
  12085. },
  12086. /**
  12087. * 向右合并单元格
  12088. */
  12089. mergeRight:function (cell) {
  12090. var cellInfo = this.getCellInfo(cell),
  12091. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  12092. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  12093. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  12094. //合并
  12095. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  12096. //被合并的单元格不应存在宽度属性
  12097. cell.removeAttribute("width");
  12098. //移动内容
  12099. this.moveContent(cell, rightCell);
  12100. //删掉被合并的Cell
  12101. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  12102. this.update();
  12103. },
  12104. /**
  12105. * 向下合并单元格
  12106. */
  12107. mergeDown:function (cell) {
  12108. var cellInfo = this.getCellInfo(cell),
  12109. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  12110. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  12111. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  12112. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  12113. cell.removeAttribute("height");
  12114. this.moveContent(cell, downCell);
  12115. this.deleteCell(downCell, downCellInfo.rowIndex);
  12116. this.update();
  12117. },
  12118. /**
  12119. * 合并整个range中的内容
  12120. */
  12121. mergeRange:function () {
  12122. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  12123. var range = this.cellsRange,
  12124. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  12125. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  12126. var index = this.indexTable,
  12127. info = this.getCellInfo(leftTopCell);
  12128. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  12129. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  12130. }
  12131. // 删除剩余的Cells
  12132. var cells = this.getCells(range);
  12133. for(var i= 0,ci;ci=cells[i++];){
  12134. if (ci !== leftTopCell) {
  12135. this.moveContent(leftTopCell, ci);
  12136. this.deleteCell(ci);
  12137. }
  12138. }
  12139. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  12140. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  12141. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  12142. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  12143. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  12144. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  12145. leftTopCell.colSpan = 1;
  12146. }
  12147. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  12148. var rowIndex = leftTopCell.parentNode.rowIndex;
  12149. //解决IE下的表格操作问题
  12150. if( this.table.deleteRow ) {
  12151. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  12152. this.table.deleteRow(curIndex);
  12153. }
  12154. } else {
  12155. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  12156. var row = this.table.rows[rowIndex + 1];
  12157. row.parentNode.removeChild(row);
  12158. }
  12159. }
  12160. leftTopCell.rowSpan = 1;
  12161. }
  12162. this.update();
  12163. },
  12164. /**
  12165. * 插入一行单元格
  12166. */
  12167. insertRow:function (rowIndex, sourceCell) {
  12168. var numCols = this.colsNum,
  12169. table = this.table,
  12170. row = table.insertRow(rowIndex), cell,
  12171. width = parseInt((table.offsetWidth - numCols * 20 - numCols - 1) / numCols, 10);
  12172. //首行直接插入,无需考虑部分单元格被rowspan的情况
  12173. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  12174. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  12175. cell = this.cloneCell(sourceCell, true,true);
  12176. this.setCellContent(cell);
  12177. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12178. row.appendChild(cell);
  12179. }
  12180. } else {
  12181. var infoRow = this.indexTable[rowIndex],
  12182. cellIndex = 0;
  12183. for (colIndex = 0; colIndex < numCols; colIndex++) {
  12184. var cellInfo = infoRow[colIndex];
  12185. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  12186. if (cellInfo.rowIndex < rowIndex) {
  12187. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12188. cell.rowSpan = cellInfo.rowSpan + 1;
  12189. } else {
  12190. cell = this.cloneCell(sourceCell, true,true);
  12191. this.setCellContent(cell);
  12192. row.appendChild(cell);
  12193. }
  12194. }
  12195. }
  12196. //框选时插入不触发contentchange,需要手动更新索引。
  12197. this.update();
  12198. return row;
  12199. },
  12200. /**
  12201. * 删除一行单元格
  12202. * @param rowIndex
  12203. */
  12204. deleteRow:function (rowIndex) {
  12205. var row = this.table.rows[rowIndex],
  12206. infoRow = this.indexTable[rowIndex],
  12207. colsNum = this.colsNum,
  12208. count = 0; //处理计数
  12209. for (var colIndex = 0; colIndex < colsNum;) {
  12210. var cellInfo = infoRow[colIndex],
  12211. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12212. if (cell.rowSpan > 1) {
  12213. if (cellInfo.rowIndex == rowIndex) {
  12214. var clone = cell.cloneNode(true);
  12215. clone.rowSpan = cell.rowSpan - 1;
  12216. clone.innerHTML = "";
  12217. cell.rowSpan = 1;
  12218. var nextRowIndex = rowIndex + 1,
  12219. nextRow = this.table.rows[nextRowIndex],
  12220. insertCellIndex,
  12221. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  12222. if (preMerged < colIndex) {
  12223. insertCellIndex = colIndex - preMerged - 1;
  12224. //nextRow.insertCell(insertCellIndex);
  12225. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  12226. } else {
  12227. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  12228. }
  12229. count += 1;
  12230. //cell.parentNode.removeChild(cell);
  12231. }
  12232. }
  12233. colIndex += cell.colSpan || 1;
  12234. }
  12235. var deleteTds = [], cacheMap = {};
  12236. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  12237. var tmpRowIndex = infoRow[colIndex].rowIndex,
  12238. tmpCellIndex = infoRow[colIndex].cellIndex,
  12239. key = tmpRowIndex + "_" + tmpCellIndex;
  12240. if (cacheMap[key])continue;
  12241. cacheMap[key] = 1;
  12242. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  12243. deleteTds.push(cell);
  12244. }
  12245. var mergeTds = [];
  12246. utils.each(deleteTds, function (td) {
  12247. if (td.rowSpan == 1) {
  12248. td.parentNode.removeChild(td);
  12249. } else {
  12250. mergeTds.push(td);
  12251. }
  12252. });
  12253. utils.each(mergeTds, function (td) {
  12254. td.rowSpan--;
  12255. });
  12256. row.parentNode.removeChild(row);
  12257. //浏览器方法本身存在bug,采用自定义方法删除
  12258. //this.table.deleteRow(rowIndex);
  12259. this.update();
  12260. },
  12261. insertCol:function (colIndex, sourceCell, defaultValue) {
  12262. var rowsNum = this.rowsNum,
  12263. rowIndex = 0,
  12264. tableRow, cell,
  12265. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10);
  12266. function replaceTdToTh(rowIndex, cell, tableRow) {
  12267. if (rowIndex == 0) {
  12268. var th = cell.nextSibling || cell.previousSibling;
  12269. if (th.tagName == 'TH') {
  12270. th = cell.ownerDocument.createElement("th");
  12271. th.appendChild(cell.firstChild);
  12272. tableRow.insertBefore(th, cell);
  12273. domUtils.remove(cell)
  12274. }
  12275. }else{
  12276. if (cell.tagName == 'TH') {
  12277. var td = cell.ownerDocument.createElement("td");
  12278. td.appendChild(cell.firstChild);
  12279. tableRow.insertBefore(td, cell);
  12280. domUtils.remove(cell)
  12281. }
  12282. }
  12283. }
  12284. var preCell;
  12285. if (colIndex == 0 || colIndex == this.colsNum) {
  12286. for (; rowIndex < rowsNum; rowIndex++) {
  12287. tableRow = this.table.rows[rowIndex];
  12288. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  12289. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  12290. this.setCellContent(cell);
  12291. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12292. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  12293. if (!colIndex) {
  12294. tableRow.insertBefore(cell, tableRow.cells[0]);
  12295. } else {
  12296. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  12297. }
  12298. replaceTdToTh(rowIndex, cell, tableRow)
  12299. }
  12300. } else {
  12301. for (; rowIndex < rowsNum; rowIndex++) {
  12302. var cellInfo = this.indexTable[rowIndex][colIndex];
  12303. if (cellInfo.colIndex < colIndex) {
  12304. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12305. cell.colSpan = cellInfo.colSpan + 1;
  12306. } else {
  12307. tableRow = this.table.rows[rowIndex];
  12308. preCell = tableRow.cells[cellInfo.cellIndex];
  12309. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  12310. this.setCellContent(cell);
  12311. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12312. preCell && cell.setAttribute('width', preCell.getAttribute('width'))
  12313. tableRow.insertBefore(cell, preCell);
  12314. }
  12315. replaceTdToTh(rowIndex, cell, tableRow);
  12316. }
  12317. }
  12318. //框选时插入不触发contentchange,需要手动更新索引
  12319. this.update();
  12320. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  12321. },
  12322. updateWidth:function (width, defaultValue) {
  12323. var table = this.table,
  12324. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  12325. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  12326. table.setAttribute("width", tmpWidth);
  12327. return;
  12328. }
  12329. var tds = domUtils.getElementsByTagName(this.table, "td");
  12330. utils.each(tds, function (td) {
  12331. td.setAttribute("width", width);
  12332. })
  12333. },
  12334. deleteCol:function (colIndex) {
  12335. var indexTable = this.indexTable,
  12336. tableRows = this.table.rows,
  12337. backTableWidth = this.table.getAttribute("width"),
  12338. backTdWidth = 0,
  12339. rowsNum = this.rowsNum,
  12340. cacheMap = {};
  12341. for (var rowIndex = 0; rowIndex < rowsNum;) {
  12342. var infoRow = indexTable[rowIndex],
  12343. cellInfo = infoRow[colIndex],
  12344. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  12345. // 跳过已经处理过的Cell
  12346. if (cacheMap[key])continue;
  12347. cacheMap[key] = 1;
  12348. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  12349. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  12350. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  12351. if (cell.colSpan > 1) {
  12352. cell.colSpan--;
  12353. } else {
  12354. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  12355. }
  12356. rowIndex += cellInfo.rowSpan || 1;
  12357. }
  12358. this.table.setAttribute("width", backTableWidth - backTdWidth);
  12359. this.update();
  12360. },
  12361. splitToCells:function (cell) {
  12362. var me = this,
  12363. cells = this.splitToRows(cell);
  12364. utils.each(cells, function (cell) {
  12365. me.splitToCols(cell);
  12366. })
  12367. },
  12368. splitToRows:function (cell) {
  12369. var cellInfo = this.getCellInfo(cell),
  12370. rowIndex = cellInfo.rowIndex,
  12371. colIndex = cellInfo.colIndex,
  12372. results = [];
  12373. // 修改Cell的rowSpan
  12374. cell.rowSpan = 1;
  12375. results.push(cell);
  12376. // 补齐单元格
  12377. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  12378. if (i == rowIndex)continue;
  12379. var tableRow = this.table.rows[i],
  12380. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  12381. tmpCell.colSpan = cellInfo.colSpan;
  12382. this.setCellContent(tmpCell);
  12383. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12384. tmpCell.setAttribute('align', cell.getAttribute('align'));
  12385. if (cell.style.cssText) {
  12386. tmpCell.style.cssText = cell.style.cssText;
  12387. }
  12388. results.push(tmpCell);
  12389. }
  12390. this.update();
  12391. return results;
  12392. },
  12393. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  12394. var indexRow = this.indexTable[rowIndex],
  12395. num = 0;
  12396. for (var i = 0; i < colIndex;) {
  12397. var colSpan = indexRow[i].colSpan,
  12398. tmpRowIndex = indexRow[i].rowIndex;
  12399. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  12400. i += colSpan;
  12401. }
  12402. return num;
  12403. },
  12404. splitToCols:function (cell) {
  12405. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  12406. cellInfo = this.getCellInfo(cell),
  12407. rowIndex = cellInfo.rowIndex,
  12408. colIndex = cellInfo.colIndex,
  12409. results = [];
  12410. // 修改Cell的rowSpan
  12411. cell.colSpan = 1;
  12412. cell.setAttribute("width", backWidth);
  12413. results.push(cell);
  12414. // 补齐单元格
  12415. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  12416. if (j == colIndex)continue;
  12417. var tableRow = this.table.rows[rowIndex],
  12418. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  12419. tmpCell.rowSpan = cellInfo.rowSpan;
  12420. this.setCellContent(tmpCell);
  12421. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12422. tmpCell.setAttribute('align', cell.getAttribute('align'));
  12423. tmpCell.setAttribute('width', backWidth);
  12424. if (cell.style.cssText) {
  12425. tmpCell.style.cssText = cell.style.cssText;
  12426. }
  12427. //处理th的情况
  12428. if (cell.tagName == 'TH') {
  12429. var th = cell.ownerDocument.createElement('th');
  12430. th.appendChild(tmpCell.firstChild);
  12431. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  12432. th.rowSpan = tmpCell.rowSpan;
  12433. tableRow.insertBefore(th, tmpCell);
  12434. domUtils.remove(tmpCell);
  12435. }
  12436. results.push(tmpCell);
  12437. }
  12438. this.update();
  12439. return results;
  12440. },
  12441. isLastCell:function (cell, rowsNum, colsNum) {
  12442. rowsNum = rowsNum || this.rowsNum;
  12443. colsNum = colsNum || this.colsNum;
  12444. var cellInfo = this.getCellInfo(cell);
  12445. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  12446. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  12447. },
  12448. getLastCell:function (cells) {
  12449. cells = cells || this.table.getElementsByTagName("td");
  12450. var firstInfo = this.getCellInfo(cells[0]);
  12451. var me = this, last = cells[0],
  12452. tr = last.parentNode,
  12453. cellsNum = 0, cols = 0, rows;
  12454. utils.each(cells, function (cell) {
  12455. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  12456. cellsNum += cell.rowSpan * cell.colSpan || 1;
  12457. });
  12458. rows = cellsNum / cols;
  12459. utils.each(cells, function (cell) {
  12460. if (me.isLastCell(cell, rows, cols)) {
  12461. last = cell;
  12462. return false;
  12463. }
  12464. });
  12465. return last;
  12466. },
  12467. selectRow:function (rowIndex) {
  12468. var indexRow = this.indexTable[rowIndex],
  12469. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  12470. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  12471. range = this.getCellsRange(start, end);
  12472. this.setSelected(range);
  12473. },
  12474. selectTable:function () {
  12475. var tds = this.table.getElementsByTagName("td"),
  12476. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  12477. this.setSelected(range);
  12478. },
  12479. sortTable:function (sortByCellIndex, compareFn) {
  12480. var table = this.table,
  12481. rows = table.rows,
  12482. trArray = [],
  12483. flag = rows[0].cells[0].tagName === "TH",
  12484. lastRowIndex = 0;
  12485. if(this.selectedTds.length){
  12486. var range = this.cellsRange,
  12487. len = range.endRowIndex + 1;
  12488. for (var i = range.beginRowIndex; i < len; i++) {
  12489. trArray[i] = rows[i];
  12490. }
  12491. trArray.splice(0,range.beginRowIndex);
  12492. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  12493. }else{
  12494. for (var i = 0,len = rows.length; i < len; i++) {
  12495. trArray[i] = rows[i];
  12496. }
  12497. }
  12498. //th不参与排序
  12499. flag && trArray.splice(0, 1);
  12500. trArray = utils.sort(trArray,function (tr1, tr2) {
  12501. var txt = function(node){
  12502. return node.innerText||node.textContent;
  12503. };
  12504. return compareFn ? (typeof compareFn === "number" ? compareFn : compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex])) : function () {
  12505. var value1 = txt(tr1.cells[sortByCellIndex]),
  12506. value2 = txt(tr2.cells[sortByCellIndex]);
  12507. return value1.localeCompare(value2);
  12508. }();
  12509. });
  12510. var fragment = table.ownerDocument.createDocumentFragment();
  12511. for (var j = 0, len = trArray.length; j < len; j++) {
  12512. fragment.appendChild(trArray[j]);
  12513. }
  12514. var tbody = table.getElementsByTagName("tbody")[0];
  12515. if(!lastRowIndex){
  12516. tbody.appendChild(fragment);
  12517. }else{
  12518. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  12519. }
  12520. },
  12521. setBackground:function (cells, value) {
  12522. if (typeof value === "string") {
  12523. utils.each(cells, function (cell) {
  12524. cell.style.backgroundColor = value;
  12525. })
  12526. } else if (typeof value === "object") {
  12527. value = utils.extend({
  12528. repeat:true,
  12529. colorList:["#ddd", "#fff"]
  12530. }, value);
  12531. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  12532. count = 0,
  12533. colors = value.colorList,
  12534. getColor = function (list, index, repeat) {
  12535. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  12536. };
  12537. for (var i = 0, cell; cell = cells[i++];) {
  12538. var cellInfo = this.getCellInfo(cell);
  12539. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  12540. }
  12541. }
  12542. },
  12543. removeBackground:function (cells) {
  12544. utils.each(cells, function (cell) {
  12545. cell.style.backgroundColor = "";
  12546. })
  12547. }
  12548. };
  12549. function showError(e) {
  12550. }
  12551. })();
  12552. /**
  12553. * Created with JetBrains PhpStorm.
  12554. * User: taoqili
  12555. * Date: 13-2-20
  12556. * Time: 下午6:25
  12557. * To change this template use File | Settings | File Templates.
  12558. */
  12559. ;
  12560. (function () {
  12561. var UT = UE.UETable,
  12562. getTableItemsByRange = function (editor) {
  12563. return UT.getTableItemsByRange(editor);
  12564. },
  12565. getUETableBySelected = function (editor) {
  12566. return UT.getUETableBySelected(editor)
  12567. },
  12568. getDefaultValue = function (editor, table) {
  12569. return UT.getDefaultValue(editor, table);
  12570. },
  12571. getUETable = function (tdOrTable) {
  12572. return UT.getUETable(tdOrTable);
  12573. };
  12574. UE.commands['inserttable'] = {
  12575. queryCommandState: function () {
  12576. return getTableItemsByRange(this).table ? -1 : 0;
  12577. },
  12578. execCommand: function (cmd, opt) {
  12579. function createTable(opt, tableWidth, tdWidth) {
  12580. var html = [],
  12581. rowsNum = opt.numRows,
  12582. colsNum = opt.numCols;
  12583. for (var r = 0; r < rowsNum; r++) {
  12584. html.push('<tr>');
  12585. for (var c = 0; c < colsNum; c++) {
  12586. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie ? domUtils.fillChar : '<br/>') + '</td>')
  12587. }
  12588. html.push('</tr>')
  12589. }
  12590. return '<table cellspacing="0" cellpadding="5" border="1" width="' + tableWidth + '" ><tbody>' + html.join('') + '</tbody></table>'
  12591. }
  12592. if (!opt) {
  12593. opt = utils.extend({}, {
  12594. numCols: this.options.defaultCols,
  12595. numRows: this.options.defaultRows,
  12596. tdvalign: this.options.tdvalign
  12597. })
  12598. }
  12599. var range = this.selection.getRange(),
  12600. start = range.startContainer,
  12601. firstParentBlock = domUtils.findParent(start, function (node) {
  12602. return domUtils.isBlockElm(node);
  12603. }, true);
  12604. var me = this,
  12605. defaultValue = getDefaultValue(me),
  12606. tableWidth = getTableWidth(me, true, defaultValue) - (firstParentBlock ? parseInt(domUtils.getXY(firstParentBlock).x, 10) : 0),
  12607. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  12608. //todo其他属性
  12609. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  12610. me.execCommand("inserthtml", createTable(opt, tableWidth, tdWidth));
  12611. }
  12612. };
  12613. UE.commands['insertparagraphbeforetable'] = {
  12614. queryCommandState: function () {
  12615. return getTableItemsByRange(this).cell ? 0 : -1;
  12616. },
  12617. execCommand: function () {
  12618. var table = getTableItemsByRange(this).table;
  12619. if (table) {
  12620. var p = this.document.createElement("p");
  12621. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  12622. table.parentNode.insertBefore(p, table);
  12623. this.selection.getRange().setStart(p, 0).setCursor();
  12624. }
  12625. }
  12626. };
  12627. UE.commands['deletetable'] = {
  12628. queryCommandState: function () {
  12629. var rng = this.selection.getRange();
  12630. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  12631. },
  12632. execCommand: function (cmd, table) {
  12633. var rng = this.selection.getRange();
  12634. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  12635. if (table) {
  12636. var next = table.nextSibling;
  12637. if (!next) {
  12638. next = domUtils.createElement(this.document, 'p', {
  12639. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  12640. });
  12641. table.parentNode.insertBefore(next, table);
  12642. }
  12643. domUtils.remove(table);
  12644. rng = this.selection.getRange();
  12645. if (next.nodeType == 3) {
  12646. rng.setStartBefore(next)
  12647. } else {
  12648. rng.setStart(next, 0)
  12649. }
  12650. rng.setCursor(false, true)
  12651. this.fireEvent("tablehasdeleted")
  12652. }
  12653. }
  12654. };
  12655. UE.commands['cellalign'] = {
  12656. queryCommandState: function () {
  12657. return getSelectedArr(this).length ? 0 : -1
  12658. },
  12659. execCommand: function (cmd, align) {
  12660. var selectedTds = getSelectedArr(this);
  12661. if (selectedTds.length) {
  12662. for (var i = 0, ci; ci = selectedTds[i++];) {
  12663. ci.setAttribute('align', align);
  12664. }
  12665. }
  12666. }
  12667. };
  12668. UE.commands['cellvalign'] = {
  12669. queryCommandState: function () {
  12670. return getSelectedArr(this).length ? 0 : -1;
  12671. },
  12672. execCommand: function (cmd, valign) {
  12673. var selectedTds = getSelectedArr(this);
  12674. if (selectedTds.length) {
  12675. for (var i = 0, ci; ci = selectedTds[i++];) {
  12676. ci.setAttribute('vAlign', valign);
  12677. }
  12678. }
  12679. }
  12680. };
  12681. UE.commands['insertcaption'] = {
  12682. queryCommandState: function () {
  12683. var table = getTableItemsByRange(this).table;
  12684. if (table) {
  12685. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  12686. }
  12687. return -1;
  12688. },
  12689. execCommand: function () {
  12690. var table = getTableItemsByRange(this).table;
  12691. if (table) {
  12692. var caption = this.document.createElement('caption');
  12693. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  12694. table.insertBefore(caption, table.firstChild);
  12695. var range = this.selection.getRange();
  12696. range.setStart(caption, 0).setCursor();
  12697. }
  12698. }
  12699. };
  12700. UE.commands['deletecaption'] = {
  12701. queryCommandState: function () {
  12702. var rng = this.selection.getRange(),
  12703. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  12704. if (table) {
  12705. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  12706. }
  12707. return -1;
  12708. },
  12709. execCommand: function () {
  12710. var rng = this.selection.getRange(),
  12711. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  12712. if (table) {
  12713. domUtils.remove(table.getElementsByTagName('caption')[0]);
  12714. var range = this.selection.getRange();
  12715. range.setStart(table.rows[0].cells[0], 0).setCursor();
  12716. }
  12717. }
  12718. };
  12719. UE.commands['inserttitle'] = {
  12720. queryCommandState: function () {
  12721. var table = getTableItemsByRange(this).table;
  12722. if (table) {
  12723. var firstRow = table.rows[0];
  12724. return firstRow.getElementsByTagName('th').length == 0 ? 0 : -1
  12725. }
  12726. return -1;
  12727. },
  12728. execCommand: function () {
  12729. var table = getTableItemsByRange(this).table;
  12730. if (table) {
  12731. getUETable(table).insertRow(0, 'th');
  12732. }
  12733. var th = table.getElementsByTagName('th')[0];
  12734. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  12735. }
  12736. };
  12737. UE.commands['deletetitle'] = {
  12738. queryCommandState: function () {
  12739. var table = getTableItemsByRange(this).table;
  12740. if (table) {
  12741. var firstRow = table.rows[0];
  12742. return firstRow.getElementsByTagName('th').length ? 0 : -1
  12743. }
  12744. return -1;
  12745. },
  12746. execCommand: function () {
  12747. var table = getTableItemsByRange(this).table;
  12748. if (table) {
  12749. domUtils.remove(table.rows[0])
  12750. }
  12751. var td = table.getElementsByTagName('td')[0];
  12752. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  12753. }
  12754. };
  12755. UE.commands["mergeright"] = {
  12756. queryCommandState: function (cmd) {
  12757. var tableItems = getTableItemsByRange(this);
  12758. if (!tableItems.cell) return -1;
  12759. var ut = getUETable(tableItems.table);
  12760. if (ut.selectedTds.length) return -1;
  12761. var cellInfo = ut.getCellInfo(tableItems.cell),
  12762. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  12763. if (rightColIndex >= ut.colsNum) return -1;
  12764. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex];
  12765. return (rightCellInfo.rowIndex == cellInfo.rowIndex
  12766. && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  12767. },
  12768. execCommand: function (cmd) {
  12769. var rng = this.selection.getRange(),
  12770. bk = rng.createBookmark(true);
  12771. var cell = getTableItemsByRange(this).cell,
  12772. ut = getUETable(cell);
  12773. ut.mergeRight(cell);
  12774. rng.moveToBookmark(bk).select();
  12775. }
  12776. };
  12777. UE.commands["mergedown"] = {
  12778. queryCommandState: function (cmd) {
  12779. var tableItems = getTableItemsByRange(this),
  12780. cell = tableItems.cell;
  12781. if (!cell || cell.tagName == "TH") return -1;
  12782. var ut = getUETable(tableItems.table);
  12783. if (ut.selectedTds.length)return -1;
  12784. var cellInfo = ut.getCellInfo(tableItems.cell),
  12785. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  12786. // 如果处于最下边则不能f向右合并
  12787. if (downRowIndex >= ut.rowsNum) return -1;
  12788. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex];
  12789. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  12790. return (downCellInfo.colIndex == cellInfo.colIndex
  12791. && downCellInfo.colSpan == cellInfo.colSpan) && tableItems.cell.tagName !== 'TH' ? 0 : -1;
  12792. },
  12793. execCommand: function () {
  12794. var rng = this.selection.getRange(),
  12795. bk = rng.createBookmark(true);
  12796. var cell = getTableItemsByRange(this).cell,
  12797. ut = getUETable(cell);
  12798. ut.mergeDown(cell);
  12799. rng.moveToBookmark(bk).select();
  12800. }
  12801. };
  12802. UE.commands["mergecells"] = {
  12803. queryCommandState: function () {
  12804. return getUETableBySelected(this) ? 0 : -1;
  12805. },
  12806. execCommand: function () {
  12807. var ut = getUETableBySelected(this);
  12808. if (ut && ut.selectedTds.length) {
  12809. var cell = ut.selectedTds[0];
  12810. ut.mergeRange();
  12811. var rng = this.selection.getRange();
  12812. if (domUtils.isEmptyBlock(cell)) {
  12813. rng.setStart(cell, 0).collapse(true)
  12814. } else {
  12815. rng.selectNodeContents(cell)
  12816. }
  12817. rng.select();
  12818. }
  12819. }
  12820. };
  12821. UE.commands["insertrow"] = {
  12822. queryCommandState: function () {
  12823. var tableItems = getTableItemsByRange(this),
  12824. cell = tableItems.cell;
  12825. return cell && cell.tagName == "TD" && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  12826. },
  12827. execCommand: function () {
  12828. var rng = this.selection.getRange(),
  12829. bk = rng.createBookmark(true);
  12830. var tableItems = getTableItemsByRange(this),
  12831. cell = tableItems.cell,
  12832. table = tableItems.table,
  12833. ut = getUETable(table),
  12834. cellInfo = ut.getCellInfo(cell);
  12835. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  12836. if (!ut.selectedTds.length) {
  12837. ut.insertRow(cellInfo.rowIndex, cell);
  12838. } else {
  12839. var range = ut.cellsRange;
  12840. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  12841. ut.insertRow(range.beginRowIndex, cell);
  12842. }
  12843. }
  12844. rng.moveToBookmark(bk).select();
  12845. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  12846. }
  12847. };
  12848. //后插入行
  12849. UE.commands["insertrownext"] = {
  12850. queryCommandState: function () {
  12851. var tableItems = getTableItemsByRange(this),
  12852. cell = tableItems.cell;
  12853. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  12854. },
  12855. execCommand: function () {
  12856. var rng = this.selection.getRange(),
  12857. bk = rng.createBookmark(true);
  12858. var tableItems = getTableItemsByRange(this),
  12859. cell = tableItems.cell,
  12860. table = tableItems.table,
  12861. ut = getUETable(table),
  12862. cellInfo = ut.getCellInfo(cell);
  12863. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  12864. if (!ut.selectedTds.length) {
  12865. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  12866. } else {
  12867. var range = ut.cellsRange;
  12868. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  12869. ut.insertRow(range.endRowIndex + 1, cell);
  12870. }
  12871. }
  12872. rng.moveToBookmark(bk).select();
  12873. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  12874. }
  12875. };
  12876. UE.commands["deleterow"] = {
  12877. queryCommandState: function () {
  12878. var tableItems = getTableItemsByRange(this);
  12879. if (!tableItems.cell) {
  12880. return -1;
  12881. }
  12882. },
  12883. execCommand: function () {
  12884. var cell = getTableItemsByRange(this).cell,
  12885. ut = getUETable(cell),
  12886. cellsRange = ut.cellsRange,
  12887. cellInfo = ut.getCellInfo(cell),
  12888. preCell = ut.getVSideCell(cell),
  12889. nextCell = ut.getVSideCell(cell, true),
  12890. rng = this.selection.getRange();
  12891. if (utils.isEmptyObject(cellsRange)) {
  12892. ut.deleteRow(cellInfo.rowIndex);
  12893. } else {
  12894. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  12895. ut.deleteRow(cellsRange.beginRowIndex);
  12896. }
  12897. }
  12898. var table = ut.table;
  12899. if (!table.getElementsByTagName('td').length) {
  12900. var nextSibling = table.nextSibling;
  12901. domUtils.remove(table);
  12902. if (nextSibling) {
  12903. rng.setStart(nextSibling, 0).setCursor(false, true);
  12904. }
  12905. } else {
  12906. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  12907. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  12908. } else {
  12909. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  12910. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  12911. }
  12912. }
  12913. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  12914. }
  12915. };
  12916. UE.commands["insertcol"] = {
  12917. queryCommandState: function (cmd) {
  12918. var tableItems = getTableItemsByRange(this),
  12919. cell = tableItems.cell;
  12920. return cell && (cell.tagName == "TD" || cell.tagName == 'TH') && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  12921. },
  12922. execCommand: function (cmd) {
  12923. var rng = this.selection.getRange(),
  12924. bk = rng.createBookmark(true);
  12925. if (this.queryCommandState(cmd) == -1)return;
  12926. var cell = getTableItemsByRange(this).cell,
  12927. ut = getUETable(cell),
  12928. cellInfo = ut.getCellInfo(cell);
  12929. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  12930. if (!ut.selectedTds.length) {
  12931. ut.insertCol(cellInfo.colIndex, cell);
  12932. } else {
  12933. var range = ut.cellsRange;
  12934. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  12935. ut.insertCol(range.beginColIndex, cell);
  12936. }
  12937. }
  12938. rng.moveToBookmark(bk).select(true);
  12939. }
  12940. };
  12941. UE.commands["insertcolnext"] = {
  12942. queryCommandState: function () {
  12943. var tableItems = getTableItemsByRange(this),
  12944. cell = tableItems.cell;
  12945. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  12946. },
  12947. execCommand: function () {
  12948. var rng = this.selection.getRange(),
  12949. bk = rng.createBookmark(true);
  12950. var cell = getTableItemsByRange(this).cell,
  12951. ut = getUETable(cell),
  12952. cellInfo = ut.getCellInfo(cell);
  12953. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  12954. if (!ut.selectedTds.length) {
  12955. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  12956. } else {
  12957. var range = ut.cellsRange;
  12958. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  12959. ut.insertCol(range.endColIndex + 1, cell);
  12960. }
  12961. }
  12962. rng.moveToBookmark(bk).select();
  12963. }
  12964. };
  12965. UE.commands["deletecol"] = {
  12966. queryCommandState: function () {
  12967. var tableItems = getTableItemsByRange(this);
  12968. if (!tableItems.cell) return -1;
  12969. },
  12970. execCommand: function () {
  12971. var cell = getTableItemsByRange(this).cell,
  12972. ut = getUETable(cell),
  12973. range = ut.cellsRange,
  12974. cellInfo = ut.getCellInfo(cell),
  12975. preCell = ut.getHSideCell(cell),
  12976. nextCell = ut.getHSideCell(cell, true);
  12977. if (utils.isEmptyObject(range)) {
  12978. ut.deleteCol(cellInfo.colIndex);
  12979. } else {
  12980. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  12981. ut.deleteCol(range.beginColIndex);
  12982. }
  12983. }
  12984. var table = ut.table,
  12985. rng = this.selection.getRange();
  12986. if (!table.getElementsByTagName('td').length) {
  12987. var nextSibling = table.nextSibling;
  12988. domUtils.remove(table);
  12989. if (nextSibling) {
  12990. rng.setStart(nextSibling, 0).setCursor(false, true);
  12991. }
  12992. } else {
  12993. if (domUtils.inDoc(cell, this.document)) {
  12994. rng.setStart(cell, 0).setCursor(false, true);
  12995. } else {
  12996. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  12997. rng.selectNodeContents(nextCell).setCursor(false, true);
  12998. } else {
  12999. if (preCell && domUtils.inDoc(preCell, this.document)) {
  13000. rng.selectNodeContents(preCell).setCursor(true, true);
  13001. }
  13002. }
  13003. }
  13004. }
  13005. }
  13006. };
  13007. UE.commands["splittocells"] = {
  13008. queryCommandState: function () {
  13009. var tableItems = getTableItemsByRange(this),
  13010. cell = tableItems.cell;
  13011. if (!cell) return -1;
  13012. var ut = getUETable(tableItems.table);
  13013. if (ut.selectedTds.length > 0) return -1;
  13014. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  13015. },
  13016. execCommand: function () {
  13017. var rng = this.selection.getRange(),
  13018. bk = rng.createBookmark(true);
  13019. var cell = getTableItemsByRange(this).cell,
  13020. ut = getUETable(cell);
  13021. ut.splitToCells(cell);
  13022. rng.moveToBookmark(bk).select();
  13023. }
  13024. };
  13025. UE.commands["splittorows"] = {
  13026. queryCommandState: function () {
  13027. var tableItems = getTableItemsByRange(this),
  13028. cell = tableItems.cell;
  13029. if (!cell) return -1;
  13030. var ut = getUETable(tableItems.table);
  13031. if (ut.selectedTds.length > 0) return -1;
  13032. return cell && cell.rowSpan > 1 ? 0 : -1;
  13033. },
  13034. execCommand: function () {
  13035. var rng = this.selection.getRange(),
  13036. bk = rng.createBookmark(true);
  13037. var cell = getTableItemsByRange(this).cell,
  13038. ut = getUETable(cell);
  13039. ut.splitToRows(cell);
  13040. rng.moveToBookmark(bk).select();
  13041. }
  13042. };
  13043. UE.commands["splittocols"] = {
  13044. queryCommandState: function () {
  13045. var tableItems = getTableItemsByRange(this),
  13046. cell = tableItems.cell;
  13047. if (!cell) return -1;
  13048. var ut = getUETable(tableItems.table);
  13049. if (ut.selectedTds.length > 0) return -1;
  13050. return cell && cell.colSpan > 1 ? 0 : -1;
  13051. },
  13052. execCommand: function () {
  13053. var rng = this.selection.getRange(),
  13054. bk = rng.createBookmark(true);
  13055. var cell = getTableItemsByRange(this).cell,
  13056. ut = getUETable(cell);
  13057. ut.splitToCols(cell);
  13058. rng.moveToBookmark(bk).select();
  13059. }
  13060. };
  13061. UE.commands["adaptbytext"] =
  13062. UE.commands["adaptbywindow"] = {
  13063. queryCommandState: function () {
  13064. return getTableItemsByRange(this).table ? 0 : -1
  13065. },
  13066. execCommand: function (cmd) {
  13067. var tableItems = getTableItemsByRange(this),
  13068. table = tableItems.table;
  13069. if (table) {
  13070. if (cmd == 'adaptbywindow') {
  13071. resetTdWidth(table, this);
  13072. } else {
  13073. var cells = domUtils.getElementsByTagName(table, "td th");
  13074. utils.each(cells, function (cell) {
  13075. cell.removeAttribute("width");
  13076. });
  13077. table.removeAttribute("width");
  13078. }
  13079. }
  13080. }
  13081. };
  13082. //平均分配各列
  13083. UE.commands['averagedistributecol'] = {
  13084. queryCommandState: function () {
  13085. var ut = getUETableBySelected(this);
  13086. if (!ut) return -1;
  13087. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  13088. },
  13089. execCommand: function (cmd) {
  13090. var me = this,
  13091. ut = getUETableBySelected(me);
  13092. function getAverageWidth() {
  13093. var tb = ut.table,
  13094. averageWidth, sumWidth = 0, colsNum = 0,
  13095. tbAttr = getDefaultValue(me, tb);
  13096. if (ut.isFullRow()) {
  13097. sumWidth = tb.offsetWidth;
  13098. colsNum = ut.colsNum;
  13099. } else {
  13100. var begin = ut.cellsRange.beginColIndex,
  13101. end = ut.cellsRange.endColIndex,
  13102. node;
  13103. for (var i = begin; i <= end;) {
  13104. node = ut.selectedTds[i];
  13105. sumWidth += node.offsetWidth;
  13106. i += node.colSpan;
  13107. colsNum += 1;
  13108. }
  13109. }
  13110. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  13111. return averageWidth;
  13112. }
  13113. function setAverageWidth(averageWidth) {
  13114. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  13115. node.setAttribute("width", "");
  13116. });
  13117. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  13118. utils.each(cells, function (node) {
  13119. if (node.colSpan == 1) {
  13120. node.setAttribute("width", averageWidth);
  13121. }
  13122. });
  13123. }
  13124. if (ut && ut.selectedTds.length) {
  13125. setAverageWidth(getAverageWidth());
  13126. }
  13127. }
  13128. };
  13129. //平均分配各行
  13130. UE.commands['averagedistributerow'] = {
  13131. queryCommandState: function () {
  13132. var ut = getUETableBySelected(this);
  13133. if (!ut) return -1;
  13134. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  13135. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  13136. },
  13137. execCommand: function (cmd) {
  13138. var me = this,
  13139. ut = getUETableBySelected(me);
  13140. function getAverageHeight() {
  13141. var averageHeight, rowNum, sumHeight = 0,
  13142. tb = ut.table,
  13143. tbAttr = getDefaultValue(me, tb),
  13144. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  13145. if (ut.isFullCol()) {
  13146. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  13147. thArr = domUtils.getElementsByTagName(tb, "th"),
  13148. captionHeight, thHeight;
  13149. if (captionArr.length > 0) {
  13150. captionHeight = captionArr[0].offsetHeight;
  13151. }
  13152. if (thArr.length > 0) {
  13153. thHeight = thArr[0].offsetHeight;
  13154. }
  13155. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  13156. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  13157. } else {
  13158. var begin = ut.cellsRange.beginRowIndex,
  13159. end = ut.cellsRange.endRowIndex,
  13160. count = 0,
  13161. trs = domUtils.getElementsByTagName(tb, "tr");
  13162. for (var i = begin; i <= end; i++) {
  13163. sumHeight += trs[i].offsetHeight;
  13164. count += 1;
  13165. }
  13166. rowNum = count;
  13167. }
  13168. //ie8下是混杂模式
  13169. if (browser.ie && browser.version < 9) {
  13170. averageHeight = Math.ceil(sumHeight / rowNum);
  13171. } else {
  13172. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  13173. }
  13174. return averageHeight;
  13175. }
  13176. function setAverageHeight(averageHeight) {
  13177. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  13178. utils.each(cells, function (node) {
  13179. if (node.rowSpan == 1) {
  13180. node.setAttribute("height", averageHeight);
  13181. }
  13182. });
  13183. }
  13184. if (ut && ut.selectedTds.length) {
  13185. setAverageHeight(getAverageHeight());
  13186. }
  13187. }
  13188. };
  13189. //单元格对齐方式
  13190. UE.commands['cellalignment'] = {
  13191. queryCommandState: function () {
  13192. return getTableItemsByRange(this).table ? 0 : -1
  13193. },
  13194. execCommand: function (cmd, data) {
  13195. var me = this,
  13196. ut = getUETableBySelected(me);
  13197. if (!ut) {
  13198. var start = me.selection.getStart(),
  13199. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  13200. if (!/caption/ig.test(cell.tagName)) {
  13201. domUtils.setAttributes(cell, data);
  13202. } else {
  13203. cell.style.textAlign = data.align;
  13204. cell.style.verticalAlign = data.vAlign;
  13205. }
  13206. me.selection.getRange().setCursor(true);
  13207. } else {
  13208. utils.each(ut.selectedTds, function (cell) {
  13209. domUtils.setAttributes(cell, data);
  13210. });
  13211. }
  13212. },
  13213. /**
  13214. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  13215. * @see UE.UETable.getTableCellAlignState
  13216. */
  13217. queryCommandValue: function (cmd) {
  13218. var activeMenuCell = getTableItemsByRange( this).cell;
  13219. if( !activeMenuCell ) {
  13220. activeMenuCell = getSelectedArr(this)[0];
  13221. }
  13222. if (!activeMenuCell) {
  13223. return null;
  13224. } else {
  13225. //获取同时选中的其他单元格
  13226. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  13227. !cells.length && ( cells = activeMenuCell );
  13228. return UE.UETable.getTableCellAlignState(cells);
  13229. }
  13230. }
  13231. };
  13232. //表格对齐方式
  13233. UE.commands['tablealignment'] = {
  13234. queryCommandState: function () {
  13235. if (browser.ie && browser.version < 8) {
  13236. return -1;
  13237. }
  13238. return getTableItemsByRange(this).table ? 0 : -1
  13239. },
  13240. execCommand: function (cmd, value) {
  13241. var me = this,
  13242. start = me.selection.getStart(),
  13243. table = start && domUtils.findParentByTagName(start, ["table"], true);
  13244. if (table) {
  13245. table.setAttribute("align",value);
  13246. }
  13247. }
  13248. };
  13249. //表格属性
  13250. UE.commands['edittable'] = {
  13251. queryCommandState: function () {
  13252. return getTableItemsByRange(this).table ? 0 : -1
  13253. },
  13254. execCommand: function (cmd, color) {
  13255. var rng = this.selection.getRange(),
  13256. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  13257. if (table) {
  13258. var arr = domUtils.getElementsByTagName(table, "td").concat(
  13259. domUtils.getElementsByTagName(table, "th"),
  13260. domUtils.getElementsByTagName(table, "caption")
  13261. );
  13262. utils.each(arr, function (node) {
  13263. node.style.borderColor = color;
  13264. });
  13265. }
  13266. }
  13267. };
  13268. //单元格属性
  13269. UE.commands['edittd'] = {
  13270. queryCommandState: function () {
  13271. return getTableItemsByRange(this).table ? 0 : -1
  13272. },
  13273. execCommand: function (cmd, bkColor) {
  13274. var me = this,
  13275. ut = getUETableBySelected(me);
  13276. if (!ut) {
  13277. var start = me.selection.getStart(),
  13278. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  13279. if (cell) {
  13280. cell.style.backgroundColor = bkColor;
  13281. }
  13282. } else {
  13283. utils.each(ut.selectedTds, function (cell) {
  13284. cell.style.backgroundColor = bkColor;
  13285. });
  13286. }
  13287. }
  13288. };
  13289. UE.commands['sorttable'] = {
  13290. queryCommandState: function () {
  13291. var me = this,
  13292. tableItems = getTableItemsByRange(me);
  13293. if (!tableItems.cell) return -1;
  13294. var table = tableItems.table,
  13295. cells = table.getElementsByTagName("td");
  13296. for (var i = 0, cell; cell = cells[i++];) {
  13297. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  13298. }
  13299. return 0;
  13300. },
  13301. execCommand: function (cmd, fn) {
  13302. var me = this,
  13303. range = me.selection.getRange(),
  13304. bk = range.createBookmark(true),
  13305. tableItems = getTableItemsByRange(me),
  13306. cell = tableItems.cell,
  13307. ut = getUETable(tableItems.table),
  13308. cellInfo = ut.getCellInfo(cell);
  13309. ut.sortTable(cellInfo.cellIndex, fn);
  13310. range.moveToBookmark(bk).select();
  13311. }
  13312. };
  13313. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  13314. queryCommandState: function () {
  13315. return getTableItemsByRange(this).table ? 0 : -1;
  13316. },
  13317. execCommand: function (cmd) {
  13318. var table = getTableItemsByRange(this).table;
  13319. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  13320. }
  13321. };
  13322. UE.commands["settablebackground"] = {
  13323. queryCommandState: function () {
  13324. var selecteds = getSelectedArr(this);
  13325. if( selecteds.length && selecteds[0].tagName.toLowerCase() === 'td' ) {
  13326. return 0;
  13327. }
  13328. return -1;
  13329. },
  13330. execCommand: function (cmd, value) {
  13331. var table, cells, ut;
  13332. cells = getSelectedArr(this);
  13333. ut = getUETable(cells[0]);
  13334. ut.setBackground(cells, value);
  13335. }
  13336. };
  13337. UE.commands["cleartablebackground"] = {
  13338. queryCommandState: function () {
  13339. var cells = getSelectedArr(this);
  13340. if (!cells.length)return -1;
  13341. for (var i = 0, cell; cell = cells[i++];) {
  13342. if (cell.style.backgroundColor !== "") return 0;
  13343. }
  13344. return -1;
  13345. },
  13346. execCommand: function () {
  13347. var cells = getSelectedArr(this),
  13348. ut = getUETable(cells[0]);
  13349. ut.removeBackground(cells);
  13350. }
  13351. };
  13352. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  13353. queryCommandState: function (cmd) {
  13354. var table = getTableItemsByRange(this).table;
  13355. if (!table) return -1;
  13356. var interlaced = table.getAttribute("interlaced");
  13357. if (cmd == "interlacetable") {
  13358. //TODO 待定
  13359. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  13360. return (interlaced === "enabled") ? -1 : 0;
  13361. } else {
  13362. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  13363. }
  13364. },
  13365. execCommand: function (cmd, classList) {
  13366. var table = getTableItemsByRange(this).table;
  13367. if (cmd == "interlacetable") {
  13368. table.setAttribute("interlaced", "enabled");
  13369. this.fireEvent("interlacetable", table, classList);
  13370. } else {
  13371. table.setAttribute("interlaced", "disabled");
  13372. this.fireEvent("uninterlacetable", table);
  13373. }
  13374. }
  13375. };
  13376. function resetTdWidth(table, editor) {
  13377. var tds = table.getElementsByTagName("td");
  13378. utils.each(tds, function (td) {
  13379. td.removeAttribute("width");
  13380. });
  13381. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  13382. setTimeout(function () {
  13383. utils.each(tds, function (td) {
  13384. (td.colSpan == 1) && td.setAttribute("width", td.offsetWidth + "");
  13385. })
  13386. }, 0);
  13387. }
  13388. function getTableWidth(editor, needIEHack, defaultValue) {
  13389. var body = editor.body;
  13390. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  13391. }
  13392. function getSelectedArr(editor) {
  13393. var cell = getTableItemsByRange(editor).cell;
  13394. if (cell) {
  13395. var ut = getUETable(cell);
  13396. return ut.selectedTds.length ? ut.selectedTds : [cell];
  13397. } else {
  13398. return [];
  13399. }
  13400. }
  13401. })();
  13402. /**
  13403. * Created with JetBrains PhpStorm.
  13404. * User: taoqili
  13405. * Date: 12-10-12
  13406. * Time: 上午10:05
  13407. * To change this template use File | Settings | File Templates.
  13408. */
  13409. UE.plugins['table'] = function () {
  13410. var me = this,
  13411. debug = true,
  13412. UT = UE.UETable,
  13413. getUETable = function (tdOrTable) {
  13414. return UT.getUETable(tdOrTable);
  13415. },
  13416. getUETableBySelected = function (editor) {
  13417. return UT.getUETableBySelected(editor);
  13418. },
  13419. getDefaultValue = function (editor, table) {
  13420. return UT.getDefaultValue(editor, table);
  13421. },
  13422. removeSelectedClass = function (cells) {
  13423. return UT.removeSelectedClass(cells);
  13424. };
  13425. function showError(e) {
  13426. if (debug) throw e;
  13427. }
  13428. me.ready(function(){
  13429. var me = this;
  13430. var orgGetText = me.selection.getText;
  13431. me.selection.getText = function(){
  13432. var table = getUETableBySelected(me);
  13433. if(table){
  13434. var str = '';
  13435. utils.each(table.selectedTds,function(td){
  13436. str += td[browser.ie?'innerText':'textContent'];
  13437. })
  13438. return str;
  13439. }else{
  13440. return orgGetText.call(me.selection)
  13441. }
  13442. }
  13443. })
  13444. //处理拖动及框选相关方法
  13445. var startTd = null, //鼠标按下时的锚点td
  13446. currentTd = null, //当前鼠标经过时的td
  13447. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  13448. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  13449. dragButton = null,
  13450. dragOver = false,
  13451. dragLine = null, //模拟的拖动线
  13452. dragTd = null; //发生拖动的目标td
  13453. var mousedown = false,
  13454. //todo 判断混乱模式
  13455. needIEHack = true;
  13456. me.setOpt({
  13457. 'maxColNum':20,
  13458. 'maxRowNum':100,
  13459. 'defaultCols':5,
  13460. 'defaultRows':5,
  13461. 'tdvalign':'top',
  13462. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  13463. 'tableDragable':false,
  13464. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  13465. });
  13466. me.getUETable = getUETable;
  13467. var commands = {
  13468. 'deletetable':1,
  13469. 'inserttable':1,
  13470. 'cellvalign':1,
  13471. 'insertcaption':1,
  13472. 'deletecaption':1,
  13473. 'inserttitle':1,
  13474. 'deletetitle':1,
  13475. "mergeright":1,
  13476. "mergedown":1,
  13477. "mergecells":1,
  13478. "insertrow":1,
  13479. "insertrownext":1,
  13480. "deleterow":1,
  13481. "insertcol":1,
  13482. "insertcolnext":1,
  13483. "deletecol":1,
  13484. "splittocells":1,
  13485. "splittorows":1,
  13486. "splittocols":1,
  13487. "adaptbytext":1,
  13488. "adaptbywindow":1,
  13489. "adaptbycustomer":1,
  13490. "insertparagraph":1,
  13491. "insertparagraphbeforetable":1,
  13492. "averagedistributecol":1,
  13493. "averagedistributerow":1
  13494. };
  13495. me.ready(function () {
  13496. utils.cssRule('table',
  13497. //选中的td上的样式
  13498. '.selectTdClass{background-color:#edf5fa !important}' +
  13499. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  13500. //插入的表格的默认样式
  13501. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  13502. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  13503. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  13504. 'th{border-top:2px solid #BBB;background:#F7F7F7;}' +
  13505. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  13506. 'td p{margin:0;padding:0;}', me.document);
  13507. var tableCopyList, isFullCol, isFullRow;
  13508. //注册del/backspace事件
  13509. me.addListener('keydown', function (cmd, evt) {
  13510. var me = this;
  13511. var keyCode = evt.keyCode || evt.which;
  13512. if (keyCode == 8) {
  13513. var ut = getUETableBySelected(me);
  13514. if (ut && ut.selectedTds.length) {
  13515. if (ut.isFullCol()) {
  13516. me.execCommand('deletecol')
  13517. } else if (ut.isFullRow()) {
  13518. me.execCommand('deleterow')
  13519. } else {
  13520. me.fireEvent('delcells');
  13521. }
  13522. domUtils.preventDefault(evt);
  13523. }
  13524. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  13525. range = me.selection.getRange();
  13526. if (range.collapsed && caption && isEmptyBlock(caption)) {
  13527. me.fireEvent('saveScene');
  13528. var table = caption.parentNode;
  13529. domUtils.remove(caption);
  13530. if (table) {
  13531. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  13532. }
  13533. me.fireEvent('saveScene');
  13534. }
  13535. }
  13536. if (keyCode == 46) {
  13537. ut = getUETableBySelected(me);
  13538. if (ut) {
  13539. me.fireEvent('saveScene');
  13540. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  13541. domUtils.fillNode(me.document, ci)
  13542. }
  13543. me.fireEvent('saveScene');
  13544. domUtils.preventDefault(evt);
  13545. }
  13546. }
  13547. if (keyCode == 13) {
  13548. var rng = me.selection.getRange(),
  13549. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  13550. if (caption) {
  13551. var table = domUtils.findParentByTagName(caption, 'table');
  13552. if (!rng.collapsed) {
  13553. rng.deleteContents();
  13554. me.fireEvent('saveScene');
  13555. } else {
  13556. if (caption) {
  13557. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  13558. }
  13559. }
  13560. domUtils.preventDefault(evt);
  13561. return;
  13562. }
  13563. if (rng.collapsed) {
  13564. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  13565. if (table) {
  13566. var cell = table.rows[0].cells[0],
  13567. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  13568. preNode = table.previousSibling;
  13569. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  13570. me.execCommand('insertparagraphbeforetable');
  13571. domUtils.preventDefault(evt);
  13572. }
  13573. }
  13574. }
  13575. }
  13576. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  13577. tableCopyList = null;
  13578. var ut = getUETableBySelected(me);
  13579. if (ut) {
  13580. var tds = ut.selectedTds;
  13581. isFullCol = ut.isFullCol();
  13582. isFullRow = ut.isFullRow();
  13583. tableCopyList = [
  13584. [ut.cloneCell(tds[0])]
  13585. ];
  13586. for (var i = 1, ci; ci = tds[i]; i++) {
  13587. if (ci.parentNode !== tds[i - 1].parentNode) {
  13588. tableCopyList.push([ut.cloneCell(ci)]);
  13589. } else {
  13590. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci));
  13591. }
  13592. }
  13593. }
  13594. }
  13595. });
  13596. me.addListener("tablehasdeleted",function(){
  13597. toggleDraggableState(this, false, "", null);
  13598. if (dragButton)domUtils.remove(dragButton);
  13599. });
  13600. me.addListener('beforepaste', function (cmd, html) {
  13601. var me = this;
  13602. var rng = me.selection.getRange();
  13603. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  13604. var div = me.document.createElement("div");
  13605. div.innerHTML = html.html;
  13606. html.html = div[browser.ie ? 'innerText' : 'textContent'];
  13607. return;
  13608. }
  13609. var table = getUETableBySelected(me);
  13610. if (tableCopyList) {
  13611. me.fireEvent('saveScene');
  13612. var rng = me.selection.getRange();
  13613. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  13614. if (td) {
  13615. var ut = getUETable(td);
  13616. if (isFullRow) {
  13617. var rowIndex = ut.getCellInfo(td).rowIndex;
  13618. if (td.tagName == 'TH') {
  13619. rowIndex++;
  13620. }
  13621. for (var i = 0, ci; ci = tableCopyList[i++];) {
  13622. var tr = ut.insertRow(rowIndex++, "td");
  13623. for (var j = 0, cj; cj = ci[j]; j++) {
  13624. var cell = tr.cells[j];
  13625. if (!cell) {
  13626. cell = tr.insertCell(j)
  13627. }
  13628. cell.innerHTML = cj.innerHTML;
  13629. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  13630. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  13631. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  13632. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  13633. }
  13634. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  13635. if (!ci[j])
  13636. break;
  13637. cj.innerHTML = ci[j].innerHTML;
  13638. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  13639. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  13640. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  13641. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  13642. }
  13643. }
  13644. } else {
  13645. if (isFullCol) {
  13646. cellInfo = ut.getCellInfo(td);
  13647. var maxColNum = 0;
  13648. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  13649. maxColNum += cj.colSpan || 1;
  13650. }
  13651. me.__hasEnterExecCommand = true;
  13652. for (i = 0; i < maxColNum; i++) {
  13653. me.execCommand('insertcol');
  13654. }
  13655. me.__hasEnterExecCommand = false;
  13656. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  13657. if (td.tagName == 'TH') {
  13658. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  13659. }
  13660. }
  13661. for (var i = 0, ci; ci = tableCopyList[i++];) {
  13662. tmpNode = td;
  13663. for (var j = 0, cj; cj = ci[j++];) {
  13664. if (td) {
  13665. td.innerHTML = cj.innerHTML;
  13666. //todo 定制处理
  13667. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  13668. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  13669. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  13670. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  13671. preNode = td;
  13672. td = td.nextSibling;
  13673. } else {
  13674. var cloneTd = cj.cloneNode(true);
  13675. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  13676. preNode.parentNode.appendChild(cloneTd)
  13677. }
  13678. }
  13679. td = ut.getNextCell(tmpNode, true, true);
  13680. if (!tableCopyList[i])
  13681. break;
  13682. if (!td) {
  13683. var cellInfo = ut.getCellInfo(tmpNode);
  13684. ut.table.insertRow(ut.table.rows.length);
  13685. ut.update();
  13686. td = ut.getVSideCell(tmpNode, true);
  13687. }
  13688. }
  13689. }
  13690. ut.update();
  13691. } else {
  13692. table = me.document.createElement('table');
  13693. for (var i = 0, ci; ci = tableCopyList[i++];) {
  13694. var tr = table.insertRow(table.rows.length);
  13695. for (var j = 0, cj; cj = ci[j++];) {
  13696. cloneTd = UT.cloneCell(cj);
  13697. domUtils.removeAttributes(cloneTd, ['class']);
  13698. tr.appendChild(cloneTd)
  13699. }
  13700. if (j == 2 && cloneTd.rowSpan > 1) {
  13701. cloneTd.rowSpan = 1;
  13702. }
  13703. }
  13704. var defaultValue = getDefaultValue(me),
  13705. width = me.body.offsetWidth -
  13706. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  13707. me.execCommand('insertHTML', '<table ' +
  13708. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  13709. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  13710. }
  13711. me.fireEvent('contentchange');
  13712. me.fireEvent('saveScene');
  13713. html.html = '';
  13714. return true;
  13715. } else {
  13716. var div = me.document.createElement("div"), tables;
  13717. div.innerHTML = html.html;
  13718. tables = div.getElementsByTagName("table");
  13719. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  13720. utils.each(tables, function (t) {
  13721. domUtils.remove(t)
  13722. });
  13723. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  13724. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  13725. }
  13726. } else {
  13727. utils.each(tables, function (table) {
  13728. removeStyleSize(table, true);
  13729. domUtils.removeAttributes(table, ['style', 'border']);
  13730. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  13731. if (isEmptyBlock(td)) {
  13732. domUtils.fillNode(me.document, td);
  13733. }
  13734. removeStyleSize(td, true);
  13735. // domUtils.removeAttributes(td, ['style'])
  13736. });
  13737. });
  13738. }
  13739. html.html = div.innerHTML;
  13740. }
  13741. });
  13742. me.addListener('afterpaste', function () {
  13743. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  13744. if (table.offsetWidth > me.body.offsetWidth) {
  13745. var defaultValue = getDefaultValue(me, table);
  13746. 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'
  13747. }
  13748. })
  13749. });
  13750. me.addListener('blur', function () {
  13751. tableCopyList = null;
  13752. });
  13753. var timer;
  13754. me.addListener('keydown', function () {
  13755. clearTimeout(timer);
  13756. timer = setTimeout(function () {
  13757. var rng = me.selection.getRange(),
  13758. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  13759. if (cell) {
  13760. var table = cell.parentNode.parentNode.parentNode;
  13761. if (table.offsetWidth > table.getAttribute("width")) {
  13762. cell.style.wordBreak = "break-all";
  13763. }
  13764. }
  13765. }, 100);
  13766. });
  13767. me.addListener("selectionchange", function () {
  13768. toggleDraggableState(me, false, "", null);
  13769. });
  13770. //内容变化时触发索引更新
  13771. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  13772. me.addListener("contentchange", function () {
  13773. var me = this;
  13774. //尽可能排除一些不需要更新的状况
  13775. hideDragLine(me);
  13776. if (getUETableBySelected(me))return;
  13777. var rng = me.selection.getRange();
  13778. var start = rng.startContainer;
  13779. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  13780. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  13781. if (me.fireEvent("excludetable", table) === true) return;
  13782. table.ueTable = new UT(table);
  13783. utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  13784. if (domUtils.isEmptyBlock(td) && td !== start) {
  13785. domUtils.fillNode(me.document, td);
  13786. if (browser.ie && browser.version == 6) {
  13787. td.innerHTML = '&nbsp;'
  13788. }
  13789. }
  13790. });
  13791. utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  13792. if (domUtils.isEmptyBlock(th) && th !== start) {
  13793. domUtils.fillNode(me.document, th);
  13794. if (browser.ie && browser.version == 6) {
  13795. th.innerHTML = '&nbsp;'
  13796. }
  13797. }
  13798. });
  13799. table.onmouseover = function () {
  13800. me.fireEvent('tablemouseover', table);
  13801. };
  13802. table.onmousemove = function () {
  13803. me.fireEvent('tablemousemove', table);
  13804. me.options.tableDragable && toggleDragButton(true, this, me);
  13805. };
  13806. table.onmouseout = function () {
  13807. me.fireEvent('tablemouseout', table);
  13808. toggleDraggableState(me, false, "", null);
  13809. hideDragLine(me);
  13810. };
  13811. table.onclick = function (evt) {
  13812. evt = me.window.event || evt;
  13813. var target = getParentTdOrTh(evt.target || evt.srcElement);
  13814. if (!target)return;
  13815. var ut = getUETable(target),
  13816. table = ut.table,
  13817. cellInfo = ut.getCellInfo(target),
  13818. cellsRange,
  13819. rng = me.selection.getRange();
  13820. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  13821. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  13822. // ut.setSelected(cellsRange);
  13823. // return;
  13824. // }
  13825. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  13826. //
  13827. // return;
  13828. // }
  13829. if (inTableSide(table, target, evt, true)) {
  13830. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  13831. if (evt.shiftKey && ut.selectedTds.length) {
  13832. if (ut.selectedTds[0] !== endTdCol) {
  13833. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  13834. ut.setSelected(cellsRange);
  13835. } else {
  13836. rng && rng.selectNodeContents(endTdCol).select();
  13837. }
  13838. } else {
  13839. if (target !== endTdCol) {
  13840. cellsRange = ut.getCellsRange(target, endTdCol);
  13841. ut.setSelected(cellsRange);
  13842. } else {
  13843. rng && rng.selectNodeContents(endTdCol).select();
  13844. }
  13845. }
  13846. return;
  13847. }
  13848. if (inTableSide(table, target, evt)) {
  13849. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  13850. if (evt.shiftKey && ut.selectedTds.length) {
  13851. if (ut.selectedTds[0] !== endTdRow) {
  13852. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  13853. ut.setSelected(cellsRange);
  13854. } else {
  13855. rng && rng.selectNodeContents(endTdRow).select();
  13856. }
  13857. } else {
  13858. if (target !== endTdRow) {
  13859. cellsRange = ut.getCellsRange(target, endTdRow);
  13860. ut.setSelected(cellsRange);
  13861. } else {
  13862. rng && rng.selectNodeContents(endTdRow).select();
  13863. }
  13864. }
  13865. }
  13866. };
  13867. table.ondblclick = function (evt) {
  13868. evt = me.window.event || evt;
  13869. var target = getParentTdOrTh(evt.target || evt.srcElement);
  13870. if (target) {
  13871. var h;
  13872. if (h = getRelation(target, mouseCoords(evt))) {
  13873. if (h == 'h1') {
  13874. h = 'h';
  13875. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  13876. me.execCommand('adaptbywindow');
  13877. } else {
  13878. target = getUETable(target).getPreviewCell(target);
  13879. if (target) {
  13880. var rng = me.selection.getRange();
  13881. rng.selectNodeContents(target).setCursor(true, true)
  13882. }
  13883. }
  13884. }
  13885. if (h == 'h') {
  13886. var line;
  13887. while (line = me.document.getElementById('ue_tableDragLine')) {
  13888. domUtils.remove(line)
  13889. }
  13890. me.fireEvent('saveScene',true);
  13891. var ut = getUETable(target),
  13892. cells = ut.getSameEndPosCells(target, "x"),
  13893. table = ut.table;
  13894. table.removeAttribute("width");
  13895. utils.each(cells, function (cell) {
  13896. cell.removeAttribute("width");
  13897. });
  13898. setTimeout(function () {
  13899. var width = cells[0].offsetWidth - 20;
  13900. utils.each(cells, function (cell) {
  13901. cell.setAttribute("width", width);
  13902. })
  13903. table.setAttribute("width", table.offsetWidth);
  13904. me.fireEvent('saveScene',true);
  13905. })
  13906. }
  13907. }
  13908. }
  13909. }
  13910. });
  13911. switchBorderColor(me, true);
  13912. });
  13913. //仅IE8以上支持
  13914. if (!browser.ie || (browser.ie && browser.version > 7)) {
  13915. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  13916. }
  13917. domUtils.on(me.document, "mouseout", function (evt) {
  13918. var target = evt.target || evt.srcElement;
  13919. if (target.tagName == "TABLE") {
  13920. toggleDraggableState(me, false, "", null);
  13921. }
  13922. });
  13923. /**
  13924. * 表格隔行变色
  13925. */
  13926. me.addListener("interlacetable",function(type,table,classList){
  13927. if(!table) return;
  13928. var me = this,
  13929. rows = table.rows,
  13930. len = rows.length,
  13931. getClass = function(list,index,repeat){
  13932. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  13933. };
  13934. var index = 0,
  13935. classIndex = 0;
  13936. if( me.queryCommandState( "inserttitle" ) === -1 ) {
  13937. index = 1;
  13938. }
  13939. for(;index<len;index++, classIndex++){
  13940. rows[index].className = getClass( classList|| me.options.classList,classIndex,true);
  13941. }
  13942. });
  13943. me.addListener("uninterlacetable",function(type,table){
  13944. if(!table) return;
  13945. var me = this,
  13946. rows = table.rows,
  13947. classList = me.options.classList,
  13948. len = rows.length;
  13949. for(var i = 0;i<len;i++){
  13950. domUtils.removeClasses( rows[i], classList );
  13951. }
  13952. });
  13953. me.addListener("mousedown", mouseDownEvent);
  13954. me.addListener("mouseup", mouseUpEvent);
  13955. var currentRowIndex = 0;
  13956. me.addListener("mousedown", function () {
  13957. currentRowIndex = 0;
  13958. });
  13959. me.addListener('tabkeydown', function () {
  13960. var range = this.selection.getRange(),
  13961. common = range.getCommonAncestor(true, true),
  13962. table = domUtils.findParentByTagName(common, 'table');
  13963. if (table) {
  13964. if (domUtils.findParentByTagName(common, 'caption', true)) {
  13965. var cell = domUtils.getElementsByTagName(table, 'th td');
  13966. if (cell && cell.length) {
  13967. range.setStart(cell[0], 0).setCursor(false, true)
  13968. }
  13969. } else {
  13970. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  13971. ua = getUETable(cell);
  13972. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  13973. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  13974. if (nextCell) {
  13975. if (isEmptyBlock(nextCell)) {
  13976. range.setStart(nextCell, 0).setCursor(false, true)
  13977. } else {
  13978. range.selectNodeContents(nextCell).select()
  13979. }
  13980. } else {
  13981. me.fireEvent('saveScene');
  13982. me.__hasEnterExecCommand = true;
  13983. this.execCommand('insertrownext');
  13984. me.__hasEnterExecCommand = false;
  13985. range = this.selection.getRange();
  13986. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  13987. me.fireEvent('saveScene');
  13988. }
  13989. }
  13990. return true;
  13991. }
  13992. });
  13993. browser.ie && me.addListener('selectionchange', function () {
  13994. toggleDraggableState(this, false, "", null);
  13995. });
  13996. me.addListener("keydown", function (type, evt) {
  13997. var me = this;
  13998. //处理在表格的最后一个输入tab产生新的表格
  13999. var keyCode = evt.keyCode || evt.which;
  14000. if (keyCode == 8 || keyCode == 46) {
  14001. return;
  14002. }
  14003. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  14004. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  14005. var ut = getUETableBySelected(me);
  14006. if (!ut) return;
  14007. notCtrlKey && ut.clearSelected();
  14008. });
  14009. me.addListener("beforegetcontent", function () {
  14010. switchBorderColor(this, false);
  14011. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  14012. if (domUtils.isEmptyNode(ci)) {
  14013. ci.innerHTML = '&nbsp;'
  14014. }
  14015. });
  14016. });
  14017. me.addListener("aftergetcontent", function () {
  14018. switchBorderColor(this, true);
  14019. });
  14020. me.addListener("getAllHtml", function () {
  14021. removeSelectedClass(me.document.getElementsByTagName("td"));
  14022. });
  14023. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  14024. me.addListener("fullscreenchanged", function (type, fullscreen) {
  14025. if (!fullscreen) {
  14026. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  14027. tables = domUtils.getElementsByTagName(this.body, "table");
  14028. utils.each(tables, function (table) {
  14029. if (table.offsetWidth < me.body.offsetWidth) return false;
  14030. var tds = domUtils.getElementsByTagName(table, "td"),
  14031. backWidths = [];
  14032. utils.each(tds, function (td) {
  14033. backWidths.push(td.offsetWidth);
  14034. });
  14035. for (var i = 0, td; td = tds[i]; i++) {
  14036. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  14037. }
  14038. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  14039. });
  14040. }
  14041. });
  14042. //重写execCommand命令,用于处理框选时的处理
  14043. var oldExecCommand = me.execCommand;
  14044. me.execCommand = function (cmd) {
  14045. var me = this;
  14046. cmd = cmd.toLowerCase();
  14047. var ut = getUETableBySelected(me), tds,
  14048. range = new dom.Range(me.document),
  14049. cmdFun = me.commands[cmd] || UE.commands[cmd],
  14050. result;
  14051. if (!cmdFun) return;
  14052. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  14053. me.__hasEnterExecCommand = true;
  14054. me.fireEvent("beforeexeccommand", cmd);
  14055. tds = ut.selectedTds;
  14056. var lastState = -2, lastValue = -2, value, state;
  14057. for (var i = 0, td; td = tds[i]; i++) {
  14058. if (isEmptyBlock(td)) {
  14059. range.setStart(td, 0).setCursor(false, true)
  14060. } else {
  14061. range.selectNodeContents(td).select(true);
  14062. }
  14063. state = me.queryCommandState(cmd);
  14064. value = me.queryCommandValue(cmd);
  14065. if (state != -1) {
  14066. if (lastState !== state || lastValue !== value) {
  14067. me._ignoreContentChange = true;
  14068. result = oldExecCommand.apply(me, arguments);
  14069. me._ignoreContentChange = false;
  14070. }
  14071. lastState = me.queryCommandState(cmd);
  14072. lastValue = me.queryCommandValue(cmd);
  14073. if (domUtils.isEmptyBlock(td)) {
  14074. domUtils.fillNode(me.document, td)
  14075. }
  14076. }
  14077. }
  14078. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  14079. me.fireEvent('contentchange');
  14080. me.fireEvent("afterexeccommand", cmd);
  14081. me.__hasEnterExecCommand = false;
  14082. me._selectionChange();
  14083. } else {
  14084. result = oldExecCommand.apply(me, arguments);
  14085. }
  14086. return result;
  14087. };
  14088. });
  14089. /**
  14090. * 删除obj的宽高style,改成属性宽高
  14091. * @param obj
  14092. * @param replaceToProperty
  14093. */
  14094. function removeStyleSize(obj, replaceToProperty) {
  14095. removeStyle(obj, "width", true);
  14096. removeStyle(obj, "height", true);
  14097. }
  14098. function removeStyle(obj, styleName, replaceToProperty) {
  14099. if (obj.style[styleName]) {
  14100. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  14101. obj.style[styleName] = "";
  14102. }
  14103. }
  14104. function getParentTdOrTh(ele) {
  14105. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  14106. var td;
  14107. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  14108. return null;
  14109. }
  14110. function isEmptyBlock(node) {
  14111. var reg = new RegExp(domUtils.fillChar, 'g');
  14112. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  14113. return 0;
  14114. }
  14115. for (var n in dtd.$isNotEmpty) {
  14116. if (node.getElementsByTagName(n).length) {
  14117. return 0;
  14118. }
  14119. }
  14120. return 1;
  14121. }
  14122. function mouseCoords(evt) {
  14123. if (evt.pageX || evt.pageY) {
  14124. return { x:evt.pageX, y:evt.pageY };
  14125. }
  14126. return {
  14127. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  14128. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  14129. };
  14130. }
  14131. function mouseMoveEvent(evt) {
  14132. try {
  14133. //普通状态下鼠标移动
  14134. var target = getParentTdOrTh(evt.target || evt.srcElement),
  14135. pos;
  14136. //修改单元格大小时的鼠标移动
  14137. if (onDrag && dragTd) {
  14138. me.document.body.style.webkitUserSelect = 'none';
  14139. me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  14140. pos = mouseCoords(evt);
  14141. toggleDraggableState(me, true, "", pos, target);
  14142. if (onDrag == "h") {
  14143. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  14144. } else if (onDrag == "v") {
  14145. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  14146. }
  14147. return;
  14148. }
  14149. //当鼠标处于table上时,修改移动过程中的光标状态
  14150. if (target) {
  14151. //针对使用table作为容器的组件不触发拖拽效果
  14152. if (me.fireEvent('excludetable', target) === true)
  14153. return;
  14154. pos = mouseCoords(evt);
  14155. var state = getRelation(target, pos),
  14156. table = domUtils.findParentByTagName(target, "table", true);
  14157. if (inTableSide(table, target, evt, true)) {
  14158. //toggleCursor(pos,true,"_h");
  14159. if (me.fireEvent("excludetable", table) === true) return;
  14160. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  14161. } else if (inTableSide(table, target, evt)) {
  14162. //toggleCursor(pos,true,"_v");
  14163. if (me.fireEvent("excludetable", table) === true) return;
  14164. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  14165. } else {
  14166. //toggleCursor(pos,false,"");
  14167. me.body.style.cursor = "text";
  14168. if (/\d/.test(state)) {
  14169. state = state.replace(/\d/, '');
  14170. target = getUETable(target).getPreviewCell(target, state == "v");
  14171. }
  14172. //位于第一行的顶部或者第一列的左边时不可拖动
  14173. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  14174. }
  14175. // toggleDragButton(inTable(pos,table),table);
  14176. } else {
  14177. toggleDragButton(false, table, me);
  14178. }
  14179. } catch (e) {
  14180. showError(e);
  14181. }
  14182. }
  14183. var dragButtonTimer;
  14184. function toggleDragButton(show, table, editor) {
  14185. if (!show) {
  14186. if (dragOver)return;
  14187. dragButtonTimer = setTimeout(function () {
  14188. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  14189. }, 2000);
  14190. } else {
  14191. createDragButton(table, editor);
  14192. }
  14193. }
  14194. function createDragButton(table, editor) {
  14195. var pos = domUtils.getXY(table),
  14196. doc = table.ownerDocument;
  14197. if (dragButton && dragButton.parentNode)return dragButton;
  14198. dragButton = doc.createElement("div");
  14199. dragButton.contentEditable = false;
  14200. dragButton.innerHTML = "";
  14201. 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;";
  14202. domUtils.unSelectable(dragButton);
  14203. dragButton.onmouseover = function (evt) {
  14204. dragOver = true;
  14205. };
  14206. dragButton.onmouseout = function (evt) {
  14207. dragOver = false;
  14208. };
  14209. domUtils.on(dragButton, 'click', function (type, evt) {
  14210. doClick(evt, this);
  14211. });
  14212. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  14213. doDblClick(evt);
  14214. });
  14215. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  14216. domUtils.preventDefault(evt);
  14217. });
  14218. var timer;
  14219. function doClick(evt, button) {
  14220. // 部分浏览器下需要清理
  14221. clearTimeout(timer);
  14222. timer = setTimeout(function () {
  14223. editor.fireEvent("tableClicked", table, button);
  14224. }, 300);
  14225. }
  14226. function doDblClick(evt) {
  14227. clearTimeout(timer);
  14228. var ut = getUETable(table),
  14229. start = table.rows[0].cells[0],
  14230. end = ut.getLastCell(),
  14231. range = ut.getCellsRange(start, end);
  14232. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  14233. ut.setSelected(range);
  14234. }
  14235. doc.body.appendChild(dragButton);
  14236. }
  14237. // function inPosition(table, pos) {
  14238. // var tablePos = domUtils.getXY(table),
  14239. // width = table.offsetWidth,
  14240. // height = table.offsetHeight;
  14241. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  14242. // return "topLeft";
  14243. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  14244. // return "bottomRight";
  14245. // }
  14246. // }
  14247. function inTableSide(table, cell, evt, top) {
  14248. var pos = mouseCoords(evt),
  14249. state = getRelation(cell, pos);
  14250. if (top) {
  14251. var caption = table.getElementsByTagName("caption")[0],
  14252. capHeight = caption ? caption.offsetHeight : 0;
  14253. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  14254. } else {
  14255. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  14256. }
  14257. }
  14258. /**
  14259. * 获取拖动时允许的X轴坐标
  14260. * @param dragTd
  14261. * @param evt
  14262. */
  14263. function getPermissionX(dragTd, evt) {
  14264. var ut = getUETable(dragTd);
  14265. if (ut) {
  14266. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  14267. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  14268. mouseX = mouseCoords(evt).x,
  14269. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  14270. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  14271. return mouseX < left ? left : mouseX > right ? right : mouseX;
  14272. }
  14273. }
  14274. /**
  14275. * 获取拖动时允许的Y轴坐标
  14276. */
  14277. function getPermissionY(dragTd, evt) {
  14278. try {
  14279. var top = domUtils.getXY(dragTd).y,
  14280. mousePosY = mouseCoords(evt).y;
  14281. return mousePosY < top ? top : mousePosY;
  14282. } catch (e) {
  14283. showError(e);
  14284. }
  14285. }
  14286. /**
  14287. * 移动状态切换
  14288. */
  14289. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  14290. try {
  14291. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  14292. if (browser.ie) {
  14293. if (dir && !mousedown && !getUETableBySelected(editor)) {
  14294. getDragLine(editor, editor.document);
  14295. showDragLineAt(dir, cell);
  14296. } else {
  14297. hideDragLine(editor)
  14298. }
  14299. }
  14300. onBorder = draggable;
  14301. } catch (e) {
  14302. showError(e);
  14303. }
  14304. }
  14305. /**
  14306. * 获取鼠标与当前单元格的相对位置
  14307. * @param ele
  14308. * @param mousePos
  14309. */
  14310. function getRelation(ele, mousePos) {
  14311. var elePos = domUtils.getXY(ele);
  14312. if (elePos.x + ele.offsetWidth - mousePos.x < 4) {
  14313. return "h";
  14314. }
  14315. if (mousePos.x - elePos.x < 4) {
  14316. return 'h1'
  14317. }
  14318. if (elePos.y + ele.offsetHeight - mousePos.y < 4) {
  14319. return "v";
  14320. }
  14321. if (mousePos.y - elePos.y < 4) {
  14322. return 'v1'
  14323. }
  14324. return '';
  14325. }
  14326. function mouseDownEvent(type, evt) {
  14327. //右键菜单单独处理
  14328. if (evt.button == 2) {
  14329. var ut = getUETableBySelected(me),
  14330. flag = false;
  14331. if (ut) {
  14332. var td = getTargetTd(me, evt);
  14333. utils.each(ut.selectedTds, function (ti) {
  14334. if (ti === td) {
  14335. flag = true;
  14336. }
  14337. });
  14338. if (!flag) {
  14339. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  14340. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th"));
  14341. ut.clearSelected()
  14342. } else {
  14343. td = ut.selectedTds[0];
  14344. setTimeout(function () {
  14345. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  14346. }, 0);
  14347. }
  14348. }
  14349. return;
  14350. }
  14351. if (evt.shiftKey) {
  14352. return;
  14353. }
  14354. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  14355. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th"));
  14356. //trace:3113
  14357. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  14358. utils.each(me.document.getElementsByTagName('table'), function (t) {
  14359. t.ueTable = null;
  14360. });
  14361. startTd = getTargetTd(me, evt);
  14362. if (!startTd) return;
  14363. var table = domUtils.findParentByTagName(startTd, "table", true);
  14364. ut = getUETable(table);
  14365. ut && ut.clearSelected();
  14366. //判断当前鼠标状态
  14367. if (!onBorder) {
  14368. me.document.body.style.webkitUserSelect = '';
  14369. mousedown = true;
  14370. me.addListener('mouseover', mouseOverEvent);
  14371. } else {
  14372. if (browser.ie && browser.version < 8) return;
  14373. var state = getRelation(startTd, mouseCoords(evt));
  14374. if (/\d/.test(state)) {
  14375. state = state.replace(/\d/, '');
  14376. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  14377. }
  14378. hideDragLine(me);
  14379. var line;
  14380. while (line = me.document.getElementById('ue_tableDragLine')) {
  14381. domUtils.remove(line)
  14382. }
  14383. me.fireEvent('saveScene');
  14384. getDragLine(me, me.document);
  14385. showDragLineAt(state, startTd);
  14386. mousedown = true;
  14387. //拖动开始
  14388. onDrag = state;
  14389. dragTd = startTd;
  14390. }
  14391. }
  14392. function mouseUpEvent(type, evt) {
  14393. if (evt.button == 2)return;
  14394. var me = this;
  14395. //清除表格上原生跨选问题
  14396. var range = me.selection.getRange(),
  14397. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  14398. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  14399. if (start || end) {
  14400. if (start === end) {
  14401. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  14402. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  14403. if (start !== end) {
  14404. me.selection.clearRange()
  14405. }
  14406. } else {
  14407. me.selection.clearRange()
  14408. }
  14409. }
  14410. mousedown = false;
  14411. me.document.body.style.webkitUserSelect = '';
  14412. //拖拽状态下的mouseUP
  14413. if ((!browser.ie || (browser.ie && browser.version > 7)) && onDrag && dragTd) {
  14414. dragLine = me.document.getElementById('ue_tableDragLine');
  14415. var dragTdPos = domUtils.getXY(dragTd),
  14416. dragLinePos = domUtils.getXY(dragLine);
  14417. switch (onDrag) {
  14418. case "h":
  14419. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x - dragTd.offsetWidth);
  14420. break;
  14421. case "v":
  14422. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  14423. break;
  14424. default:
  14425. }
  14426. onDrag = "";
  14427. dragTd = null;
  14428. var line;
  14429. while (line = me.document.getElementById('ue_tableDragLine')) {
  14430. domUtils.remove(line)
  14431. }
  14432. me.fireEvent('saveScene');
  14433. line && me.document.appendChild(line);
  14434. return;
  14435. }
  14436. //正常状态下的mouseup
  14437. if (!startTd) {
  14438. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  14439. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  14440. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  14441. if (me.fireEvent("excludetable", target) === true) return;
  14442. range = new dom.Range(me.document);
  14443. range.setStart(target, 0).setCursor(false, true);
  14444. }
  14445. } else {
  14446. var ut = getUETable(startTd),
  14447. cell = ut ? ut.selectedTds[0] : null;
  14448. if (cell) {
  14449. range = new dom.Range(me.document);
  14450. if (domUtils.isEmptyBlock(cell)) {
  14451. range.setStart(cell, 0).setCursor(false, true);
  14452. } else {
  14453. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  14454. }
  14455. } else {
  14456. range = me.selection.getRange().shrinkBoundary();
  14457. if (!range.collapsed) {
  14458. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  14459. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  14460. //在table里边的不能清除
  14461. if (start && !end || !start && end || start && end && start !== end) {
  14462. range.setCursor(false, true);
  14463. }
  14464. }
  14465. }
  14466. startTd = null;
  14467. me.removeListener('mouseover', mouseOverEvent);
  14468. }
  14469. me._selectionChange(250, evt);
  14470. }
  14471. function mouseOverEvent(type, evt) {
  14472. var me = this,
  14473. tar = evt.target || evt.srcElement;
  14474. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  14475. //需要判断两个TD是否位于同一个表格内
  14476. if (startTd && currentTd &&
  14477. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  14478. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  14479. var ut = getUETable(currentTd);
  14480. if (startTd != currentTd) {
  14481. me.document.body.style.webkitUserSelect = 'none';
  14482. me.selection.getNative()[browser.ie ? 'empty' : 'removeAllRanges']();
  14483. var range = ut.getCellsRange(startTd, currentTd);
  14484. ut.setSelected(range);
  14485. } else {
  14486. me.document.body.style.webkitUserSelect = '';
  14487. ut.clearSelected();
  14488. }
  14489. }
  14490. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14491. }
  14492. function setCellHeight(cell, height, backHeight) {
  14493. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  14494. tmpHeight = backHeight + height;
  14495. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  14496. if (cell.style.height) cell.style.height = "";
  14497. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  14498. }
  14499. function getWidth(cell) {
  14500. if (!cell)return 0;
  14501. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  14502. }
  14503. function changeColWidth(cell, changeValue) {
  14504. if (Math.abs(changeValue) < 10) return;
  14505. var ut = getUETable(cell);
  14506. if (ut) {
  14507. var table = ut.table,
  14508. backTableWidth = getWidth(table),
  14509. defaultValue = getDefaultValue(me, table),
  14510. //这里不考虑一个都没有情况,如果一个都没有,可以认为该表格的结构可以精简
  14511. leftCells = ut.getSameEndPosCells(cell, "x"),
  14512. backLeftWidth = getWidth(leftCells[0]) - defaultValue.tdPadding * 2 - defaultValue.tdBorder,
  14513. rightCells = ut.getSameStartPosXCells(cell),
  14514. backRightWidth = getWidth(rightCells[0]) - defaultValue.tdPadding * 2 - defaultValue.tdBorder;
  14515. //整列被rowspan时存在
  14516. utils.each(leftCells, function (cell) {
  14517. if (cell.style.width) cell.style.width = "";
  14518. if (changeValue < 0)cell.style.wordBreak = "break-all";
  14519. cell.setAttribute("width", backLeftWidth + changeValue);
  14520. });
  14521. utils.each(rightCells, function (cell) {
  14522. if (cell.style.width) cell.style.width = "";
  14523. if (changeValue > 0)cell.style.wordBreak = "break-all";
  14524. cell.setAttribute("width", backRightWidth - changeValue);
  14525. });
  14526. //如果是在表格最右边拖动,则还需要调整表格宽度,否则在合并过的单元格中输入文字,表格会被撑开
  14527. if (!cell.nextSibling) {
  14528. if (table.style.width) table.style.width = "";
  14529. table.setAttribute("width", backTableWidth + changeValue);
  14530. }
  14531. }
  14532. }
  14533. function changeRowHeight(td, changeValue) {
  14534. if (Math.abs(changeValue) < 10) return;
  14535. var ut = getUETable(td);
  14536. if (ut) {
  14537. var cells = ut.getSameEndPosCells(td, "y"),
  14538. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  14539. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  14540. for (var i = 0, cell; cell = cells[i++];) {
  14541. setCellHeight(cell, changeValue, backHeight);
  14542. }
  14543. }
  14544. }
  14545. function getDragLine(editor, doc) {
  14546. if (mousedown)return;
  14547. dragLine = editor.document.createElement("div");
  14548. domUtils.setAttributes(dragLine, {
  14549. id:"ue_tableDragLine",
  14550. unselectable:'on',
  14551. contenteditable:false,
  14552. 'onresizestart':'return false',
  14553. 'ondragstart':'return false',
  14554. 'onselectstart':'return false',
  14555. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  14556. });
  14557. editor.body.appendChild(dragLine);
  14558. }
  14559. function hideDragLine(editor) {
  14560. if (mousedown)return;
  14561. var line;
  14562. while (line = editor.document.getElementById('ue_tableDragLine')) {
  14563. domUtils.remove(line)
  14564. }
  14565. }
  14566. /**
  14567. * 依据state(v|h)在cell位置显示横线
  14568. * @param state
  14569. * @param cell
  14570. */
  14571. function showDragLineAt(state, cell) {
  14572. if (!cell) return;
  14573. var table = domUtils.findParentByTagName(cell, "table"),
  14574. caption = table.getElementsByTagName('caption'),
  14575. width = table.offsetWidth,
  14576. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  14577. tablePos = domUtils.getXY(table),
  14578. cellPos = domUtils.getXY(cell), css;
  14579. switch (state) {
  14580. case "h":
  14581. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth - 2);
  14582. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  14583. break;
  14584. case "v":
  14585. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight - 2 );
  14586. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  14587. 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)';
  14588. break;
  14589. default:
  14590. }
  14591. }
  14592. /**
  14593. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  14594. * @param editor
  14595. * @param flag
  14596. */
  14597. function switchBorderColor(editor, flag) {
  14598. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  14599. for (var i = 0, node; node = tableArr[i++];) {
  14600. var td = domUtils.getElementsByTagName(node, "td");
  14601. if (td[0]) {
  14602. if (flag) {
  14603. color = (td[0].style.borderColor).replace(/\s/g, "");
  14604. if (/(#ffffff)|(rgb\(255,f55,255\))/ig.test(color))
  14605. domUtils.addClass(node, "noBorderTable")
  14606. } else {
  14607. domUtils.removeClasses(node, "noBorderTable")
  14608. }
  14609. }
  14610. }
  14611. }
  14612. function getTableWidth(editor, needIEHack, defaultValue) {
  14613. var body = editor.body;
  14614. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  14615. }
  14616. function getTargetTd(editor, evt) {
  14617. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true);
  14618. //排除了非td内部以及用于代码高亮部分的td
  14619. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  14620. }
  14621. };
  14622. ///import core
  14623. ///commands 右键菜单
  14624. ///commandsName ContextMenu
  14625. ///commandsTitle 右键菜单
  14626. /**
  14627. * 右键菜单
  14628. * @function
  14629. * @name baidu.editor.plugins.contextmenu
  14630. * @author zhanyi
  14631. */
  14632. UE.plugins['contextmenu'] = function () {
  14633. var me = this,
  14634. lang = me.getLang( "contextMenu" ),
  14635. menu,
  14636. items = me.options.contextMenu || [
  14637. {label:lang['selectall'], cmdName:'selectall'},
  14638. {
  14639. label:lang.deletecode,
  14640. cmdName:'highlightcode',
  14641. icon:'deletehighlightcode'
  14642. },
  14643. {
  14644. label:lang.cleardoc,
  14645. cmdName:'cleardoc',
  14646. exec:function () {
  14647. if ( confirm( lang.confirmclear ) ) {
  14648. this.execCommand( 'cleardoc' );
  14649. }
  14650. }
  14651. },
  14652. {
  14653. label:lang.insertword,
  14654. cmdName:'insertword',
  14655. exec:function () {
  14656. this.execCommand( 'insertword' );
  14657. }
  14658. },
  14659. '-',
  14660. {
  14661. label:lang.unlink,
  14662. cmdName:'unlink'
  14663. },
  14664. '-',
  14665. {
  14666. group:lang.paragraph,
  14667. icon:'justifyjustify',
  14668. subMenu:[
  14669. {
  14670. label:lang.justifyleft,
  14671. cmdName:'justify',
  14672. value:'left'
  14673. },
  14674. {
  14675. label:lang.justifyright,
  14676. cmdName:'justify',
  14677. value:'right'
  14678. },
  14679. {
  14680. label:lang.justifycenter,
  14681. cmdName:'justify',
  14682. value:'center'
  14683. },
  14684. {
  14685. label:lang.justifyjustify,
  14686. cmdName:'justify',
  14687. value:'justify'
  14688. }
  14689. ]
  14690. },
  14691. '-',
  14692. {
  14693. group:lang.table,
  14694. icon:'table',
  14695. subMenu:[
  14696. {
  14697. label:lang.inserttable,
  14698. cmdName:'inserttable'
  14699. },
  14700. {
  14701. label:lang.deletetable,
  14702. cmdName:'deletetable'
  14703. },
  14704. '-',
  14705. {
  14706. label:lang.deleterow,
  14707. cmdName:'deleterow'
  14708. },
  14709. {
  14710. label:lang.deletecol,
  14711. cmdName:'deletecol'
  14712. },
  14713. {
  14714. label:lang.insertcol,
  14715. cmdName:'insertcol'
  14716. },
  14717. {
  14718. label:lang.insertcolnext,
  14719. cmdName:'insertcolnext'
  14720. },
  14721. {
  14722. label:lang.insertrow,
  14723. cmdName:'insertrow'
  14724. },
  14725. {
  14726. label:lang.insertrownext,
  14727. cmdName:'insertrownext'
  14728. },
  14729. '-',
  14730. {
  14731. label:lang.insertcaption,
  14732. cmdName:'insertcaption'
  14733. },
  14734. {
  14735. label:lang.deletecaption,
  14736. cmdName:'deletecaption'
  14737. },
  14738. {
  14739. label:lang.inserttitle,
  14740. cmdName:'inserttitle'
  14741. },
  14742. {
  14743. label:lang.deletetitle,
  14744. cmdName:'deletetitle'
  14745. },
  14746. '-',
  14747. {
  14748. label:lang.mergecells,
  14749. cmdName:'mergecells'
  14750. },
  14751. {
  14752. label:lang.mergeright,
  14753. cmdName:'mergeright'
  14754. },
  14755. {
  14756. label:lang.mergedown,
  14757. cmdName:'mergedown'
  14758. },
  14759. '-',
  14760. {
  14761. label:lang.splittorows,
  14762. cmdName:'splittorows'
  14763. },
  14764. {
  14765. label:lang.splittocols,
  14766. cmdName:'splittocols'
  14767. },
  14768. {
  14769. label:lang.splittocells,
  14770. cmdName:'splittocells'
  14771. },
  14772. '-',
  14773. {
  14774. label:lang.averageDiseRow,
  14775. cmdName:'averagedistributerow'
  14776. },
  14777. {
  14778. label:lang.averageDisCol,
  14779. cmdName:'averagedistributecol'
  14780. },
  14781. '-',
  14782. {
  14783. label:lang.edittd,
  14784. cmdName:'edittd',
  14785. exec:function () {
  14786. if ( UE.ui['edittd'] ) {
  14787. new UE.ui['edittd']( this );
  14788. }
  14789. this.getDialog('edittd').open();
  14790. }
  14791. },
  14792. {
  14793. label:lang.edittable,
  14794. cmdName:'edittable',
  14795. exec:function () {
  14796. if ( UE.ui['edittable'] ) {
  14797. new UE.ui['edittable']( this );
  14798. }
  14799. this.getDialog('edittable').open();
  14800. }
  14801. }
  14802. ]
  14803. },
  14804. {
  14805. group:lang.tablesort,
  14806. icon:'tablesort',
  14807. subMenu:[
  14808. {
  14809. label:lang.reversecurrent,
  14810. cmdName:'sorttable',
  14811. value:1
  14812. },
  14813. {
  14814. label:lang.orderbyasc,
  14815. cmdName:'sorttable'
  14816. },
  14817. {
  14818. label:lang.reversebyasc,
  14819. cmdName:'sorttable',
  14820. exec:function(){
  14821. this.execCommand("sorttable",function(td1,td2){
  14822. var value1 = td1.innerHTML,
  14823. value2 = td2.innerHTML;
  14824. return value2.localeCompare(value1);
  14825. });
  14826. }
  14827. },
  14828. {
  14829. label:lang.orderbynum,
  14830. cmdName:'sorttable',
  14831. exec:function(){
  14832. this.execCommand("sorttable",function(td1,td2){
  14833. var value1 = td1.innerHTML.match(/\d+/),
  14834. value2 = td2.innerHTML.match(/\d+/);
  14835. if(value1) value1 = +value1[0];
  14836. if(value2) value2 = +value2[0];
  14837. return (value1||0) - (value2||0);
  14838. });
  14839. }
  14840. },
  14841. {
  14842. label:lang.reversebynum,
  14843. cmdName:'sorttable',
  14844. exec:function(){
  14845. this.execCommand("sorttable",function(td1,td2){
  14846. var value1 = td1.innerHTML.match(/\d+/),
  14847. value2 = td2.innerHTML.match(/\d+/);
  14848. if(value1) value1 = +value1[0];
  14849. if(value2) value2 = +value2[0];
  14850. return (value2||0) - (value1||0);
  14851. });
  14852. }
  14853. }
  14854. ]
  14855. },
  14856. {
  14857. group:lang.borderbk,
  14858. icon:'borderBack',
  14859. subMenu:[
  14860. {
  14861. label:lang.setcolor,
  14862. cmdName:"interlacetable",
  14863. exec:function(){
  14864. this.execCommand("interlacetable");
  14865. }
  14866. },
  14867. {
  14868. label:lang.unsetcolor,
  14869. cmdName:"uninterlacetable",
  14870. exec:function(){
  14871. this.execCommand("uninterlacetable");
  14872. }
  14873. },
  14874. {
  14875. label:lang.setbackground,
  14876. cmdName:"settablebackground",
  14877. exec:function(){
  14878. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  14879. }
  14880. },
  14881. {
  14882. label:lang.unsetbackground,
  14883. cmdName:"cleartablebackground",
  14884. exec:function(){
  14885. this.execCommand("cleartablebackground");
  14886. }
  14887. },
  14888. {
  14889. label:lang.redandblue,
  14890. cmdName:"settablebackground",
  14891. exec:function(){
  14892. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  14893. }
  14894. },
  14895. {
  14896. label:lang.threecolorgradient,
  14897. cmdName:"settablebackground",
  14898. exec:function(){
  14899. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  14900. }
  14901. }
  14902. ]
  14903. },
  14904. {
  14905. group:lang.aligntd,
  14906. icon:'aligntd',
  14907. subMenu:[
  14908. {
  14909. cmdName:'cellalignment',
  14910. value:{align:'left',vAlign:'top'}
  14911. },
  14912. {
  14913. cmdName:'cellalignment',
  14914. value:{align:'center',vAlign:'top'}
  14915. },
  14916. {
  14917. cmdName:'cellalignment',
  14918. value:{align:'right',vAlign:'top'}
  14919. },
  14920. {
  14921. cmdName:'cellalignment',
  14922. value:{align:'left',vAlign:'middle'}
  14923. },
  14924. {
  14925. cmdName:'cellalignment',
  14926. value:{align:'center',vAlign:'middle'}
  14927. },
  14928. {
  14929. cmdName:'cellalignment',
  14930. value:{align:'right',vAlign:'middle'}
  14931. },
  14932. {
  14933. cmdName:'cellalignment',
  14934. value:{align:'left',vAlign:'bottom'}
  14935. },
  14936. {
  14937. cmdName:'cellalignment',
  14938. value:{align:'center',vAlign:'bottom'}
  14939. },
  14940. {
  14941. cmdName:'cellalignment',
  14942. value:{align:'right',vAlign:'bottom'}
  14943. }
  14944. ]
  14945. },
  14946. {
  14947. group:lang.aligntable,
  14948. icon:'aligntable',
  14949. subMenu:[
  14950. {
  14951. cmdName:'tablealignment',
  14952. className: 'left',
  14953. label:lang.tableleft,
  14954. value:"left"
  14955. },
  14956. {
  14957. cmdName:'tablealignment',
  14958. className: 'center',
  14959. label:lang.tablecenter,
  14960. value:"center"
  14961. },
  14962. {
  14963. cmdName:'tablealignment',
  14964. className: 'right',
  14965. label:lang.tableright,
  14966. value:"right"
  14967. }
  14968. ]
  14969. },
  14970. '-',
  14971. {
  14972. label:lang.insertparagraphbefore,
  14973. cmdName:'insertparagraph',
  14974. value:true
  14975. },
  14976. {
  14977. label:lang.insertparagraphafter,
  14978. cmdName:'insertparagraph'
  14979. },
  14980. {
  14981. label:lang['copy'],
  14982. cmdName:'copy',
  14983. exec:function () {
  14984. alert( lang.copymsg );
  14985. },
  14986. query:function () {
  14987. return 0;
  14988. }
  14989. },
  14990. {
  14991. label:lang['paste'],
  14992. cmdName:'paste',
  14993. exec:function () {
  14994. alert( lang.pastemsg );
  14995. },
  14996. query:function () {
  14997. return 0;
  14998. }
  14999. },{
  15000. label:lang['highlightcode'],
  15001. cmdName:'highlightcode',
  15002. exec:function () {
  15003. if ( UE.ui['highlightcode'] ) {
  15004. new UE.ui['highlightcode']( this );
  15005. }
  15006. this.ui._dialogs['highlightcodeDialog'].open();
  15007. }
  15008. }
  15009. ];
  15010. if ( !items.length ) {
  15011. return;
  15012. }
  15013. var uiUtils = UE.ui.uiUtils;
  15014. me.addListener( 'contextmenu', function ( type, evt ) {
  15015. var offset = uiUtils.getViewportOffsetByEvent( evt );
  15016. me.fireEvent( 'beforeselectionchange' );
  15017. if ( menu ) {
  15018. menu.destroy();
  15019. }
  15020. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  15021. var last;
  15022. (function ( item ) {
  15023. if ( item == '-' ) {
  15024. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  15025. contextItems.push( '-' );
  15026. }
  15027. } else if ( item.hasOwnProperty( "group" ) ) {
  15028. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  15029. (function ( subItem ) {
  15030. if ( subItem == '-' ) {
  15031. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  15032. subMenu.push( '-' );
  15033. }else{
  15034. subMenu.splice(subMenu.length-1);
  15035. }
  15036. } else {
  15037. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  15038. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  15039. subMenu.push( {
  15040. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  15041. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  15042. onclick:subItem.exec ? function () {
  15043. subItem.exec.call( me );
  15044. } : function () {
  15045. me.execCommand( subItem.cmdName, subItem.value );
  15046. }
  15047. } );
  15048. }
  15049. }
  15050. })( cj );
  15051. }
  15052. if ( subMenu.length ) {
  15053. function getLabel(){
  15054. switch (item.icon){
  15055. case "table":
  15056. return me.getLang( "contextMenu.table" );
  15057. case "justifyjustify":
  15058. return me.getLang( "contextMenu.paragraph" );
  15059. case "aligntd":
  15060. return me.getLang("contextMenu.aligntd");
  15061. case "aligntable":
  15062. return me.getLang("contextMenu.aligntable");
  15063. case "tablesort":
  15064. return lang.tablesort;
  15065. case "borderBack":
  15066. return lang.borderbk;
  15067. default :
  15068. return '';
  15069. }
  15070. }
  15071. contextItems.push( {
  15072. //todo 修正成自动获取方式
  15073. 'label':getLabel(),
  15074. className:'edui-for-' + item.icon,
  15075. 'subMenu':{
  15076. items:subMenu,
  15077. editor:me
  15078. }
  15079. } );
  15080. }
  15081. } else {
  15082. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  15083. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  15084. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  15085. //highlight todo
  15086. if ( item.cmdName == 'highlightcode' ) {
  15087. if(me.queryCommandState( item.cmdName ) == 1 && item.icon != 'deletehighlightcode'){
  15088. return;
  15089. }
  15090. if(me.queryCommandState( item.cmdName ) != 1 && item.icon == 'deletehighlightcode'){
  15091. return;
  15092. }
  15093. }
  15094. contextItems.push( {
  15095. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  15096. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  15097. onclick:item.exec ? function () {
  15098. item.exec.call( me );
  15099. } : function () {
  15100. me.execCommand( item.cmdName, item.value );
  15101. }
  15102. } );
  15103. }
  15104. }
  15105. })( ti );
  15106. }
  15107. if ( contextItems[contextItems.length - 1] == '-' ) {
  15108. contextItems.pop();
  15109. }
  15110. menu = new UE.ui.Menu( {
  15111. items:contextItems,
  15112. editor:me
  15113. } );
  15114. menu.render();
  15115. menu.showAt( offset );
  15116. domUtils.preventDefault( evt );
  15117. if ( browser.ie ) {
  15118. var ieRange;
  15119. try {
  15120. ieRange = me.selection.getNative().createRange();
  15121. } catch ( e ) {
  15122. return;
  15123. }
  15124. if ( ieRange.item ) {
  15125. var range = new dom.Range( me.document );
  15126. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  15127. }
  15128. }
  15129. } );
  15130. };
  15131. ///import core
  15132. ///commands 加粗,斜体,上标,下标
  15133. ///commandsName Bold,Italic,Subscript,Superscript
  15134. ///commandsTitle 加粗,加斜,下标,上标
  15135. /**
  15136. * b u i等基础功能实现
  15137. * @function
  15138. * @name baidu.editor.execCommands
  15139. * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。
  15140. */
  15141. UE.plugins['basestyle'] = function(){
  15142. var basestyles = {
  15143. 'bold':['strong','b'],
  15144. 'italic':['em','i'],
  15145. 'subscript':['sub'],
  15146. 'superscript':['sup']
  15147. },
  15148. getObj = function(editor,tagNames){
  15149. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  15150. },
  15151. me = this;
  15152. //添加快捷键
  15153. me.addshortcutkey({
  15154. "Bold" : "ctrl+66",//^B
  15155. "Italic" : "ctrl+73", //^I
  15156. "Underline" : "ctrl+85"//^U
  15157. });
  15158. me.addInputRule(function(root){
  15159. utils.each(root.getNodesByTagName('b i'),function(node){
  15160. switch (node.tagName){
  15161. case 'b':
  15162. node.tagName = 'strong';
  15163. break;
  15164. case 'i':
  15165. node.tagName = 'em';
  15166. }
  15167. });
  15168. });
  15169. for ( var style in basestyles ) {
  15170. (function( cmd, tagNames ) {
  15171. me.commands[cmd] = {
  15172. execCommand : function( cmdName ) {
  15173. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  15174. if ( range.collapsed ) {
  15175. if ( obj ) {
  15176. var tmpText = me.document.createTextNode('');
  15177. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  15178. range.setStartBefore(tmpText);
  15179. domUtils.remove(tmpText);
  15180. } else {
  15181. var tmpNode = range.document.createElement( tagNames[0] );
  15182. if(cmdName == 'superscript' || cmdName == 'subscript'){
  15183. tmpText = me.document.createTextNode('');
  15184. range.insertNode(tmpText)
  15185. .removeInlineStyle(['sub','sup'])
  15186. .setStartBefore(tmpText)
  15187. .collapse(true);
  15188. }
  15189. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  15190. }
  15191. range.collapse( true );
  15192. } else {
  15193. if(cmdName == 'superscript' || cmdName == 'subscript'){
  15194. if(!obj || obj.tagName.toLowerCase() != cmdName){
  15195. range.removeInlineStyle(['sub','sup']);
  15196. }
  15197. }
  15198. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  15199. }
  15200. range.select();
  15201. },
  15202. queryCommandState : function() {
  15203. return getObj(this,tagNames) ? 1 : 0;
  15204. }
  15205. };
  15206. })( style, basestyles[style] );
  15207. }
  15208. };
  15209. ///import core
  15210. ///commands 选区路径
  15211. ///commandsName ElementPath,elementPathEnabled
  15212. ///commandsTitle 选区路径
  15213. /**
  15214. * 选区路径
  15215. * @function
  15216. * @name baidu.editor.execCommand
  15217. * @param {String} cmdName elementpath选区路径
  15218. */
  15219. UE.plugins['elementpath'] = function(){
  15220. var currentLevel,
  15221. tagNames,
  15222. me = this;
  15223. me.setOpt('elementPathEnabled',true);
  15224. if(!me.options.elementPathEnabled){
  15225. return;
  15226. }
  15227. me.commands['elementpath'] = {
  15228. execCommand : function( cmdName, level ) {
  15229. var start = tagNames[level],
  15230. range = me.selection.getRange();
  15231. currentLevel = level*1;
  15232. range.selectNode(start).select();
  15233. },
  15234. queryCommandValue : function() {
  15235. //产生一个副本,不能修改原来的startElementPath;
  15236. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  15237. names = [];
  15238. tagNames = parents;
  15239. for(var i=0,ci;ci=parents[i];i++){
  15240. if(ci.nodeType == 3) {
  15241. continue;
  15242. }
  15243. var name = ci.tagName.toLowerCase();
  15244. if(name == 'img' && ci.getAttribute('anchorname')){
  15245. name = 'anchor';
  15246. }
  15247. names[i] = name;
  15248. if(currentLevel == i){
  15249. currentLevel = -1;
  15250. break;
  15251. }
  15252. }
  15253. return names;
  15254. }
  15255. };
  15256. };
  15257. ///import core
  15258. ///import plugins\removeformat.js
  15259. ///commands 格式刷
  15260. ///commandsName FormatMatch
  15261. ///commandsTitle 格式刷
  15262. /**
  15263. * 格式刷,只格式inline的
  15264. * @function
  15265. * @name baidu.editor.execCommand
  15266. * @param {String} cmdName formatmatch执行格式刷
  15267. */
  15268. UE.plugins['formatmatch'] = function(){
  15269. var me = this,
  15270. list = [],img,
  15271. flag = 0;
  15272. me.addListener('reset',function(){
  15273. list = [];
  15274. flag = 0;
  15275. });
  15276. function addList(type,evt){
  15277. if(browser.webkit){
  15278. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  15279. }
  15280. function addFormat(range){
  15281. if(text){
  15282. range.selectNode(text);
  15283. }
  15284. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  15285. }
  15286. me.undoManger && me.undoManger.save();
  15287. var range = me.selection.getRange(),
  15288. imgT = target || range.getClosedNode();
  15289. if(img && imgT && imgT.tagName == 'IMG'){
  15290. //trace:964
  15291. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  15292. img = null;
  15293. }else{
  15294. if(!img){
  15295. var collapsed = range.collapsed;
  15296. if(collapsed){
  15297. var text = me.document.createTextNode('match');
  15298. range.insertNode(text).select();
  15299. }
  15300. me.__hasEnterExecCommand = true;
  15301. //不能把block上的属性干掉
  15302. //trace:1553
  15303. var removeFormatAttributes = me.options.removeFormatAttributes;
  15304. me.options.removeFormatAttributes = '';
  15305. me.execCommand('removeformat');
  15306. me.options.removeFormatAttributes = removeFormatAttributes;
  15307. me.__hasEnterExecCommand = false;
  15308. //trace:969
  15309. range = me.selection.getRange();
  15310. if(list.length){
  15311. addFormat(range);
  15312. }
  15313. if(text){
  15314. range.setStartBefore(text).collapse(true);
  15315. }
  15316. range.select();
  15317. text && domUtils.remove(text);
  15318. }
  15319. }
  15320. me.undoManger && me.undoManger.save();
  15321. me.removeListener('mouseup',addList);
  15322. flag = 0;
  15323. }
  15324. me.commands['formatmatch'] = {
  15325. execCommand : function( cmdName ) {
  15326. if(flag){
  15327. flag = 0;
  15328. list = [];
  15329. me.removeListener('mouseup',addList);
  15330. return;
  15331. }
  15332. var range = me.selection.getRange();
  15333. img = range.getClosedNode();
  15334. if(!img || img.tagName != 'IMG'){
  15335. range.collapse(true).shrinkBoundary();
  15336. var start = range.startContainer;
  15337. list = domUtils.findParents(start,true,function(node){
  15338. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  15339. });
  15340. //a不能加入格式刷, 并且克隆节点
  15341. for(var i=0,ci;ci=list[i];i++){
  15342. if(ci.tagName == 'A'){
  15343. list.splice(i,1);
  15344. break;
  15345. }
  15346. }
  15347. }
  15348. me.addListener('mouseup',addList);
  15349. flag = 1;
  15350. },
  15351. queryCommandState : function() {
  15352. return flag;
  15353. },
  15354. notNeedUndo : 1
  15355. };
  15356. };
  15357. ///import core
  15358. ///commands 查找替换
  15359. ///commandsName SearchReplace
  15360. ///commandsTitle 查询替换
  15361. ///commandsDialog dialogs\searchreplace
  15362. /**
  15363. * @description 查找替换
  15364. * @author zhanyi
  15365. */
  15366. UE.plugins['searchreplace'] = function(){
  15367. var currentRange,
  15368. first,
  15369. me = this;
  15370. me.addListener('reset',function(){
  15371. currentRange = null;
  15372. first = null;
  15373. });
  15374. me.commands['searchreplace'] = {
  15375. execCommand : function(cmdName,opt){
  15376. var me = this,
  15377. sel = me.selection,
  15378. range,
  15379. nativeRange,
  15380. num = 0,
  15381. opt = utils.extend(opt,{
  15382. all : false,
  15383. casesensitive : false,
  15384. dir : 1
  15385. },true);
  15386. if(browser.ie){
  15387. me.focus();
  15388. while(1){
  15389. var tmpRange;
  15390. nativeRange = me.document.selection.createRange();
  15391. tmpRange = nativeRange.duplicate();
  15392. tmpRange.moveToElementText(me.document.body);
  15393. if(opt.all){
  15394. first = 0;
  15395. opt.dir = 1;
  15396. if(currentRange){
  15397. tmpRange.setEndPoint(opt.dir == -1 ? 'EndToStart' : 'StartToEnd',currentRange);
  15398. }else{
  15399. tmpRange.moveToElementText(me.document.body);
  15400. }
  15401. }else{
  15402. tmpRange.setEndPoint(opt.dir == -1 ? 'EndToStart' : 'StartToEnd',nativeRange);
  15403. if(opt.hasOwnProperty("replaceStr")){
  15404. tmpRange.setEndPoint(opt.dir == -1 ? 'StartToEnd' : 'EndToStart',nativeRange);
  15405. }
  15406. }
  15407. nativeRange = tmpRange.duplicate();
  15408. if(!tmpRange.findText(opt.searchStr,opt.dir,opt.casesensitive ? 4 : 0)){
  15409. currentRange = null;
  15410. tmpRange = me.document.selection.createRange();
  15411. tmpRange.scrollIntoView();
  15412. return num;
  15413. }
  15414. tmpRange.select();
  15415. //替换
  15416. if(opt.hasOwnProperty("replaceStr")){
  15417. range = sel.getRange();
  15418. range.deleteContents().insertNode(range.document.createTextNode(opt.replaceStr)).select();
  15419. currentRange = sel.getNative().createRange();
  15420. }
  15421. num++;
  15422. if(!opt.all){
  15423. break;
  15424. }
  15425. }
  15426. }else{
  15427. var w = me.window,nativeSel = sel.getNative(),tmpRange;
  15428. while(1){
  15429. if(opt.all){
  15430. if(currentRange){
  15431. currentRange.collapse(false);
  15432. nativeRange = currentRange;
  15433. }else{
  15434. nativeRange = me.document.createRange();
  15435. nativeRange.setStart(me.document.body,0);
  15436. nativeRange.collapse(true);
  15437. }
  15438. nativeSel.removeAllRanges();
  15439. nativeSel.addRange( nativeRange );
  15440. first = 0;
  15441. opt.dir = 1;
  15442. }else{
  15443. //safari弹出层,原生已经找不到range了,所以需要先选回来,再取原生
  15444. if(browser.safari){
  15445. me.selection.getRange().select();
  15446. }
  15447. var nativeSel = w.getSelection();
  15448. if(!nativeSel.rangeCount){
  15449. nativeRange = me.document.createRange();
  15450. nativeRange.setStart(me.body,0);
  15451. nativeRange.collapse(true);
  15452. nativeSel.addRange(nativeRange);
  15453. }else{
  15454. nativeRange = nativeSel.getRangeAt(0);
  15455. }
  15456. if(opt.hasOwnProperty("replaceStr")){
  15457. nativeRange.collapse(opt.dir == 1 ? true : false);
  15458. }
  15459. }
  15460. //如果是第一次并且海选中了内容那就要清除,为find做准备
  15461. if(!first){
  15462. nativeRange.collapse( opt.dir <0 ? true : false);
  15463. nativeSel.removeAllRanges();
  15464. nativeSel.addRange( nativeRange );
  15465. }else{
  15466. nativeSel.removeAllRanges();
  15467. }
  15468. if(!w.find(opt.searchStr,opt.casesensitive,opt.dir < 0 ? true : false) ) {
  15469. currentRange = null;
  15470. nativeSel.removeAllRanges();
  15471. return num;
  15472. }
  15473. first = 0;
  15474. range = w.getSelection().getRangeAt(0);
  15475. if(!range.collapsed){
  15476. if(opt.hasOwnProperty("replaceStr")){
  15477. range.deleteContents();
  15478. var text = w.document.createTextNode(opt.replaceStr);
  15479. range.insertNode(text);
  15480. range.selectNode(text);
  15481. nativeSel.addRange(range);
  15482. currentRange = range.cloneRange();
  15483. }
  15484. }
  15485. num++;
  15486. if(!opt.all){
  15487. break;
  15488. }
  15489. }
  15490. }
  15491. return true;
  15492. }
  15493. };
  15494. };
  15495. ///import core
  15496. ///commands 自定义样式
  15497. ///commandsName CustomStyle
  15498. ///commandsTitle 自定义样式
  15499. UE.plugins['customstyle'] = function() {
  15500. var me = this;
  15501. me.setOpt({ 'customstyle':[
  15502. {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;'},
  15503. {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;'},
  15504. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  15505. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  15506. ]});
  15507. me.commands['customstyle'] = {
  15508. execCommand : function(cmdName, obj) {
  15509. var me = this,
  15510. tagName = obj.tag,
  15511. node = domUtils.findParent(me.selection.getStart(), function(node) {
  15512. return node.getAttribute('label');
  15513. }, true),
  15514. range,bk,tmpObj = {};
  15515. for (var p in obj) {
  15516. if(obj[p]!==undefined)
  15517. tmpObj[p] = obj[p];
  15518. }
  15519. delete tmpObj.tag;
  15520. if (node && node.getAttribute('label') == obj.label) {
  15521. range = this.selection.getRange();
  15522. bk = range.createBookmark();
  15523. if (range.collapsed) {
  15524. //trace:1732 删掉自定义标签,要有p来回填站位
  15525. if(dtd.$block[node.tagName]){
  15526. var fillNode = me.document.createElement('p');
  15527. domUtils.moveChild(node, fillNode);
  15528. node.parentNode.insertBefore(fillNode, node);
  15529. domUtils.remove(node);
  15530. }else{
  15531. domUtils.remove(node,true);
  15532. }
  15533. } else {
  15534. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  15535. nodes = domUtils.getElementsByTagName(common, tagName);
  15536. if(new RegExp(tagName,'i').test(common.tagName)){
  15537. nodes.push(common);
  15538. }
  15539. for (var i = 0,ni; ni = nodes[i++];) {
  15540. if (ni.getAttribute('label') == obj.label) {
  15541. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  15542. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  15543. &&
  15544. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  15545. )
  15546. if (dtd.$block[tagName]) {
  15547. var fillNode = me.document.createElement('p');
  15548. domUtils.moveChild(ni, fillNode);
  15549. ni.parentNode.insertBefore(fillNode, ni);
  15550. }
  15551. domUtils.remove(ni, true);
  15552. }
  15553. }
  15554. node = domUtils.findParent(common, function(node) {
  15555. return node.getAttribute('label') == obj.label;
  15556. }, true);
  15557. if (node) {
  15558. domUtils.remove(node, true);
  15559. }
  15560. }
  15561. range.moveToBookmark(bk).select();
  15562. } else {
  15563. if (dtd.$block[tagName]) {
  15564. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  15565. range = me.selection.getRange();
  15566. if (!range.collapsed) {
  15567. range.collapse();
  15568. node = domUtils.findParent(me.selection.getStart(), function(node) {
  15569. return node.getAttribute('label') == obj.label;
  15570. }, true);
  15571. var pNode = me.document.createElement('p');
  15572. domUtils.insertAfter(node, pNode);
  15573. domUtils.fillNode(me.document, pNode);
  15574. range.setStart(pNode, 0).setCursor();
  15575. }
  15576. } else {
  15577. range = me.selection.getRange();
  15578. if (range.collapsed) {
  15579. node = me.document.createElement(tagName);
  15580. domUtils.setAttributes(node, tmpObj);
  15581. range.insertNode(node).setStart(node, 0).setCursor();
  15582. return;
  15583. }
  15584. bk = range.createBookmark();
  15585. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  15586. }
  15587. }
  15588. },
  15589. queryCommandValue : function() {
  15590. var parent = domUtils.filterNodeList(
  15591. this.selection.getStartElementPath(),
  15592. function(node){return node.getAttribute('label')}
  15593. );
  15594. return parent ? parent.getAttribute('label') : '';
  15595. }
  15596. };
  15597. //当去掉customstyle是,如果是块元素,用p代替
  15598. me.addListener('keyup', function(type, evt) {
  15599. var keyCode = evt.keyCode || evt.which;
  15600. if (keyCode == 32 || keyCode == 13) {
  15601. var range = me.selection.getRange();
  15602. if (range.collapsed) {
  15603. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  15604. return node.getAttribute('label');
  15605. }, true);
  15606. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  15607. var p = me.document.createElement('p');
  15608. domUtils.insertAfter(node, p);
  15609. domUtils.fillNode(me.document, p);
  15610. domUtils.remove(node);
  15611. range.setStart(p, 0).setCursor();
  15612. }
  15613. }
  15614. }
  15615. });
  15616. };
  15617. ///import core
  15618. ///commands 远程图片抓取
  15619. ///commandsName catchRemoteImage,catchremoteimageenable
  15620. ///commandsTitle 远程图片抓取
  15621. /**
  15622. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  15623. *
  15624. */
  15625. UE.plugins['catchremoteimage'] = function () {
  15626. if (this.options.catchRemoteImageEnable===false){
  15627. return;
  15628. }
  15629. var me = this;
  15630. this.setOpt({
  15631. localDomain:["127.0.0.1","localhost","img.baidu.com"],
  15632. separater:'ue_separate_ue',
  15633. catchFieldName:"upfile",
  15634. catchRemoteImageEnable:true
  15635. });
  15636. var ajax = UE.ajax,
  15637. localDomain = me.options.localDomain ,
  15638. catcherUrl = me.options.catcherUrl,
  15639. separater = me.options.separater;
  15640. function catchremoteimage(imgs, callbacks) {
  15641. var submitStr = imgs.join(separater);
  15642. var tmpOption = {
  15643. timeout:60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  15644. onsuccess:callbacks["success"],
  15645. onerror:callbacks["error"]
  15646. };
  15647. tmpOption[me.options.catchFieldName] = submitStr;
  15648. ajax.request(catcherUrl, tmpOption);
  15649. }
  15650. me.addListener("afterpaste", function () {
  15651. me.fireEvent("catchRemoteImage");
  15652. });
  15653. me.addListener("catchRemoteImage", function () {
  15654. var remoteImages = [];
  15655. var imgs = domUtils.getElementsByTagName(me.document, "img");
  15656. var test = function (src,urls) {
  15657. for (var j = 0, url; url = urls[j++];) {
  15658. if (src.indexOf(url) !== -1) {
  15659. return true;
  15660. }
  15661. }
  15662. return false;
  15663. };
  15664. for (var i = 0, ci; ci = imgs[i++];) {
  15665. if (ci.getAttribute("word_img")){
  15666. continue;
  15667. }
  15668. var src = ci.getAttribute("_src") || ci.src || "";
  15669. if (/^(https?|ftp):/i.test(src) && !test(src,localDomain)) {
  15670. remoteImages.push(src);
  15671. }
  15672. }
  15673. if (remoteImages.length) {
  15674. catchremoteimage(remoteImages, {
  15675. //成功抓取
  15676. success:function (xhr) {
  15677. try {
  15678. var info = eval("(" + xhr.responseText + ")");
  15679. } catch (e) {
  15680. return;
  15681. }
  15682. var srcUrls = info.srcUrl.split(separater),
  15683. urls = info.url.split(separater);
  15684. for (var i = 0, ci; ci = imgs[i++];) {
  15685. var src = ci.getAttribute("_src") || ci.src || "";
  15686. for (var j = 0, cj; cj = srcUrls[j++];) {
  15687. var url = urls[j - 1];
  15688. if (src == cj && url != "error") { //抓取失败时不做替换处理
  15689. //地址修正
  15690. var newSrc = me.options.catcherPath + url;
  15691. domUtils.setAttributes(ci, {
  15692. "src":newSrc,
  15693. "_src":newSrc
  15694. });
  15695. break;
  15696. }
  15697. }
  15698. }
  15699. me.fireEvent('catchremotesuccess')
  15700. },
  15701. //回调失败,本次请求超时
  15702. error:function () {
  15703. me.fireEvent("catchremoteerror");
  15704. }
  15705. });
  15706. }
  15707. });
  15708. };
  15709. ///import core
  15710. ///import plugins\inserthtml.js
  15711. ///import plugins\image.js
  15712. ///commandsName snapscreen
  15713. ///commandsTitle 截屏
  15714. /**
  15715. * 截屏插件
  15716. */
  15717. UE.plugins['snapscreen'] = function(){
  15718. var me = this,
  15719. doc,
  15720. snapplugin;
  15721. me.setOpt({
  15722. snapscreenServerPort: location.port //屏幕截图的server端端口
  15723. ,snapscreenImgAlign: '' //截图的图片默认的排版方式
  15724. ,snapscreenHost: location.hostname //屏幕截图的server端文件所在的网站地址或者ip,请不要加http://
  15725. });
  15726. me.commands['snapscreen'] = {
  15727. execCommand: function(){
  15728. var me = this,lang = me.getLang("snapScreen_plugin");
  15729. if(!snapplugin){
  15730. var container = me.container;
  15731. doc = container.ownerDocument || container.document;
  15732. snapplugin = doc.createElement("object");
  15733. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  15734. return;
  15735. }
  15736. snapplugin.style.cssText = "position:absolute;left:-9999px;";
  15737. snapplugin.setAttribute("width","0");
  15738. snapplugin.setAttribute("height","0");
  15739. container.appendChild(snapplugin);
  15740. }
  15741. var editorOptions = me.options;
  15742. var onSuccess = function(rs){
  15743. try{
  15744. rs = eval("("+ rs +")");
  15745. }catch(e){
  15746. alert(lang.callBackErrorMsg);
  15747. return;
  15748. }
  15749. if(rs.state != 'SUCCESS'){
  15750. alert(rs.state);
  15751. return;
  15752. }
  15753. me.execCommand('insertimage', {
  15754. src: editorOptions.snapscreenPath + rs.url,
  15755. floatStyle: editorOptions.snapscreenImgAlign,
  15756. _src:editorOptions.snapscreenPath + rs.url
  15757. });
  15758. };
  15759. var onStartUpload = function(){
  15760. //开始截图上传
  15761. };
  15762. var onError = function(){
  15763. alert(lang.uploadErrorMsg);
  15764. };
  15765. try{
  15766. var port = editorOptions.snapscreenServerPort + '';
  15767. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.split( editorOptions.snapscreenHost );
  15768. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl[1] || editorOptions.snapscreenServerUrl[0];
  15769. if( editorOptions.snapscreenServerUrl.indexOf(":"+port) === 0 ) {
  15770. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.substring( port.length+1 );
  15771. }
  15772. var ret =snapplugin.saveSnapshot(editorOptions.snapscreenHost, editorOptions.snapscreenServerUrl, port);
  15773. onSuccess(ret);
  15774. }catch(e){
  15775. me.ui._dialogs['snapscreenDialog'].open();
  15776. }
  15777. }
  15778. };
  15779. }
  15780. ///import core
  15781. ///commands 插入空行
  15782. ///commandsName insertparagraph
  15783. ///commandsTitle 插入空行
  15784. /**
  15785. * 插入空行
  15786. * @function
  15787. * @name baidu.editor.execCommand
  15788. * @param {String} cmdName insertparagraph
  15789. */
  15790. UE.commands['insertparagraph'] = {
  15791. execCommand : function( cmdName,front) {
  15792. var me = this,
  15793. range = me.selection.getRange(),
  15794. start = range.startContainer,tmpNode;
  15795. while(start ){
  15796. if(domUtils.isBody(start)){
  15797. break;
  15798. }
  15799. tmpNode = start;
  15800. start = start.parentNode;
  15801. }
  15802. if(tmpNode){
  15803. var p = me.document.createElement('p');
  15804. if(front){
  15805. tmpNode.parentNode.insertBefore(p,tmpNode)
  15806. }else{
  15807. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  15808. }
  15809. domUtils.fillNode(me.document,p);
  15810. range.setStart(p,0).setCursor(false,true);
  15811. }
  15812. }
  15813. };
  15814. ///import core
  15815. ///import plugins/inserthtml.js
  15816. ///commands 百度应用
  15817. ///commandsName webapp
  15818. ///commandsTitle 百度应用
  15819. ///commandsDialog dialogs\webapp
  15820. UE.plugins['webapp'] = function () {
  15821. var me = this;
  15822. function createInsertStr( obj, toIframe, addParagraph ) {
  15823. return !toIframe ?
  15824. (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  15825. ' 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 + '" />' +
  15826. (addParagraph ? '</p>' : '')
  15827. :
  15828. '<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>';
  15829. }
  15830. function switchImgAndIframe( img2frame ) {
  15831. var tmpdiv,
  15832. nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  15833. for ( var i = 0, node; node = nodes[i++]; ) {
  15834. if ( node.className != "edui-faked-webapp" ){
  15835. continue;
  15836. }
  15837. tmpdiv = me.document.createElement( "div" );
  15838. 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 );
  15839. node.parentNode.replaceChild( tmpdiv.firstChild, node );
  15840. }
  15841. }
  15842. me.addListener( "beforegetcontent", function () {
  15843. switchImgAndIframe( true );
  15844. } );
  15845. me.addListener( 'aftersetcontent', function () {
  15846. switchImgAndIframe( false );
  15847. } );
  15848. me.addListener( 'aftergetcontent', function ( cmdName ) {
  15849. if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  15850. return;
  15851. }
  15852. switchImgAndIframe( false );
  15853. } );
  15854. me.commands['webapp'] = {
  15855. execCommand:function ( cmd, obj ) {
  15856. me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  15857. }
  15858. };
  15859. };
  15860. ///import core
  15861. ///import plugins\inserthtml.js
  15862. ///import plugins\cleardoc.js
  15863. ///commands 模板
  15864. ///commandsName template
  15865. ///commandsTitle 模板
  15866. ///commandsDialog dialogs\template
  15867. UE.plugins['template'] = function () {
  15868. UE.commands['template'] = {
  15869. execCommand:function (cmd, obj) {
  15870. obj.html && this.execCommand("inserthtml", obj.html);
  15871. }
  15872. };
  15873. this.addListener("click", function (type, evt) {
  15874. var el = evt.target || evt.srcElement,
  15875. range = this.selection.getRange();
  15876. var tnode = domUtils.findParent(el, function (node) {
  15877. if (node.className && domUtils.hasClass(node, "ue_t")) {
  15878. return node;
  15879. }
  15880. }, true);
  15881. tnode && range.selectNode(tnode).shrinkBoundary().select();
  15882. });
  15883. this.addListener("keydown", function (type, evt) {
  15884. var range = this.selection.getRange();
  15885. if (!range.collapsed) {
  15886. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  15887. var tnode = domUtils.findParent(range.startContainer, function (node) {
  15888. if (node.className && domUtils.hasClass(node, "ue_t")) {
  15889. return node;
  15890. }
  15891. }, true);
  15892. if (tnode) {
  15893. domUtils.removeClasses(tnode, ["ue_t"]);
  15894. }
  15895. }
  15896. }
  15897. });
  15898. };
  15899. ///import core
  15900. ///import plugins/inserthtml.js
  15901. ///commands 音乐
  15902. ///commandsName Music
  15903. ///commandsTitle 插入音乐
  15904. ///commandsDialog dialogs\music
  15905. UE.plugins['music'] = function () {
  15906. var me = this,
  15907. div;
  15908. /**
  15909. * 创建插入音乐字符窜
  15910. * @param url 音乐地址
  15911. * @param width 音乐宽度
  15912. * @param height 音乐高度
  15913. * @param align 阴雨对齐
  15914. * @param toEmbed 是否以flash代替显示
  15915. * @param addParagraph 是否需要添加P标签
  15916. */
  15917. function creatInsertStr(url,width,height,align,toEmbed,addParagraph){
  15918. return !toEmbed ?
  15919. (addParagraph? ('<p '+ (align !="none" ? ( align == "center"? ' style="text-align:center;" ':' style="float:"'+ align ) : '') + '>'): '') +
  15920. '<img align="'+align+'" width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  15921. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />' +
  15922. (addParagraph?'</p>':'')
  15923. :
  15924. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  15925. ' src="' + url + '" width="' + width + '" height="' + height + '" align="' + align + '"' +
  15926. ( align !="none" ? ' style= "'+ ( align == "center"? "display:block;":" float: "+ align ) + '"' :'' ) +
  15927. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  15928. }
  15929. function switchImgAndEmbed(img2embed) {
  15930. var tmpdiv,
  15931. nodes = domUtils.getElementsByTagName(me.document, !img2embed ? "embed" : "img");
  15932. for (var i = 0, node; node = nodes[i++];) {
  15933. if (node.className != "edui-faked-music") {
  15934. continue;
  15935. }
  15936. tmpdiv = me.document.createElement("div");
  15937. //先看float在看align,浮动有的是时候是在float上定义的
  15938. var align = domUtils.getComputedStyle(node,'float');
  15939. align = align == 'none' ? (node.getAttribute('align') || '') : align;
  15940. tmpdiv.innerHTML = creatInsertStr(img2embed ? node.getAttribute("_url") : node.getAttribute("src"), node.width, node.height, align, img2embed);
  15941. node.parentNode.replaceChild(tmpdiv.firstChild, node);
  15942. }
  15943. }
  15944. me.addListener("beforegetcontent", function () {
  15945. switchImgAndEmbed(true);
  15946. });
  15947. me.addListener('aftersetcontent', function () {
  15948. switchImgAndEmbed(false);
  15949. });
  15950. me.addListener('aftergetcontent', function (cmdName) {
  15951. if (cmdName == 'aftergetcontent' && me.queryCommandState('source')) {
  15952. return;
  15953. }
  15954. switchImgAndEmbed(false);
  15955. });
  15956. me.commands["music"] = {
  15957. execCommand:function (cmd, musicObj) {
  15958. var me = this,
  15959. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false, true);
  15960. me.execCommand("inserthtml",str);
  15961. },
  15962. queryCommandState:function () {
  15963. var me = this,
  15964. img = me.selection.getRange().getClosedNode(),
  15965. flag = img && (img.className == "edui-faked-music");
  15966. return flag ? 1 : 0;
  15967. }
  15968. };
  15969. };
  15970. var baidu = baidu || {};
  15971. baidu.editor = baidu.editor || {};
  15972. baidu.editor.ui = {};
  15973. (function (){
  15974. var browser = baidu.editor.browser,
  15975. domUtils = baidu.editor.dom.domUtils;
  15976. var magic = '$EDITORUI';
  15977. var root = window[magic] = {};
  15978. var uidMagic = 'ID' + magic;
  15979. var uidCount = 0;
  15980. var uiUtils = baidu.editor.ui.uiUtils = {
  15981. uid: function (obj){
  15982. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  15983. },
  15984. hook: function ( fn, callback ) {
  15985. var dg;
  15986. if (fn && fn._callbacks) {
  15987. dg = fn;
  15988. } else {
  15989. dg = function (){
  15990. var q;
  15991. if (fn) {
  15992. q = fn.apply(this, arguments);
  15993. }
  15994. var callbacks = dg._callbacks;
  15995. var k = callbacks.length;
  15996. while (k --) {
  15997. var r = callbacks[k].apply(this, arguments);
  15998. if (q === undefined) {
  15999. q = r;
  16000. }
  16001. }
  16002. return q;
  16003. };
  16004. dg._callbacks = [];
  16005. }
  16006. dg._callbacks.push(callback);
  16007. return dg;
  16008. },
  16009. createElementByHtml: function (html){
  16010. var el = document.createElement('div');
  16011. el.innerHTML = html;
  16012. el = el.firstChild;
  16013. el.parentNode.removeChild(el);
  16014. return el;
  16015. },
  16016. getViewportElement: function (){
  16017. return (browser.ie && browser.quirks) ?
  16018. document.body : document.documentElement;
  16019. },
  16020. getClientRect: function (element){
  16021. var bcr;
  16022. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  16023. try{
  16024. bcr = element.getBoundingClientRect();
  16025. }catch(e){
  16026. bcr={left:0,top:0,height:0,width:0}
  16027. }
  16028. var rect = {
  16029. left: Math.round(bcr.left),
  16030. top: Math.round(bcr.top),
  16031. height: Math.round(bcr.bottom - bcr.top),
  16032. width: Math.round(bcr.right - bcr.left)
  16033. };
  16034. var doc;
  16035. while ((doc = element.ownerDocument) !== document &&
  16036. (element = domUtils.getWindow(doc).frameElement)) {
  16037. bcr = element.getBoundingClientRect();
  16038. rect.left += bcr.left;
  16039. rect.top += bcr.top;
  16040. }
  16041. rect.bottom = rect.top + rect.height;
  16042. rect.right = rect.left + rect.width;
  16043. return rect;
  16044. },
  16045. getViewportRect: function (){
  16046. var viewportEl = uiUtils.getViewportElement();
  16047. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  16048. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  16049. return {
  16050. left: 0,
  16051. top: 0,
  16052. height: height,
  16053. width: width,
  16054. bottom: height,
  16055. right: width
  16056. };
  16057. },
  16058. setViewportOffset: function (element, offset){
  16059. var rect;
  16060. var fixedLayer = uiUtils.getFixedLayer();
  16061. if (element.parentNode === fixedLayer) {
  16062. element.style.left = offset.left + 'px';
  16063. element.style.top = offset.top + 'px';
  16064. } else {
  16065. domUtils.setViewportOffset(element, offset);
  16066. }
  16067. },
  16068. getEventOffset: function (evt){
  16069. var el = evt.target || evt.srcElement;
  16070. var rect = uiUtils.getClientRect(el);
  16071. var offset = uiUtils.getViewportOffsetByEvent(evt);
  16072. return {
  16073. left: offset.left - rect.left,
  16074. top: offset.top - rect.top
  16075. };
  16076. },
  16077. getViewportOffsetByEvent: function (evt){
  16078. var el = evt.target || evt.srcElement;
  16079. var frameEl = domUtils.getWindow(el).frameElement;
  16080. var offset = {
  16081. left: evt.clientX,
  16082. top: evt.clientY
  16083. };
  16084. if (frameEl && el.ownerDocument !== document) {
  16085. var rect = uiUtils.getClientRect(frameEl);
  16086. offset.left += rect.left;
  16087. offset.top += rect.top;
  16088. }
  16089. return offset;
  16090. },
  16091. setGlobal: function (id, obj){
  16092. root[id] = obj;
  16093. return magic + '["' + id + '"]';
  16094. },
  16095. unsetGlobal: function (id){
  16096. delete root[id];
  16097. },
  16098. copyAttributes: function (tgt, src){
  16099. var attributes = src.attributes;
  16100. var k = attributes.length;
  16101. while (k --) {
  16102. var attrNode = attributes[k];
  16103. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  16104. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  16105. }
  16106. }
  16107. if (src.className) {
  16108. domUtils.addClass(tgt,src.className);
  16109. }
  16110. if (src.style.cssText) {
  16111. tgt.style.cssText += ';' + src.style.cssText;
  16112. }
  16113. },
  16114. removeStyle: function (el, styleName){
  16115. if (el.style.removeProperty) {
  16116. el.style.removeProperty(styleName);
  16117. } else if (el.style.removeAttribute) {
  16118. el.style.removeAttribute(styleName);
  16119. } else throw '';
  16120. },
  16121. contains: function (elA, elB){
  16122. return elA && elB && (elA === elB ? false : (
  16123. elA.contains ? elA.contains(elB) :
  16124. elA.compareDocumentPosition(elB) & 16
  16125. ));
  16126. },
  16127. startDrag: function (evt, callbacks,doc){
  16128. var doc = doc || document;
  16129. var startX = evt.clientX;
  16130. var startY = evt.clientY;
  16131. function handleMouseMove(evt){
  16132. var x = evt.clientX - startX;
  16133. var y = evt.clientY - startY;
  16134. callbacks.ondragmove(x, y,evt);
  16135. if (evt.stopPropagation) {
  16136. evt.stopPropagation();
  16137. } else {
  16138. evt.cancelBubble = true;
  16139. }
  16140. }
  16141. if (doc.addEventListener) {
  16142. function handleMouseUp(evt){
  16143. doc.removeEventListener('mousemove', handleMouseMove, true);
  16144. doc.removeEventListener('mouseup', handleMouseUp, true);
  16145. window.removeEventListener('mouseup', handleMouseUp, true);
  16146. callbacks.ondragstop();
  16147. }
  16148. doc.addEventListener('mousemove', handleMouseMove, true);
  16149. doc.addEventListener('mouseup', handleMouseUp, true);
  16150. window.addEventListener('mouseup', handleMouseUp, true);
  16151. evt.preventDefault();
  16152. } else {
  16153. var elm = evt.srcElement;
  16154. elm.setCapture();
  16155. function releaseCaptrue(){
  16156. elm.releaseCapture();
  16157. elm.detachEvent('onmousemove', handleMouseMove);
  16158. elm.detachEvent('onmouseup', releaseCaptrue);
  16159. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  16160. callbacks.ondragstop();
  16161. }
  16162. elm.attachEvent('onmousemove', handleMouseMove);
  16163. elm.attachEvent('onmouseup', releaseCaptrue);
  16164. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  16165. evt.returnValue = false;
  16166. }
  16167. callbacks.ondragstart();
  16168. },
  16169. getFixedLayer: function (){
  16170. var layer = document.getElementById('edui_fixedlayer');
  16171. if (layer == null) {
  16172. layer = document.createElement('div');
  16173. layer.id = 'edui_fixedlayer';
  16174. document.body.appendChild(layer);
  16175. if (browser.ie && browser.version <= 8) {
  16176. layer.style.position = 'absolute';
  16177. bindFixedLayer();
  16178. setTimeout(updateFixedOffset);
  16179. } else {
  16180. layer.style.position = 'fixed';
  16181. }
  16182. layer.style.left = '0';
  16183. layer.style.top = '0';
  16184. layer.style.width = '0';
  16185. layer.style.height = '0';
  16186. }
  16187. return layer;
  16188. },
  16189. makeUnselectable: function (element){
  16190. if (browser.opera || (browser.ie && browser.version < 9)) {
  16191. element.unselectable = 'on';
  16192. if (element.hasChildNodes()) {
  16193. for (var i=0; i<element.childNodes.length; i++) {
  16194. if (element.childNodes[i].nodeType == 1) {
  16195. uiUtils.makeUnselectable(element.childNodes[i]);
  16196. }
  16197. }
  16198. }
  16199. } else {
  16200. if (element.style.MozUserSelect !== undefined) {
  16201. element.style.MozUserSelect = 'none';
  16202. } else if (element.style.WebkitUserSelect !== undefined) {
  16203. element.style.WebkitUserSelect = 'none';
  16204. } else if (element.style.KhtmlUserSelect !== undefined) {
  16205. element.style.KhtmlUserSelect = 'none';
  16206. }
  16207. }
  16208. }
  16209. };
  16210. function updateFixedOffset(){
  16211. var layer = document.getElementById('edui_fixedlayer');
  16212. uiUtils.setViewportOffset(layer, {
  16213. left: 0,
  16214. top: 0
  16215. });
  16216. // layer.style.display = 'none';
  16217. // layer.style.display = 'block';
  16218. //#trace: 1354
  16219. // setTimeout(updateFixedOffset);
  16220. }
  16221. function bindFixedLayer(adjOffset){
  16222. domUtils.on(window, 'scroll', updateFixedOffset);
  16223. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  16224. }
  16225. })();
  16226. (function () {
  16227. var utils = baidu.editor.utils,
  16228. uiUtils = baidu.editor.ui.uiUtils,
  16229. EventBase = baidu.editor.EventBase,
  16230. UIBase = baidu.editor.ui.UIBase = function () {
  16231. };
  16232. UIBase.prototype = {
  16233. className:'',
  16234. uiName:'',
  16235. initOptions:function (options) {
  16236. var me = this;
  16237. for (var k in options) {
  16238. me[k] = options[k];
  16239. }
  16240. this.id = this.id || 'edui' + uiUtils.uid();
  16241. },
  16242. initUIBase:function () {
  16243. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  16244. },
  16245. render:function (holder) {
  16246. var html = this.renderHtml();
  16247. var el = uiUtils.createElementByHtml(html);
  16248. //by xuheng 给每个node添加class
  16249. var list = domUtils.getElementsByTagName(el, "*");
  16250. var theme = "edui-" + (this.theme || this.editor.options.theme);
  16251. var layer = document.getElementById('edui_fixedlayer');
  16252. for (var i = 0, node; node = list[i++];) {
  16253. domUtils.addClass(node, theme);
  16254. }
  16255. domUtils.addClass(el, theme);
  16256. if(layer){
  16257. layer.className="";
  16258. domUtils.addClass(layer,theme);
  16259. }
  16260. var seatEl = this.getDom();
  16261. if (seatEl != null) {
  16262. seatEl.parentNode.replaceChild(el, seatEl);
  16263. uiUtils.copyAttributes(el, seatEl);
  16264. } else {
  16265. if (typeof holder == 'string') {
  16266. holder = document.getElementById(holder);
  16267. }
  16268. holder = holder || uiUtils.getFixedLayer();
  16269. domUtils.addClass(holder, theme);
  16270. holder.appendChild(el);
  16271. }
  16272. this.postRender();
  16273. },
  16274. getDom:function (name) {
  16275. if (!name) {
  16276. return document.getElementById(this.id);
  16277. } else {
  16278. return document.getElementById(this.id + '_' + name);
  16279. }
  16280. },
  16281. postRender:function () {
  16282. this.fireEvent('postrender');
  16283. },
  16284. getHtmlTpl:function () {
  16285. return '';
  16286. },
  16287. formatHtml:function (tpl) {
  16288. var prefix = 'edui-' + this.uiName;
  16289. return (tpl
  16290. .replace(/##/g, this.id)
  16291. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  16292. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  16293. .replace(/\$\$/g, this._globalKey));
  16294. },
  16295. renderHtml:function () {
  16296. return this.formatHtml(this.getHtmlTpl());
  16297. },
  16298. dispose:function () {
  16299. var box = this.getDom();
  16300. if (box) baidu.editor.dom.domUtils.remove(box);
  16301. uiUtils.unsetGlobal(this.id);
  16302. }
  16303. };
  16304. utils.inherits(UIBase, EventBase);
  16305. })();
  16306. (function (){
  16307. var utils = baidu.editor.utils,
  16308. UIBase = baidu.editor.ui.UIBase,
  16309. Separator = baidu.editor.ui.Separator = function (options){
  16310. this.initOptions(options);
  16311. this.initSeparator();
  16312. };
  16313. Separator.prototype = {
  16314. uiName: 'separator',
  16315. initSeparator: function (){
  16316. this.initUIBase();
  16317. },
  16318. getHtmlTpl: function (){
  16319. return '<div id="##" class="edui-box %%"></div>';
  16320. }
  16321. };
  16322. utils.inherits(Separator, UIBase);
  16323. })();
  16324. ///import core
  16325. ///import uicore
  16326. (function (){
  16327. var utils = baidu.editor.utils,
  16328. domUtils = baidu.editor.dom.domUtils,
  16329. UIBase = baidu.editor.ui.UIBase,
  16330. uiUtils = baidu.editor.ui.uiUtils;
  16331. var Mask = baidu.editor.ui.Mask = function (options){
  16332. this.initOptions(options);
  16333. this.initUIBase();
  16334. };
  16335. Mask.prototype = {
  16336. getHtmlTpl: function (){
  16337. return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>';
  16338. },
  16339. postRender: function (){
  16340. var me = this;
  16341. domUtils.on(window, 'resize', function (){
  16342. setTimeout(function (){
  16343. if (!me.isHidden()) {
  16344. me._fill();
  16345. }
  16346. });
  16347. });
  16348. },
  16349. show: function (zIndex){
  16350. this._fill();
  16351. this.getDom().style.display = '';
  16352. this.getDom().style.zIndex = zIndex;
  16353. },
  16354. hide: function (){
  16355. this.getDom().style.display = 'none';
  16356. this.getDom().style.zIndex = '';
  16357. },
  16358. isHidden: function (){
  16359. return this.getDom().style.display == 'none';
  16360. },
  16361. _onMouseDown: function (){
  16362. return false;
  16363. },
  16364. _fill: function (){
  16365. var el = this.getDom();
  16366. var vpRect = uiUtils.getViewportRect();
  16367. el.style.width = vpRect.width + 'px';
  16368. el.style.height = vpRect.height + 'px';
  16369. }
  16370. };
  16371. utils.inherits(Mask, UIBase);
  16372. })();
  16373. ///import core
  16374. ///import uicore
  16375. (function () {
  16376. var utils = baidu.editor.utils,
  16377. uiUtils = baidu.editor.ui.uiUtils,
  16378. domUtils = baidu.editor.dom.domUtils,
  16379. UIBase = baidu.editor.ui.UIBase,
  16380. Popup = baidu.editor.ui.Popup = function (options){
  16381. this.initOptions(options);
  16382. this.initPopup();
  16383. };
  16384. var allPopups = [];
  16385. function closeAllPopup( evt,el ){
  16386. var newAll = [];
  16387. for ( var i = 0; i < allPopups.length; i++ ) {
  16388. var pop = allPopups[i];
  16389. if (!pop.isHidden()) {
  16390. if (pop.queryAutoHide(el) !== false) {
  16391. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  16392. pop.hide();
  16393. }
  16394. }
  16395. }
  16396. }
  16397. Popup.postHide = closeAllPopup;
  16398. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  16399. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  16400. Popup.prototype = {
  16401. SHADOW_RADIUS: 5,
  16402. content: null,
  16403. _hidden: false,
  16404. autoRender: true,
  16405. canSideLeft: true,
  16406. canSideUp: true,
  16407. initPopup: function (){
  16408. this.initUIBase();
  16409. allPopups.push( this );
  16410. },
  16411. getHtmlTpl: function (){
  16412. return '<div id="##" class="edui-popup %%">' +
  16413. ' <div id="##_body" class="edui-popup-body">' +
  16414. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="javascript:"></iframe>' +
  16415. ' <div class="edui-shadow"></div>' +
  16416. ' <div id="##_content" class="edui-popup-content">' +
  16417. this.getContentHtmlTpl() +
  16418. ' </div>' +
  16419. ' </div>' +
  16420. '</div>';
  16421. },
  16422. getContentHtmlTpl: function (){
  16423. if(this.content){
  16424. if (typeof this.content == 'string') {
  16425. return this.content;
  16426. }
  16427. return this.content.renderHtml();
  16428. }else{
  16429. return ''
  16430. }
  16431. },
  16432. _UIBase_postRender: UIBase.prototype.postRender,
  16433. postRender: function (){
  16434. if (this.content instanceof UIBase) {
  16435. this.content.postRender();
  16436. }
  16437. this.fireEvent('postRenderAfter');
  16438. this.hide(true);
  16439. this._UIBase_postRender();
  16440. },
  16441. _doAutoRender: function (){
  16442. if (!this.getDom() && this.autoRender) {
  16443. this.render();
  16444. }
  16445. },
  16446. mesureSize: function (){
  16447. var box = this.getDom('content');
  16448. return uiUtils.getClientRect(box);
  16449. },
  16450. fitSize: function (){
  16451. var popBodyEl = this.getDom('body');
  16452. popBodyEl.style.width = '';
  16453. popBodyEl.style.height = '';
  16454. var size = this.mesureSize();
  16455. popBodyEl.style.width = size.width + 'px';
  16456. popBodyEl.style.height = size.height + 'px';
  16457. return size;
  16458. },
  16459. showAnchor: function ( element, hoz ){
  16460. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  16461. },
  16462. showAnchorRect: function ( rect, hoz, adj ){
  16463. this._doAutoRender();
  16464. var vpRect = uiUtils.getViewportRect();
  16465. this._show();
  16466. var popSize = this.fitSize();
  16467. var sideLeft, sideUp, left, top;
  16468. if (hoz) {
  16469. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  16470. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  16471. left = (sideLeft ? rect.left - popSize.width : rect.right);
  16472. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  16473. } else {
  16474. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  16475. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  16476. //left = (sideLeft ? rect.right - popSize.width : rect.left);
  16477. left = rect.left;
  16478. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  16479. }
  16480. var popEl = this.getDom();
  16481. uiUtils.setViewportOffset(popEl, {
  16482. left: left,
  16483. top: top
  16484. });
  16485. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  16486. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  16487. if(this.editor){
  16488. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  16489. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  16490. }
  16491. },
  16492. showAt: function (offset) {
  16493. var left = offset.left;
  16494. var top = offset.top;
  16495. var rect = {
  16496. left: left,
  16497. top: top,
  16498. right: left,
  16499. bottom: top,
  16500. height: 0,
  16501. width: 0
  16502. };
  16503. this.showAnchorRect(rect, false, true);
  16504. },
  16505. _show: function (){
  16506. if (this._hidden) {
  16507. var box = this.getDom();
  16508. box.style.display = '';
  16509. this._hidden = false;
  16510. // if (box.setActive) {
  16511. // box.setActive();
  16512. // }
  16513. this.fireEvent('show');
  16514. }
  16515. },
  16516. isHidden: function (){
  16517. return this._hidden;
  16518. },
  16519. show: function (){
  16520. this._doAutoRender();
  16521. this._show();
  16522. },
  16523. hide: function (notNofity){
  16524. if (!this._hidden && this.getDom()) {
  16525. // this.getDom().style.visibility = 'hidden';
  16526. this.getDom().style.display = 'none';
  16527. this._hidden = true;
  16528. if (!notNofity) {
  16529. this.fireEvent('hide');
  16530. }
  16531. }
  16532. },
  16533. queryAutoHide: function (el){
  16534. return !el || !uiUtils.contains(this.getDom(), el);
  16535. }
  16536. };
  16537. utils.inherits(Popup, UIBase);
  16538. domUtils.on( document, 'mousedown', function ( evt ) {
  16539. var el = evt.target || evt.srcElement;
  16540. closeAllPopup( evt,el );
  16541. } );
  16542. domUtils.on( window, 'scroll', function (evt,el) {
  16543. closeAllPopup( evt,el );
  16544. } );
  16545. // var lastVpRect = uiUtils.getViewportRect();
  16546. // domUtils.on( window, 'resize', function () {
  16547. // var vpRect = uiUtils.getViewportRect();
  16548. // if (vpRect.width != lastVpRect.width || vpRect.height != lastVpRect.height) {
  16549. // closeAllPopup();
  16550. // }
  16551. // } );
  16552. })();
  16553. ///import core
  16554. ///import uicore
  16555. (function (){
  16556. var utils = baidu.editor.utils,
  16557. UIBase = baidu.editor.ui.UIBase,
  16558. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  16559. this.initOptions(options);
  16560. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  16561. this.initUIBase();
  16562. };
  16563. ColorPicker.prototype = {
  16564. getHtmlTpl: function (){
  16565. return genColorPicker(this.noColorText,this.editor);
  16566. },
  16567. _onTableClick: function (evt){
  16568. var tgt = evt.target || evt.srcElement;
  16569. var color = tgt.getAttribute('data-color');
  16570. if (color) {
  16571. this.fireEvent('pickcolor', color);
  16572. }
  16573. },
  16574. _onTableOver: function (evt){
  16575. var tgt = evt.target || evt.srcElement;
  16576. var color = tgt.getAttribute('data-color');
  16577. if (color) {
  16578. this.getDom('preview').style.backgroundColor = color;
  16579. }
  16580. },
  16581. _onTableOut: function (){
  16582. this.getDom('preview').style.backgroundColor = '';
  16583. },
  16584. _onPickNoColor: function (){
  16585. this.fireEvent('picknocolor');
  16586. }
  16587. };
  16588. utils.inherits(ColorPicker, UIBase);
  16589. var COLORS = (
  16590. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  16591. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  16592. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  16593. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  16594. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  16595. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  16596. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  16597. function genColorPicker(noColorText,editor){
  16598. var html = '<div id="##" class="edui-colorpicker %%">' +
  16599. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  16600. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  16601. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  16602. '</div>' +
  16603. '<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">' +
  16604. '<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>'+
  16605. '<tr class="edui-colorpicker-tablefirstrow" >';
  16606. for (var i=0; i<COLORS.length; i++) {
  16607. if (i && i%10 === 0) {
  16608. 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"':'')+'>';
  16609. }
  16610. 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"' +
  16611. ' data-color="#'+ COLORS[i] +'"'+
  16612. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  16613. (i<10 || i>=60?'border-width:1px;':
  16614. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  16615. 'border-width:0 1px 0 1px;')+
  16616. '"' +
  16617. '></a></td>':'';
  16618. }
  16619. html += '</tr></table></div>';
  16620. return html;
  16621. }
  16622. })();
  16623. ///import core
  16624. ///import uicore
  16625. (function (){
  16626. var utils = baidu.editor.utils,
  16627. uiUtils = baidu.editor.ui.uiUtils,
  16628. UIBase = baidu.editor.ui.UIBase;
  16629. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  16630. this.initOptions(options);
  16631. this.initTablePicker();
  16632. };
  16633. TablePicker.prototype = {
  16634. defaultNumRows: 10,
  16635. defaultNumCols: 10,
  16636. maxNumRows: 20,
  16637. maxNumCols: 20,
  16638. numRows: 10,
  16639. numCols: 10,
  16640. lengthOfCellSide: 22,
  16641. initTablePicker: function (){
  16642. this.initUIBase();
  16643. },
  16644. getHtmlTpl: function (){
  16645. var me = this;
  16646. return '<div id="##" class="edui-tablepicker %%">' +
  16647. '<div class="edui-tablepicker-body">' +
  16648. '<div class="edui-infoarea">' +
  16649. '<span id="##_label" class="edui-label"></span>' +
  16650. '</div>' +
  16651. '<div class="edui-pickarea"' +
  16652. ' onmousemove="$$._onMouseMove(event, this);"' +
  16653. ' onmouseover="$$._onMouseOver(event, this);"' +
  16654. ' onmouseout="$$._onMouseOut(event, this);"' +
  16655. ' onclick="$$._onClick(event, this);"' +
  16656. '>' +
  16657. '<div id="##_overlay" class="edui-overlay"></div>' +
  16658. '</div>' +
  16659. '</div>' +
  16660. '</div>';
  16661. },
  16662. _UIBase_render: UIBase.prototype.render,
  16663. render: function (holder){
  16664. this._UIBase_render(holder);
  16665. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  16666. },
  16667. _track: function (numCols, numRows){
  16668. var style = this.getDom('overlay').style;
  16669. var sideLen = this.lengthOfCellSide;
  16670. style.width = numCols * sideLen + 'px';
  16671. style.height = numRows * sideLen + 'px';
  16672. var label = this.getDom('label');
  16673. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  16674. this.numCols = numCols;
  16675. this.numRows = numRows;
  16676. },
  16677. _onMouseOver: function (evt, el){
  16678. var rel = evt.relatedTarget || evt.fromElement;
  16679. if (!uiUtils.contains(el, rel) && el !== rel) {
  16680. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  16681. this.getDom('overlay').style.visibility = '';
  16682. }
  16683. },
  16684. _onMouseOut: function (evt, el){
  16685. var rel = evt.relatedTarget || evt.toElement;
  16686. if (!uiUtils.contains(el, rel) && el !== rel) {
  16687. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  16688. this.getDom('overlay').style.visibility = 'hidden';
  16689. }
  16690. },
  16691. _onMouseMove: function (evt, el){
  16692. var style = this.getDom('overlay').style;
  16693. var offset = uiUtils.getEventOffset(evt);
  16694. var sideLen = this.lengthOfCellSide;
  16695. var numCols = Math.ceil(offset.left / sideLen);
  16696. var numRows = Math.ceil(offset.top / sideLen);
  16697. this._track(numCols, numRows);
  16698. },
  16699. _onClick: function (){
  16700. this.fireEvent('picktable', this.numCols, this.numRows);
  16701. }
  16702. };
  16703. utils.inherits(TablePicker, UIBase);
  16704. })();
  16705. (function (){
  16706. var browser = baidu.editor.browser,
  16707. domUtils = baidu.editor.dom.domUtils,
  16708. uiUtils = baidu.editor.ui.uiUtils;
  16709. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  16710. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  16711. ( browser.ie ? (
  16712. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  16713. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  16714. : (
  16715. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  16716. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  16717. baidu.editor.ui.Stateful = {
  16718. alwalysHoverable: false,
  16719. target:null,//目标元素和this指向dom不一样
  16720. Stateful_init: function (){
  16721. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  16722. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  16723. },
  16724. Stateful_getHtmlTpl: function (){
  16725. var tpl = this._Stateful_dGetHtmlTpl();
  16726. // 使用function避免$转义
  16727. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  16728. },
  16729. Stateful_onMouseEnter: function (evt, el){
  16730. this.target=el;
  16731. if (!this.isDisabled() || this.alwalysHoverable) {
  16732. this.addState('hover');
  16733. this.fireEvent('over');
  16734. }
  16735. },
  16736. Stateful_onMouseLeave: function (evt, el){
  16737. if (!this.isDisabled() || this.alwalysHoverable) {
  16738. this.removeState('hover');
  16739. this.removeState('active');
  16740. this.fireEvent('out');
  16741. }
  16742. },
  16743. Stateful_onMouseOver: function (evt, el){
  16744. var rel = evt.relatedTarget;
  16745. if (!uiUtils.contains(el, rel) && el !== rel) {
  16746. this.Stateful_onMouseEnter(evt, el);
  16747. }
  16748. },
  16749. Stateful_onMouseOut: function (evt, el){
  16750. var rel = evt.relatedTarget;
  16751. if (!uiUtils.contains(el, rel) && el !== rel) {
  16752. this.Stateful_onMouseLeave(evt, el);
  16753. }
  16754. },
  16755. Stateful_onMouseDown: function (evt, el){
  16756. if (!this.isDisabled()) {
  16757. this.addState('active');
  16758. }
  16759. },
  16760. Stateful_onMouseUp: function (evt, el){
  16761. if (!this.isDisabled()) {
  16762. this.removeState('active');
  16763. }
  16764. },
  16765. Stateful_postRender: function (){
  16766. if (this.disabled && !this.hasState('disabled')) {
  16767. this.addState('disabled');
  16768. }
  16769. },
  16770. hasState: function (state){
  16771. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  16772. },
  16773. addState: function (state){
  16774. if (!this.hasState(state)) {
  16775. this.getStateDom().className += ' edui-state-' + state;
  16776. }
  16777. },
  16778. removeState: function (state){
  16779. if (this.hasState(state)) {
  16780. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  16781. }
  16782. },
  16783. getStateDom: function (){
  16784. return this.getDom('state');
  16785. },
  16786. isChecked: function (){
  16787. return this.hasState('checked');
  16788. },
  16789. setChecked: function (checked){
  16790. if (!this.isDisabled() && checked) {
  16791. this.addState('checked');
  16792. } else {
  16793. this.removeState('checked');
  16794. }
  16795. },
  16796. isDisabled: function(){
  16797. return this.hasState('disabled');
  16798. },
  16799. setDisabled: function (disabled){
  16800. if (disabled) {
  16801. this.removeState('hover');
  16802. this.removeState('checked');
  16803. this.removeState('active');
  16804. this.addState('disabled');
  16805. } else {
  16806. this.removeState('disabled');
  16807. }
  16808. }
  16809. };
  16810. })();
  16811. ///import core
  16812. ///import uicore
  16813. ///import ui/stateful.js
  16814. (function (){
  16815. var utils = baidu.editor.utils,
  16816. UIBase = baidu.editor.ui.UIBase,
  16817. Stateful = baidu.editor.ui.Stateful,
  16818. Button = baidu.editor.ui.Button = function (options){
  16819. this.initOptions(options);
  16820. this.initButton();
  16821. };
  16822. Button.prototype = {
  16823. uiName: 'button',
  16824. label: '',
  16825. title: '',
  16826. showIcon: true,
  16827. showText: true,
  16828. initButton: function (){
  16829. this.initUIBase();
  16830. this.Stateful_init();
  16831. },
  16832. getHtmlTpl: function (){
  16833. return '<div id="##" class="edui-box %%">' +
  16834. '<div id="##_state" stateful>' +
  16835. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  16836. ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' +
  16837. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  16838. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  16839. '</div>' +
  16840. '</div>' +
  16841. '</div></div>';
  16842. },
  16843. postRender: function (){
  16844. this.Stateful_postRender();
  16845. this.setDisabled(this.disabled)
  16846. },
  16847. _onClick: function (){
  16848. if (!this.isDisabled()) {
  16849. this.fireEvent('click');
  16850. }
  16851. }
  16852. };
  16853. utils.inherits(Button, UIBase);
  16854. utils.extend(Button.prototype, Stateful);
  16855. })();
  16856. ///import core
  16857. ///import uicore
  16858. ///import ui/stateful.js
  16859. (function (){
  16860. var utils = baidu.editor.utils,
  16861. uiUtils = baidu.editor.ui.uiUtils,
  16862. domUtils = baidu.editor.dom.domUtils,
  16863. UIBase = baidu.editor.ui.UIBase,
  16864. Stateful = baidu.editor.ui.Stateful,
  16865. SplitButton = baidu.editor.ui.SplitButton = function (options){
  16866. this.initOptions(options);
  16867. this.initSplitButton();
  16868. };
  16869. SplitButton.prototype = {
  16870. popup: null,
  16871. uiName: 'splitbutton',
  16872. title: '',
  16873. initSplitButton: function (){
  16874. this.initUIBase();
  16875. this.Stateful_init();
  16876. var me = this;
  16877. if (this.popup != null) {
  16878. var popup = this.popup;
  16879. this.popup = null;
  16880. this.setPopup(popup);
  16881. }
  16882. },
  16883. _UIBase_postRender: UIBase.prototype.postRender,
  16884. postRender: function (){
  16885. this.Stateful_postRender();
  16886. this._UIBase_postRender();
  16887. },
  16888. setPopup: function (popup){
  16889. if (this.popup === popup) return;
  16890. if (this.popup != null) {
  16891. this.popup.dispose();
  16892. }
  16893. popup.addListener('show', utils.bind(this._onPopupShow, this));
  16894. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  16895. popup.addListener('postrender', utils.bind(function (){
  16896. popup.getDom('body').appendChild(
  16897. uiUtils.createElementByHtml('<div id="' +
  16898. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  16899. (uiUtils.getClientRect(this.getDom()).width - 2) + 'px"></div>')
  16900. );
  16901. popup.getDom().className += ' ' + this.className;
  16902. }, this));
  16903. this.popup = popup;
  16904. },
  16905. _onPopupShow: function (){
  16906. this.addState('opened');
  16907. },
  16908. _onPopupHide: function (){
  16909. this.removeState('opened');
  16910. },
  16911. getHtmlTpl: function (){
  16912. return '<div id="##" class="edui-box %%">' +
  16913. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  16914. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  16915. '<div class="edui-box edui-icon"></div>' +
  16916. '</div>' +
  16917. '<div class="edui-box edui-splitborder"></div>' +
  16918. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  16919. '</div></div></div>';
  16920. },
  16921. showPopup: function (){
  16922. // 当popup往上弹出的时候,做特殊处理
  16923. var rect = uiUtils.getClientRect(this.getDom());
  16924. rect.top -= this.popup.SHADOW_RADIUS;
  16925. rect.height += this.popup.SHADOW_RADIUS;
  16926. this.popup.showAnchorRect(rect);
  16927. },
  16928. _onArrowClick: function (event, el){
  16929. if (!this.isDisabled()) {
  16930. this.showPopup();
  16931. }
  16932. },
  16933. _onButtonClick: function (){
  16934. if (!this.isDisabled()) {
  16935. this.fireEvent('buttonclick');
  16936. }
  16937. }
  16938. };
  16939. utils.inherits(SplitButton, UIBase);
  16940. utils.extend(SplitButton.prototype, Stateful, true);
  16941. })();
  16942. ///import core
  16943. ///import uicore
  16944. ///import ui/colorpicker.js
  16945. ///import ui/popup.js
  16946. ///import ui/splitbutton.js
  16947. (function (){
  16948. var utils = baidu.editor.utils,
  16949. uiUtils = baidu.editor.ui.uiUtils,
  16950. ColorPicker = baidu.editor.ui.ColorPicker,
  16951. Popup = baidu.editor.ui.Popup,
  16952. SplitButton = baidu.editor.ui.SplitButton,
  16953. ColorButton = baidu.editor.ui.ColorButton = function (options){
  16954. this.initOptions(options);
  16955. this.initColorButton();
  16956. };
  16957. ColorButton.prototype = {
  16958. initColorButton: function (){
  16959. var me = this;
  16960. this.popup = new Popup({
  16961. content: new ColorPicker({
  16962. noColorText: me.editor.getLang("clearColor"),
  16963. editor:me.editor,
  16964. onpickcolor: function (t, color){
  16965. me._onPickColor(color);
  16966. },
  16967. onpicknocolor: function (t, color){
  16968. me._onPickNoColor(color);
  16969. }
  16970. }),
  16971. editor:me.editor
  16972. });
  16973. this.initSplitButton();
  16974. },
  16975. _SplitButton_postRender: SplitButton.prototype.postRender,
  16976. postRender: function (){
  16977. this._SplitButton_postRender();
  16978. this.getDom('button_body').appendChild(
  16979. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  16980. );
  16981. this.getDom().className += ' edui-colorbutton';
  16982. },
  16983. setColor: function (color){
  16984. this.getDom('colorlump').style.backgroundColor = color;
  16985. this.color = color;
  16986. },
  16987. _onPickColor: function (color){
  16988. if (this.fireEvent('pickcolor', color) !== false) {
  16989. this.setColor(color);
  16990. this.popup.hide();
  16991. }
  16992. },
  16993. _onPickNoColor: function (color){
  16994. if (this.fireEvent('picknocolor') !== false) {
  16995. this.popup.hide();
  16996. }
  16997. }
  16998. };
  16999. utils.inherits(ColorButton, SplitButton);
  17000. })();
  17001. ///import core
  17002. ///import uicore
  17003. ///import ui/popup.js
  17004. ///import ui/tablepicker.js
  17005. ///import ui/splitbutton.js
  17006. (function (){
  17007. var utils = baidu.editor.utils,
  17008. Popup = baidu.editor.ui.Popup,
  17009. TablePicker = baidu.editor.ui.TablePicker,
  17010. SplitButton = baidu.editor.ui.SplitButton,
  17011. TableButton = baidu.editor.ui.TableButton = function (options){
  17012. this.initOptions(options);
  17013. this.initTableButton();
  17014. };
  17015. TableButton.prototype = {
  17016. initTableButton: function (){
  17017. var me = this;
  17018. this.popup = new Popup({
  17019. content: new TablePicker({
  17020. editor:me.editor,
  17021. onpicktable: function (t, numCols, numRows){
  17022. me._onPickTable(numCols, numRows);
  17023. }
  17024. }),
  17025. 'editor':me.editor
  17026. });
  17027. this.initSplitButton();
  17028. },
  17029. _onPickTable: function (numCols, numRows){
  17030. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  17031. this.popup.hide();
  17032. }
  17033. }
  17034. };
  17035. utils.inherits(TableButton, SplitButton);
  17036. })();
  17037. ///import core
  17038. ///import uicore
  17039. (function () {
  17040. var utils = baidu.editor.utils,
  17041. UIBase = baidu.editor.ui.UIBase;
  17042. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  17043. this.initOptions(options);
  17044. this.initAutoTypeSetPicker();
  17045. };
  17046. AutoTypeSetPicker.prototype = {
  17047. initAutoTypeSetPicker:function () {
  17048. this.initUIBase();
  17049. },
  17050. getHtmlTpl:function () {
  17051. var me = this.editor,
  17052. opt = me.options.autotypeset,
  17053. lang = me.getLang("autoTypeSet");
  17054. var textAlignInputName = 'textAlignValue' + me.uid,
  17055. imageBlockInputName = 'imageBlockLineValue' + me.uid;
  17056. return '<div id="##" class="edui-autotypesetpicker %%">' +
  17057. '<div class="edui-autotypesetpicker-body">' +
  17058. '<table >' +
  17059. '<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>' +
  17060. '<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>' +
  17061. '<tr><td nowrap colspan="2"><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td><td colspan="2" id="' + textAlignInputName + '"><input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + ' </tr>' +
  17062. '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  17063. '<td nowrap colspan="2" id="'+ imageBlockInputName +'">' +
  17064. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  17065. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  17066. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  17067. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' +
  17068. '<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>' +
  17069. '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  17070. '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  17071. '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' +
  17072. '</table>' +
  17073. '</div>' +
  17074. '</div>';
  17075. },
  17076. _UIBase_render:UIBase.prototype.render
  17077. };
  17078. utils.inherits(AutoTypeSetPicker, UIBase);
  17079. })();
  17080. ///import core
  17081. ///import uicore
  17082. ///import ui/popup.js
  17083. ///import ui/autotypesetpicker.js
  17084. ///import ui/splitbutton.js
  17085. (function (){
  17086. var utils = baidu.editor.utils,
  17087. Popup = baidu.editor.ui.Popup,
  17088. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  17089. SplitButton = baidu.editor.ui.SplitButton,
  17090. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  17091. this.initOptions(options);
  17092. this.initAutoTypeSetButton();
  17093. };
  17094. function getPara(me){
  17095. var opt = me.editor.options.autotypeset,
  17096. cont = me.getDom(),
  17097. editorId = me.editor.uid,
  17098. inputType = null,
  17099. attrName = null,
  17100. ipts = domUtils.getElementsByTagName(cont,"input");
  17101. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  17102. inputType = ipt.getAttribute("type");
  17103. if(inputType=="checkbox"){
  17104. attrName = ipt.getAttribute("name");
  17105. opt[attrName] && delete opt[attrName];
  17106. if(ipt.checked){
  17107. var attrValue = document.getElementById( attrName+"Value" + editorId );
  17108. if(attrValue){
  17109. if(/input/ig.test(attrValue.tagName)){
  17110. opt[attrName] = attrValue.value;
  17111. }else{
  17112. var iptChilds = attrValue.getElementsByTagName("input");
  17113. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  17114. if(iptchild.checked){
  17115. opt[attrName] = iptchild.value;
  17116. break;
  17117. }
  17118. }
  17119. }
  17120. }else{
  17121. opt[attrName] = true;
  17122. }
  17123. }
  17124. }
  17125. }
  17126. var selects = domUtils.getElementsByTagName(cont,"select");
  17127. for(var i=0,si;si=selects[i++];){
  17128. var attr = si.getAttribute('name');
  17129. opt[attr] = opt[attr] ? si.value : '';
  17130. }
  17131. me.editor.options.autotypeset = opt;
  17132. }
  17133. AutoTypeSetButton.prototype = {
  17134. initAutoTypeSetButton: function (){
  17135. var me = this;
  17136. this.popup = new Popup({
  17137. //传入配置参数
  17138. content: new AutoTypeSetPicker({editor:me.editor}),
  17139. 'editor':me.editor,
  17140. hide : function(){
  17141. if (!this._hidden && this.getDom()) {
  17142. getPara(this);
  17143. this.getDom().style.display = 'none';
  17144. this._hidden = true;
  17145. this.fireEvent('hide');
  17146. }
  17147. }
  17148. });
  17149. var flag = 0;
  17150. this.popup.addListener('postRenderAfter',function(){
  17151. var popupUI = this;
  17152. if(flag)return;
  17153. var cont = this.getDom(),
  17154. btn = cont.getElementsByTagName('button')[0];
  17155. btn.onclick = function(){
  17156. getPara(popupUI);
  17157. me.editor.execCommand('autotypeset');
  17158. popupUI.hide()
  17159. };
  17160. flag = 1;
  17161. });
  17162. this.initSplitButton();
  17163. }
  17164. };
  17165. utils.inherits(AutoTypeSetButton, SplitButton);
  17166. })();
  17167. ///import core
  17168. ///import uicore
  17169. (function () {
  17170. var utils = baidu.editor.utils,
  17171. Popup = baidu.editor.ui.Popup,
  17172. Stateful = baidu.editor.ui.Stateful,
  17173. UIBase = baidu.editor.ui.UIBase;
  17174. /**
  17175. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  17176. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  17177. * @update 2013/4/2 hancong03@baidu.com
  17178. */
  17179. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  17180. this.initOptions(options);
  17181. this.initSelected();
  17182. this.initCellAlignPicker();
  17183. };
  17184. CellAlignPicker.prototype = {
  17185. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  17186. initSelected: function(){
  17187. var status = {
  17188. valign: {
  17189. top: 0,
  17190. middle: 1,
  17191. bottom: 2
  17192. },
  17193. align: {
  17194. left: 0,
  17195. center: 1,
  17196. right: 2
  17197. },
  17198. count: 3
  17199. },
  17200. result = -1;
  17201. if( this.selected ) {
  17202. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  17203. }
  17204. },
  17205. initCellAlignPicker:function () {
  17206. this.initUIBase();
  17207. this.Stateful_init();
  17208. },
  17209. getHtmlTpl:function () {
  17210. var alignType = [ 'left', 'center', 'right' ],
  17211. COUNT = 9,
  17212. tempClassName = null,
  17213. tempIndex = -1,
  17214. tmpl = [];
  17215. for( var i= 0; i<COUNT; i++ ) {
  17216. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  17217. tempIndex = i % 3;
  17218. tempIndex === 0 && tmpl.push('<tr>');
  17219. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  17220. tempIndex === 2 && tmpl.push('</tr>');
  17221. }
  17222. return '<div id="##" class="edui-cellalignpicker %%">' +
  17223. '<div class="edui-cellalignpicker-body">' +
  17224. '<table onclick="$$._onClick(event);">' +
  17225. tmpl.join('') +
  17226. '</table>' +
  17227. '</div>' +
  17228. '</div>';
  17229. },
  17230. getStateDom: function (){
  17231. return this.target;
  17232. },
  17233. _onClick: function (evt){
  17234. var target= evt.target || evt.srcElement;
  17235. if(/icon/.test(target.className)){
  17236. this.items[target.parentNode.getAttribute("index")].onclick();
  17237. Popup.postHide(evt);
  17238. }
  17239. },
  17240. _UIBase_render:UIBase.prototype.render
  17241. };
  17242. utils.inherits(CellAlignPicker, UIBase);
  17243. utils.extend(CellAlignPicker.prototype, Stateful,true);
  17244. })();
  17245. ///import core
  17246. ///import uicore
  17247. (function () {
  17248. var utils = baidu.editor.utils,
  17249. Stateful = baidu.editor.ui.Stateful,
  17250. uiUtils = baidu.editor.ui.uiUtils,
  17251. UIBase = baidu.editor.ui.UIBase;
  17252. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  17253. this.initOptions(options);
  17254. this.initPastePicker();
  17255. };
  17256. PastePicker.prototype = {
  17257. initPastePicker:function () {
  17258. this.initUIBase();
  17259. this.Stateful_init();
  17260. },
  17261. getHtmlTpl:function () {
  17262. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  17263. '<div class="edui-pastecontainer">' +
  17264. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  17265. '<div class="edui-button">' +
  17266. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  17267. '<div class="edui-richtxticon"></div></div>' +
  17268. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  17269. '<div class="edui-tagicon"></div></div>' +
  17270. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  17271. '<div class="edui-plaintxticon"></div></div>' +
  17272. '</div>' +
  17273. '</div>' +
  17274. '</div>'
  17275. },
  17276. getStateDom:function () {
  17277. return this.target;
  17278. },
  17279. format:function (param) {
  17280. this.editor.ui._isTransfer = true;
  17281. this.editor.fireEvent('pasteTransfer', param);
  17282. },
  17283. _onClick:function (cur) {
  17284. var node = domUtils.getNextDomNode(cur),
  17285. screenHt = uiUtils.getViewportRect().height,
  17286. subPop = uiUtils.getClientRect(node);
  17287. if ((subPop.top + subPop.height) > screenHt)
  17288. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  17289. else
  17290. node.style.top = "";
  17291. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  17292. node.style.visibility = "visible";
  17293. domUtils.addClass(cur, "edui-state-opened");
  17294. } else {
  17295. node.style.visibility = "hidden";
  17296. domUtils.removeClasses(cur, "edui-state-opened")
  17297. }
  17298. },
  17299. _UIBase_render:UIBase.prototype.render
  17300. };
  17301. utils.inherits(PastePicker, UIBase);
  17302. utils.extend(PastePicker.prototype, Stateful, true);
  17303. })();
  17304. (function (){
  17305. var utils = baidu.editor.utils,
  17306. uiUtils = baidu.editor.ui.uiUtils,
  17307. UIBase = baidu.editor.ui.UIBase,
  17308. Toolbar = baidu.editor.ui.Toolbar = function (options){
  17309. this.initOptions(options);
  17310. this.initToolbar();
  17311. };
  17312. Toolbar.prototype = {
  17313. items: null,
  17314. initToolbar: function (){
  17315. this.items = this.items || [];
  17316. this.initUIBase();
  17317. },
  17318. add: function (item){
  17319. this.items.push(item);
  17320. },
  17321. getHtmlTpl: function (){
  17322. var buff = [];
  17323. for (var i=0; i<this.items.length; i++) {
  17324. buff[i] = this.items[i].renderHtml();
  17325. }
  17326. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  17327. buff.join('') +
  17328. '</div>'
  17329. },
  17330. postRender: function (){
  17331. var box = this.getDom();
  17332. for (var i=0; i<this.items.length; i++) {
  17333. this.items[i].postRender();
  17334. }
  17335. uiUtils.makeUnselectable(box);
  17336. },
  17337. _onMouseDown: function (){
  17338. return false;
  17339. }
  17340. };
  17341. utils.inherits(Toolbar, UIBase);
  17342. })();
  17343. ///import core
  17344. ///import uicore
  17345. ///import ui\popup.js
  17346. ///import ui\stateful.js
  17347. (function () {
  17348. var utils = baidu.editor.utils,
  17349. domUtils = baidu.editor.dom.domUtils,
  17350. uiUtils = baidu.editor.ui.uiUtils,
  17351. UIBase = baidu.editor.ui.UIBase,
  17352. Popup = baidu.editor.ui.Popup,
  17353. Stateful = baidu.editor.ui.Stateful,
  17354. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  17355. Menu = baidu.editor.ui.Menu = function (options) {
  17356. this.initOptions(options);
  17357. this.initMenu();
  17358. };
  17359. var menuSeparator = {
  17360. renderHtml:function () {
  17361. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  17362. },
  17363. postRender:function () {
  17364. },
  17365. queryAutoHide:function () {
  17366. return true;
  17367. }
  17368. };
  17369. Menu.prototype = {
  17370. items:null,
  17371. uiName:'menu',
  17372. initMenu:function () {
  17373. this.items = this.items || [];
  17374. this.initPopup();
  17375. this.initItems();
  17376. },
  17377. initItems:function () {
  17378. for (var i = 0; i < this.items.length; i++) {
  17379. var item = this.items[i];
  17380. if (item == '-') {
  17381. this.items[i] = this.getSeparator();
  17382. } else if (!(item instanceof MenuItem)) {
  17383. item.editor = this.editor;
  17384. item.theme = this.editor.options.theme;
  17385. this.items[i] = this.createItem(item);
  17386. }
  17387. }
  17388. },
  17389. getSeparator:function () {
  17390. return menuSeparator;
  17391. },
  17392. createItem:function (item) {
  17393. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  17394. item.menu = this;
  17395. return new MenuItem(item);
  17396. },
  17397. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  17398. getContentHtmlTpl:function () {
  17399. if (this.items.length == 0) {
  17400. return this._Popup_getContentHtmlTpl();
  17401. }
  17402. var buff = [];
  17403. for (var i = 0; i < this.items.length; i++) {
  17404. var item = this.items[i];
  17405. buff[i] = item.renderHtml();
  17406. }
  17407. return ('<div class="%%-body">' + buff.join('') + '</div>');
  17408. },
  17409. _Popup_postRender:Popup.prototype.postRender,
  17410. postRender:function () {
  17411. var me = this;
  17412. for (var i = 0; i < this.items.length; i++) {
  17413. var item = this.items[i];
  17414. item.ownerMenu = this;
  17415. item.postRender();
  17416. }
  17417. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  17418. evt = evt || event;
  17419. var rel = evt.relatedTarget || evt.fromElement;
  17420. var el = me.getDom();
  17421. if (!uiUtils.contains(el, rel) && el !== rel) {
  17422. me.fireEvent('over');
  17423. }
  17424. });
  17425. this._Popup_postRender();
  17426. },
  17427. queryAutoHide:function (el) {
  17428. if (el) {
  17429. if (uiUtils.contains(this.getDom(), el)) {
  17430. return false;
  17431. }
  17432. for (var i = 0; i < this.items.length; i++) {
  17433. var item = this.items[i];
  17434. if (item.queryAutoHide(el) === false) {
  17435. return false;
  17436. }
  17437. }
  17438. }
  17439. },
  17440. clearItems:function () {
  17441. for (var i = 0; i < this.items.length; i++) {
  17442. var item = this.items[i];
  17443. clearTimeout(item._showingTimer);
  17444. clearTimeout(item._closingTimer);
  17445. if (item.subMenu) {
  17446. item.subMenu.destroy();
  17447. }
  17448. }
  17449. this.items = [];
  17450. },
  17451. destroy:function () {
  17452. if (this.getDom()) {
  17453. domUtils.remove(this.getDom());
  17454. }
  17455. this.clearItems();
  17456. },
  17457. dispose:function () {
  17458. this.destroy();
  17459. }
  17460. };
  17461. utils.inherits(Menu, Popup);
  17462. /**
  17463. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  17464. * @type {Function}
  17465. */
  17466. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  17467. this.initOptions(options);
  17468. this.initUIBase();
  17469. this.Stateful_init();
  17470. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  17471. if (options.className && options.className.indexOf("aligntd") != -1) {
  17472. var me = this;
  17473. //获取单元格对齐初始状态
  17474. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  17475. this.subMenu = new Popup({
  17476. content:new CellAlignPicker(this.subMenu),
  17477. parentMenu:me,
  17478. editor:me.editor,
  17479. destroy:function () {
  17480. if (this.getDom()) {
  17481. domUtils.remove(this.getDom());
  17482. }
  17483. }
  17484. });
  17485. this.subMenu.addListener("postRenderAfter", function () {
  17486. domUtils.on(this.getDom(), "mouseover", function () {
  17487. me.addState('opened');
  17488. });
  17489. });
  17490. } else {
  17491. this.subMenu = new Menu(this.subMenu);
  17492. }
  17493. }
  17494. };
  17495. MenuItem.prototype = {
  17496. label:'',
  17497. subMenu:null,
  17498. ownerMenu:null,
  17499. uiName:'menuitem',
  17500. alwalysHoverable:true,
  17501. getHtmlTpl:function () {
  17502. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  17503. '<div class="%%-body">' +
  17504. this.renderLabelHtml() +
  17505. '</div>' +
  17506. '</div>';
  17507. },
  17508. postRender:function () {
  17509. var me = this;
  17510. this.addListener('over', function () {
  17511. me.ownerMenu.fireEvent('submenuover', me);
  17512. if (me.subMenu) {
  17513. me.delayShowSubMenu();
  17514. }
  17515. });
  17516. if (this.subMenu) {
  17517. this.getDom().className += ' edui-hassubmenu';
  17518. this.subMenu.render();
  17519. this.addListener('out', function () {
  17520. me.delayHideSubMenu();
  17521. });
  17522. this.subMenu.addListener('over', function () {
  17523. clearTimeout(me._closingTimer);
  17524. me._closingTimer = null;
  17525. me.addState('opened');
  17526. });
  17527. this.ownerMenu.addListener('hide', function () {
  17528. me.hideSubMenu();
  17529. });
  17530. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  17531. if (subMenu !== me) {
  17532. me.delayHideSubMenu();
  17533. }
  17534. });
  17535. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  17536. this.subMenu.queryAutoHide = function (el) {
  17537. if (el && uiUtils.contains(me.getDom(), el)) {
  17538. return false;
  17539. }
  17540. return this._bakQueryAutoHide(el);
  17541. };
  17542. }
  17543. this.getDom().style.tabIndex = '-1';
  17544. uiUtils.makeUnselectable(this.getDom());
  17545. this.Stateful_postRender();
  17546. },
  17547. delayShowSubMenu:function () {
  17548. var me = this;
  17549. if (!me.isDisabled()) {
  17550. me.addState('opened');
  17551. clearTimeout(me._showingTimer);
  17552. clearTimeout(me._closingTimer);
  17553. me._closingTimer = null;
  17554. me._showingTimer = setTimeout(function () {
  17555. me.showSubMenu();
  17556. }, 250);
  17557. }
  17558. },
  17559. delayHideSubMenu:function () {
  17560. var me = this;
  17561. if (!me.isDisabled()) {
  17562. me.removeState('opened');
  17563. clearTimeout(me._showingTimer);
  17564. if (!me._closingTimer) {
  17565. me._closingTimer = setTimeout(function () {
  17566. if (!me.hasState('opened')) {
  17567. me.hideSubMenu();
  17568. }
  17569. me._closingTimer = null;
  17570. }, 400);
  17571. }
  17572. }
  17573. },
  17574. renderLabelHtml:function () {
  17575. return '<div class="edui-arrow"></div>' +
  17576. '<div class="edui-box edui-icon"></div>' +
  17577. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  17578. },
  17579. getStateDom:function () {
  17580. return this.getDom();
  17581. },
  17582. queryAutoHide:function (el) {
  17583. if (this.subMenu && this.hasState('opened')) {
  17584. return this.subMenu.queryAutoHide(el);
  17585. }
  17586. },
  17587. _onClick:function (event, this_) {
  17588. if (this.hasState('disabled')) return;
  17589. if (this.fireEvent('click', event, this_) !== false) {
  17590. if (this.subMenu) {
  17591. this.showSubMenu();
  17592. } else {
  17593. Popup.postHide(event);
  17594. }
  17595. }
  17596. },
  17597. showSubMenu:function () {
  17598. var rect = uiUtils.getClientRect(this.getDom());
  17599. rect.right -= 5;
  17600. rect.left += 2;
  17601. rect.width -= 7;
  17602. rect.top -= 4;
  17603. rect.bottom += 4;
  17604. rect.height += 8;
  17605. this.subMenu.showAnchorRect(rect, true, true);
  17606. },
  17607. hideSubMenu:function () {
  17608. this.subMenu.hide();
  17609. }
  17610. };
  17611. utils.inherits(MenuItem, UIBase);
  17612. utils.extend(MenuItem.prototype, Stateful, true);
  17613. })();
  17614. ///import core
  17615. ///import uicore
  17616. ///import ui/menu.js
  17617. ///import ui/splitbutton.js
  17618. (function (){
  17619. // todo: menu和item提成通用list
  17620. var utils = baidu.editor.utils,
  17621. uiUtils = baidu.editor.ui.uiUtils,
  17622. Menu = baidu.editor.ui.Menu,
  17623. SplitButton = baidu.editor.ui.SplitButton,
  17624. Combox = baidu.editor.ui.Combox = function (options){
  17625. this.initOptions(options);
  17626. this.initCombox();
  17627. };
  17628. Combox.prototype = {
  17629. uiName: 'combox',
  17630. initCombox: function (){
  17631. var me = this;
  17632. this.items = this.items || [];
  17633. for (var i=0; i<this.items.length; i++) {
  17634. var item = this.items[i];
  17635. item.uiName = 'listitem';
  17636. item.index = i;
  17637. item.onclick = function (){
  17638. me.selectByIndex(this.index);
  17639. };
  17640. }
  17641. this.popup = new Menu({
  17642. items: this.items,
  17643. uiName: 'list',
  17644. editor:this.editor
  17645. });
  17646. this.initSplitButton();
  17647. },
  17648. _SplitButton_postRender: SplitButton.prototype.postRender,
  17649. postRender: function (){
  17650. this._SplitButton_postRender();
  17651. this.setLabel(this.label || '');
  17652. this.setValue(this.initValue || '');
  17653. },
  17654. showPopup: function (){
  17655. var rect = uiUtils.getClientRect(this.getDom());
  17656. rect.top += 1;
  17657. rect.bottom -= 1;
  17658. rect.height -= 2;
  17659. this.popup.showAnchorRect(rect);
  17660. },
  17661. getValue: function (){
  17662. return this.value;
  17663. },
  17664. setValue: function (value){
  17665. var index = this.indexByValue(value);
  17666. if (index != -1) {
  17667. this.selectedIndex = index;
  17668. this.setLabel(this.items[index].label);
  17669. this.value = this.items[index].value;
  17670. } else {
  17671. this.selectedIndex = -1;
  17672. this.setLabel(this.getLabelForUnknowValue(value));
  17673. this.value = value;
  17674. }
  17675. },
  17676. setLabel: function (label){
  17677. this.getDom('button_body').innerHTML = label;
  17678. this.label = label;
  17679. },
  17680. getLabelForUnknowValue: function (value){
  17681. return value;
  17682. },
  17683. indexByValue: function (value){
  17684. for (var i=0; i<this.items.length; i++) {
  17685. if (value == this.items[i].value) {
  17686. return i;
  17687. }
  17688. }
  17689. return -1;
  17690. },
  17691. getItem: function (index){
  17692. return this.items[index];
  17693. },
  17694. selectByIndex: function (index){
  17695. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  17696. this.selectedIndex = index;
  17697. this.value = this.items[index].value;
  17698. this.setLabel(this.items[index].label);
  17699. }
  17700. }
  17701. };
  17702. utils.inherits(Combox, SplitButton);
  17703. })();
  17704. ///import core
  17705. ///import uicore
  17706. ///import ui/mask.js
  17707. ///import ui/button.js
  17708. (function (){
  17709. var utils = baidu.editor.utils,
  17710. domUtils = baidu.editor.dom.domUtils,
  17711. uiUtils = baidu.editor.ui.uiUtils,
  17712. Mask = baidu.editor.ui.Mask,
  17713. UIBase = baidu.editor.ui.UIBase,
  17714. Button = baidu.editor.ui.Button,
  17715. Dialog = baidu.editor.ui.Dialog = function (options){
  17716. this.initOptions(utils.extend({
  17717. autoReset: true,
  17718. draggable: true,
  17719. onok: function (){},
  17720. oncancel: function (){},
  17721. onclose: function (t, ok){
  17722. return ok ? this.onok() : this.oncancel();
  17723. },
  17724. //是否控制dialog中的scroll事件, 默认为不阻止
  17725. holdScroll: false
  17726. },options));
  17727. this.initDialog();
  17728. };
  17729. var modalMask;
  17730. var dragMask;
  17731. Dialog.prototype = {
  17732. draggable: false,
  17733. uiName: 'dialog',
  17734. initDialog: function (){
  17735. var me = this,
  17736. theme=this.editor.options.theme;
  17737. this.initUIBase();
  17738. this.modalMask = (modalMask || (modalMask = new Mask({
  17739. className: 'edui-dialog-modalmask',
  17740. theme:theme
  17741. })));
  17742. this.dragMask = (dragMask || (dragMask = new Mask({
  17743. className: 'edui-dialog-dragmask',
  17744. theme:theme
  17745. })));
  17746. this.closeButton = new Button({
  17747. className: 'edui-dialog-closebutton',
  17748. title: me.closeDialog,
  17749. theme:theme,
  17750. onclick: function (){
  17751. me.close(false);
  17752. }
  17753. });
  17754. if (this.buttons) {
  17755. for (var i=0; i<this.buttons.length; i++) {
  17756. if (!(this.buttons[i] instanceof Button)) {
  17757. this.buttons[i] = new Button(this.buttons[i]);
  17758. }
  17759. }
  17760. }
  17761. },
  17762. fitSize: function (){
  17763. var popBodyEl = this.getDom('body');
  17764. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  17765. // uiUtils.removeStyle(popBodyEl, 'width');
  17766. // uiUtils.removeStyle(popBodyEl, 'height');
  17767. // }
  17768. var size = this.mesureSize();
  17769. popBodyEl.style.width = size.width + 'px';
  17770. popBodyEl.style.height = size.height + 'px';
  17771. return size;
  17772. },
  17773. safeSetOffset: function (offset){
  17774. var me = this;
  17775. var el = me.getDom();
  17776. var vpRect = uiUtils.getViewportRect();
  17777. var rect = uiUtils.getClientRect(el);
  17778. var left = offset.left;
  17779. if (left + rect.width > vpRect.right) {
  17780. left = vpRect.right - rect.width;
  17781. }
  17782. var top = offset.top;
  17783. if (top + rect.height > vpRect.bottom) {
  17784. top = vpRect.bottom - rect.height;
  17785. }
  17786. el.style.left = Math.max(left, 0) + 'px';
  17787. el.style.top = Math.max(top, 0) + 'px';
  17788. },
  17789. showAtCenter: function (){
  17790. this.getDom().style.display = '';
  17791. var vpRect = uiUtils.getViewportRect();
  17792. var popSize = this.fitSize();
  17793. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  17794. var left = vpRect.width / 2 - popSize.width / 2;
  17795. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  17796. var popEl = this.getDom();
  17797. this.safeSetOffset({
  17798. left: Math.max(left | 0, 0),
  17799. top: Math.max(top | 0, 0)
  17800. });
  17801. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  17802. popEl.className += ' edui-state-centered';
  17803. }
  17804. this._show();
  17805. },
  17806. getContentHtml: function (){
  17807. var contentHtml = '';
  17808. if (typeof this.content == 'string') {
  17809. contentHtml = this.content;
  17810. } else if (this.iframeUrl) {
  17811. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  17812. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  17813. }
  17814. return contentHtml;
  17815. },
  17816. getHtmlTpl: function (){
  17817. var footHtml = '';
  17818. if (this.buttons) {
  17819. var buff = [];
  17820. for (var i=0; i<this.buttons.length; i++) {
  17821. buff[i] = this.buttons[i].renderHtml();
  17822. }
  17823. footHtml = '<div class="%%-foot">' +
  17824. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  17825. '</div>';
  17826. }
  17827. return '<div id="##" class="%%"><div class="%%-wrap"><div id="##_body" class="%%-body">' +
  17828. '<div class="%%-shadow"></div>' +
  17829. '<div id="##_titlebar" class="%%-titlebar">' +
  17830. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  17831. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  17832. '</div>' +
  17833. this.closeButton.renderHtml() +
  17834. '</div>' +
  17835. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  17836. footHtml +
  17837. '</div></div></div>';
  17838. },
  17839. postRender: function (){
  17840. // todo: 保持居中/记住上次关闭位置选项
  17841. if (!this.modalMask.getDom()) {
  17842. this.modalMask.render();
  17843. this.modalMask.hide();
  17844. }
  17845. if (!this.dragMask.getDom()) {
  17846. this.dragMask.render();
  17847. this.dragMask.hide();
  17848. }
  17849. var me = this;
  17850. this.addListener('show', function (){
  17851. me.modalMask.show(this.getDom().style.zIndex - 2);
  17852. });
  17853. this.addListener('hide', function (){
  17854. me.modalMask.hide();
  17855. });
  17856. if (this.buttons) {
  17857. for (var i=0; i<this.buttons.length; i++) {
  17858. this.buttons[i].postRender();
  17859. }
  17860. }
  17861. domUtils.on(window, 'resize', function (){
  17862. setTimeout(function (){
  17863. if (!me.isHidden()) {
  17864. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  17865. }
  17866. });
  17867. });
  17868. //hold住scroll事件,防止dialog的滚动影响页面
  17869. if( this.holdScroll ) {
  17870. if( !me.iframeUrl ) {
  17871. domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  17872. domUtils.preventDefault(e);
  17873. } );
  17874. } else {
  17875. me.addListener('dialogafterreset', function(){
  17876. window.setTimeout(function(){
  17877. var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  17878. if( browser.ie ) {
  17879. var timer = window.setInterval(function(){
  17880. if( iframeWindow.document && iframeWindow.document.body ) {
  17881. window.clearInterval( timer );
  17882. timer = null;
  17883. domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  17884. domUtils.preventDefault(e);
  17885. } );
  17886. }
  17887. }, 100);
  17888. } else {
  17889. domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  17890. domUtils.preventDefault(e);
  17891. } );
  17892. }
  17893. }, 1);
  17894. });
  17895. }
  17896. }
  17897. this._hide();
  17898. },
  17899. mesureSize: function (){
  17900. var body = this.getDom('body');
  17901. var width = uiUtils.getClientRect(this.getDom('content')).width;
  17902. var dialogBodyStyle = body.style;
  17903. dialogBodyStyle.width = width;
  17904. return uiUtils.getClientRect(body);
  17905. },
  17906. _onTitlebarMouseDown: function (evt, el){
  17907. if (this.draggable) {
  17908. var rect;
  17909. var vpRect = uiUtils.getViewportRect();
  17910. var me = this;
  17911. uiUtils.startDrag(evt, {
  17912. ondragstart: function (){
  17913. rect = uiUtils.getClientRect(me.getDom());
  17914. me.getDom('contmask').style.visibility = 'visible';
  17915. me.dragMask.show(me.getDom().style.zIndex - 1);
  17916. },
  17917. ondragmove: function (x, y){
  17918. var left = rect.left + x;
  17919. var top = rect.top + y;
  17920. me.safeSetOffset({
  17921. left: left,
  17922. top: top
  17923. });
  17924. },
  17925. ondragstop: function (){
  17926. me.getDom('contmask').style.visibility = 'hidden';
  17927. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  17928. me.dragMask.hide();
  17929. }
  17930. });
  17931. }
  17932. },
  17933. reset: function (){
  17934. this.getDom('content').innerHTML = this.getContentHtml();
  17935. this.fireEvent('dialogafterreset');
  17936. },
  17937. _show: function (){
  17938. if (this._hidden) {
  17939. this.getDom().style.display = '';
  17940. //要高过编辑器的zindxe
  17941. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  17942. this._hidden = false;
  17943. this.fireEvent('show');
  17944. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  17945. }
  17946. },
  17947. isHidden: function (){
  17948. return this._hidden;
  17949. },
  17950. _hide: function (){
  17951. if (!this._hidden) {
  17952. this.getDom().style.display = 'none';
  17953. this.getDom().style.zIndex = '';
  17954. this._hidden = true;
  17955. this.fireEvent('hide');
  17956. }
  17957. },
  17958. open: function (){
  17959. if (this.autoReset) {
  17960. //有可能还没有渲染
  17961. try{
  17962. this.reset();
  17963. }catch(e){
  17964. this.render();
  17965. this.open()
  17966. }
  17967. }
  17968. this.showAtCenter();
  17969. if (this.iframeUrl) {
  17970. try {
  17971. this.getDom('iframe').focus();
  17972. } catch(ex){}
  17973. }
  17974. },
  17975. _onCloseButtonClick: function (evt, el){
  17976. this.close(false);
  17977. },
  17978. close: function (ok){
  17979. if (this.fireEvent('close', ok) !== false) {
  17980. this._hide();
  17981. }
  17982. }
  17983. };
  17984. utils.inherits(Dialog, UIBase);
  17985. })();
  17986. ///import core
  17987. ///import uicore
  17988. ///import ui/menu.js
  17989. ///import ui/splitbutton.js
  17990. (function (){
  17991. var utils = baidu.editor.utils,
  17992. Menu = baidu.editor.ui.Menu,
  17993. SplitButton = baidu.editor.ui.SplitButton,
  17994. MenuButton = baidu.editor.ui.MenuButton = function (options){
  17995. this.initOptions(options);
  17996. this.initMenuButton();
  17997. };
  17998. MenuButton.prototype = {
  17999. initMenuButton: function (){
  18000. var me = this;
  18001. this.uiName = "menubutton";
  18002. this.popup = new Menu({
  18003. items: me.items,
  18004. className: me.className,
  18005. editor:me.editor
  18006. });
  18007. this.popup.addListener('show', function (){
  18008. var list = this;
  18009. for (var i=0; i<list.items.length; i++) {
  18010. list.items[i].removeState('checked');
  18011. if (list.items[i].value == me._value) {
  18012. list.items[i].addState('checked');
  18013. this.value = me._value;
  18014. }
  18015. }
  18016. });
  18017. this.initSplitButton();
  18018. },
  18019. setValue : function(value){
  18020. this._value = value;
  18021. }
  18022. };
  18023. utils.inherits(MenuButton, SplitButton);
  18024. })();
  18025. //ui跟编辑器的适配層
  18026. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  18027. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  18028. (function () {
  18029. var utils = baidu.editor.utils;
  18030. var editorui = baidu.editor.ui;
  18031. var _Dialog = editorui.Dialog;
  18032. editorui.buttons = {};
  18033. editorui.Dialog = function (options) {
  18034. var dialog = new _Dialog(options);
  18035. dialog.addListener('hide', function () {
  18036. if (dialog.editor) {
  18037. var editor = dialog.editor;
  18038. try {
  18039. if (browser.gecko) {
  18040. var y = editor.window.scrollY,
  18041. x = editor.window.scrollX;
  18042. editor.body.focus();
  18043. editor.window.scrollTo(x, y);
  18044. } else {
  18045. editor.focus();
  18046. }
  18047. } catch (ex) {
  18048. }
  18049. }
  18050. });
  18051. return dialog;
  18052. };
  18053. var iframeUrlMap = {
  18054. 'anchor':'~/dialogs/anchor/anchor.html',
  18055. 'insertimage':'~/dialogs/image/image.html',
  18056. 'link':'~/dialogs/link/link.html',
  18057. 'spechars':'~/dialogs/spechars/spechars.html',
  18058. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  18059. 'map':'~/dialogs/map/map.html',
  18060. 'gmap':'~/dialogs/gmap/gmap.html',
  18061. 'insertvideo':'~/dialogs/video/video.html',
  18062. 'help':'~/dialogs/help/help.html',
  18063. //'highlightcode':'~/dialogs/highlightcode/highlightcode.html',
  18064. 'emotion':'~/dialogs/emotion/emotion.html',
  18065. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  18066. 'attachment':'~/dialogs/attachment/attachment.html',
  18067. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  18068. 'edittip':'~/dialogs/table/edittip.html',
  18069. 'edittable':'~/dialogs/table/edittable.html',
  18070. 'edittd':'~/dialogs/table/edittd.html',
  18071. 'webapp':'~/dialogs/webapp/webapp.html',
  18072. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  18073. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  18074. 'music':'~/dialogs/music/music.html',
  18075. 'template':'~/dialogs/template/template.html',
  18076. 'background':'~/dialogs/background/background.html'
  18077. };
  18078. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  18079. var btnCmds = ['undo', 'redo', 'formatmatch',
  18080. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  18081. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  18082. 'blockquote', 'pasteplain', 'pagebreak',
  18083. 'selectall', 'print', 'preview', 'horizontal', 'removeformat', 'time', 'date', 'unlink',
  18084. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  18085. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable','formula','videotl','tiankong'];
  18086. for (var i = 0, ci; ci = btnCmds[i++];) {
  18087. ci = ci.toLowerCase();
  18088. editorui[ci] = function (cmd) {
  18089. return function (editor) {
  18090. var ui = new editorui.Button({
  18091. className:'edui-for-' + cmd,
  18092. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  18093. onclick:function () {
  18094. editor.execCommand(cmd);
  18095. },
  18096. theme:editor.options.theme,
  18097. showText:false
  18098. });
  18099. editorui.buttons[cmd] = ui;
  18100. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18101. var state = editor.queryCommandState(cmd);
  18102. if (state == -1) {
  18103. ui.setDisabled(true);
  18104. ui.setChecked(false);
  18105. } else {
  18106. if (!uiReady) {
  18107. ui.setDisabled(false);
  18108. ui.setChecked(state);
  18109. }
  18110. }
  18111. });
  18112. return ui;
  18113. };
  18114. }(ci);
  18115. }
  18116. //清除文档
  18117. editorui.cleardoc = function (editor) {
  18118. var ui = new editorui.Button({
  18119. className:'edui-for-cleardoc',
  18120. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  18121. theme:editor.options.theme,
  18122. onclick:function () {
  18123. if (confirm(editor.getLang("confirmClear"))) {
  18124. editor.execCommand('cleardoc');
  18125. }
  18126. }
  18127. });
  18128. editorui.buttons["cleardoc"] = ui;
  18129. editor.addListener('selectionchange', function () {
  18130. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  18131. });
  18132. return ui;
  18133. };
  18134. //排版,图片排版,文字方向
  18135. var typeset = {
  18136. 'justify':['left', 'right', 'center', 'justify'],
  18137. 'imagefloat':['none', 'left', 'center', 'right'],
  18138. 'directionality':['ltr', 'rtl']
  18139. };
  18140. for (var p in typeset) {
  18141. (function (cmd, val) {
  18142. for (var i = 0, ci; ci = val[i++];) {
  18143. (function (cmd2) {
  18144. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  18145. var ui = new editorui.Button({
  18146. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  18147. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  18148. theme:editor.options.theme,
  18149. onclick:function () {
  18150. editor.execCommand(cmd, cmd2);
  18151. }
  18152. });
  18153. editorui.buttons[cmd] = ui;
  18154. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18155. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  18156. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  18157. });
  18158. return ui;
  18159. };
  18160. })(ci)
  18161. }
  18162. })(p, typeset[p])
  18163. }
  18164. //字体颜色和背景颜色
  18165. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  18166. editorui[ci] = function (cmd) {
  18167. return function (editor) {
  18168. var ui = new editorui.ColorButton({
  18169. className:'edui-for-' + cmd,
  18170. color:'default',
  18171. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  18172. editor:editor,
  18173. onpickcolor:function (t, color) {
  18174. editor.execCommand(cmd, color);
  18175. },
  18176. onpicknocolor:function () {
  18177. editor.execCommand(cmd, 'default');
  18178. this.setColor('transparent');
  18179. this.color = 'default';
  18180. },
  18181. onbuttonclick:function () {
  18182. editor.execCommand(cmd, this.color);
  18183. }
  18184. });
  18185. editorui.buttons[cmd] = ui;
  18186. editor.addListener('selectionchange', function () {
  18187. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  18188. });
  18189. return ui;
  18190. };
  18191. }(ci);
  18192. }
  18193. var dialogBtns = {
  18194. noOk:['searchreplace', 'help', 'spechars', 'webapp'],
  18195. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  18196. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background']
  18197. };
  18198. for (var p in dialogBtns) {
  18199. (function (type, vals) {
  18200. for (var i = 0, ci; ci = vals[i++];) {
  18201. //todo opera下存在问题
  18202. if (browser.opera && ci === "searchreplace") {
  18203. continue;
  18204. }
  18205. (function (cmd) {
  18206. editorui[cmd] = function (editor, iframeUrl, title) {
  18207. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  18208. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  18209. var dialog;
  18210. //没有iframeUrl不创建dialog
  18211. if (iframeUrl) {
  18212. dialog = new editorui.Dialog(utils.extend({
  18213. iframeUrl:editor.ui.mapUrl(iframeUrl),
  18214. editor:editor,
  18215. className:'edui-for-' + cmd,
  18216. title:title,
  18217. holdScroll: cmd === 'insertimage',
  18218. closeDialog:editor.getLang("closeDialog")
  18219. }, type == 'ok' ? {
  18220. buttons:[
  18221. {
  18222. className:'edui-okbutton',
  18223. label:editor.getLang("ok"),
  18224. editor:editor,
  18225. onclick:function () {
  18226. dialog.close(true);
  18227. }
  18228. },
  18229. {
  18230. className:'edui-cancelbutton',
  18231. label:editor.getLang("cancel"),
  18232. editor:editor,
  18233. onclick:function () {
  18234. dialog.close(false);
  18235. }
  18236. }
  18237. ]
  18238. } : {}));
  18239. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  18240. }
  18241. var ui = new editorui.Button({
  18242. className:'edui-for-' + cmd,
  18243. title:title,
  18244. onclick:function () {
  18245. if (dialog) {
  18246. switch (cmd) {
  18247. case "wordimage":
  18248. editor.execCommand("wordimage", "word_img");
  18249. if (editor.word_img) {
  18250. dialog.render();
  18251. dialog.open();
  18252. }
  18253. break;
  18254. case "scrawl":
  18255. if (editor.queryCommandState("scrawl") != -1) {
  18256. dialog.render();
  18257. dialog.open();
  18258. }
  18259. break;
  18260. default:
  18261. dialog.render();
  18262. dialog.open();
  18263. }
  18264. }
  18265. },
  18266. theme:editor.options.theme,
  18267. disabled:cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1
  18268. });
  18269. editorui.buttons[cmd] = ui;
  18270. editor.addListener('selectionchange', function () {
  18271. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  18272. var unNeedCheckState = {'edittable':1};
  18273. if (cmd in unNeedCheckState)return;
  18274. var state = editor.queryCommandState(cmd);
  18275. if (ui.getDom()) {
  18276. ui.setDisabled(state == -1);
  18277. ui.setChecked(state);
  18278. }
  18279. });
  18280. return ui;
  18281. };
  18282. })(ci.toLowerCase())
  18283. }
  18284. })(p, dialogBtns[p])
  18285. }
  18286. editorui.snapscreen = function (editor, iframeUrl, title) {
  18287. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  18288. var ui = new editorui.Button({
  18289. className:'edui-for-snapscreen',
  18290. title:title,
  18291. onclick:function () {
  18292. editor.execCommand("snapscreen");
  18293. },
  18294. theme:editor.options.theme
  18295. });
  18296. editorui.buttons['snapscreen'] = ui;
  18297. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  18298. if (iframeUrl) {
  18299. var dialog = new editorui.Dialog({
  18300. iframeUrl:editor.ui.mapUrl(iframeUrl),
  18301. editor:editor,
  18302. className:'edui-for-snapscreen',
  18303. title:title,
  18304. buttons:[
  18305. {
  18306. className:'edui-okbutton',
  18307. label:editor.getLang("ok"),
  18308. editor:editor,
  18309. onclick:function () {
  18310. dialog.close(true);
  18311. }
  18312. },
  18313. {
  18314. className:'edui-cancelbutton',
  18315. label:editor.getLang("cancel"),
  18316. editor:editor,
  18317. onclick:function () {
  18318. dialog.close(false);
  18319. }
  18320. }
  18321. ]
  18322. });
  18323. dialog.render();
  18324. editor.ui._dialogs["snapscreenDialog"] = dialog;
  18325. }
  18326. editor.addListener('selectionchange', function () {
  18327. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  18328. });
  18329. return ui;
  18330. };
  18331. editorui.insertcode = function (editor, list, title) {
  18332. list = editor.options['insertcode'] || [];
  18333. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  18334. // if (!list.length) return;
  18335. var items = [];
  18336. utils.each(list,function(key,val){
  18337. items.push({
  18338. label:key,
  18339. value:val,
  18340. theme:editor.options.theme,
  18341. renderLabelHtml:function () {
  18342. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  18343. }
  18344. });
  18345. });
  18346. var ui = new editorui.Combox({
  18347. editor:editor,
  18348. items:items,
  18349. onselect:function (t, index) {
  18350. editor.execCommand('insertcode', this.items[index].value);
  18351. },
  18352. onbuttonclick:function () {
  18353. this.showPopup();
  18354. },
  18355. title:title,
  18356. initValue:title,
  18357. className:'edui-for-insertcode',
  18358. indexByValue:function (value) {
  18359. if (value) {
  18360. for (var i = 0, ci; ci = this.items[i]; i++) {
  18361. if (ci.value.indexOf(value) != -1)
  18362. return i;
  18363. }
  18364. }
  18365. return -1;
  18366. }
  18367. });
  18368. editorui.buttons['insertcode'] = ui;
  18369. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18370. if (!uiReady) {
  18371. var state = editor.queryCommandState('insertcode');
  18372. if (state == -1) {
  18373. ui.setDisabled(true);
  18374. } else {
  18375. ui.setDisabled(false);
  18376. var value = editor.queryCommandValue('insertcode');
  18377. if(!value){
  18378. ui.setValue(title);
  18379. return;
  18380. }
  18381. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  18382. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  18383. ui.setValue(value);
  18384. }
  18385. }
  18386. });
  18387. return ui;
  18388. };
  18389. editorui.fontfamily = function (editor, list, title) {
  18390. list = editor.options['fontfamily'] || [];
  18391. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  18392. if (!list.length) return;
  18393. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  18394. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  18395. (function (key, val) {
  18396. items.push({
  18397. label:key,
  18398. value:val,
  18399. theme:editor.options.theme,
  18400. renderLabelHtml:function () {
  18401. return '<div class="edui-label %%-label" style="font-family:' +
  18402. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  18403. }
  18404. });
  18405. })(ci.label || langLabel, ci.val)
  18406. }
  18407. var ui = new editorui.Combox({
  18408. editor:editor,
  18409. items:items,
  18410. onselect:function (t, index) {
  18411. editor.execCommand('FontFamily', this.items[index].value);
  18412. },
  18413. onbuttonclick:function () {
  18414. this.showPopup();
  18415. },
  18416. title:title,
  18417. initValue:title,
  18418. className:'edui-for-fontfamily',
  18419. indexByValue:function (value) {
  18420. if (value) {
  18421. for (var i = 0, ci; ci = this.items[i]; i++) {
  18422. if (ci.value.indexOf(value) != -1)
  18423. return i;
  18424. }
  18425. }
  18426. return -1;
  18427. }
  18428. });
  18429. editorui.buttons['fontfamily'] = ui;
  18430. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18431. if (!uiReady) {
  18432. var state = editor.queryCommandState('FontFamily');
  18433. if (state == -1) {
  18434. ui.setDisabled(true);
  18435. } else {
  18436. ui.setDisabled(false);
  18437. var value = editor.queryCommandValue('FontFamily');
  18438. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  18439. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  18440. ui.setValue(value);
  18441. }
  18442. }
  18443. });
  18444. return ui;
  18445. };
  18446. editorui.fontsize = function (editor, list, title) {
  18447. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  18448. list = list || editor.options['fontsize'] || [];
  18449. if (!list.length) return;
  18450. var items = [];
  18451. for (var i = 0; i < list.length; i++) {
  18452. var size = list[i] + 'px';
  18453. items.push({
  18454. label:size,
  18455. value:size,
  18456. theme:editor.options.theme,
  18457. renderLabelHtml:function () {
  18458. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  18459. this.value + '">' + (this.label || '') + '</div>';
  18460. }
  18461. });
  18462. }
  18463. var ui = new editorui.Combox({
  18464. editor:editor,
  18465. items:items,
  18466. title:title,
  18467. initValue:title,
  18468. onselect:function (t, index) {
  18469. editor.execCommand('FontSize', this.items[index].value);
  18470. },
  18471. onbuttonclick:function () {
  18472. this.showPopup();
  18473. },
  18474. className:'edui-for-fontsize'
  18475. });
  18476. editorui.buttons['fontsize'] = ui;
  18477. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18478. if (!uiReady) {
  18479. var state = editor.queryCommandState('FontSize');
  18480. if (state == -1) {
  18481. ui.setDisabled(true);
  18482. } else {
  18483. ui.setDisabled(false);
  18484. ui.setValue(editor.queryCommandValue('FontSize'));
  18485. }
  18486. }
  18487. });
  18488. return ui;
  18489. };
  18490. editorui.paragraph = function (editor, list, title) {
  18491. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  18492. list = editor.options['paragraph'] || [];
  18493. if (utils.isEmptyObject(list)) return;
  18494. var items = [];
  18495. for (var i in list) {
  18496. items.push({
  18497. value:i,
  18498. label:list[i] || editor.getLang("paragraph")[i],
  18499. theme:editor.options.theme,
  18500. renderLabelHtml:function () {
  18501. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  18502. }
  18503. })
  18504. }
  18505. var ui = new editorui.Combox({
  18506. editor:editor,
  18507. items:items,
  18508. title:title,
  18509. initValue:title,
  18510. className:'edui-for-paragraph',
  18511. onselect:function (t, index) {
  18512. editor.execCommand('Paragraph', this.items[index].value);
  18513. },
  18514. onbuttonclick:function () {
  18515. this.showPopup();
  18516. }
  18517. });
  18518. editorui.buttons['paragraph'] = ui;
  18519. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18520. if (!uiReady) {
  18521. var state = editor.queryCommandState('Paragraph');
  18522. if (state == -1) {
  18523. ui.setDisabled(true);
  18524. } else {
  18525. ui.setDisabled(false);
  18526. var value = editor.queryCommandValue('Paragraph');
  18527. var index = ui.indexByValue(value);
  18528. if (index != -1) {
  18529. ui.setValue(value);
  18530. } else {
  18531. ui.setValue(ui.initValue);
  18532. }
  18533. }
  18534. }
  18535. });
  18536. return ui;
  18537. };
  18538. //自定义标题
  18539. editorui.customstyle = function (editor) {
  18540. var list = editor.options['customstyle'] || [],
  18541. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  18542. if (!list.length)return;
  18543. var langCs = editor.getLang('customstyle');
  18544. for (var i = 0, items = [], t; t = list[i++];) {
  18545. (function (t) {
  18546. var ck = {};
  18547. ck.label = t.label ? t.label : langCs[t.name];
  18548. ck.style = t.style;
  18549. ck.className = t.className;
  18550. ck.tag = t.tag;
  18551. items.push({
  18552. label:ck.label,
  18553. value:ck,
  18554. theme:editor.options.theme,
  18555. renderLabelHtml:function () {
  18556. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  18557. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  18558. + '</div>';
  18559. }
  18560. });
  18561. })(t);
  18562. }
  18563. var ui = new editorui.Combox({
  18564. editor:editor,
  18565. items:items,
  18566. title:title,
  18567. initValue:title,
  18568. className:'edui-for-customstyle',
  18569. onselect:function (t, index) {
  18570. editor.execCommand('customstyle', this.items[index].value);
  18571. },
  18572. onbuttonclick:function () {
  18573. this.showPopup();
  18574. },
  18575. indexByValue:function (value) {
  18576. for (var i = 0, ti; ti = this.items[i++];) {
  18577. if (ti.label == value) {
  18578. return i - 1
  18579. }
  18580. }
  18581. return -1;
  18582. }
  18583. });
  18584. editorui.buttons['customstyle'] = ui;
  18585. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  18586. if (!uiReady) {
  18587. var state = editor.queryCommandState('customstyle');
  18588. if (state == -1) {
  18589. ui.setDisabled(true);
  18590. } else {
  18591. ui.setDisabled(false);
  18592. var value = editor.queryCommandValue('customstyle');
  18593. var index = ui.indexByValue(value);
  18594. if (index != -1) {
  18595. ui.setValue(value);
  18596. } else {
  18597. ui.setValue(ui.initValue);
  18598. }
  18599. }
  18600. }
  18601. });
  18602. return ui;
  18603. };
  18604. editorui.inserttable = function (editor, iframeUrl, title) {
  18605. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  18606. var ui = new editorui.TableButton({
  18607. editor:editor,
  18608. title:title,
  18609. className:'edui-for-inserttable',
  18610. onpicktable:function (t, numCols, numRows) {
  18611. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  18612. },
  18613. onbuttonclick:function () {
  18614. this.showPopup();
  18615. }
  18616. });
  18617. editorui.buttons['inserttable'] = ui;
  18618. editor.addListener('selectionchange', function () {
  18619. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  18620. });
  18621. return ui;
  18622. };
  18623. editorui.lineheight = function (editor) {
  18624. var val = editor.options.lineheight || [];
  18625. if (!val.length)return;
  18626. for (var i = 0, ci, items = []; ci = val[i++];) {
  18627. items.push({
  18628. //todo:写死了
  18629. label:ci,
  18630. value:ci,
  18631. theme:editor.options.theme,
  18632. onclick:function () {
  18633. editor.execCommand("lineheight", this.value);
  18634. }
  18635. })
  18636. }
  18637. var ui = new editorui.MenuButton({
  18638. editor:editor,
  18639. className:'edui-for-lineheight',
  18640. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  18641. items:items,
  18642. onbuttonclick:function () {
  18643. var value = editor.queryCommandValue('LineHeight') || this.value;
  18644. editor.execCommand("LineHeight", value);
  18645. }
  18646. });
  18647. editorui.buttons['lineheight'] = ui;
  18648. editor.addListener('selectionchange', function () {
  18649. var state = editor.queryCommandState('LineHeight');
  18650. if (state == -1) {
  18651. ui.setDisabled(true);
  18652. } else {
  18653. ui.setDisabled(false);
  18654. var value = editor.queryCommandValue('LineHeight');
  18655. value && ui.setValue((value + '').replace(/cm/, ''));
  18656. ui.setChecked(state)
  18657. }
  18658. });
  18659. return ui;
  18660. };
  18661. var rowspacings = ['top', 'bottom'];
  18662. for (var r = 0, ri; ri = rowspacings[r++];) {
  18663. (function (cmd) {
  18664. editorui['rowspacing' + cmd] = function (editor) {
  18665. var val = editor.options['rowspacing' + cmd] || [];
  18666. if (!val.length) return null;
  18667. for (var i = 0, ci, items = []; ci = val[i++];) {
  18668. items.push({
  18669. label:ci,
  18670. value:ci,
  18671. theme:editor.options.theme,
  18672. onclick:function () {
  18673. editor.execCommand("rowspacing", this.value, cmd);
  18674. }
  18675. })
  18676. }
  18677. var ui = new editorui.MenuButton({
  18678. editor:editor,
  18679. className:'edui-for-rowspacing' + cmd,
  18680. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  18681. items:items,
  18682. onbuttonclick:function () {
  18683. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  18684. editor.execCommand("rowspacing", value, cmd);
  18685. }
  18686. });
  18687. editorui.buttons[cmd] = ui;
  18688. editor.addListener('selectionchange', function () {
  18689. var state = editor.queryCommandState('rowspacing', cmd);
  18690. if (state == -1) {
  18691. ui.setDisabled(true);
  18692. } else {
  18693. ui.setDisabled(false);
  18694. var value = editor.queryCommandValue('rowspacing', cmd);
  18695. value && ui.setValue((value + '').replace(/%/, ''));
  18696. ui.setChecked(state)
  18697. }
  18698. });
  18699. return ui;
  18700. }
  18701. })(ri)
  18702. }
  18703. //有序,无序列表
  18704. var lists = ['insertorderedlist', 'insertunorderedlist'];
  18705. for (var l = 0, cl; cl = lists[l++];) {
  18706. (function (cmd) {
  18707. editorui[cmd] = function (editor) {
  18708. var vals = editor.options[cmd],
  18709. _onMenuClick = function () {
  18710. editor.execCommand(cmd, this.value);
  18711. }, items = [];
  18712. for (var i in vals) {
  18713. items.push({
  18714. label:vals[i] || editor.getLang()[cmd][i] || "",
  18715. value:i,
  18716. theme:editor.options.theme,
  18717. onclick:_onMenuClick
  18718. })
  18719. }
  18720. var ui = new editorui.MenuButton({
  18721. editor:editor,
  18722. className:'edui-for-' + cmd,
  18723. title:editor.getLang("labelMap." + cmd) || '',
  18724. 'items':items,
  18725. onbuttonclick:function () {
  18726. var value = editor.queryCommandValue(cmd) || this.value;
  18727. editor.execCommand(cmd, value);
  18728. }
  18729. });
  18730. editorui.buttons[cmd] = ui;
  18731. editor.addListener('selectionchange', function () {
  18732. var state = editor.queryCommandState(cmd);
  18733. if (state == -1) {
  18734. ui.setDisabled(true);
  18735. } else {
  18736. ui.setDisabled(false);
  18737. var value = editor.queryCommandValue(cmd);
  18738. ui.setValue(value);
  18739. ui.setChecked(state)
  18740. }
  18741. });
  18742. return ui;
  18743. };
  18744. })(cl)
  18745. }
  18746. editorui.fullscreen = function (editor, title) {
  18747. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  18748. var ui = new editorui.Button({
  18749. className:'edui-for-fullscreen',
  18750. title:title,
  18751. theme:editor.options.theme,
  18752. onclick:function () {
  18753. if (editor.ui) {
  18754. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  18755. }
  18756. this.setChecked(editor.ui.isFullScreen());
  18757. }
  18758. });
  18759. editorui.buttons['fullscreen'] = ui;
  18760. editor.addListener('selectionchange', function () {
  18761. var state = editor.queryCommandState('fullscreen');
  18762. ui.setDisabled(state == -1);
  18763. ui.setChecked(editor.ui.isFullScreen());
  18764. });
  18765. return ui;
  18766. };
  18767. // 表情
  18768. editorui["emotion"] = function (editor, iframeUrl) {
  18769. var cmd = "emotion";
  18770. var ui = new editorui.MultiMenuPop({
  18771. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  18772. editor:editor,
  18773. className:'edui-for-' + cmd,
  18774. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  18775. });
  18776. editorui.buttons[cmd] = ui;
  18777. editor.addListener('selectionchange', function () {
  18778. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  18779. });
  18780. return ui;
  18781. };
  18782. editorui.autotypeset = function (editor) {
  18783. var ui = new editorui.AutoTypeSetButton({
  18784. editor:editor,
  18785. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  18786. className:'edui-for-autotypeset',
  18787. onbuttonclick:function () {
  18788. editor.execCommand('autotypeset')
  18789. }
  18790. });
  18791. editorui.buttons['autotypeset'] = ui;
  18792. editor.addListener('selectionchange', function () {
  18793. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  18794. });
  18795. return ui;
  18796. };
  18797. })();
  18798. ///import core
  18799. ///commands 全屏
  18800. ///commandsName FullScreen
  18801. ///commandsTitle 全屏
  18802. (function () {
  18803. var utils = baidu.editor.utils,
  18804. uiUtils = baidu.editor.ui.uiUtils,
  18805. UIBase = baidu.editor.ui.UIBase,
  18806. domUtils = baidu.editor.dom.domUtils;
  18807. var nodeStack = [];
  18808. function EditorUI(options) {
  18809. this.initOptions(options);
  18810. this.initEditorUI();
  18811. }
  18812. EditorUI.prototype = {
  18813. uiName:'editor',
  18814. initEditorUI:function () {
  18815. this.editor.ui = this;
  18816. this._dialogs = {};
  18817. this.initUIBase();
  18818. this._initToolbars();
  18819. var editor = this.editor,
  18820. me = this;
  18821. editor.addListener('ready', function () {
  18822. //提供getDialog方法
  18823. editor.getDialog = function (name) {
  18824. return editor.ui._dialogs[name + "Dialog"];
  18825. };
  18826. domUtils.on(editor.window, 'scroll', function (evt) {
  18827. baidu.editor.ui.Popup.postHide(evt);
  18828. });
  18829. //提供编辑器实时宽高(全屏时宽高不变化)
  18830. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  18831. //display bottom-bar label based on config
  18832. if (editor.options.elementPathEnabled) {
  18833. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  18834. }
  18835. if (editor.options.wordCount) {
  18836. function countFn() {
  18837. setCount(editor,me);
  18838. domUtils.un(editor.document, "click", arguments.callee);
  18839. }
  18840. domUtils.on(editor.document, "click", countFn);
  18841. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  18842. }
  18843. editor.ui._scale();
  18844. if (editor.options.scaleEnabled) {
  18845. if (editor.autoHeightEnabled) {
  18846. editor.disableAutoHeight();
  18847. }
  18848. me.enableScale();
  18849. } else {
  18850. me.disableScale();
  18851. }
  18852. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  18853. editor.ui.getDom('elementpath').style.display = "none";
  18854. editor.ui.getDom('wordcount').style.display = "none";
  18855. editor.ui.getDom('scale').style.display = "none";
  18856. }
  18857. if (!editor.selection.isFocus())return;
  18858. editor.fireEvent('selectionchange', false, true);
  18859. });
  18860. editor.addListener('mousedown', function (t, evt) {
  18861. var el = evt.target || evt.srcElement;
  18862. baidu.editor.ui.Popup.postHide(evt, el);
  18863. });
  18864. editor.addListener("delcells", function () {
  18865. if (UE.ui['edittip']) {
  18866. new UE.ui['edittip'](editor);
  18867. }
  18868. editor.getDialog('edittip').open();
  18869. });
  18870. var pastePop, isPaste = false, timer;
  18871. editor.addListener("afterpaste", function () {
  18872. if(editor.queryCommandState('pasteplain'))
  18873. return;
  18874. pastePop = new baidu.editor.ui.Popup({
  18875. content:new baidu.editor.ui.PastePicker({editor:editor}),
  18876. editor:editor,
  18877. className:'edui-wordpastepop'
  18878. });
  18879. pastePop.render();
  18880. isPaste = true;
  18881. });
  18882. editor.addListener("afterinserthtml", function () {
  18883. clearTimeout(timer);
  18884. timer = setTimeout(function () {
  18885. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  18886. var span = domUtils.createElement(editor.document, 'span', {
  18887. 'style':"line-height:0px;",
  18888. 'innerHTML':'\ufeff'
  18889. }),
  18890. range = editor.selection.getRange();
  18891. range.insertNode(span);
  18892. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  18893. pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  18894. domUtils.remove(span);
  18895. delete editor.ui._isTransfer;
  18896. isPaste = false;
  18897. }
  18898. }, 200)
  18899. });
  18900. editor.addListener('contextmenu', function (t, evt) {
  18901. baidu.editor.ui.Popup.postHide(evt);
  18902. });
  18903. editor.addListener('keydown', function (t, evt) {
  18904. if (pastePop) pastePop.dispose(evt);
  18905. var keyCode = evt.keyCode || evt.which;
  18906. if(evt.altKey&&keyCode==90){
  18907. UE.ui.buttons['fullscreen'].onclick();
  18908. }
  18909. });
  18910. editor.addListener('wordcount', function (type) {
  18911. setCount(this,me);
  18912. });
  18913. function setCount(editor,ui) {
  18914. editor.setOpt({
  18915. wordCount:true,
  18916. maximumWords:10000,
  18917. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  18918. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  18919. });
  18920. var opt = editor.options,
  18921. max = opt.maximumWords,
  18922. msg = opt.wordCountMsg ,
  18923. errMsg = opt.wordOverFlowMsg,
  18924. countDom = ui.getDom('wordcount');
  18925. if (!opt.wordCount) {
  18926. return;
  18927. }
  18928. var count = editor.getContentLength(true);
  18929. if (count > max) {
  18930. countDom.innerHTML = errMsg;
  18931. editor.fireEvent("wordcountoverflow");
  18932. } else {
  18933. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  18934. }
  18935. }
  18936. editor.addListener('selectionchange', function () {
  18937. if (editor.options.elementPathEnabled) {
  18938. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  18939. }
  18940. if (editor.options.scaleEnabled) {
  18941. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  18942. }
  18943. });
  18944. var popup = new baidu.editor.ui.Popup({
  18945. editor:editor,
  18946. content:'',
  18947. className:'edui-bubble',
  18948. _onEditButtonClick:function () {
  18949. this.hide();
  18950. editor.ui._dialogs.linkDialog.open();
  18951. },
  18952. _onImgEditButtonClick:function (name) {
  18953. this.hide();
  18954. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  18955. },
  18956. _onImgSetFloat:function (value) {
  18957. this.hide();
  18958. editor.execCommand("imagefloat", value);
  18959. },
  18960. setftImgSizeDown : function(type,obj,e){
  18961. switch(e.keyCode){
  18962. case 38:
  18963. obj.value = parseInt(obj.value) + 2;
  18964. return false;
  18965. break;
  18966. case 40:
  18967. obj.value = parseInt(obj.value) - 2;
  18968. return false;
  18969. break;
  18970. }
  18971. },
  18972. setftImgSize : function(type,obj,e){
  18973. if(type=="width"){
  18974. obj = obj;
  18975. }else if(type=="height"){
  18976. var prev = obj.previousElementSibling;
  18977. if(obj.nextElementSibling.getElementsByTagName("input")[0].checked){
  18978. prev.value = parseInt(obj.value*prev.getAttribute("bl"));
  18979. }
  18980. obj = prev;
  18981. }
  18982. var hObj = obj.nextElementSibling;
  18983. var checked = hObj.nextElementSibling.getElementsByTagName("input")[0].checked;
  18984. if(checked && type!="height"){
  18985. hObj.value = parseInt(obj.value/obj.getAttribute("bl")) || "";
  18986. }
  18987. var img = this.editor.selection.getRange().getClosedNode();
  18988. var width = obj.value;
  18989. var height = obj.nextElementSibling.value;
  18990. if(width){
  18991. img.width = width;
  18992. }else{
  18993. img.removeAttribute("width");
  18994. }
  18995. if(height){
  18996. img.height = height;
  18997. }else{
  18998. img.removeAttribute("height");
  18999. }
  19000. var ue = this.editor;
  19001. var arrFunc = ue.__allListeners.contentchange;
  19002. arrFunc[arrFunc.length-1].call(ue);
  19003. ue.textarea.value = ue.getContent();
  19004. },
  19005. _setIframeAlign:function (value) {
  19006. var frame = popup.anchorEl;
  19007. var newFrame = frame.cloneNode(true);
  19008. switch (value) {
  19009. case -2:
  19010. newFrame.setAttribute("align", "");
  19011. break;
  19012. case -1:
  19013. newFrame.setAttribute("align", "left");
  19014. break;
  19015. case 1:
  19016. newFrame.setAttribute("align", "right");
  19017. break;
  19018. }
  19019. frame.parentNode.insertBefore(newFrame, frame);
  19020. domUtils.remove(frame);
  19021. popup.anchorEl = newFrame;
  19022. popup.showAnchor(popup.anchorEl);
  19023. },
  19024. _updateIframe:function () {
  19025. editor._iframe = popup.anchorEl;
  19026. editor.ui._dialogs.insertframeDialog.open();
  19027. popup.hide();
  19028. },
  19029. _onRemoveButtonClick:function (cmdName) {
  19030. editor.execCommand(cmdName);
  19031. this.hide();
  19032. },
  19033. queryAutoHide:function (el) {
  19034. if (el && el.ownerDocument == editor.document) {
  19035. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  19036. return el !== popup.anchorEl;
  19037. }
  19038. }
  19039. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  19040. }
  19041. });
  19042. popup.render();
  19043. if (editor.options.imagePopup) {
  19044. editor.addListener('mouseover', function (t, evt) {
  19045. evt = evt || window.event;
  19046. var el = evt.target || evt.srcElement;
  19047. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  19048. var html = popup.formatHtml(
  19049. '<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;' +
  19050. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  19051. if (html) {
  19052. popup.getDom('content').innerHTML = html;
  19053. popup.anchorEl = el;
  19054. popup.showAnchor(popup.anchorEl);
  19055. } else {
  19056. popup.hide();
  19057. }
  19058. }
  19059. });
  19060. editor.addListener('selectionchange', function (t, causeByUi) {
  19061. if (!causeByUi) return;
  19062. var html = '', str = "",
  19063. img = editor.selection.getRange().getClosedNode(),
  19064. dialogs = editor.ui._dialogs;
  19065. if(img && (img.className=="gseditor" || img.className.indexOf("gsImgLatex")>=0)){
  19066. return;
  19067. }
  19068. if (img && img.tagName == 'IMG') {
  19069. var dialogName = 'insertimageDialog';
  19070. if (img.className.indexOf("edui-faked-video") != -1) {
  19071. dialogName = "insertvideoDialog"
  19072. }
  19073. if (img.className.indexOf("edui-faked-webapp") != -1) {
  19074. dialogName = "webappDialog"
  19075. }
  19076. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  19077. dialogName = "mapDialog"
  19078. }
  19079. if (img.className.indexOf("edui-faked-music") != -1) {
  19080. dialogName = "musicDialog"
  19081. }
  19082. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  19083. dialogName = "gmapDialog"
  19084. }
  19085. if (img.getAttribute("anchorname")) {
  19086. dialogName = "anchorDialog";
  19087. html = popup.formatHtml(
  19088. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  19089. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  19090. }
  19091. if (img.getAttribute("word_img")) {
  19092. //todo 放到dialog去做查询
  19093. editor.word_img = [img.getAttribute("word_img")];
  19094. dialogName = "wordimageDialog"
  19095. }
  19096. if (!dialogs[dialogName]) {
  19097. return;
  19098. }
  19099. str = '<nobr>' + editor.getLang("property") + ': '+
  19100. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;' +
  19101. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;' +
  19102. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;' +
  19103. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;'+
  19104. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  19105. str += '<p class="ft_ue_img">宽:<input bl="'+img.width/img.height+'" type="text" onkeyup=\'$$.setftImgSize("width",this,event)\' onkeydown=\'return $$.setftImgSizeDown("width",this,event)\' class="ft_txt" name="ft_ue_imgwidth" value="'+img.width+'"/> 高:<input type="text" onkeydown=\'return $$.setftImgSizeDown("height",this,event)\' onkeyup=\'$$.setftImgSize("height",this,event)\' name="ft_ue_imgheight" class="ft_txt" value="'+img.height+'"/> <label><input type="checkbox" id="ft_ue_imgchecked" class="ft_ue_box" checked/>自动</label></p>'
  19106. !html && (html = popup.formatHtml(str))
  19107. }
  19108. if (editor.ui._dialogs.linkDialog) {
  19109. var link = editor.queryCommandValue('link');
  19110. var url;
  19111. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  19112. var txt = url;
  19113. if (url.length > 30) {
  19114. txt = url.substring(0, 20) + "...";
  19115. }
  19116. if (html) {
  19117. html += '<div style="height:5px;"></div>'
  19118. }
  19119. html += popup.formatHtml(
  19120. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  19121. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  19122. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  19123. popup.showAnchor(link);
  19124. }
  19125. }
  19126. if (html) {
  19127. popup.getDom('content').innerHTML = html;
  19128. popup.anchorEl = img || link;
  19129. popup.showAnchor(popup.anchorEl);
  19130. } else {
  19131. popup.hide();
  19132. }
  19133. });
  19134. }
  19135. },
  19136. _initToolbars:function () {
  19137. var editor = this.editor;
  19138. var toolbars = this.toolbars || [];
  19139. var toolbarUis = [];
  19140. for (var i = 0; i < toolbars.length; i++) {
  19141. var toolbar = toolbars[i];
  19142. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  19143. for (var j = 0; j < toolbar.length; j++) {
  19144. var toolbarItem = toolbar[j];
  19145. var toolbarItemUi = null;
  19146. if (typeof toolbarItem == 'string') {
  19147. toolbarItem = toolbarItem.toLowerCase();
  19148. if (toolbarItem == '|') {
  19149. toolbarItem = 'Separator';
  19150. }
  19151. if (baidu.editor.ui[toolbarItem]) {
  19152. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  19153. }
  19154. //fullscreen这里单独处理一下,放到首行去
  19155. if (toolbarItem == 'fullscreen') {
  19156. if (toolbarUis && toolbarUis[0]) {
  19157. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  19158. } else {
  19159. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  19160. }
  19161. continue;
  19162. }
  19163. } else {
  19164. toolbarItemUi = toolbarItem;
  19165. }
  19166. if (toolbarItemUi && toolbarItemUi.id) {
  19167. toolbarUi.add(toolbarItemUi);
  19168. }
  19169. }
  19170. toolbarUis[i] = toolbarUi;
  19171. }
  19172. this.toolbars = toolbarUis;
  19173. },
  19174. getHtmlTpl:function () {
  19175. return '<div id="##" class="%%">' +
  19176. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  19177. (this.toolbars.length ?
  19178. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  19179. this.renderToolbarBoxHtml() +
  19180. '</div></div>' : '') +
  19181. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  19182. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  19183. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  19184. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  19185. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  19186. '</div>' +
  19187. '</div>' +
  19188. '<div id="##_iframeholder" class="%%-iframeholder"></div>' +
  19189. //modify wdcount by matao
  19190. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  19191. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  19192. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  19193. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  19194. '</tr></table></div>' +
  19195. '<div id="##_scalelayer"></div>' +
  19196. '</div>';
  19197. },
  19198. showWordImageDialog:function () {
  19199. this.editor.execCommand("wordimage", "word_img");
  19200. this._dialogs['wordimageDialog'].open();
  19201. },
  19202. renderToolbarBoxHtml:function () {
  19203. var buff = [];
  19204. for (var i = 0; i < this.toolbars.length; i++) {
  19205. buff.push(this.toolbars[i].renderHtml());
  19206. }
  19207. return buff.join('');
  19208. },
  19209. setFullScreen:function (fullscreen) {
  19210. var editor = this.editor,
  19211. container = editor.container.parentNode.parentNode;
  19212. if (this._fullscreen != fullscreen) {
  19213. this._fullscreen = fullscreen;
  19214. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  19215. if (baidu.editor.browser.gecko) {
  19216. var bk = editor.selection.getRange().createBookmark();
  19217. }
  19218. if (fullscreen) {
  19219. while (container.tagName != "BODY") {
  19220. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  19221. nodeStack.push(position);
  19222. container.style.position = "static";
  19223. container = container.parentNode;
  19224. }
  19225. this._bakHtmlOverflow = document.documentElement.style.overflow;
  19226. this._bakBodyOverflow = document.body.style.overflow;
  19227. this._bakAutoHeight = this.editor.autoHeightEnabled;
  19228. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  19229. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  19230. if (this._bakAutoHeight) {
  19231. //当全屏时不能执行自动长高
  19232. editor.autoHeightEnabled = false;
  19233. this.editor.disableAutoHeight();
  19234. }
  19235. document.documentElement.style.overflow = 'hidden';
  19236. document.body.style.overflow = 'hidden';
  19237. this._bakCssText = this.getDom().style.cssText;
  19238. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  19239. editor.iframe.parentNode.style.width = '';
  19240. this._updateFullScreen();
  19241. } else {
  19242. while (container.tagName != "BODY") {
  19243. container.style.position = nodeStack.shift();
  19244. container = container.parentNode;
  19245. }
  19246. this.getDom().style.cssText = this._bakCssText;
  19247. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  19248. if (this._bakAutoHeight) {
  19249. editor.autoHeightEnabled = true;
  19250. this.editor.enableAutoHeight();
  19251. }
  19252. document.documentElement.style.overflow = this._bakHtmlOverflow;
  19253. document.body.style.overflow = this._bakBodyOverflow;
  19254. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  19255. window.scrollTo(0, this._bakScrollTop);
  19256. }
  19257. if (baidu.editor.browser.gecko && editor.body.contentEditable === 'true') {
  19258. var input = document.createElement('input');
  19259. document.body.appendChild(input);
  19260. editor.body.contentEditable = false;
  19261. setTimeout(function () {
  19262. input.focus();
  19263. setTimeout(function () {
  19264. editor.body.contentEditable = true;
  19265. editor.selection.getRange().moveToBookmark(bk).select(true);
  19266. baidu.editor.dom.domUtils.remove(input);
  19267. fullscreen && window.scroll(0, 0);
  19268. }, 0)
  19269. }, 0)
  19270. }
  19271. if(editor.body.contentEditable === 'true'){
  19272. this.editor.fireEvent('fullscreenchanged', fullscreen);
  19273. this.triggerLayout();
  19274. }
  19275. }
  19276. },
  19277. _updateFullScreen:function () {
  19278. if (this._fullscreen) {
  19279. var vpRect = uiUtils.getViewportRect();
  19280. 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);
  19281. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  19282. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0));
  19283. //不手动调一下,会导致全屏失效
  19284. if(browser.gecko){
  19285. window.onresize();
  19286. }
  19287. }
  19288. },
  19289. _updateElementPath:function () {
  19290. var bottom = this.getDom('elementpath'), list;
  19291. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  19292. var buff = [];
  19293. for (var i = 0, ci; ci = list[i]; i++) {
  19294. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  19295. }
  19296. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  19297. } else {
  19298. bottom.style.display = 'none'
  19299. }
  19300. },
  19301. disableElementPath:function () {
  19302. var bottom = this.getDom('elementpath');
  19303. bottom.innerHTML = '';
  19304. bottom.style.display = 'none';
  19305. this.elementPathEnabled = false;
  19306. },
  19307. enableElementPath:function () {
  19308. var bottom = this.getDom('elementpath');
  19309. bottom.style.display = '';
  19310. this.elementPathEnabled = true;
  19311. this._updateElementPath();
  19312. },
  19313. _scale:function () {
  19314. var doc = document,
  19315. editor = this.editor,
  19316. editorHolder = editor.container,
  19317. editorDocument = editor.document,
  19318. toolbarBox = this.getDom("toolbarbox"),
  19319. bottombar = this.getDom("bottombar"),
  19320. scale = this.getDom("scale"),
  19321. scalelayer = this.getDom("scalelayer");
  19322. var isMouseMove = false,
  19323. position = null,
  19324. minEditorHeight = 0,
  19325. minEditorWidth = editor.options.minFrameWidth,
  19326. pageX = 0,
  19327. pageY = 0,
  19328. scaleWidth = 0,
  19329. scaleHeight = 0;
  19330. function down() {
  19331. position = domUtils.getXY(editorHolder);
  19332. if (!minEditorHeight) {
  19333. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  19334. }
  19335. 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:"
  19336. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  19337. domUtils.on(doc, "mousemove", move);
  19338. domUtils.on(editorDocument, "mouseup", up);
  19339. domUtils.on(doc, "mouseup", up);
  19340. }
  19341. var me = this;
  19342. //by xuheng 全屏时关掉缩放
  19343. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  19344. if (fullScreen) {
  19345. me.disableScale();
  19346. } else {
  19347. if (me.editor.options.scaleEnabled) {
  19348. me.enableScale();
  19349. var tmpNode = me.editor.document.createElement('span');
  19350. me.editor.body.appendChild(tmpNode);
  19351. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  19352. domUtils.remove(tmpNode)
  19353. }
  19354. }
  19355. });
  19356. function move(event) {
  19357. clearSelection();
  19358. var e = event || window.event;
  19359. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  19360. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  19361. scaleWidth = pageX - position.x;
  19362. scaleHeight = pageY - position.y;
  19363. if (scaleWidth >= minEditorWidth) {
  19364. isMouseMove = true;
  19365. scalelayer.style.width = scaleWidth + 'px';
  19366. }
  19367. if (scaleHeight >= minEditorHeight) {
  19368. isMouseMove = true;
  19369. scalelayer.style.height = scaleHeight + "px";
  19370. }
  19371. }
  19372. function up() {
  19373. if (isMouseMove) {
  19374. isMouseMove = false;
  19375. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  19376. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  19377. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2);
  19378. }
  19379. if (scalelayer) {
  19380. scalelayer.style.display = "none";
  19381. }
  19382. clearSelection();
  19383. domUtils.un(doc, "mousemove", move);
  19384. domUtils.un(editorDocument, "mouseup", up);
  19385. domUtils.un(doc, "mouseup", up);
  19386. }
  19387. function clearSelection() {
  19388. if (browser.ie)
  19389. doc.selection.clear();
  19390. else
  19391. window.getSelection().removeAllRanges();
  19392. }
  19393. this.enableScale = function () {
  19394. //trace:2868
  19395. if (editor.queryCommandState("source") == 1) return;
  19396. scale.style.display = "";
  19397. this.scaleEnabled = true;
  19398. domUtils.on(scale, "mousedown", down);
  19399. };
  19400. this.disableScale = function () {
  19401. scale.style.display = "none";
  19402. this.scaleEnabled = false;
  19403. domUtils.un(scale, "mousedown", down);
  19404. };
  19405. },
  19406. isFullScreen:function () {
  19407. return this._fullscreen;
  19408. },
  19409. postRender:function () {
  19410. UIBase.prototype.postRender.call(this);
  19411. for (var i = 0; i < this.toolbars.length; i++) {
  19412. this.toolbars[i].postRender();
  19413. }
  19414. var me = this;
  19415. var timerId,
  19416. domUtils = baidu.editor.dom.domUtils,
  19417. updateFullScreenTime = function () {
  19418. clearTimeout(timerId);
  19419. timerId = setTimeout(function () {
  19420. me._updateFullScreen();
  19421. });
  19422. };
  19423. domUtils.on(window, 'resize', updateFullScreenTime);
  19424. me.addListener('destroy', function () {
  19425. domUtils.un(window, 'resize', updateFullScreenTime);
  19426. clearTimeout(timerId);
  19427. })
  19428. },
  19429. showToolbarMsg:function (msg, flag) {
  19430. this.getDom('toolbarmsg_label').innerHTML = msg;
  19431. this.getDom('toolbarmsg').style.display = '';
  19432. //
  19433. if (!flag) {
  19434. var w = this.getDom('upload_dialog');
  19435. w.style.display = 'none';
  19436. }
  19437. },
  19438. hideToolbarMsg:function () {
  19439. this.getDom('toolbarmsg').style.display = 'none';
  19440. },
  19441. mapUrl:function (url) {
  19442. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  19443. },
  19444. triggerLayout:function () {
  19445. var dom = this.getDom();
  19446. if (dom.style.zoom == '1') {
  19447. dom.style.zoom = '100%';
  19448. } else {
  19449. dom.style.zoom = '1';
  19450. }
  19451. }
  19452. };
  19453. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  19454. var instances = {};
  19455. UE.ui.Editor = function (options) {
  19456. var editor = new baidu.editor.Editor(options);
  19457. editor.options.editor = editor;
  19458. utils.loadFile(document, {
  19459. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  19460. tag:"link",
  19461. type:"text/css",
  19462. rel:"stylesheet"
  19463. });
  19464. var oldRender = editor.render;
  19465. editor.render = function (holder) {
  19466. if (holder.constructor === String) {
  19467. editor.key = holder;
  19468. instances[holder] = editor;
  19469. }
  19470. utils.domReady(function () {
  19471. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  19472. function renderUI() {
  19473. editor.setOpt({
  19474. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  19475. });
  19476. new EditorUI(editor.options);
  19477. if (holder) {
  19478. if (holder.constructor === String) {
  19479. holder = document.getElementById(holder);
  19480. }
  19481. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  19482. if (holder && /script|textarea/ig.test(holder.tagName)) {
  19483. var newDiv = document.createElement('div');
  19484. holder.parentNode.insertBefore(newDiv, holder);
  19485. var cont = holder.value || holder.innerHTML;
  19486. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  19487. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  19488. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  19489. .replace(/>[\n\r\t]+</g, '><');
  19490. holder.className && (newDiv.className = holder.className);
  19491. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  19492. if (/textarea/i.test(holder.tagName)) {
  19493. editor.textarea = holder;
  19494. editor.textarea.style.display = 'none';
  19495. } else {
  19496. holder.parentNode.removeChild(holder);
  19497. holder.id && (newDiv.id = holder.id);
  19498. }
  19499. holder = newDiv;
  19500. holder.innerHTML = '';
  19501. }
  19502. }
  19503. domUtils.addClass(holder, "edui-" + editor.options.theme);
  19504. editor.ui.render(holder);
  19505. var opt = editor.options;
  19506. //给实例添加一个编辑器的容器引用
  19507. editor.container = editor.ui.getDom();
  19508. var parents = domUtils.findParents(holder,true);
  19509. var displays = [];
  19510. for(var i = 0 ,ci;ci=parents[i];i++){
  19511. displays[i] = ci.style.display;
  19512. ci.style.display = 'block'
  19513. }
  19514. if (opt.initialFrameWidth) {
  19515. opt.minFrameWidth = opt.initialFrameWidth;
  19516. } else {
  19517. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  19518. }
  19519. if (opt.initialFrameHeight) {
  19520. opt.minFrameHeight = opt.initialFrameHeight;
  19521. } else {
  19522. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  19523. }
  19524. for(var i = 0 ,ci;ci=parents[i];i++){
  19525. ci.style.display = displays[i]
  19526. }
  19527. //编辑器最外容器设置了高度,会导致,编辑器不占位
  19528. //todo 先去掉,没有找到原因
  19529. if(holder.style.height){
  19530. holder.style.height = ''
  19531. }
  19532. editor.container.style.width = opt.initialFrameWidth+ 'px';
  19533. editor.container.style.zIndex = opt.zIndex;
  19534. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  19535. }
  19536. })
  19537. };
  19538. return editor;
  19539. };
  19540. /**
  19541. * @file
  19542. * @name UE
  19543. * @short UE
  19544. * @desc UEditor的顶部命名空间
  19545. */
  19546. /**
  19547. * @name getEditor
  19548. * @since 1.2.4+
  19549. * @grammar UE.getEditor(id,[opt]) => Editor实例
  19550. * @desc 提供一个全局的方法得到编辑器实例
  19551. *
  19552. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  19553. * * ''opt'' 编辑器的可选参数
  19554. * @example
  19555. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  19556. * this.setContent('hello')
  19557. * }});
  19558. * UE.getEditor('containerId'); //返回刚创建的实例
  19559. *
  19560. */
  19561. UE.getEditor = function (id, opt) {
  19562. var editor = instances[id];
  19563. if (!editor) {
  19564. editor = instances[id] = new UE.ui.Editor(opt);
  19565. editor.render(id);
  19566. setTimeout(function(){
  19567. if(editor.isReady){
  19568. $(editor.iframe.contentWindow.document.body).click(function(e){
  19569. var s = e.srcElement || e.target;
  19570. if(s.className=="gseditor"){
  19571. eval("(function(){"+s.getAttribute("x")+"})").call(s);
  19572. }
  19573. });
  19574. }else{
  19575. editor.addListener("ready",function(){
  19576. $(this.iframe.contentWindow.document.body).click(function(e){
  19577. var s = e.srcElement || e.target;
  19578. if(s.className=="gseditor"){
  19579. eval("(function(){"+s.getAttribute("x")+"})").call(s);
  19580. }
  19581. });
  19582. });
  19583. }
  19584. },1000);
  19585. }
  19586. return editor;
  19587. };
  19588. UE.delEditor = function (id) {
  19589. var editor;
  19590. if (editor = instances[id]) {
  19591. editor.key && editor.destroy();
  19592. delete instances[id]
  19593. }
  19594. }
  19595. })();
  19596. ///import core
  19597. ///import uicore
  19598. ///commands 表情
  19599. (function(){
  19600. var utils = baidu.editor.utils,
  19601. Popup = baidu.editor.ui.Popup,
  19602. SplitButton = baidu.editor.ui.SplitButton,
  19603. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  19604. this.initOptions(options);
  19605. this.initMultiMenu();
  19606. };
  19607. MultiMenuPop.prototype = {
  19608. initMultiMenu: function (){
  19609. var me = this;
  19610. this.popup = new Popup({
  19611. content: '',
  19612. editor : me.editor,
  19613. iframe_rendered: false,
  19614. onshow: function (){
  19615. if (!this.iframe_rendered) {
  19616. this.iframe_rendered = true;
  19617. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  19618. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  19619. }
  19620. }
  19621. // canSideUp:false,
  19622. // canSideLeft:false
  19623. });
  19624. this.onbuttonclick = function(){
  19625. this.showPopup();
  19626. };
  19627. this.initSplitButton();
  19628. }
  19629. };
  19630. utils.inherits(MultiMenuPop, SplitButton);
  19631. })();
  19632. })();
  19633. UE.commands['formula'] = {
  19634. execCommand : function(call){
  19635. return false;
  19636. var str = '<div class="pup_upbox open_dialog_jquery pup_gseditor" id="gseditor" style="display: none;float:left;overflow:hidden"> '+
  19637. ' <div class="pup_uptitle"> '+
  19638. ' <p class="icon_align"> '+
  19639. ' <span class="pup_titlename">&nbsp;&nbsp;&nbsp;公式编辑器</span> '+
  19640. ' </p> '+
  19641. ' <span class="icon_skin pup_close"></span> '+
  19642. ' </div>'+
  19643. ' <div class="pup_content" id="editorContainer" style="position:absolute;left:-530px"></div> '+
  19644. ' <div class="gsedit_loading" id="gsedit_loading"><img src="/images/editLoading.gif"/></div>'+
  19645. ' <div class="clearfix"> '+
  19646. ' <a class="fr mr15px mt1px" href="javascript:void(0);" onclick="return false;" id="gsinsert"> '+
  19647. ' <span class="web_skin grayleft_addbtn pad_lr">插入公式</span> '+
  19648. ' <span class="web_skin grayright_addbtn"></span> '+
  19649. ' </a> '+
  19650. ' </div> '+
  19651. '</div>';
  19652. if(document.getElementById("editorContainer")==null){
  19653. $("body").append(str);
  19654. $("#gseditor").css({
  19655. backgroundColor : "#ffffff",
  19656. zIndex : 999
  19657. }).ui("dialog",{
  19658. close : ".pup_close",
  19659. width : 525,
  19660. dymamic : false,
  19661. dymamicOff : true,
  19662. zIndex : 999
  19663. });
  19664. }else{
  19665. $("#gseditor").ui("dialog",{
  19666. close : ".pup_close",
  19667. zIndex : 999
  19668. });
  19669. //setTimeout(function(){
  19670. // gseditor.focus();
  19671. //},500);
  19672. gseditor.editorModel.reset();
  19673. gseditor.editorModel.insertText("");
  19674. }
  19675. $("#gsinsert").removeData("element");
  19676. var me = this;
  19677. $[me.textarea.id] = $[me.textarea.id] || {};
  19678. $.gs = $.gs || {};
  19679. UI.js(!window.com,UEDITOR_HOME_URL+"gseditor.js",function(){
  19680. UI.js(!window.enableGsEditor,UEDITOR_HOME_URL+"initGs.js",function(){
  19681. $("#gsinsert").unbind("click").click(function(){
  19682. if($(this).hasClass("fadeTo04")){
  19683. return false;
  19684. }
  19685. var gsObj = gseditor.formulaDisplay.element.children[1];
  19686. var gsHtml = "<span class='"+gsObj.className+"' style='"+gsObj.getAttribute("style")+"'>"+gsObj.innerHTML+"</span>";
  19687. var mathml = gseditor.getMathML();
  19688. var id = "gs"+new Date().getTime();
  19689. $(this).addClass("fadeTo04");
  19690. var meThis = this;
  19691. //var postMathml = mathml.replace(/\&/g,"&amp;");
  19692. //console.log(postMathml);
  19693. var url = getImg();//获取图片数据
  19694. //$.post('/topic/mathToLatex',{m:postMathml},function(url){
  19695. $(meThis).removeClass("fadeTo04");
  19696. var insertHtml = '<img class="gseditor" id="'+id+'" x="return parent.editGs(this)" editorid="'+me.textarea.id+'" src="'+url+'"/>';
  19697. var element = $(this).data("element");
  19698. if(element){
  19699. element.src = url;
  19700. id = element.id;
  19701. }else{
  19702. me.execCommand('insertHtml',insertHtml,true);
  19703. }
  19704. $[me.textarea.id][id] = $.gs[id] = mathml;
  19705. if(mathml=='<math xmlns="http://www.w3.org/1998/Math/MathML"/>'){
  19706. me = gseditor.me || me;
  19707. $(me.iframe.contentWindow.document.getElementById(id)).remove();
  19708. }
  19709. $("#gseditor").closeDialog();
  19710. me.focus(true);
  19711. //});
  19712. window.IS_CHANGE = true;
  19713. });
  19714. if(typeof call == 'function'){
  19715. call();
  19716. }
  19717. });
  19718. });
  19719. }
  19720. };
  19721. UE.commands['videotl'] = {
  19722. execCommand : function(){
  19723. var str = '<div class="pup_upbox open_dialog_jquery" id="swfuploadDiv" style="display: none;float:left;overflow:hidden;width:325px"> '+
  19724. ' <div class="pup_uptitle"> '+
  19725. ' <p class="icon_align"> '+
  19726. ' <span class="pup_titlename">&nbsp;&nbsp;&nbsp;插入音频</span> '+
  19727. ' </p> '+
  19728. ' <span class="icon_skin pup_close"></span> '+
  19729. ' </div>'+
  19730. ' <div class="pup_content" style="text-align:left">'+
  19731. ' <span id="spanButtonPlaceHolder"></span>'+
  19732. ' <span class="uploadLine" style="display:none" id="fsUploadProgressLine">'+
  19733. ' <span class="uploadBar" id="fsUploadProgress">'+
  19734. ' </span>'+
  19735. ' </span>'+
  19736. ' <span class="successLine" style="display:none" id="successLine">'+
  19737. ' </span>'+
  19738. ' <span class="errorLine" style="display:none" id="errorLine">'+
  19739. ' </span>'+
  19740. ' <input type="hidden" id="filename" name="filename"/>'+
  19741. '</div> '+
  19742. '</div>';
  19743. if($("#swfuploadDiv").length==0){
  19744. $("body").append(str);
  19745. }
  19746. $("#swfuploadDiv").ui("dialog",{
  19747. close : ".pup_close",
  19748. width : 350,
  19749. onclose : function(){
  19750. $("#successLine").html("");
  19751. }
  19752. });
  19753. if(!window.uploadInit){
  19754. UI.jsArr([
  19755. '/js/ui/swfupload/swfupload.js',
  19756. '/js/ui/upload.js'
  19757. ]);
  19758. }
  19759. $("#swfuploadDiv").data("editor",this);
  19760. }
  19761. }
  19762. UE.commands['tiankong'] = {
  19763. execCommand : function(){
  19764. tiankongFunc.call(this)(); //tkt.js
  19765. }
  19766. }
  19767. //根据HTML生成图片
  19768. function getImg(slt){
  19769. if(document.getElementById("cs")==null){
  19770. $("body").append('<canvas id="cs" style="position:absolute;left:-1000px;"></canvas>');
  19771. }
  19772. var c = document.getElementById("cs").getContext("2d");
  19773. var sw = $(slt || "span.wrs_container");
  19774. var sl = 0.9;
  19775. c.canvas.width = sw.width()*sl;
  19776. c.canvas.height = (sw.height()+5)*sl;
  19777. c.scale(sl,sl);
  19778. c.globalAlpha = 0.8;
  19779. c.translate(0.5,0.5);
  19780. sw.find("*").each(function(){
  19781. var p = $(this).position();
  19782. var tag = this.tagName.toLowerCase();
  19783. if(tag=="img"){
  19784. var image = new Image();
  19785. image.src = this.src;
  19786. if($(this).width()>0){
  19787. if(this.src.indexOf("f140.png")>=0){
  19788. p.top+=2;
  19789. }
  19790. c.drawImage(image,p.left,p.top);
  19791. }
  19792. }else if(/svg|line|ellipse/.test(tag)){
  19793. if(tag=="line"){
  19794. var p = $(this).parent().parent().position();
  19795. var x1 = p.left + parseInt($(this).attr("x1"));
  19796. var y1 = p.top + parseInt($(this).attr("y1"));
  19797. var x2 = p.left + parseInt($(this).attr("x2"));
  19798. var y2 = p.top + parseInt($(this).attr("y2"));
  19799. c.moveTo(x1,y1);
  19800. c.lineTo(x2,y2);
  19801. }else if(tag=="ellipse"){
  19802. var p = $(this).parent().parent().position();
  19803. var cx = parseInt($(this).attr("cx"));
  19804. var cy = parseInt($(this).attr("cy"));
  19805. var rx = parseInt($(this).attr("rx"));
  19806. var ry = parseInt($(this).attr("ry"));
  19807. c.save();
  19808. c.scale(1,ry/rx);
  19809. p.top = p.top*(rx/ry)+(rx-ry)/2*rx/ry;
  19810. c.translate(p.left,p.top);
  19811. c.moveTo(cx*2,cy);
  19812. c.arc(cx, cy, rx, 0, 2 * Math.PI, false);
  19813. c.restore();
  19814. }
  19815. }else if(this.style.backgroundColor){
  19816. var height = $(this).height();
  19817. var width = $(this).width();
  19818. if(height>width){
  19819. c.moveTo(p.left+width,p.top);
  19820. c.lineTo(p.left+width,p.top+height);
  19821. }else{
  19822. var top = p.top+height;
  19823. if(top%2==1){
  19824. top-=0.5;
  19825. }
  19826. c.moveTo(p.left-1,top);
  19827. c.lineTo(p.left+width,top);
  19828. }
  19829. }else{
  19830. if($(this).children().length==0){
  19831. var content = $(this).html().replace(/\&nbsp;/g," ").replace(/\&lt;/g,"<").replace(/\&gt;/g,">");
  19832. if($.browser.webkit){
  19833. c.font = $(this).css("font");
  19834. }else{
  19835. c.font = $(this).css("fontSize") + " " + $(this).css("fontFamily");
  19836. }
  19837. var top = p.top+parseInt($(this).css("fontSize"))-2;
  19838. if($(this).hasClass("wrs_specialSmallChar")){
  19839. top-=4;
  19840. }
  19841. c.fillStyle = $(this).css("color");
  19842. c.fillText(content,p.left,top);
  19843. }
  19844. }
  19845. });
  19846. c.stroke();
  19847. return c.canvas.toDataURL("png");
  19848. }