ueditor.all.card.js 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558
  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Wed Dec 26 2018 17:25:05 GMT+0800 (CST)
  5. */
  6. /* eslint-disable */
  7. (function(){
  8. // editor.js
  9. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  10. var baidu = window.baidu || {};
  11. window.baidu = baidu;
  12. window.UE = baidu.editor = window.UE || {};
  13. UE.plugins = {};
  14. UE.commands = {};
  15. UE.instants = {};
  16. UE.I18N = {};
  17. UE._customizeUI = {};
  18. UE.version = "1.4.3";
  19. var dom = UE.dom = {};
  20. // core/browser.js
  21. /**
  22. * 浏览器判断模块
  23. * @file
  24. * @module UE.browser
  25. * @since 1.2.6.1
  26. */
  27. /**
  28. * 提供浏览器检测的模块
  29. * @unfile
  30. * @module UE.browser
  31. */
  32. var browser = UE.browser = function(){
  33. var agent = navigator.userAgent.toLowerCase(),
  34. opera = window.opera,
  35. browser = {
  36. /**
  37. * @property {boolean} ie 检测当前浏览器是否为IE
  38. * @example
  39. * ```javascript
  40. * if ( UE.browser.ie ) {
  41. * console.log( '当前浏览器是IE' );
  42. * }
  43. * ```
  44. */
  45. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  46. /**
  47. * @property {boolean} opera 检测当前浏览器是否为Opera
  48. * @example
  49. * ```javascript
  50. * if ( UE.browser.opera ) {
  51. * console.log( '当前浏览器是Opera' );
  52. * }
  53. * ```
  54. */
  55. opera : ( !!opera && opera.version ),
  56. /**
  57. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  58. * @example
  59. * ```javascript
  60. * if ( UE.browser.webkit ) {
  61. * console.log( '当前浏览器是webkit内核浏览器' );
  62. * }
  63. * ```
  64. */
  65. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  66. /**
  67. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  68. * @example
  69. * ```javascript
  70. * if ( UE.browser.mac ) {
  71. * console.log( '当前浏览器运行在mac平台下' );
  72. * }
  73. * ```
  74. */
  75. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  76. /**
  77. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  78. * @example
  79. * ```javascript
  80. * if ( UE.browser.quirks ) {
  81. * console.log( '当前浏览器运行处于“怪异模式”' );
  82. * }
  83. * ```
  84. */
  85. quirks : ( document.compatMode == 'BackCompat' )
  86. };
  87. /**
  88. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  89. * @example
  90. * ```javascript
  91. * if ( UE.browser.gecko ) {
  92. * console.log( '当前浏览器内核是gecko内核' );
  93. * }
  94. * ```
  95. */
  96. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  97. var version = 0;
  98. // Internet Explorer 6.0+
  99. if ( browser.ie ){
  100. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  101. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  102. if(v1 && v2 && v1[1] && v2[1]){
  103. version = Math.max(v1[1]*1,v2[1]*1);
  104. }else if(v1 && v1[1]){
  105. version = v1[1]*1;
  106. }else if(v2 && v2[1]){
  107. version = v2[1]*1;
  108. }else{
  109. version = 0;
  110. }
  111. browser.ie11Compat = document.documentMode == 11;
  112. /**
  113. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  114. * @warning 如果浏览器不是IE, 则该值为undefined
  115. * @example
  116. * ```javascript
  117. * if ( UE.browser.ie9Compat ) {
  118. * console.log( '当前浏览器运行在IE9兼容模式下' );
  119. * }
  120. * ```
  121. */
  122. browser.ie9Compat = document.documentMode == 9;
  123. /**
  124. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  125. * @warning 如果浏览器不是IE, 则该值为undefined
  126. * @example
  127. * ```javascript
  128. * if ( UE.browser.ie8 ) {
  129. * console.log( '当前浏览器是IE8浏览器' );
  130. * }
  131. * ```
  132. */
  133. browser.ie8 = !!document.documentMode;
  134. /**
  135. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  136. * @warning 如果浏览器不是IE, 则该值为undefined
  137. * @example
  138. * ```javascript
  139. * if ( UE.browser.ie8Compat ) {
  140. * console.log( '当前浏览器运行在IE8兼容模式下' );
  141. * }
  142. * ```
  143. */
  144. browser.ie8Compat = document.documentMode == 8;
  145. /**
  146. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  147. * @warning 如果浏览器不是IE, 则该值为undefined
  148. * @example
  149. * ```javascript
  150. * if ( UE.browser.ie7Compat ) {
  151. * console.log( '当前浏览器运行在IE7兼容模式下' );
  152. * }
  153. * ```
  154. */
  155. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  156. || document.documentMode == 7 );
  157. /**
  158. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  159. * @warning 如果浏览器不是IE, 则该值为undefined
  160. * @example
  161. * ```javascript
  162. * if ( UE.browser.ie6Compat ) {
  163. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  164. * }
  165. * ```
  166. */
  167. browser.ie6Compat = ( version < 7 || browser.quirks );
  168. browser.ie9above = version > 8;
  169. browser.ie9below = version < 9;
  170. browser.ie11above = version > 10;
  171. browser.ie11below = version < 11;
  172. }
  173. // Gecko.
  174. if ( browser.gecko ){
  175. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  176. if ( geckoRelease )
  177. {
  178. geckoRelease = geckoRelease[1].split( '.' );
  179. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  180. }
  181. }
  182. /**
  183. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  184. * @warning 如果浏览器不是chrome, 则该值为undefined
  185. * @example
  186. * ```javascript
  187. * if ( UE.browser.chrome ) {
  188. * console.log( '当前浏览器是Chrome' );
  189. * }
  190. * ```
  191. */
  192. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  193. browser.chrome = + RegExp['\x241'];
  194. }
  195. /**
  196. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  197. * @warning 如果浏览器不是safari, 则该值为undefined
  198. * @example
  199. * ```javascript
  200. * if ( UE.browser.safari ) {
  201. * console.log( '当前浏览器是Safari' );
  202. * }
  203. * ```
  204. */
  205. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  206. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  207. }
  208. // Opera 9.50+
  209. if ( browser.opera )
  210. version = parseFloat( opera.version() );
  211. // WebKit 522+ (Safari 3+)
  212. if ( browser.webkit )
  213. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  214. /**
  215. * @property { Number } version 检测当前浏览器版本号
  216. * @remind
  217. * <ul>
  218. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  219. * <li>gecko系列会返回10900,158900等</li>
  220. * <li>webkit系列会返回其build号 (如 522等)</li>
  221. * </ul>
  222. * @example
  223. * ```javascript
  224. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  225. * ```
  226. */
  227. browser.version = version;
  228. /**
  229. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  230. * @example
  231. * ```javascript
  232. * if ( UE.browser.isCompatible ) {
  233. * console.log( '浏览器与UEditor能够良好兼容' );
  234. * }
  235. * ```
  236. */
  237. browser.isCompatible =
  238. !browser.mobile && (
  239. ( browser.ie && version >= 6 ) ||
  240. ( browser.gecko && version >= 10801 ) ||
  241. ( browser.opera && version >= 9.5 ) ||
  242. ( browser.air && version >= 1 ) ||
  243. ( browser.webkit && version >= 522 ) ||
  244. false );
  245. return browser;
  246. }();
  247. //快捷方式
  248. var ie = browser.ie,
  249. webkit = browser.webkit,
  250. gecko = browser.gecko,
  251. opera = browser.opera;
  252. // core/utils.js
  253. /**
  254. * 工具函数包
  255. * @file
  256. * @module UE.utils
  257. * @since 1.2.6.1
  258. */
  259. /**
  260. * UEditor封装使用的静态工具函数
  261. * @module UE.utils
  262. * @unfile
  263. */
  264. var utils = UE.utils = {
  265. /**
  266. * 用给定的迭代器遍历对象
  267. * @method each
  268. * @param { Object } obj 需要遍历的对象
  269. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  270. * @example
  271. * ```javascript
  272. * var demoObj = {
  273. * key1: 1,
  274. * key2: 2
  275. * };
  276. *
  277. * //output: key1: 1, key2: 2
  278. * UE.utils.each( demoObj, funciton ( value, key ) {
  279. *
  280. * console.log( key + ":" + value );
  281. *
  282. * } );
  283. * ```
  284. */
  285. /**
  286. * 用给定的迭代器遍历数组或类数组对象
  287. * @method each
  288. * @param { Array } array 需要遍历的数组或者类数组
  289. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  290. * @example
  291. * ```javascript
  292. * var divs = document.getElmentByTagNames( "div" );
  293. *
  294. * //output: 0: DIV, 1: DIV ...
  295. * UE.utils.each( divs, funciton ( value, key ) {
  296. *
  297. * console.log( key + ":" + value.tagName );
  298. *
  299. * } );
  300. * ```
  301. */
  302. each : function(obj, iterator, context) {
  303. if (obj == null) return;
  304. if (obj.length === +obj.length) {
  305. for (var i = 0, l = obj.length; i < l; i++) {
  306. if(iterator.call(context, obj[i], i, obj) === false)
  307. return false;
  308. }
  309. } else {
  310. for (var key in obj) {
  311. if (obj.hasOwnProperty(key)) {
  312. if(iterator.call(context, obj[key], key, obj) === false)
  313. return false;
  314. }
  315. }
  316. }
  317. },
  318. /**
  319. * 以给定对象作为原型创建一个新对象
  320. * @method makeInstance
  321. * @param { Object } protoObject 该对象将作为新创建对象的原型
  322. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  323. * @example
  324. * ```javascript
  325. *
  326. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  327. *
  328. * var newObject = UE.utils.makeInstance( protoObject );
  329. * //output: Hello UEditor!
  330. * newObject.sayHello();
  331. * ```
  332. */
  333. makeInstance:function (obj) {
  334. var noop = new Function();
  335. noop.prototype = obj;
  336. obj = new noop;
  337. noop.prototype = null;
  338. return obj;
  339. },
  340. /**
  341. * 将source对象中的属性扩展到target对象上
  342. * @method extend
  343. * @remind 该方法将强制把source对象上的属性复制到target对象上
  344. * @see UE.utils.extend(Object,Object,Boolean)
  345. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  346. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  347. * @return { Object } 返回target对象
  348. * @example
  349. * ```javascript
  350. *
  351. * var target = { name: 'target', sex: 1 },
  352. * source = { name: 'source', age: 17 };
  353. *
  354. * UE.utils.extend( target, source );
  355. *
  356. * //output: { name: 'source', sex: 1, age: 17 }
  357. * console.log( target );
  358. *
  359. * ```
  360. */
  361. /**
  362. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  363. * 源对象属性名相同的属性值。
  364. * @method extend
  365. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  366. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  367. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  368. * @return { Object } 返回target对象
  369. * @example
  370. * ```javascript
  371. *
  372. * var target = { name: 'target', sex: 1 },
  373. * source = { name: 'source', age: 17 };
  374. *
  375. * UE.utils.extend( target, source, true );
  376. *
  377. * //output: { name: 'target', sex: 1, age: 17 }
  378. * console.log( target );
  379. *
  380. * ```
  381. */
  382. extend:function (t, s, b) {
  383. if (s) {
  384. for (var k in s) {
  385. if (!b || !t.hasOwnProperty(k)) {
  386. t[k] = s[k];
  387. }
  388. }
  389. }
  390. return t;
  391. },
  392. /**
  393. * 将给定的多个对象的属性复制到目标对象target上
  394. * @method extend2
  395. * @remind 该方法将强制把源对象上的属性复制到target对象上
  396. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  397. * 将会覆盖掉之前的值。
  398. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  399. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  400. * @return { Object } 返回target对象
  401. * @example
  402. * ```javascript
  403. *
  404. * var target = {},
  405. * source1 = { name: 'source', age: 17 },
  406. * source2 = { title: 'dev' };
  407. *
  408. * UE.utils.extend2( target, source1, source2 );
  409. *
  410. * //output: { name: 'source', age: 17, title: 'dev' }
  411. * console.log( target );
  412. *
  413. * ```
  414. */
  415. extend2:function (t) {
  416. var a = arguments;
  417. for (var i = 1; i < a.length; i++) {
  418. var x = a[i];
  419. for (var k in x) {
  420. if (!t.hasOwnProperty(k)) {
  421. t[k] = x[k];
  422. }
  423. }
  424. }
  425. return t;
  426. },
  427. /**
  428. * 模拟继承机制, 使得subClass继承自superClass
  429. * @method inherits
  430. * @param { Object } subClass 子类对象
  431. * @param { Object } superClass 超类对象
  432. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  433. * @return { Object } 继承superClass后的子类对象
  434. * @example
  435. * ```javascript
  436. * function SuperClass(){
  437. * this.name = "小李";
  438. * }
  439. *
  440. * SuperClass.prototype = {
  441. * hello:function(str){
  442. * console.log(this.name + str);
  443. * }
  444. * }
  445. *
  446. * function SubClass(){
  447. * this.name = "小张";
  448. * }
  449. *
  450. * UE.utils.inherits(SubClass,SuperClass);
  451. *
  452. * var sub = new SubClass();
  453. * //output: '小张早上好!
  454. * sub.hello("早上好!");
  455. * ```
  456. */
  457. inherits:function (subClass, superClass) {
  458. var oldP = subClass.prototype,
  459. newP = utils.makeInstance(superClass.prototype);
  460. utils.extend(newP, oldP, true);
  461. subClass.prototype = newP;
  462. return (newP.constructor = subClass);
  463. },
  464. /**
  465. * 用指定的context对象作为函数fn的上下文
  466. * @method bind
  467. * @param { Function } fn 需要绑定上下文的函数对象
  468. * @param { Object } content 函数fn新的上下文对象
  469. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  470. * @example
  471. * ```javascript
  472. *
  473. * var name = 'window',
  474. * newTest = null;
  475. *
  476. * function test () {
  477. * console.log( this.name );
  478. * }
  479. *
  480. * newTest = UE.utils.bind( test, { name: 'object' } );
  481. *
  482. * //output: object
  483. * newTest();
  484. *
  485. * //output: window
  486. * test();
  487. *
  488. * ```
  489. */
  490. bind:function (fn, context) {
  491. return function () {
  492. return fn.apply(context, arguments);
  493. };
  494. },
  495. /**
  496. * 创建延迟指定时间后执行的函数fn
  497. * @method defer
  498. * @param { Function } fn 需要延迟执行的函数对象
  499. * @param { int } delay 延迟的时间, 单位是毫秒
  500. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  501. * 而不能保证刚好到达延迟时间时执行。
  502. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  503. * @example
  504. * ```javascript
  505. * var start = 0;
  506. *
  507. * function test(){
  508. * console.log( new Date() - start );
  509. * }
  510. *
  511. * var testDefer = UE.utils.defer( test, 1000 );
  512. * //
  513. * start = new Date();
  514. * //output: (大约在1000毫秒之后输出) 1000
  515. * testDefer();
  516. * ```
  517. */
  518. /**
  519. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  520. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  521. * @method defer
  522. * @param { Function } fn 需要延迟执行的函数对象
  523. * @param { int } delay 延迟的时间, 单位是毫秒
  524. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  525. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  526. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  527. * 而不能保证刚好到达延迟时间时执行。
  528. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  529. * @example
  530. * ```javascript
  531. *
  532. * function test(){
  533. * console.log(1);
  534. * }
  535. *
  536. * var testDefer = UE.utils.defer( test, 1000, true );
  537. *
  538. * //output: (两次调用仅有一次输出) 1
  539. * testDefer();
  540. * testDefer();
  541. * ```
  542. */
  543. defer:function (fn, delay, exclusion) {
  544. var timerID;
  545. return function () {
  546. if (exclusion) {
  547. clearTimeout(timerID);
  548. }
  549. timerID = setTimeout(fn, delay);
  550. };
  551. },
  552. /**
  553. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  554. * @method indexOf
  555. * @remind 该方法的匹配过程使用的是恒等“===”
  556. * @param { Array } array 需要查找的数组对象
  557. * @param { * } item 需要在目标数组中查找的值
  558. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  559. * @example
  560. * ```javascript
  561. * var item = 1,
  562. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  563. *
  564. * //output: 4
  565. * console.log( UE.utils.indexOf( arr, item ) );
  566. * ```
  567. */
  568. /**
  569. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  570. * @method indexOf
  571. * @remind 该方法的匹配过程使用的是恒等“===”
  572. * @param { Array } array 需要查找的数组对象
  573. * @param { * } item 需要在目标数组中查找的值
  574. * @param { int } start 搜索的起始位置
  575. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  576. * @example
  577. * ```javascript
  578. * var item = 1,
  579. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  580. *
  581. * //output: 9
  582. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  583. * ```
  584. */
  585. indexOf:function (array, item, start) {
  586. var index = -1;
  587. start = this.isNumber(start) ? start : 0;
  588. this.each(array, function (v, i) {
  589. if (i >= start && v === item) {
  590. index = i;
  591. return false;
  592. }
  593. });
  594. return index;
  595. },
  596. /**
  597. * 移除数组array中所有的元素item
  598. * @method removeItem
  599. * @param { Array } array 要移除元素的目标数组
  600. * @param { * } item 将要被移除的元素
  601. * @remind 该方法的匹配过程使用的是恒等“===”
  602. * @example
  603. * ```javascript
  604. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  605. *
  606. * UE.utils.removeItem( arr, 4 );
  607. * //output: [ 5, 7, 1, 3, 6 ]
  608. * console.log( arr );
  609. *
  610. * ```
  611. */
  612. removeItem:function (array, item) {
  613. for (var i = 0, l = array.length; i < l; i++) {
  614. if (array[i] === item) {
  615. array.splice(i, 1);
  616. i--;
  617. }
  618. }
  619. },
  620. /**
  621. * 删除字符串str的首尾空格
  622. * @method trim
  623. * @param { String } str 需要删除首尾空格的字符串
  624. * @return { String } 删除了首尾的空格后的字符串
  625. * @example
  626. * ```javascript
  627. *
  628. * var str = " UEdtior ";
  629. *
  630. * //output: 9
  631. * console.log( str.length );
  632. *
  633. * //output: 7
  634. * console.log( UE.utils.trim( " UEdtior " ).length );
  635. *
  636. * //output: 9
  637. * console.log( str.length );
  638. *
  639. * ```
  640. */
  641. trim:function (str) {
  642. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  643. },
  644. /**
  645. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  646. * @method listToMap
  647. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  648. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  649. * @return { Object } 转化之后的hash对象
  650. * @example
  651. * ```javascript
  652. *
  653. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  654. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  655. *
  656. * ```
  657. */
  658. /**
  659. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  660. * @method listToMap
  661. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  662. * @param { Array } arr 字符串数组
  663. * @return { Object } 转化之后的hash对象
  664. * @example
  665. * ```javascript
  666. *
  667. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  668. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  669. *
  670. * ```
  671. */
  672. listToMap:function (list) {
  673. if (!list)return {};
  674. list = utils.isArray(list) ? list : list.split(',');
  675. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  676. obj[ci.toUpperCase()] = obj[ci] = 1;
  677. }
  678. return obj;
  679. },
  680. /**
  681. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  682. * @method unhtml
  683. * @param { String } str 需要转义的字符串
  684. * @return { String } 转义后的字符串
  685. * @example
  686. * ```javascript
  687. * var html = '<body>&</body>';
  688. *
  689. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  690. * console.log( UE.utils.unhtml( html ) );
  691. *
  692. * ```
  693. */
  694. unhtml:function (str, reg) {
  695. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
  696. if (b) {
  697. return a;
  698. } else {
  699. return {
  700. '<':'&lt;',
  701. '&':'&amp;',
  702. '"':'&quot;',
  703. '>':'&gt;',
  704. "'":'&#39;'
  705. }[a]
  706. }
  707. }) : '';
  708. },
  709. /**
  710. * 将url中的html字符转义, 仅转义 ', ", <, > 四个字符
  711. * @param { String } str 需要转义的字符串
  712. * @param { RegExp } reg 自定义的正则
  713. * @return { String } 转义后的字符串
  714. */
  715. unhtmlForUrl:function (str, reg) {
  716. return str ? str.replace(reg || /[<">']/g, function (a) {
  717. return {
  718. '<':'&lt;',
  719. '&':'&amp;',
  720. '"':'&quot;',
  721. '>':'&gt;',
  722. "'":'&#39;'
  723. }[a]
  724. }) : '';
  725. },
  726. /**
  727. * 将str中的转义字符还原成html字符
  728. * @see UE.utils.unhtml(String);
  729. * @method html
  730. * @param { String } str 需要逆转义的字符串
  731. * @return { String } 逆转义后的字符串
  732. * @example
  733. * ```javascript
  734. *
  735. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  736. *
  737. * //output: <body>&</body>
  738. * console.log( UE.utils.html( str ) );
  739. *
  740. * ```
  741. */
  742. html:function (str) {
  743. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  744. return {
  745. '&lt;':'<',
  746. '&amp;':'&',
  747. '&quot;':'"',
  748. '&gt;':'>',
  749. '&#39;':"'",
  750. '&nbsp;':' '
  751. }[m]
  752. }) : '';
  753. },
  754. /**
  755. * 将css样式转换为驼峰的形式
  756. * @method cssStyleToDomStyle
  757. * @param { String } cssName 需要转换的css样式名
  758. * @return { String } 转换成驼峰形式后的css样式名
  759. * @example
  760. * ```javascript
  761. *
  762. * var str = 'border-top';
  763. *
  764. * //output: borderTop
  765. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  766. *
  767. * ```
  768. */
  769. cssStyleToDomStyle:function () {
  770. var test = document.createElement('div').style,
  771. cache = {
  772. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  773. };
  774. return function (cssName) {
  775. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  776. return match.charAt(1).toUpperCase();
  777. }));
  778. };
  779. }(),
  780. /**
  781. * 动态加载文件到doc中
  782. * @method loadFile
  783. * @param { DomDocument } document 需要加载资源文件的文档对象
  784. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  785. * @example
  786. * ```javascript
  787. *
  788. * UE.utils.loadFile( document, {
  789. * src:"test.js",
  790. * tag:"script",
  791. * type:"text/javascript",
  792. * defer:"defer"
  793. * } );
  794. *
  795. * ```
  796. */
  797. /**
  798. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  799. * @method loadFile
  800. * @param { DomDocument } document 需要加载资源文件的文档对象
  801. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  802. * @param { Function } fn 资源文件加载成功之后执行的回调
  803. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  804. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  805. * @example
  806. * ```javascript
  807. *
  808. * UE.utils.loadFile( document, {
  809. * src:"test.js",
  810. * tag:"script",
  811. * type:"text/javascript",
  812. * defer:"defer"
  813. * }, function () {
  814. * console.log('加载成功');
  815. * } );
  816. *
  817. * ```
  818. */
  819. loadFile:function () {
  820. var tmpList = [];
  821. function getItem(doc, obj) {
  822. try {
  823. for (var i = 0, ci; ci = tmpList[i++];) {
  824. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  825. return ci;
  826. }
  827. }
  828. } catch (e) {
  829. return null;
  830. }
  831. }
  832. return function (doc, obj, fn) {
  833. var item = getItem(doc, obj);
  834. if (item) {
  835. if (item.ready) {
  836. fn && fn();
  837. } else {
  838. item.funs.push(fn)
  839. }
  840. return;
  841. }
  842. tmpList.push({
  843. doc:doc,
  844. url:obj.src || obj.href,
  845. funs:[fn]
  846. });
  847. if (!doc.body) {
  848. var html = [];
  849. for (var p in obj) {
  850. if (p == 'tag')continue;
  851. html.push(p + '="' + obj[p] + '"')
  852. }
  853. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  854. return;
  855. }
  856. if (obj.id && doc.getElementById(obj.id)) {
  857. return;
  858. }
  859. var element = doc.createElement(obj.tag);
  860. delete obj.tag;
  861. for (var p in obj) {
  862. element.setAttribute(p, obj[p]);
  863. }
  864. element.onload = element.onreadystatechange = function () {
  865. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  866. item = getItem(doc, obj);
  867. if (item.funs.length > 0) {
  868. item.ready = 1;
  869. for (var fi; fi = item.funs.pop();) {
  870. fi();
  871. }
  872. }
  873. element.onload = element.onreadystatechange = null;
  874. }
  875. };
  876. element.onerror = function () {
  877. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  878. };
  879. doc.getElementsByTagName("head")[0].appendChild(element);
  880. }
  881. }(),
  882. /**
  883. * 判断obj对象是否为空
  884. * @method isEmptyObject
  885. * @param { * } obj 需要判断的对象
  886. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  887. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  888. * @return { Boolean } 对象是否为空
  889. * @example
  890. * ```javascript
  891. *
  892. * //output: true
  893. * console.log( UE.utils.isEmptyObject( {} ) );
  894. *
  895. * //output: true
  896. * console.log( UE.utils.isEmptyObject( [] ) );
  897. *
  898. * //output: true
  899. * console.log( UE.utils.isEmptyObject( "" ) );
  900. *
  901. * //output: false
  902. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  903. *
  904. * //output: false
  905. * console.log( UE.utils.isEmptyObject( [1] ) );
  906. *
  907. * //output: false
  908. * console.log( UE.utils.isEmptyObject( "1" ) );
  909. *
  910. * ```
  911. */
  912. isEmptyObject:function (obj) {
  913. if (obj == null) return true;
  914. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  915. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  916. return true;
  917. },
  918. /**
  919. * 把rgb格式的颜色值转换成16进制格式
  920. * @method fixColor
  921. * @param { String } rgb格式的颜色值
  922. * @param { String }
  923. * @example
  924. * rgb(255,255,255) => "#ffffff"
  925. */
  926. fixColor:function (name, value) {
  927. if (/color/i.test(name) && /rgba?/.test(value)) {
  928. var array = value.split(",");
  929. if (array.length > 3)
  930. return "";
  931. value = "#";
  932. for (var i = 0, color; color = array[i++];) {
  933. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  934. value += color.length == 1 ? "0" + color : color;
  935. }
  936. value = value.toUpperCase();
  937. }
  938. return value;
  939. },
  940. /**
  941. * 只针对border,padding,margin做了处理,因为性能问题
  942. * @public
  943. * @function
  944. * @param {String} val style字符串
  945. */
  946. optCss:function (val) {
  947. var padding, margin, border;
  948. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  949. if (val.split(' ').length == 1) {
  950. switch (key) {
  951. case 'padding':
  952. !padding && (padding = {});
  953. padding[name] = val;
  954. return '';
  955. case 'margin':
  956. !margin && (margin = {});
  957. margin[name] = val;
  958. return '';
  959. case 'border':
  960. return val == 'initial' ? '' : str;
  961. }
  962. }
  963. return str;
  964. });
  965. function opt(obj, name) {
  966. if (!obj) {
  967. return '';
  968. }
  969. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  970. if (!t || !l || !b || !r) {
  971. for (var p in obj) {
  972. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  973. }
  974. } else {
  975. val += ';' + name + ':' +
  976. (t == b && b == l && l == r ? t :
  977. t == b && l == r ? (t + ' ' + l) :
  978. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  979. }
  980. return val;
  981. }
  982. val += opt(padding, 'padding') + opt(margin, 'margin');
  983. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  984. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  985. return b ? b + ";;" : ';'
  986. });
  987. },
  988. /**
  989. * 克隆对象
  990. * @method clone
  991. * @param { Object } source 源对象
  992. * @return { Object } source的一个副本
  993. */
  994. /**
  995. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  996. * @method clone
  997. * @param { Object } source 源对象
  998. * @param { Object } target 目标对象
  999. * @return { Object } 附加了source对象所有属性的target对象
  1000. */
  1001. clone:function (source, target) {
  1002. var tmp;
  1003. target = target || {};
  1004. for (var i in source) {
  1005. if (source.hasOwnProperty(i)) {
  1006. tmp = source[i];
  1007. if (typeof tmp == 'object') {
  1008. target[i] = utils.isArray(tmp) ? [] : {};
  1009. utils.clone(source[i], target[i])
  1010. } else {
  1011. target[i] = tmp;
  1012. }
  1013. }
  1014. }
  1015. return target;
  1016. },
  1017. /**
  1018. * 把cm/pt为单位的值转换为px为单位的值
  1019. * @method transUnitToPx
  1020. * @param { String } 待转换的带单位的字符串
  1021. * @return { String } 转换为px为计量单位的值的字符串
  1022. * @example
  1023. * ```javascript
  1024. *
  1025. * //output: 500px
  1026. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1027. *
  1028. * //output: 27px
  1029. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1030. *
  1031. * ```
  1032. */
  1033. transUnitToPx:function (val) {
  1034. if (!/(pt|cm)/.test(val)) {
  1035. return val
  1036. }
  1037. var unit;
  1038. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1039. val = v;
  1040. unit = u;
  1041. });
  1042. switch (unit) {
  1043. case 'cm':
  1044. val = parseFloat(val) * 25;
  1045. break;
  1046. case 'pt':
  1047. val = Math.round(parseFloat(val) * 96 / 72);
  1048. }
  1049. return val + (val ? 'px' : '');
  1050. },
  1051. /**
  1052. * 在dom树ready之后执行给定的回调函数
  1053. * @method domReady
  1054. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1055. * @param { Function } fn dom树ready之后的回调函数
  1056. * @example
  1057. * ```javascript
  1058. *
  1059. * UE.utils.domReady( function () {
  1060. *
  1061. * console.log('123');
  1062. *
  1063. * } );
  1064. *
  1065. * ```
  1066. */
  1067. domReady:function () {
  1068. var fnArr = [];
  1069. function doReady(doc) {
  1070. //确保onready只执行一次
  1071. doc.isReady = true;
  1072. for (var ci; ci = fnArr.pop(); ci()) {
  1073. }
  1074. }
  1075. return function (onready, win) {
  1076. win = win || window;
  1077. var doc = win.document;
  1078. onready && fnArr.push(onready);
  1079. if (doc.readyState === "complete") {
  1080. doReady(doc);
  1081. } else {
  1082. doc.isReady && doReady(doc);
  1083. if (browser.ie && browser.version != 11) {
  1084. (function () {
  1085. if (doc.isReady) return;
  1086. try {
  1087. doc.documentElement.doScroll("left");
  1088. } catch (error) {
  1089. setTimeout(arguments.callee, 0);
  1090. return;
  1091. }
  1092. doReady(doc);
  1093. })();
  1094. win.attachEvent('onload', function () {
  1095. doReady(doc)
  1096. });
  1097. } else {
  1098. doc.addEventListener("DOMContentLoaded", function () {
  1099. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1100. doReady(doc);
  1101. }, false);
  1102. win.addEventListener('load', function () {
  1103. doReady(doc)
  1104. }, false);
  1105. }
  1106. }
  1107. }
  1108. }(),
  1109. /**
  1110. * 动态添加css样式
  1111. * @method cssRule
  1112. * @param { String } 节点名称
  1113. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1114. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1115. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1116. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1117. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1118. */
  1119. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1120. var indexList, index;
  1121. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1122. //获取样式
  1123. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1124. indexList = doc.indexList || (doc.indexList = {});
  1125. index = indexList[key];
  1126. if(index !== undefined){
  1127. return doc.styleSheets[index].cssText
  1128. }
  1129. return undefined;
  1130. }
  1131. doc = doc || document;
  1132. indexList = doc.indexList || (doc.indexList = {});
  1133. index = indexList[key];
  1134. //清除样式
  1135. if(style === ''){
  1136. if(index!== undefined){
  1137. doc.styleSheets[index].cssText = '';
  1138. delete indexList[key];
  1139. return true
  1140. }
  1141. return false;
  1142. }
  1143. //添加样式
  1144. if(index!== undefined){
  1145. sheetStyle = doc.styleSheets[index];
  1146. }else{
  1147. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1148. indexList[key] = index;
  1149. }
  1150. sheetStyle.cssText = style;
  1151. }: function (key, style, doc) {
  1152. var head, node;
  1153. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1154. //获取样式
  1155. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1156. node = doc.getElementById(key);
  1157. return node ? node.innerHTML : undefined;
  1158. }
  1159. doc = doc || document;
  1160. node = doc.getElementById(key);
  1161. //清除样式
  1162. if(style === ''){
  1163. if(node){
  1164. node.parentNode.removeChild(node);
  1165. return true
  1166. }
  1167. return false;
  1168. }
  1169. //添加样式
  1170. if(node){
  1171. node.innerHTML = style;
  1172. }else{
  1173. node = doc.createElement('style');
  1174. node.id = key;
  1175. node.innerHTML = style;
  1176. doc.getElementsByTagName('head')[0].appendChild(node);
  1177. }
  1178. },
  1179. sort:function(array,compareFn){
  1180. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1181. for(var i= 0,len = array.length; i<len; i++){
  1182. for(var j = i,length = array.length; j<length; j++){
  1183. if(compareFn(array[i], array[j]) > 0){
  1184. var t = array[i];
  1185. array[i] = array[j];
  1186. array[j] = t;
  1187. }
  1188. }
  1189. }
  1190. return array;
  1191. },
  1192. serializeParam:function (json) {
  1193. var strArr = [];
  1194. for (var i in json) {
  1195. //忽略默认的几个参数
  1196. if(i=="method" || i=="timeout" || i=="async") continue;
  1197. //传递过来的对象和函数不在提交之列
  1198. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1199. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  1200. } else if (utils.isArray(json[i])) {
  1201. //支持传数组内容
  1202. for(var j = 0; j < json[i].length; j++) {
  1203. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  1204. }
  1205. }
  1206. }
  1207. return strArr.join("&");
  1208. },
  1209. formatUrl:function (url) {
  1210. var u = url.replace(/&&/g, '&');
  1211. u = u.replace(/\?&/g, '?');
  1212. u = u.replace(/&$/g, '');
  1213. u = u.replace(/&#/g, '#');
  1214. u = u.replace(/&+/g, '&');
  1215. return u;
  1216. },
  1217. isCrossDomainUrl:function (url) {
  1218. var a = document.createElement('a');
  1219. a.href = url;
  1220. if (browser.ie) {
  1221. a.href = a.href;
  1222. }
  1223. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1224. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1225. },
  1226. clearEmptyAttrs : function(obj){
  1227. for(var p in obj){
  1228. if(obj[p] === ''){
  1229. delete obj[p]
  1230. }
  1231. }
  1232. return obj;
  1233. },
  1234. str2json : function(s){
  1235. if (!utils.isString(s)) return null;
  1236. if (window.JSON) {
  1237. return JSON.parse(s);
  1238. } else {
  1239. return (new Function("return " + utils.trim(s || '')))();
  1240. }
  1241. },
  1242. json2str : (function(){
  1243. if (window.JSON) {
  1244. return JSON.stringify;
  1245. } else {
  1246. var escapeMap = {
  1247. "\b": '\\b',
  1248. "\t": '\\t',
  1249. "\n": '\\n',
  1250. "\f": '\\f',
  1251. "\r": '\\r',
  1252. '"' : '\\"',
  1253. "\\": '\\\\'
  1254. };
  1255. function encodeString(source) {
  1256. if (/["\\\x00-\x1f]/.test(source)) {
  1257. source = source.replace(
  1258. /["\\\x00-\x1f]/g,
  1259. function (match) {
  1260. var c = escapeMap[match];
  1261. if (c) {
  1262. return c;
  1263. }
  1264. c = match.charCodeAt();
  1265. return "\\u00"
  1266. + Math.floor(c / 16).toString(16)
  1267. + (c % 16).toString(16);
  1268. });
  1269. }
  1270. return '"' + source + '"';
  1271. }
  1272. function encodeArray(source) {
  1273. var result = ["["],
  1274. l = source.length,
  1275. preComma, i, item;
  1276. for (i = 0; i < l; i++) {
  1277. item = source[i];
  1278. switch (typeof item) {
  1279. case "undefined":
  1280. case "function":
  1281. case "unknown":
  1282. break;
  1283. default:
  1284. if(preComma) {
  1285. result.push(',');
  1286. }
  1287. result.push(utils.json2str(item));
  1288. preComma = 1;
  1289. }
  1290. }
  1291. result.push("]");
  1292. return result.join("");
  1293. }
  1294. function pad(source) {
  1295. return source < 10 ? '0' + source : source;
  1296. }
  1297. function encodeDate(source){
  1298. return '"' + source.getFullYear() + "-"
  1299. + pad(source.getMonth() + 1) + "-"
  1300. + pad(source.getDate()) + "T"
  1301. + pad(source.getHours()) + ":"
  1302. + pad(source.getMinutes()) + ":"
  1303. + pad(source.getSeconds()) + '"';
  1304. }
  1305. return function (value) {
  1306. switch (typeof value) {
  1307. case 'undefined':
  1308. return 'undefined';
  1309. case 'number':
  1310. return isFinite(value) ? String(value) : "null";
  1311. case 'string':
  1312. return encodeString(value);
  1313. case 'boolean':
  1314. return String(value);
  1315. default:
  1316. if (value === null) {
  1317. return 'null';
  1318. } else if (utils.isArray(value)) {
  1319. return encodeArray(value);
  1320. } else if (utils.isDate(value)) {
  1321. return encodeDate(value);
  1322. } else {
  1323. var result = ['{'],
  1324. encode = utils.json2str,
  1325. preComma,
  1326. item;
  1327. for (var key in value) {
  1328. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1329. item = value[key];
  1330. switch (typeof item) {
  1331. case 'undefined':
  1332. case 'unknown':
  1333. case 'function':
  1334. break;
  1335. default:
  1336. if (preComma) {
  1337. result.push(',');
  1338. }
  1339. preComma = 1;
  1340. result.push(encode(key) + ':' + encode(item));
  1341. }
  1342. }
  1343. }
  1344. result.push('}');
  1345. return result.join('');
  1346. }
  1347. }
  1348. };
  1349. }
  1350. })()
  1351. };
  1352. /**
  1353. * 判断给定的对象是否是字符串
  1354. * @method isString
  1355. * @param { * } object 需要判断的对象
  1356. * @return { Boolean } 给定的对象是否是字符串
  1357. */
  1358. /**
  1359. * 判断给定的对象是否是数组
  1360. * @method isArray
  1361. * @param { * } object 需要判断的对象
  1362. * @return { Boolean } 给定的对象是否是数组
  1363. */
  1364. /**
  1365. * 判断给定的对象是否是一个Function
  1366. * @method isFunction
  1367. * @param { * } object 需要判断的对象
  1368. * @return { Boolean } 给定的对象是否是Function
  1369. */
  1370. /**
  1371. * 判断给定的对象是否是Number
  1372. * @method isNumber
  1373. * @param { * } object 需要判断的对象
  1374. * @return { Boolean } 给定的对象是否是Number
  1375. */
  1376. /**
  1377. * 判断给定的对象是否是一个正则表达式
  1378. * @method isRegExp
  1379. * @param { * } object 需要判断的对象
  1380. * @return { Boolean } 给定的对象是否是正则表达式
  1381. */
  1382. /**
  1383. * 判断给定的对象是否是一个普通对象
  1384. * @method isObject
  1385. * @param { * } object 需要判断的对象
  1386. * @return { Boolean } 给定的对象是否是普通对象
  1387. */
  1388. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1389. UE.utils['is' + v] = function (obj) {
  1390. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1391. }
  1392. });
  1393. // core/EventBase.js
  1394. /**
  1395. * UE采用的事件基类
  1396. * @file
  1397. * @module UE
  1398. * @class EventBase
  1399. * @since 1.2.6.1
  1400. */
  1401. /**
  1402. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1403. * @unfile
  1404. * @module UE
  1405. */
  1406. /**
  1407. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1408. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1409. * @unfile
  1410. * @module UE
  1411. * @class EventBase
  1412. */
  1413. /**
  1414. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1415. * @constructor
  1416. * @example
  1417. * ```javascript
  1418. * UE.EventBase.call(editor);
  1419. * ```
  1420. */
  1421. var EventBase = UE.EventBase = function () {};
  1422. EventBase.prototype = {
  1423. /**
  1424. * 注册事件监听器
  1425. * @method addListener
  1426. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1427. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1428. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1429. * @example
  1430. * ```javascript
  1431. * editor.addListener('selectionchange',function(){
  1432. * console.log("选区已经变化!");
  1433. * })
  1434. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1435. * if(type == 'beforegetcontent'){
  1436. * //do something
  1437. * }else{
  1438. * //do something
  1439. * }
  1440. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1441. * })
  1442. * ```
  1443. * @see UE.EventBase:fireEvent(String)
  1444. */
  1445. addListener:function (types, listener) {
  1446. types = utils.trim(types).split(/\s+/);
  1447. for (var i = 0, ti; ti = types[i++];) {
  1448. getListener(this, ti, true).push(listener);
  1449. }
  1450. },
  1451. on : function(types, listener){
  1452. return this.addListener(types,listener);
  1453. },
  1454. off : function(types, listener){
  1455. return this.removeListener(types, listener)
  1456. },
  1457. trigger:function(){
  1458. return this.fireEvent.apply(this,arguments);
  1459. },
  1460. /**
  1461. * 移除事件监听器
  1462. * @method removeListener
  1463. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1464. * @param { Function } fn 移除监听事件的函数引用
  1465. * @example
  1466. * ```javascript
  1467. * //changeCallback为方法体
  1468. * editor.removeListener("selectionchange",changeCallback);
  1469. * ```
  1470. */
  1471. removeListener:function (types, listener) {
  1472. types = utils.trim(types).split(/\s+/);
  1473. for (var i = 0, ti; ti = types[i++];) {
  1474. utils.removeItem(getListener(this, ti) || [], listener);
  1475. }
  1476. },
  1477. /**
  1478. * 触发事件
  1479. * @method fireEvent
  1480. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1481. * @remind 该方法会触发addListener
  1482. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1483. * @example
  1484. * ```javascript
  1485. * editor.fireEvent("selectionchange");
  1486. * ```
  1487. */
  1488. /**
  1489. * 触发事件
  1490. * @method fireEvent
  1491. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1492. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1493. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1494. * @example
  1495. * ```javascript
  1496. *
  1497. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1498. *
  1499. * console.log( arg1 + " " + arg2 );
  1500. *
  1501. * } );
  1502. *
  1503. * //触发selectionchange事件, 会执行上面的事件监听器
  1504. * //output: Hello World
  1505. * editor.fireEvent("selectionchange", "Hello", "World");
  1506. * ```
  1507. */
  1508. fireEvent:function () {
  1509. var types = arguments[0];
  1510. types = utils.trim(types).split(' ');
  1511. for (var i = 0, ti; ti = types[i++];) {
  1512. var listeners = getListener(this, ti),
  1513. r, t, k;
  1514. if (listeners) {
  1515. k = listeners.length;
  1516. while (k--) {
  1517. if(!listeners[k])continue;
  1518. t = listeners[k].apply(this, arguments);
  1519. if(t === true){
  1520. return t;
  1521. }
  1522. if (t !== undefined) {
  1523. r = t;
  1524. }
  1525. }
  1526. }
  1527. if (t = this['on' + ti.toLowerCase()]) {
  1528. r = t.apply(this, arguments);
  1529. }
  1530. }
  1531. return r;
  1532. }
  1533. };
  1534. /**
  1535. * 获得对象所拥有监听类型的所有监听器
  1536. * @unfile
  1537. * @module UE
  1538. * @since 1.2.6.1
  1539. * @method getListener
  1540. * @public
  1541. * @param { Object } obj 查询监听器的对象
  1542. * @param { String } type 事件类型
  1543. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1544. * @return { Array } 监听器数组
  1545. */
  1546. function getListener(obj, type, force) {
  1547. var allListeners;
  1548. type = type.toLowerCase();
  1549. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1550. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1551. }
  1552. // core/dtd.js
  1553. ///import editor.js
  1554. ///import core/dom/dom.js
  1555. ///import core/utils.js
  1556. /**
  1557. * dtd html语义化的体现类
  1558. * @constructor
  1559. * @namespace dtd
  1560. */
  1561. var dtd = dom.dtd = (function() {
  1562. function _( s ) {
  1563. for (var k in s) {
  1564. s[k.toUpperCase()] = s[k];
  1565. }
  1566. return s;
  1567. }
  1568. var X = utils.extend2;
  1569. var A = _({isindex:1,fieldset:1}),
  1570. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1571. C = X( _({a:1}), B ),
  1572. D = X( {iframe:1}, C ),
  1573. 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}),
  1574. F = _({ins:1,del:1,script:1,style:1}),
  1575. 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 ),
  1576. 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 ),
  1577. I = X( _({p:1}), H ),
  1578. J = X( _({iframe:1}), H, B ),
  1579. 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}),
  1580. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1581. M = _({tr:1}),
  1582. N = _({'#':1}),
  1583. O = X( _({param:1}), K ),
  1584. P = X( _({form:1}), A, D, E, I ),
  1585. Q = _({li:1,ol:1,ul:1}),
  1586. R = _({style:1,script:1}),
  1587. S = _({base:1,link:1,meta:1,title:1}),
  1588. T = X( S, R ),
  1589. U = _({head:1,body:1}),
  1590. V = _({html:1});
  1591. 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}),
  1592. 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});
  1593. return _({
  1594. // $ 表示自定的属性
  1595. // body外的元素列表.
  1596. $nonBodyContent: X( V, U, S ),
  1597. //块结构元素列表
  1598. $block : block,
  1599. //内联元素列表
  1600. $inline : L,
  1601. $inlineWithA : X(_({a:1}),L),
  1602. $body : X( _({script:1,style:1}), block ),
  1603. $cdata : _({script:1,style:1}),
  1604. //自闭和元素
  1605. $empty : empty,
  1606. //不是自闭合,但不能让range选中里边
  1607. $nonChild : _({iframe:1,textarea:1}),
  1608. //列表元素列表
  1609. $listItem : _({dd:1,dt:1,li:1}),
  1610. //列表根元素列表
  1611. $list: _({ul:1,ol:1,dl:1}),
  1612. //不能认为是空的元素
  1613. $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}),
  1614. //如果没有子节点就可以删除的元素列表,像span,a
  1615. $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}),
  1616. $removeEmptyBlock : _({'p':1,'div':1}),
  1617. //在table元素里的元素列表
  1618. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1619. //不转换的标签
  1620. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1621. html: U,
  1622. head: T,
  1623. style: N,
  1624. script: N,
  1625. body: P,
  1626. base: {},
  1627. link: {},
  1628. meta: {},
  1629. title: N,
  1630. col : {},
  1631. tr : _({td:1,th:1}),
  1632. img : {},
  1633. embed: {},
  1634. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1635. noscript : P,
  1636. td : P,
  1637. br : {},
  1638. th : P,
  1639. center : P,
  1640. kbd : L,
  1641. button : X( I, E ),
  1642. basefont : {},
  1643. h5 : L,
  1644. h4 : L,
  1645. samp : L,
  1646. h6 : L,
  1647. ol : Q,
  1648. h1 : L,
  1649. h3 : L,
  1650. option : N,
  1651. h2 : L,
  1652. form : X( A, D, E, I ),
  1653. select : _({optgroup:1,option:1}),
  1654. font : L,
  1655. ins : L,
  1656. menu : Q,
  1657. abbr : L,
  1658. label : L,
  1659. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1660. code : L,
  1661. tfoot : M,
  1662. cite : L,
  1663. li : P,
  1664. input : {},
  1665. iframe : P,
  1666. strong : L,
  1667. textarea : N,
  1668. noframes : P,
  1669. big : L,
  1670. small : L,
  1671. //trace:
  1672. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1673. hr : L,
  1674. dt : L,
  1675. sub : L,
  1676. optgroup : _({option:1}),
  1677. param : {},
  1678. bdo : L,
  1679. 'var' : L,
  1680. div : P,
  1681. object : O,
  1682. sup : L,
  1683. dd : P,
  1684. strike : L,
  1685. area : {},
  1686. dir : Q,
  1687. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1688. applet : O,
  1689. dl : _({dt:1,dd:1}),
  1690. del : L,
  1691. isindex : {},
  1692. fieldset : X( _({legend:1}), K ),
  1693. thead : M,
  1694. ul : Q,
  1695. acronym : L,
  1696. b : L,
  1697. a : X( _({a:1}), J ),
  1698. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1699. caption : L,
  1700. i : L,
  1701. u : L,
  1702. tbody : M,
  1703. s : L,
  1704. address : X( D, I ),
  1705. tt : L,
  1706. legend : L,
  1707. q : L,
  1708. pre : X( G, C ),
  1709. p : X(_({'a':1}),L),
  1710. em :L,
  1711. dfn : L
  1712. });
  1713. })();
  1714. // core/domUtils.js
  1715. /**
  1716. * Dom操作工具包
  1717. * @file
  1718. * @module UE.dom.domUtils
  1719. * @since 1.2.6.1
  1720. */
  1721. /**
  1722. * Dom操作工具包
  1723. * @unfile
  1724. * @module UE.dom.domUtils
  1725. */
  1726. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1727. var tmpNode = startFromChild && node[start],
  1728. parent;
  1729. !tmpNode && (tmpNode = node[ltr]);
  1730. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1731. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1732. return null;
  1733. }
  1734. tmpNode = parent[ltr];
  1735. }
  1736. if (tmpNode && fn && !fn(tmpNode)) {
  1737. return getDomNode(tmpNode, start, ltr, false, fn);
  1738. }
  1739. return tmpNode;
  1740. }
  1741. var attrFix = ie && browser.version < 9 ? {
  1742. tabindex:"tabIndex",
  1743. readonly:"readOnly",
  1744. "for":"htmlFor",
  1745. "class":"className",
  1746. maxlength:"maxLength",
  1747. cellspacing:"cellSpacing",
  1748. cellpadding:"cellPadding",
  1749. rowspan:"rowSpan",
  1750. colspan:"colSpan",
  1751. usemap:"useMap",
  1752. frameborder:"frameBorder"
  1753. } : {
  1754. tabindex:"tabIndex",
  1755. readonly:"readOnly"
  1756. },
  1757. styleBlock = utils.listToMap([
  1758. '-webkit-box', '-moz-box', 'block' ,
  1759. 'list-item' , 'table' , 'table-row-group' ,
  1760. 'table-header-group', 'table-footer-group' ,
  1761. 'table-row' , 'table-column-group' , 'table-column' ,
  1762. 'table-cell' , 'table-caption'
  1763. ]);
  1764. var domUtils = dom.domUtils = {
  1765. //节点常量
  1766. NODE_ELEMENT:1,
  1767. NODE_DOCUMENT:9,
  1768. NODE_TEXT:3,
  1769. NODE_COMMENT:8,
  1770. NODE_DOCUMENT_FRAGMENT:11,
  1771. //位置关系
  1772. POSITION_IDENTICAL:0,
  1773. POSITION_DISCONNECTED:1,
  1774. POSITION_FOLLOWING:2,
  1775. POSITION_PRECEDING:4,
  1776. POSITION_IS_CONTAINED:8,
  1777. POSITION_CONTAINS:16,
  1778. //ie6使用其他的会有一段空白出现
  1779. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1780. //-------------------------Node部分--------------------------------
  1781. keys:{
  1782. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1783. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1784. 37:1, 38:1, 39:1, 40:1,
  1785. 13:1 /*enter*/
  1786. },
  1787. /**
  1788. * 获取节点A相对于节点B的位置关系
  1789. * @method getPosition
  1790. * @param { Node } nodeA 需要查询位置关系的节点A
  1791. * @param { Node } nodeB 需要查询位置关系的节点B
  1792. * @return { Number } 节点A与节点B的关系
  1793. * @example
  1794. * ```javascript
  1795. * //output: 20
  1796. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1797. *
  1798. * switch ( position ) {
  1799. *
  1800. * //0
  1801. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1802. * console.log('元素相同');
  1803. * break;
  1804. * //1
  1805. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1806. * console.log('两个节点在不同的文档中');
  1807. * break;
  1808. * //2
  1809. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1810. * console.log('节点A在节点B之后');
  1811. * break;
  1812. * //4
  1813. * case UE.dom.domUtils.POSITION_PRECEDING;
  1814. * console.log('节点A在节点B之前');
  1815. * break;
  1816. * //8
  1817. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1818. * console.log('节点A被节点B包含');
  1819. * break;
  1820. * case 10:
  1821. * console.log('节点A被节点B包含且节点A在节点B之后');
  1822. * break;
  1823. * //16
  1824. * case UE.dom.domUtils.POSITION_CONTAINS:
  1825. * console.log('节点A包含节点B');
  1826. * break;
  1827. * case 20:
  1828. * console.log('节点A包含节点B且节点A在节点B之前');
  1829. * break;
  1830. *
  1831. * }
  1832. * ```
  1833. */
  1834. getPosition:function (nodeA, nodeB) {
  1835. // 如果两个节点是同一个节点
  1836. if (nodeA === nodeB) {
  1837. // domUtils.POSITION_IDENTICAL
  1838. return 0;
  1839. }
  1840. var node,
  1841. parentsA = [nodeA],
  1842. parentsB = [nodeB];
  1843. node = nodeA;
  1844. while (node = node.parentNode) {
  1845. // 如果nodeB是nodeA的祖先节点
  1846. if (node === nodeB) {
  1847. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1848. return 10;
  1849. }
  1850. parentsA.push(node);
  1851. }
  1852. node = nodeB;
  1853. while (node = node.parentNode) {
  1854. // 如果nodeA是nodeB的祖先节点
  1855. if (node === nodeA) {
  1856. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1857. return 20;
  1858. }
  1859. parentsB.push(node);
  1860. }
  1861. parentsA.reverse();
  1862. parentsB.reverse();
  1863. if (parentsA[0] !== parentsB[0]) {
  1864. // domUtils.POSITION_DISCONNECTED
  1865. return 1;
  1866. }
  1867. var i = -1;
  1868. while (i++, parentsA[i] === parentsB[i]) {
  1869. }
  1870. nodeA = parentsA[i];
  1871. nodeB = parentsB[i];
  1872. while (nodeA = nodeA.nextSibling) {
  1873. if (nodeA === nodeB) {
  1874. // domUtils.POSITION_PRECEDING
  1875. return 4
  1876. }
  1877. }
  1878. // domUtils.POSITION_FOLLOWING
  1879. return 2;
  1880. },
  1881. /**
  1882. * 检测节点node在父节点中的索引位置
  1883. * @method getNodeIndex
  1884. * @param { Node } node 需要检测的节点对象
  1885. * @return { Number } 该节点在父节点中的位置
  1886. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1887. */
  1888. /**
  1889. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1890. * @method getNodeIndex
  1891. * @param { Node } node 需要检测的节点对象
  1892. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1893. * @return { Number } 该节点在父节点中的位置
  1894. * @example
  1895. * ```javascript
  1896. *
  1897. * var node = document.createElement("div");
  1898. *
  1899. * node.appendChild( document.createTextNode( "hello" ) );
  1900. * node.appendChild( document.createTextNode( "world" ) );
  1901. * node.appendChild( node = document.createElement( "div" ) );
  1902. *
  1903. * //output: 2
  1904. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1905. *
  1906. * //output: 1
  1907. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1908. *
  1909. * ```
  1910. */
  1911. getNodeIndex:function (node, ignoreTextNode) {
  1912. var preNode = node,
  1913. i = 0;
  1914. while (preNode = preNode.previousSibling) {
  1915. if (ignoreTextNode && preNode.nodeType == 3) {
  1916. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1917. i++;
  1918. }
  1919. continue;
  1920. }
  1921. i++;
  1922. }
  1923. return i;
  1924. },
  1925. /**
  1926. * 检测节点node是否在给定的document对象上
  1927. * @method inDoc
  1928. * @param { Node } node 需要检测的节点对象
  1929. * @param { DomDocument } doc 需要检测的document对象
  1930. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1931. * @example
  1932. * ```javascript
  1933. *
  1934. * var node = document.createElement("div");
  1935. *
  1936. * //output: false
  1937. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1938. *
  1939. * document.body.appendChild( node );
  1940. *
  1941. * //output: true
  1942. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1943. *
  1944. * ```
  1945. */
  1946. inDoc:function (node, doc) {
  1947. return domUtils.getPosition(node, doc) == 10;
  1948. },
  1949. /**
  1950. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1951. * 查找的起点是给定node节点的父节点。
  1952. * @method findParent
  1953. * @param { Node } node 需要查找的节点
  1954. * @param { Function } filterFn 自定义的过滤方法。
  1955. * @warning 查找的终点是到body节点为止
  1956. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1957. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1958. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1959. * @example
  1960. * ```javascript
  1961. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1962. *
  1963. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1964. * return node.tagName === "HTML";
  1965. *
  1966. * } );
  1967. *
  1968. * //output: true
  1969. * console.log( filterNode === null );
  1970. * ```
  1971. */
  1972. /**
  1973. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1974. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1975. * @method findParent
  1976. * @param { Node } node 需要查找的节点
  1977. * @param { Function } filterFn 自定义的过滤方法。
  1978. * @param { Boolean } includeSelf 查找过程是否包含自身
  1979. * @warning 查找的终点是到body节点为止
  1980. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1981. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1982. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1983. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1984. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1985. * @example
  1986. * ```html
  1987. * <body>
  1988. *
  1989. * <div id="test">
  1990. * </div>
  1991. *
  1992. * <script type="text/javascript">
  1993. *
  1994. * //output: DIV, BODY
  1995. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1996. *
  1997. * console.log( node.tagName );
  1998. * return false;
  1999. *
  2000. * }, true );
  2001. *
  2002. * </script>
  2003. * </body>
  2004. * ```
  2005. */
  2006. findParent:function (node, filterFn, includeSelf) {
  2007. if (node && !domUtils.isBody(node)) {
  2008. node = includeSelf ? node : node.parentNode;
  2009. while (node) {
  2010. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  2011. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  2012. }
  2013. node = node.parentNode;
  2014. }
  2015. }
  2016. return null;
  2017. },
  2018. /**
  2019. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2020. * @method findParentByTagName
  2021. * @param { Node } node 需要查找的节点对象
  2022. * @param { Array } tagNames 需要查找的父节点的名称数组
  2023. * @warning 查找的终点是到body节点为止
  2024. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2025. * @example
  2026. * ```javascript
  2027. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2028. * //output: BODY
  2029. * console.log( node.tagName );
  2030. * ```
  2031. */
  2032. /**
  2033. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2034. * 否则, 起点是node的父节点。
  2035. * @method findParentByTagName
  2036. * @param { Node } node 需要查找的节点对象
  2037. * @param { Array } tagNames 需要查找的父节点的名称数组
  2038. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2039. * @warning 查找的终点是到body节点为止
  2040. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2041. * @example
  2042. * ```javascript
  2043. * var queryTarget = document.getElementsByTagName("div")[0];
  2044. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2045. * //output: true
  2046. * console.log( queryTarget === node );
  2047. * ```
  2048. */
  2049. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  2050. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2051. return domUtils.findParent(node, function (node) {
  2052. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2053. }, includeSelf);
  2054. },
  2055. /**
  2056. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2057. * @method findParents
  2058. * @param { Node } node 需要查找的节点对象
  2059. * @return { Array } 给定节点的祖先节点数组
  2060. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2061. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2062. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2063. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2064. */
  2065. /**
  2066. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2067. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2068. * @method findParents
  2069. * @param { Node } node 需要查找的节点对象
  2070. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2071. * @return { Array } 给定节点的祖先节点数组
  2072. */
  2073. findParents:function (node, includeSelf, filterFn, closerFirst) {
  2074. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  2075. while (node = domUtils.findParent(node, filterFn)) {
  2076. parents.push(node);
  2077. }
  2078. return closerFirst ? parents : parents.reverse();
  2079. },
  2080. /**
  2081. * 在节点node后面插入新节点newNode
  2082. * @method insertAfter
  2083. * @param { Node } node 目标节点
  2084. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2085. * @return { Node } 新插入的节点
  2086. */
  2087. insertAfter:function (node, newNode) {
  2088. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  2089. node.parentNode.appendChild(newNode);
  2090. },
  2091. /**
  2092. * 删除节点node及其下属的所有节点
  2093. * @method remove
  2094. * @param { Node } node 需要删除的节点对象
  2095. * @return { Node } 返回刚删除的节点对象
  2096. * @example
  2097. * ```html
  2098. * <div id="test">
  2099. * <div id="child">你好</div>
  2100. * </div>
  2101. * <script>
  2102. * UE.dom.domUtils.remove( document.body, false );
  2103. * //output: false
  2104. * console.log( document.getElementById( "child" ) !== null );
  2105. * </script>
  2106. * ```
  2107. */
  2108. /**
  2109. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2110. * @method remove
  2111. * @param { Node } node 需要删除的节点对象
  2112. * @param { Boolean } keepChildren 是否需要保留子节点
  2113. * @return { Node } 返回刚删除的节点对象
  2114. * @example
  2115. * ```html
  2116. * <div id="test">
  2117. * <div id="child">你好</div>
  2118. * </div>
  2119. * <script>
  2120. * UE.dom.domUtils.remove( document.body, true );
  2121. * //output: true
  2122. * console.log( document.getElementById( "child" ) !== null );
  2123. * </script>
  2124. * ```
  2125. */
  2126. remove:function (node, keepChildren) {
  2127. var parent = node.parentNode,
  2128. child;
  2129. if (parent) {
  2130. if (keepChildren && node.hasChildNodes()) {
  2131. while (child = node.firstChild) {
  2132. parent.insertBefore(child, node);
  2133. }
  2134. }
  2135. parent.removeChild(node);
  2136. }
  2137. return node;
  2138. },
  2139. /**
  2140. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2141. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2142. * @method getNextDomNode
  2143. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2144. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2145. * @example
  2146. * ```html
  2147. * <body>
  2148. * <div id="test">
  2149. * <span></span>
  2150. * </div>
  2151. * <i>xxx</i>
  2152. * </body>
  2153. * <script>
  2154. *
  2155. * //output: i节点
  2156. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2157. *
  2158. * </script>
  2159. * ```
  2160. * @example
  2161. * ```html
  2162. * <body>
  2163. * <div>
  2164. * <span></span>
  2165. * <i id="test">xxx</i>
  2166. * </div>
  2167. * <b>xxx</b>
  2168. * </body>
  2169. * <script>
  2170. *
  2171. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2172. * //output: b节点
  2173. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2174. *
  2175. * </script>
  2176. * ```
  2177. */
  2178. /**
  2179. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2180. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2181. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2182. * @method getNextDomNode
  2183. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2184. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2185. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2186. * @see UE.dom.domUtils.getNextDomNode(Node)
  2187. */
  2188. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2189. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2190. },
  2191. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2192. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2193. },
  2194. /**
  2195. * 检测节点node是否属是UEditor定义的bookmark节点
  2196. * @method isBookmarkNode
  2197. * @private
  2198. * @param { Node } node 需要检测的节点对象
  2199. * @return { Boolean } 是否是bookmark节点
  2200. * @example
  2201. * ```html
  2202. * <span id="_baidu_bookmark_1"></span>
  2203. * <script>
  2204. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2205. * //output: true
  2206. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2207. * </script>
  2208. * ```
  2209. */
  2210. isBookmarkNode:function (node) {
  2211. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2212. },
  2213. /**
  2214. * 获取节点node所属的window对象
  2215. * @method getWindow
  2216. * @param { Node } node 节点对象
  2217. * @return { Window } 当前节点所属的window对象
  2218. * @example
  2219. * ```javascript
  2220. * //output: true
  2221. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2222. * ```
  2223. */
  2224. getWindow:function (node) {
  2225. var doc = node.ownerDocument || node;
  2226. return doc.defaultView || doc.parentWindow;
  2227. },
  2228. /**
  2229. * 获取离nodeA与nodeB最近的公共的祖先节点
  2230. * @method getCommonAncestor
  2231. * @param { Node } nodeA 第一个节点
  2232. * @param { Node } nodeB 第二个节点
  2233. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2234. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2235. * @example
  2236. * ```javascript
  2237. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2238. * //output: true
  2239. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2240. * ```
  2241. */
  2242. getCommonAncestor:function (nodeA, nodeB) {
  2243. if (nodeA === nodeB)
  2244. return nodeA;
  2245. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2246. while (parent = parent.parentNode) {
  2247. if (parent === nodeB) {
  2248. return parent;
  2249. }
  2250. parentsA.push(parent);
  2251. }
  2252. parent = nodeB;
  2253. while (parent = parent.parentNode) {
  2254. if (parent === nodeA)
  2255. return parent;
  2256. parentsB.push(parent);
  2257. }
  2258. parentsA.reverse();
  2259. parentsB.reverse();
  2260. while (i++, parentsA[i] === parentsB[i]) {
  2261. }
  2262. return i == 0 ? null : parentsA[i - 1];
  2263. },
  2264. /**
  2265. * 清除node节点左右连续为空的兄弟inline节点
  2266. * @method clearEmptySibling
  2267. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2268. * 则这些兄弟节点将被删除
  2269. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2270. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2271. * @example
  2272. * ```html
  2273. * <body>
  2274. * <div></div>
  2275. * <span id="test"></span>
  2276. * <i></i>
  2277. * <b></b>
  2278. * <em>xxx</em>
  2279. * <span></span>
  2280. * </body>
  2281. * <script>
  2282. *
  2283. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2284. *
  2285. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2286. * console.log( document.body.innerHTML );
  2287. *
  2288. * </script>
  2289. * ```
  2290. */
  2291. /**
  2292. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2293. * 则忽略对右边兄弟节点的操作。
  2294. * @method clearEmptySibling
  2295. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2296. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2297. * 则这些兄弟节点将被删除
  2298. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2299. */
  2300. /**
  2301. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2302. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2303. * @method clearEmptySibling
  2304. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2305. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2306. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2307. * 则这些兄弟节点将被删除
  2308. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2309. */
  2310. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2311. function clear(next, dir) {
  2312. var tmpNode;
  2313. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2314. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2315. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2316. tmpNode = next[dir];
  2317. domUtils.remove(next);
  2318. next = tmpNode;
  2319. }
  2320. }
  2321. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2322. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2323. },
  2324. /**
  2325. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2326. * @method split
  2327. * @param { Node } textNode 需要拆分的文本节点对象
  2328. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2329. * @return { Node } 拆分后形成的新节点
  2330. * @example
  2331. * ```html
  2332. * <div id="test">abcdef</div>
  2333. * <script>
  2334. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2335. * //output: def
  2336. * console.log( newNode.nodeValue );
  2337. * </script>
  2338. * ```
  2339. */
  2340. split:function (node, offset) {
  2341. var doc = node.ownerDocument;
  2342. if (browser.ie && offset == node.nodeValue.length) {
  2343. var next = doc.createTextNode('');
  2344. return domUtils.insertAfter(node, next);
  2345. }
  2346. var retval = node.splitText(offset);
  2347. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2348. if (browser.ie8) {
  2349. var tmpNode = doc.createTextNode('');
  2350. domUtils.insertAfter(retval, tmpNode);
  2351. domUtils.remove(tmpNode);
  2352. }
  2353. return retval;
  2354. },
  2355. /**
  2356. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2357. * @method isWhitespace
  2358. * @param { Node } node 需要检测的节点对象
  2359. * @return { Boolean } 检测的节点是否为空
  2360. * @example
  2361. * ```html
  2362. * <div id="test">
  2363. *
  2364. * </div>
  2365. * <script>
  2366. * //output: true
  2367. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2368. * </script>
  2369. * ```
  2370. */
  2371. isWhitespace:function (node) {
  2372. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2373. },
  2374. /**
  2375. * 获取元素element相对于viewport的位置坐标
  2376. * @method getXY
  2377. * @param { Node } element 需要计算位置的节点对象
  2378. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2379. * y代表垂直偏移距离。
  2380. *
  2381. * @example
  2382. * ```javascript
  2383. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2384. * //output: test的坐标为: 12, 24
  2385. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2386. * ```
  2387. */
  2388. getXY:function (element) {
  2389. var x = 0, y = 0;
  2390. while (element.offsetParent) {
  2391. y += element.offsetTop;
  2392. x += element.offsetLeft;
  2393. element = element.offsetParent;
  2394. }
  2395. return { 'x':x, 'y':y};
  2396. },
  2397. /**
  2398. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2399. * @method on
  2400. * @param { Node } element 需要绑定事件的节点对象
  2401. * @param { String } type 绑定的事件类型
  2402. * @param { Function } handler 事件处理器
  2403. * @example
  2404. * ```javascript
  2405. * UE.dom.domUtils.on(document.body,"click",function(e){
  2406. * //e为事件对象,this为被点击元素对戏那个
  2407. * });
  2408. * ```
  2409. */
  2410. /**
  2411. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2412. * @method on
  2413. * @param { Node } element 需要绑定事件的节点对象
  2414. * @param { Array } type 绑定的事件类型数组
  2415. * @param { Function } handler 事件处理器
  2416. * @example
  2417. * ```javascript
  2418. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2419. * //evt为事件对象,this为被点击元素对象
  2420. * });
  2421. * ```
  2422. */
  2423. on:function (element, type, handler) {
  2424. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2425. k = types.length;
  2426. if (k) while (k--) {
  2427. type = types[k];
  2428. if (element.addEventListener) {
  2429. element.addEventListener(type, handler, false);
  2430. } else {
  2431. if (!handler._d) {
  2432. handler._d = {
  2433. els : []
  2434. };
  2435. }
  2436. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2437. if (!handler._d[key] || index == -1) {
  2438. if(index == -1){
  2439. handler._d.els.push(element);
  2440. }
  2441. if(!handler._d[key]){
  2442. handler._d[key] = function (evt) {
  2443. return handler.call(evt.srcElement, evt || window.event);
  2444. };
  2445. }
  2446. element.attachEvent('on' + type, handler._d[key]);
  2447. }
  2448. }
  2449. }
  2450. element = null;
  2451. },
  2452. /**
  2453. * 解除DOM事件绑定
  2454. * @method un
  2455. * @param { Node } element 需要解除事件绑定的节点对象
  2456. * @param { String } type 需要接触绑定的事件类型
  2457. * @param { Function } handler 对应的事件处理器
  2458. * @example
  2459. * ```javascript
  2460. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2461. * //evt为事件对象,this为被点击元素对象
  2462. * });
  2463. * ```
  2464. */
  2465. /**
  2466. * 解除DOM事件绑定
  2467. * @method un
  2468. * @param { Node } element 需要解除事件绑定的节点对象
  2469. * @param { Array } type 需要接触绑定的事件类型数组
  2470. * @param { Function } handler 对应的事件处理器
  2471. * @example
  2472. * ```javascript
  2473. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2474. * //evt为事件对象,this为被点击元素对象
  2475. * });
  2476. * ```
  2477. */
  2478. un:function (element, type, handler) {
  2479. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2480. k = types.length;
  2481. if (k) while (k--) {
  2482. type = types[k];
  2483. if (element.removeEventListener) {
  2484. element.removeEventListener(type, handler, false);
  2485. } else {
  2486. var key = type + handler.toString();
  2487. try{
  2488. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2489. }catch(e){}
  2490. if (handler._d && handler._d[key]) {
  2491. var index = utils.indexOf(handler._d.els,element);
  2492. if(index!=-1){
  2493. handler._d.els.splice(index,1);
  2494. }
  2495. handler._d.els.length == 0 && delete handler._d[key];
  2496. }
  2497. }
  2498. }
  2499. },
  2500. /**
  2501. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2502. * @method isSameElement
  2503. * @param { Node } nodeA 需要比较的节点
  2504. * @param { Node } nodeB 需要比较的节点
  2505. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2506. * @example
  2507. * ```html
  2508. * <span style="font-size:12px">ssss</span>
  2509. * <span style="font-size:12px">bbbbb</span>
  2510. * <span style="font-size:13px">ssss</span>
  2511. * <span style="font-size:14px">bbbbb</span>
  2512. *
  2513. * <script>
  2514. *
  2515. * var nodes = document.getElementsByTagName( "span" );
  2516. *
  2517. * //output: true
  2518. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2519. *
  2520. * //output: false
  2521. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2522. *
  2523. * </script>
  2524. * ```
  2525. */
  2526. isSameElement:function (nodeA, nodeB) {
  2527. if (nodeA.tagName != nodeB.tagName) {
  2528. return false;
  2529. }
  2530. var thisAttrs = nodeA.attributes,
  2531. otherAttrs = nodeB.attributes;
  2532. if (!ie && thisAttrs.length != otherAttrs.length) {
  2533. return false;
  2534. }
  2535. var attrA, attrB, al = 0, bl = 0;
  2536. for (var i = 0; attrA = thisAttrs[i++];) {
  2537. if (attrA.nodeName == 'style') {
  2538. if (attrA.specified) {
  2539. al++;
  2540. }
  2541. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2542. continue;
  2543. } else {
  2544. return false;
  2545. }
  2546. }
  2547. if (ie) {
  2548. if (attrA.specified) {
  2549. al++;
  2550. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2551. } else {
  2552. continue;
  2553. }
  2554. } else {
  2555. attrB = nodeB.attributes[attrA.nodeName];
  2556. }
  2557. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2558. return false;
  2559. }
  2560. }
  2561. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2562. if (ie) {
  2563. for (i = 0; attrB = otherAttrs[i++];) {
  2564. if (attrB.specified) {
  2565. bl++;
  2566. }
  2567. }
  2568. if (al != bl) {
  2569. return false;
  2570. }
  2571. }
  2572. return true;
  2573. },
  2574. /**
  2575. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2576. * @method isSameStyle
  2577. * @param { Node } nodeA 需要比较的节点
  2578. * @param { Node } nodeB 需要比较的节点
  2579. * @return { Boolean } 两个节点是否具有相同的style属性值
  2580. * @example
  2581. * ```html
  2582. * <span style="font-size:12px">ssss</span>
  2583. * <span style="font-size:12px">bbbbb</span>
  2584. * <span style="font-size:13px">ssss</span>
  2585. * <span style="font-size:14px">bbbbb</span>
  2586. *
  2587. * <script>
  2588. *
  2589. * var nodes = document.getElementsByTagName( "span" );
  2590. *
  2591. * //output: true
  2592. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2593. *
  2594. * //output: false
  2595. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2596. *
  2597. * </script>
  2598. * ```
  2599. */
  2600. isSameStyle:function (nodeA, nodeB) {
  2601. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2602. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2603. if (browser.opera) {
  2604. styleA = nodeA.style;
  2605. styleB = nodeB.style;
  2606. if (styleA.length != styleB.length)
  2607. return false;
  2608. for (var p in styleA) {
  2609. if (/^(\d+|csstext)$/i.test(p)) {
  2610. continue;
  2611. }
  2612. if (styleA[p] != styleB[p]) {
  2613. return false;
  2614. }
  2615. }
  2616. return true;
  2617. }
  2618. if (!styleA || !styleB) {
  2619. return styleA == styleB;
  2620. }
  2621. styleA = styleA.split(';');
  2622. styleB = styleB.split(';');
  2623. if (styleA.length != styleB.length) {
  2624. return false;
  2625. }
  2626. for (var i = 0, ci; ci = styleA[i++];) {
  2627. if (utils.indexOf(styleB, ci) == -1) {
  2628. return false;
  2629. }
  2630. }
  2631. return true;
  2632. },
  2633. /**
  2634. * 检查节点node是否为block元素
  2635. * @method isBlockElm
  2636. * @param { Node } node 需要检测的节点对象
  2637. * @return { Boolean } 是否是block元素节点
  2638. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2639. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2640. * @example
  2641. * ```html
  2642. * <span id="test1" style="display: block"></span>
  2643. * <span id="test2"></span>
  2644. * <div id="test3" style="display: inline"></div>
  2645. *
  2646. * <script>
  2647. *
  2648. * //output: true
  2649. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2650. *
  2651. * //output: false
  2652. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2653. *
  2654. * //output: true
  2655. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2656. *
  2657. * </script>
  2658. * ```
  2659. */
  2660. isBlockElm:function (node) {
  2661. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2662. },
  2663. /**
  2664. * 检测node节点是否为body节点
  2665. * @method isBody
  2666. * @param { Element } node 需要检测的dom元素
  2667. * @return { Boolean } 给定的元素是否是body元素
  2668. * @example
  2669. * ```javascript
  2670. * //output: true
  2671. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2672. * ```
  2673. */
  2674. isBody:function (node) {
  2675. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2676. },
  2677. /**
  2678. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2679. * 拆分形成的两个节点之间是node节点
  2680. * @method breakParent
  2681. * @param { Node } node 作为分界的节点对象
  2682. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2683. * @return { Node } 给定的node分界节点
  2684. * @example
  2685. * ```javascript
  2686. *
  2687. * var node = document.createElement("span"),
  2688. * wrapNode = document.createElement( "div" ),
  2689. * parent = document.createElement("p");
  2690. *
  2691. * parent.appendChild( node );
  2692. * wrapNode.appendChild( parent );
  2693. *
  2694. * //拆分前
  2695. * //output: <p><span></span></p>
  2696. * console.log( wrapNode.innerHTML );
  2697. *
  2698. *
  2699. * UE.dom.domUtils.breakParent( node, parent );
  2700. * //拆分后
  2701. * //output: <p></p><span></span><p></p>
  2702. * console.log( wrapNode.innerHTML );
  2703. *
  2704. * ```
  2705. */
  2706. breakParent:function (node, parent) {
  2707. var tmpNode,
  2708. parentClone = node,
  2709. clone = node,
  2710. leftNodes,
  2711. rightNodes;
  2712. do {
  2713. parentClone = parentClone.parentNode;
  2714. if (leftNodes) {
  2715. tmpNode = parentClone.cloneNode(false);
  2716. tmpNode.appendChild(leftNodes);
  2717. leftNodes = tmpNode;
  2718. tmpNode = parentClone.cloneNode(false);
  2719. tmpNode.appendChild(rightNodes);
  2720. rightNodes = tmpNode;
  2721. } else {
  2722. leftNodes = parentClone.cloneNode(false);
  2723. rightNodes = leftNodes.cloneNode(false);
  2724. }
  2725. while (tmpNode = clone.previousSibling) {
  2726. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2727. }
  2728. while (tmpNode = clone.nextSibling) {
  2729. rightNodes.appendChild(tmpNode);
  2730. }
  2731. clone = parentClone;
  2732. } while (parent !== parentClone);
  2733. tmpNode = parent.parentNode;
  2734. tmpNode.insertBefore(leftNodes, parent);
  2735. tmpNode.insertBefore(rightNodes, parent);
  2736. tmpNode.insertBefore(node, rightNodes);
  2737. domUtils.remove(parent);
  2738. return node;
  2739. },
  2740. /**
  2741. * 检查节点node是否是空inline节点
  2742. * @method isEmptyInlineElement
  2743. * @param { Node } node 需要检测的节点对象
  2744. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2745. * @example
  2746. * ```html
  2747. * <b><i></i></b> => 1
  2748. * <b><i></i><u></u></b> => 1
  2749. * <b></b> => 1
  2750. * <b>xx<i></i></b> => 0
  2751. * ```
  2752. */
  2753. isEmptyInlineElement:function (node) {
  2754. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2755. return 0;
  2756. }
  2757. node = node.firstChild;
  2758. while (node) {
  2759. //如果是创建的bookmark就跳过
  2760. if (domUtils.isBookmarkNode(node)) {
  2761. return 0;
  2762. }
  2763. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2764. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2765. ) {
  2766. return 0;
  2767. }
  2768. node = node.nextSibling;
  2769. }
  2770. return 1;
  2771. },
  2772. /**
  2773. * 删除node节点下首尾两端的空白文本子节点
  2774. * @method trimWhiteTextNode
  2775. * @param { Element } node 需要执行删除操作的元素对象
  2776. * @example
  2777. * ```javascript
  2778. * var node = document.createElement("div");
  2779. *
  2780. * node.appendChild( document.createTextNode( "" ) );
  2781. *
  2782. * node.appendChild( document.createElement("div") );
  2783. *
  2784. * node.appendChild( document.createTextNode( "" ) );
  2785. *
  2786. * //3
  2787. * console.log( node.childNodes.length );
  2788. *
  2789. * UE.dom.domUtils.trimWhiteTextNode( node );
  2790. *
  2791. * //1
  2792. * console.log( node.childNodes.length );
  2793. * ```
  2794. */
  2795. trimWhiteTextNode:function (node) {
  2796. function remove(dir) {
  2797. var child;
  2798. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2799. node.removeChild(child);
  2800. }
  2801. }
  2802. remove('firstChild');
  2803. remove('lastChild');
  2804. },
  2805. /**
  2806. * 合并node节点下相同的子节点
  2807. * @name mergeChild
  2808. * @desc
  2809. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2810. * @example
  2811. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2812. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2813. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2814. */
  2815. mergeChild:function (node, tagName, attrs) {
  2816. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2817. for (var i = 0, ci; ci = list[i++];) {
  2818. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2819. continue;
  2820. }
  2821. //span单独处理
  2822. if (ci.tagName.toLowerCase() == 'span') {
  2823. if (node === ci.parentNode) {
  2824. domUtils.trimWhiteTextNode(node);
  2825. if (node.childNodes.length == 1) {
  2826. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2827. domUtils.remove(ci, true);
  2828. continue;
  2829. }
  2830. }
  2831. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2832. if (attrs) {
  2833. var style = attrs.style;
  2834. if (style) {
  2835. style = style.split(';');
  2836. for (var j = 0, s; s = style[j++];) {
  2837. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2838. }
  2839. }
  2840. }
  2841. if (domUtils.isSameStyle(ci, node)) {
  2842. domUtils.remove(ci, true);
  2843. }
  2844. continue;
  2845. }
  2846. if (domUtils.isSameElement(node, ci)) {
  2847. domUtils.remove(ci, true);
  2848. }
  2849. }
  2850. },
  2851. /**
  2852. * 原生方法getElementsByTagName的封装
  2853. * @method getElementsByTagName
  2854. * @param { Node } node 目标节点对象
  2855. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2856. * @return { Array } 符合条件的节点集合
  2857. */
  2858. getElementsByTagName:function (node, name,filter) {
  2859. if(filter && utils.isString(filter)){
  2860. var className = filter;
  2861. filter = function(node){return domUtils.hasClass(node,className)}
  2862. }
  2863. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2864. var arr = [];
  2865. for(var n = 0,ni;ni=name[n++];){
  2866. var list = node.getElementsByTagName(ni);
  2867. for (var i = 0, ci; ci = list[i++];) {
  2868. if(!filter || filter(ci))
  2869. arr.push(ci);
  2870. }
  2871. }
  2872. return arr;
  2873. },
  2874. /**
  2875. * 将节点node提取到父节点上
  2876. * @method mergeToParent
  2877. * @param { Element } node 需要提取的元素对象
  2878. * @example
  2879. * ```html
  2880. * <div id="parent">
  2881. * <div id="sub">
  2882. * <span id="child"></span>
  2883. * </div>
  2884. * </div>
  2885. *
  2886. * <script>
  2887. *
  2888. * var child = document.getElementById( "child" );
  2889. *
  2890. * //output: sub
  2891. * console.log( child.parentNode.id );
  2892. *
  2893. * UE.dom.domUtils.mergeToParent( child );
  2894. *
  2895. * //output: parent
  2896. * console.log( child.parentNode.id );
  2897. *
  2898. * </script>
  2899. * ```
  2900. */
  2901. mergeToParent:function (node) {
  2902. var parent = node.parentNode;
  2903. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2904. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2905. domUtils.trimWhiteTextNode(parent);
  2906. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2907. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2908. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2909. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2910. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2911. parent = parent.parentNode;
  2912. continue;
  2913. } else {
  2914. parent.style.cssText += ";" + node.style.cssText;
  2915. //trace:952 a标签要保持下划线
  2916. if (parent.tagName == 'A') {
  2917. parent.style.textDecoration = 'underline';
  2918. }
  2919. }
  2920. }
  2921. if (parent.tagName != 'A') {
  2922. parent === node.parentNode && domUtils.remove(node, true);
  2923. break;
  2924. }
  2925. }
  2926. parent = parent.parentNode;
  2927. }
  2928. },
  2929. /**
  2930. * 合并节点node的左右兄弟节点
  2931. * @method mergeSibling
  2932. * @param { Element } node 需要合并的目标节点
  2933. * @example
  2934. * ```html
  2935. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2936. *
  2937. * <script>
  2938. * var demoNode = document.getElementById("test");
  2939. * UE.dom.domUtils.mergeSibling( demoNode );
  2940. * //output: xxxxoooxxxx
  2941. * console.log( demoNode.innerHTML );
  2942. * </script>
  2943. * ```
  2944. */
  2945. /**
  2946. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2947. * @method mergeSibling
  2948. * @param { Element } node 需要合并的目标节点
  2949. * @param { Boolean } ignorePre 是否忽略合并左节点
  2950. * @example
  2951. * ```html
  2952. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2953. *
  2954. * <script>
  2955. * var demoNode = document.getElementById("test");
  2956. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2957. * //output: oooxxxx
  2958. * console.log( demoNode.innerHTML );
  2959. * </script>
  2960. * ```
  2961. */
  2962. /**
  2963. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2964. * @method mergeSibling
  2965. * @param { Element } node 需要合并的目标节点
  2966. * @param { Boolean } ignorePre 是否忽略合并左节点
  2967. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2968. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2969. * @example
  2970. * ```html
  2971. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2972. *
  2973. * <script>
  2974. * var demoNode = document.getElementById("test");
  2975. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2976. * //output: xxxxooo
  2977. * console.log( demoNode.innerHTML );
  2978. * </script>
  2979. * ```
  2980. */
  2981. mergeSibling:function (node, ignorePre, ignoreNext) {
  2982. function merge(rtl, start, node) {
  2983. var next;
  2984. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2985. while (next.firstChild) {
  2986. if (start == 'firstChild') {
  2987. node.insertBefore(next.lastChild, node.firstChild);
  2988. } else {
  2989. node.appendChild(next.firstChild);
  2990. }
  2991. }
  2992. domUtils.remove(next);
  2993. }
  2994. }
  2995. !ignorePre && merge('previousSibling', 'firstChild', node);
  2996. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2997. },
  2998. /**
  2999. * 设置节点node及其子节点不会被选中
  3000. * @method unSelectable
  3001. * @param { Element } node 需要执行操作的dom元素
  3002. * @remind 执行该操作后的节点, 将不能被鼠标选中
  3003. * @example
  3004. * ```javascript
  3005. * UE.dom.domUtils.unSelectable( document.body );
  3006. * ```
  3007. */
  3008. unSelectable:ie && browser.ie9below || browser.opera ? function (node) {
  3009. //for ie9
  3010. node.onselectstart = function () {
  3011. return false;
  3012. };
  3013. node.onclick = node.onkeyup = node.onkeydown = function () {
  3014. return false;
  3015. };
  3016. node.unselectable = 'on';
  3017. node.setAttribute("unselectable", "on");
  3018. for (var i = 0, ci; ci = node.all[i++];) {
  3019. switch (ci.tagName.toLowerCase()) {
  3020. case 'iframe' :
  3021. case 'textarea' :
  3022. case 'input' :
  3023. case 'select' :
  3024. break;
  3025. default :
  3026. ci.unselectable = 'on';
  3027. node.setAttribute("unselectable", "on");
  3028. }
  3029. }
  3030. } : function (node) {
  3031. node.style.MozUserSelect =
  3032. node.style.webkitUserSelect =
  3033. node.style.msUserSelect =
  3034. node.style.KhtmlUserSelect = 'none';
  3035. },
  3036. /**
  3037. * 删除节点node上的指定属性名称的属性
  3038. * @method removeAttributes
  3039. * @param { Node } node 需要删除属性的节点对象
  3040. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3041. * @example
  3042. * ```html
  3043. * <div id="wrap">
  3044. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3045. * </div>
  3046. *
  3047. * <script>
  3048. *
  3049. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3050. *
  3051. * //output: <span style="font-size:14px;">xxxxx</span>
  3052. * console.log( document.getElementById("wrap").innerHTML );
  3053. *
  3054. * </script>
  3055. * ```
  3056. */
  3057. /**
  3058. * 删除节点node上的指定属性名称的属性
  3059. * @method removeAttributes
  3060. * @param { Node } node 需要删除属性的节点对象
  3061. * @param { Array } attrNames 需要删除的属性名数组
  3062. * @example
  3063. * ```html
  3064. * <div id="wrap">
  3065. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3066. * </div>
  3067. *
  3068. * <script>
  3069. *
  3070. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3071. *
  3072. * //output: <span style="font-size:14px;">xxxxx</span>
  3073. * console.log( document.getElementById("wrap").innerHTML );
  3074. *
  3075. * </script>
  3076. * ```
  3077. */
  3078. removeAttributes:function (node, attrNames) {
  3079. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  3080. for (var i = 0, ci; ci = attrNames[i++];) {
  3081. ci = attrFix[ci] || ci;
  3082. switch (ci) {
  3083. case 'className':
  3084. node[ci] = '';
  3085. break;
  3086. case 'style':
  3087. node.style.cssText = '';
  3088. var val = node.getAttributeNode('style');
  3089. !browser.ie && val && node.removeAttributeNode(val);
  3090. }
  3091. node.removeAttribute(ci);
  3092. }
  3093. },
  3094. /**
  3095. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3096. * @method createElement
  3097. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3098. * @param { String } tagName 需要创建的元素的标签名
  3099. * @param { Object } attrs 新创建的元素的属性key-value集合
  3100. * @return { Element } 新创建的元素对象
  3101. * @example
  3102. * ```javascript
  3103. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3104. * id: 'test'
  3105. * } );
  3106. *
  3107. * //output: DIV
  3108. * console.log( ele.tagName );
  3109. *
  3110. * //output: test
  3111. * console.log( ele.id );
  3112. *
  3113. * ```
  3114. */
  3115. createElement:function (doc, tag, attrs) {
  3116. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3117. },
  3118. /**
  3119. * 为节点node添加属性attrs,attrs为属性键值对
  3120. * @method setAttributes
  3121. * @param { Element } node 需要设置属性的元素对象
  3122. * @param { Object } attrs 需要设置的属性名-值对
  3123. * @return { Element } 设置属性的元素对象
  3124. * @example
  3125. * ```html
  3126. * <span id="test"></span>
  3127. *
  3128. * <script>
  3129. *
  3130. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3131. * id: 'demo'
  3132. * } );
  3133. *
  3134. * //output: demo
  3135. * console.log( testNode.id );
  3136. *
  3137. * </script>
  3138. *
  3139. */
  3140. setAttributes:function (node, attrs) {
  3141. for (var attr in attrs) {
  3142. if(attrs.hasOwnProperty(attr)){
  3143. var value = attrs[attr];
  3144. switch (attr) {
  3145. case 'class':
  3146. //ie下要这样赋值,setAttribute不起作用
  3147. node.className = value;
  3148. break;
  3149. case 'style' :
  3150. node.style.cssText = node.style.cssText + ";" + value;
  3151. break;
  3152. case 'innerHTML':
  3153. node[attr] = value;
  3154. break;
  3155. case 'value':
  3156. node.value = value;
  3157. break;
  3158. default:
  3159. node.setAttribute(attrFix[attr] || attr, value);
  3160. }
  3161. }
  3162. }
  3163. return node;
  3164. },
  3165. /**
  3166. * 获取元素element经过计算后的样式值
  3167. * @method getComputedStyle
  3168. * @param { Element } element 需要获取样式的元素对象
  3169. * @param { String } styleName 需要获取的样式名
  3170. * @return { String } 获取到的样式值
  3171. * @example
  3172. * ```html
  3173. * <style type="text/css">
  3174. * #test {
  3175. * font-size: 15px;
  3176. * }
  3177. * </style>
  3178. *
  3179. * <span id="test"></span>
  3180. *
  3181. * <script>
  3182. * //output: 15px
  3183. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3184. * </script>
  3185. * ```
  3186. */
  3187. getComputedStyle:function (element, styleName) {
  3188. //一下的属性单独处理
  3189. var pros = 'width height top left';
  3190. if(pros.indexOf(styleName) > -1){
  3191. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3192. }
  3193. //忽略文本节点
  3194. if (element.nodeType == 3) {
  3195. element = element.parentNode;
  3196. }
  3197. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3198. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3199. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3200. var span = element.ownerDocument.createElement('span');
  3201. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3202. span.innerHTML = '.';
  3203. element.appendChild(span);
  3204. var result = span.offsetHeight;
  3205. element.removeChild(span);
  3206. span = null;
  3207. return result + 'px';
  3208. }
  3209. try {
  3210. var value = domUtils.getStyle(element, styleName) ||
  3211. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3212. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3213. } catch (e) {
  3214. return "";
  3215. }
  3216. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3217. },
  3218. /**
  3219. * 删除元素element指定的className
  3220. * @method removeClasses
  3221. * @param { Element } ele 需要删除class的元素节点
  3222. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3223. * @example
  3224. * ```html
  3225. * <span id="test" class="test1 test2 test3">xxx</span>
  3226. *
  3227. * <script>
  3228. *
  3229. * var testNode = document.getElementById( "test" );
  3230. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3231. *
  3232. * //output: test3
  3233. * console.log( testNode.className );
  3234. *
  3235. * </script>
  3236. * ```
  3237. */
  3238. /**
  3239. * 删除元素element指定的className
  3240. * @method removeClasses
  3241. * @param { Element } ele 需要删除class的元素节点
  3242. * @param { Array } classNames 需要删除的className数组
  3243. * @example
  3244. * ```html
  3245. * <span id="test" class="test1 test2 test3">xxx</span>
  3246. *
  3247. * <script>
  3248. *
  3249. * var testNode = document.getElementById( "test" );
  3250. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3251. *
  3252. * //output: test3
  3253. * console.log( testNode.className );
  3254. *
  3255. * </script>
  3256. * ```
  3257. */
  3258. removeClasses:function (elm, classNames) {
  3259. classNames = utils.isArray(classNames) ? classNames :
  3260. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3261. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3262. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3263. }
  3264. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3265. if(cls){
  3266. elm.className = cls;
  3267. }else{
  3268. domUtils.removeAttributes(elm,['class']);
  3269. }
  3270. },
  3271. /**
  3272. * 给元素element添加className
  3273. * @method addClass
  3274. * @param { Node } ele 需要增加className的元素
  3275. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3276. * @remind 相同的类名不会被重复添加
  3277. * @example
  3278. * ```html
  3279. * <span id="test" class="cls1 cls2"></span>
  3280. *
  3281. * <script>
  3282. * var testNode = document.getElementById("test");
  3283. *
  3284. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3285. *
  3286. * //output: cl1 cls2 cls3 cls4
  3287. * console.log( testNode.className );
  3288. *
  3289. * <script>
  3290. * ```
  3291. */
  3292. /**
  3293. * 给元素element添加className
  3294. * @method addClass
  3295. * @param { Node } ele 需要增加className的元素
  3296. * @param { Array } classNames 需要添加的className的数组
  3297. * @remind 相同的类名不会被重复添加
  3298. * @example
  3299. * ```html
  3300. * <span id="test" class="cls1 cls2"></span>
  3301. *
  3302. * <script>
  3303. * var testNode = document.getElementById("test");
  3304. *
  3305. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3306. *
  3307. * //output: cl1 cls2 cls3 cls4
  3308. * console.log( testNode.className );
  3309. *
  3310. * <script>
  3311. * ```
  3312. */
  3313. addClass:function (elm, classNames) {
  3314. if(!elm)return;
  3315. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3316. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3317. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3318. cls += ' ' + ci;
  3319. }
  3320. }
  3321. elm.className = utils.trim(cls);
  3322. },
  3323. /**
  3324. * 判断元素element是否包含给定的样式类名className
  3325. * @method hasClass
  3326. * @param { Node } ele 需要检测的元素
  3327. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3328. * @return { Boolean } 元素是否包含所有给定的className
  3329. * @example
  3330. * ```html
  3331. * <span id="test1" class="cls1 cls2"></span>
  3332. *
  3333. * <script>
  3334. * var test1 = document.getElementById("test1");
  3335. *
  3336. * //output: false
  3337. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3338. *
  3339. * //output: true
  3340. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3341. * </script>
  3342. * ```
  3343. */
  3344. /**
  3345. * 判断元素element是否包含给定的样式类名className
  3346. * @method hasClass
  3347. * @param { Node } ele 需要检测的元素
  3348. * @param { Array } classNames 需要检测的className数组
  3349. * @return { Boolean } 元素是否包含所有给定的className
  3350. * @example
  3351. * ```html
  3352. * <span id="test1" class="cls1 cls2"></span>
  3353. *
  3354. * <script>
  3355. * var test1 = document.getElementById("test1");
  3356. *
  3357. * //output: false
  3358. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3359. *
  3360. * //output: true
  3361. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3362. * </script>
  3363. * ```
  3364. */
  3365. hasClass:function (element, className) {
  3366. if(utils.isRegExp(className)){
  3367. return className.test(element.className)
  3368. }
  3369. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3370. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3371. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3372. return false;
  3373. }
  3374. }
  3375. return i - 1 == className.length;
  3376. },
  3377. /**
  3378. * 阻止事件默认行为
  3379. * @method preventDefault
  3380. * @param { Event } evt 需要阻止默认行为的事件对象
  3381. * @example
  3382. * ```javascript
  3383. * UE.dom.domUtils.preventDefault( evt );
  3384. * ```
  3385. */
  3386. preventDefault:function (evt) {
  3387. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3388. },
  3389. /**
  3390. * 删除元素element指定的样式
  3391. * @method removeStyle
  3392. * @param { Element } element 需要删除样式的元素
  3393. * @param { String } styleName 需要删除的样式名
  3394. * @example
  3395. * ```html
  3396. * <span id="test" style="color: red; background: blue;"></span>
  3397. *
  3398. * <script>
  3399. *
  3400. * var testNode = document.getElementById("test");
  3401. *
  3402. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3403. *
  3404. * //output: background: blue;
  3405. * console.log( testNode.style.cssText );
  3406. *
  3407. * </script>
  3408. * ```
  3409. */
  3410. removeStyle:function (element, name) {
  3411. if(browser.ie ){
  3412. //针对color先单独处理一下
  3413. if(name == 'color'){
  3414. name = '(^|;)' + name;
  3415. }
  3416. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3417. }else{
  3418. if (element.style.removeProperty) {
  3419. element.style.removeProperty (name);
  3420. }else {
  3421. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3422. }
  3423. }
  3424. if (!element.style.cssText) {
  3425. domUtils.removeAttributes(element, ['style']);
  3426. }
  3427. },
  3428. /**
  3429. * 获取元素element的style属性的指定值
  3430. * @method getStyle
  3431. * @param { Element } element 需要获取属性值的元素
  3432. * @param { String } styleName 需要获取的style的名称
  3433. * @warning 该方法仅获取元素style属性中所标明的值
  3434. * @return { String } 该元素包含指定的style属性值
  3435. * @example
  3436. * ```html
  3437. * <div id="test" style="color: red;"></div>
  3438. *
  3439. * <script>
  3440. *
  3441. * var testNode = document.getElementById( "test" );
  3442. *
  3443. * //output: red
  3444. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3445. *
  3446. * //output: ""
  3447. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3448. *
  3449. * </script>
  3450. * ```
  3451. */
  3452. getStyle:function (element, name) {
  3453. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3454. return utils.fixColor(name, value);
  3455. },
  3456. /**
  3457. * 为元素element设置样式属性值
  3458. * @method setStyle
  3459. * @param { Element } element 需要设置样式的元素
  3460. * @param { String } styleName 样式名
  3461. * @param { String } styleValue 样式值
  3462. * @example
  3463. * ```html
  3464. * <div id="test"></div>
  3465. *
  3466. * <script>
  3467. *
  3468. * var testNode = document.getElementById( "test" );
  3469. *
  3470. * //output: ""
  3471. * console.log( testNode.style.color );
  3472. *
  3473. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3474. * //output: "red"
  3475. * console.log( testNode.style.color );
  3476. *
  3477. * </script>
  3478. * ```
  3479. */
  3480. setStyle:function (element, name, value) {
  3481. element.style[utils.cssStyleToDomStyle(name)] = value;
  3482. if(!utils.trim(element.style.cssText)){
  3483. this.removeAttributes(element,'style')
  3484. }
  3485. },
  3486. /**
  3487. * 为元素element设置多个样式属性值
  3488. * @method setStyles
  3489. * @param { Element } element 需要设置样式的元素
  3490. * @param { Object } styles 样式名值对
  3491. * @example
  3492. * ```html
  3493. * <div id="test"></div>
  3494. *
  3495. * <script>
  3496. *
  3497. * var testNode = document.getElementById( "test" );
  3498. *
  3499. * //output: ""
  3500. * console.log( testNode.style.color );
  3501. *
  3502. * UE.dom.domUtils.setStyles( testNode, {
  3503. * 'color': 'red'
  3504. * } );
  3505. * //output: "red"
  3506. * console.log( testNode.style.color );
  3507. *
  3508. * </script>
  3509. * ```
  3510. */
  3511. setStyles:function (element, styles) {
  3512. for (var name in styles) {
  3513. if (styles.hasOwnProperty(name)) {
  3514. domUtils.setStyle(element, name, styles[name]);
  3515. }
  3516. }
  3517. },
  3518. /**
  3519. * 删除_moz_dirty属性
  3520. * @private
  3521. * @method removeDirtyAttr
  3522. */
  3523. removeDirtyAttr:function (node) {
  3524. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3525. ci.removeAttribute('_moz_dirty');
  3526. }
  3527. node.removeAttribute('_moz_dirty');
  3528. },
  3529. /**
  3530. * 获取子节点的数量
  3531. * @method getChildCount
  3532. * @param { Element } node 需要检测的元素
  3533. * @return { Number } 给定的node元素的子节点数量
  3534. * @example
  3535. * ```html
  3536. * <div id="test">
  3537. * <span></span>
  3538. * </div>
  3539. *
  3540. * <script>
  3541. *
  3542. * //output: 3
  3543. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3544. *
  3545. * </script>
  3546. * ```
  3547. */
  3548. /**
  3549. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3550. * @method getChildCount
  3551. * @param { Element } node 需要检测的元素
  3552. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3553. * @return { Number } 符合过滤条件的node元素的子节点数量
  3554. * @example
  3555. * ```html
  3556. * <div id="test">
  3557. * <span></span>
  3558. * </div>
  3559. *
  3560. * <script>
  3561. *
  3562. * //output: 1
  3563. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3564. *
  3565. * return node.nodeType === 1;
  3566. *
  3567. * } ) );
  3568. *
  3569. * </script>
  3570. * ```
  3571. */
  3572. getChildCount:function (node, fn) {
  3573. var count = 0, first = node.firstChild;
  3574. fn = fn || function () {
  3575. return 1;
  3576. };
  3577. while (first) {
  3578. if (fn(first)) {
  3579. count++;
  3580. }
  3581. first = first.nextSibling;
  3582. }
  3583. return count;
  3584. },
  3585. /**
  3586. * 判断给定节点是否为空节点
  3587. * @method isEmptyNode
  3588. * @param { Node } node 需要检测的节点对象
  3589. * @return { Boolean } 节点是否为空
  3590. * @example
  3591. * ```javascript
  3592. * UE.dom.domUtils.isEmptyNode( document.body );
  3593. * ```
  3594. */
  3595. isEmptyNode:function (node) {
  3596. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3597. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3598. }) == 0
  3599. },
  3600. clearSelectedArr:function (nodes) {
  3601. var node;
  3602. while (node = nodes.pop()) {
  3603. domUtils.removeAttributes(node, ['class']);
  3604. }
  3605. },
  3606. /**
  3607. * 将显示区域滚动到指定节点的位置
  3608. * @method scrollToView
  3609. * @param {Node} node 节点
  3610. * @param {window} win window对象
  3611. * @param {Number} offsetTop 距离上方的偏移量
  3612. */
  3613. scrollToView:function (node, win, offsetTop) {
  3614. var getViewPaneSize = function () {
  3615. var doc = win.document,
  3616. mode = doc.compatMode == 'CSS1Compat';
  3617. return {
  3618. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3619. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3620. };
  3621. },
  3622. getScrollPosition = function (win) {
  3623. if ('pageXOffset' in win) {
  3624. return {
  3625. x:win.pageXOffset || 0,
  3626. y:win.pageYOffset || 0
  3627. };
  3628. }
  3629. else {
  3630. var doc = win.document;
  3631. return {
  3632. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3633. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3634. };
  3635. }
  3636. };
  3637. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3638. offset += (node.offsetHeight || 0);
  3639. var elementPosition = domUtils.getXY(node);
  3640. offset += elementPosition.y;
  3641. var currentScroll = getScrollPosition(win).y;
  3642. // offset += 50;
  3643. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3644. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3645. }
  3646. },
  3647. /**
  3648. * 判断给定节点是否为br
  3649. * @method isBr
  3650. * @param { Node } node 需要判断的节点对象
  3651. * @return { Boolean } 给定的节点是否是br节点
  3652. */
  3653. isBr:function (node) {
  3654. return node.nodeType == 1 && node.tagName == 'BR';
  3655. },
  3656. /**
  3657. * 判断给定的节点是否是一个“填充”节点
  3658. * @private
  3659. * @method isFillChar
  3660. * @param { Node } node 需要判断的节点
  3661. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3662. * @returns { Boolean } 节点是否是填充节点
  3663. */
  3664. isFillChar:function (node,isInStart) {
  3665. if(node.nodeType != 3)
  3666. return false;
  3667. var text = node.nodeValue;
  3668. if(isInStart){
  3669. return new RegExp('^' + domUtils.fillChar).test(text)
  3670. }
  3671. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3672. },
  3673. isStartInblock:function (range) {
  3674. var tmpRange = range.cloneRange(),
  3675. flag = 0,
  3676. start = tmpRange.startContainer,
  3677. tmp;
  3678. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3679. start = start.childNodes[tmpRange.startOffset];
  3680. var pre = start.previousSibling;
  3681. while(pre && domUtils.isFillChar(pre)){
  3682. start = pre;
  3683. pre = pre.previousSibling;
  3684. }
  3685. }
  3686. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3687. tmpRange.setStartBefore(start);
  3688. start = tmpRange.startContainer;
  3689. }
  3690. while (start && domUtils.isFillChar(start)) {
  3691. tmp = start;
  3692. start = start.previousSibling
  3693. }
  3694. if (tmp) {
  3695. tmpRange.setStartBefore(tmp);
  3696. start = tmpRange.startContainer;
  3697. }
  3698. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3699. tmpRange.setStart(start, 0).collapse(true);
  3700. }
  3701. while (!tmpRange.startOffset) {
  3702. start = tmpRange.startContainer;
  3703. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3704. flag = 1;
  3705. break;
  3706. }
  3707. var pre = tmpRange.startContainer.previousSibling,
  3708. tmpNode;
  3709. if (!pre) {
  3710. tmpRange.setStartBefore(tmpRange.startContainer);
  3711. } else {
  3712. while (pre && domUtils.isFillChar(pre)) {
  3713. tmpNode = pre;
  3714. pre = pre.previousSibling;
  3715. }
  3716. if (tmpNode) {
  3717. tmpRange.setStartBefore(tmpNode);
  3718. } else {
  3719. tmpRange.setStartBefore(tmpRange.startContainer);
  3720. }
  3721. }
  3722. }
  3723. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3724. },
  3725. /**
  3726. * 判断给定的元素是否是一个空元素
  3727. * @method isEmptyBlock
  3728. * @param { Element } node 需要判断的元素
  3729. * @return { Boolean } 是否是空元素
  3730. * @example
  3731. * ```html
  3732. * <div id="test"></div>
  3733. *
  3734. * <script>
  3735. * //output: true
  3736. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3737. * </script>
  3738. * ```
  3739. */
  3740. /**
  3741. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3742. * @method isEmptyBlock
  3743. * @param { Element } node 需要判断的元素
  3744. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3745. * @return { Boolean } 是否是空元素
  3746. */
  3747. isEmptyBlock:function (node,reg) {
  3748. // HaoChuan9421
  3749. if(!node){
  3750. return;
  3751. }
  3752. if(node.nodeType != 1)
  3753. return 0;
  3754. reg = reg || new RegExp('[ \xa0\t\r\n' + domUtils.fillChar + ']', 'g');
  3755. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3756. return 0;
  3757. }
  3758. for (var n in dtd.$isNotEmpty) {
  3759. if (node.getElementsByTagName(n).length) {
  3760. return 0;
  3761. }
  3762. }
  3763. return 1;
  3764. },
  3765. /**
  3766. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3767. * @method setViewportOffset
  3768. * @param { Element } element 需要设置偏移量的元素
  3769. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3770. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3771. * offset.top的距离
  3772. * @example
  3773. * ```html
  3774. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3775. *
  3776. * <script>
  3777. *
  3778. * var testNode = document.getElementById("test");
  3779. *
  3780. * UE.dom.domUtils.setViewportOffset( testNode, {
  3781. * left: 200,
  3782. * top: 50
  3783. * } );
  3784. *
  3785. * //output: top: 300px; left: 100px; position: absolute;
  3786. * console.log( testNode.style.cssText );
  3787. *
  3788. * </script>
  3789. * ```
  3790. */
  3791. setViewportOffset:function (element, offset) {
  3792. var left = parseInt(element.style.left) | 0;
  3793. var top = parseInt(element.style.top) | 0;
  3794. var rect = element.getBoundingClientRect();
  3795. var offsetLeft = offset.left - rect.left;
  3796. var offsetTop = offset.top - rect.top;
  3797. if (offsetLeft) {
  3798. element.style.left = left + offsetLeft + 'px';
  3799. }
  3800. if (offsetTop) {
  3801. element.style.top = top + offsetTop + 'px';
  3802. }
  3803. },
  3804. /**
  3805. * 用“填充字符”填充节点
  3806. * @method fillNode
  3807. * @private
  3808. * @param { DomDocument } doc 填充的节点所在的docment对象
  3809. * @param { Node } node 需要填充的节点对象
  3810. * @example
  3811. * ```html
  3812. * <div id="test"></div>
  3813. *
  3814. * <script>
  3815. * var testNode = document.getElementById("test");
  3816. *
  3817. * //output: 0
  3818. * console.log( testNode.childNodes.length );
  3819. *
  3820. * UE.dom.domUtils.fillNode( document, testNode );
  3821. *
  3822. * //output: 1
  3823. * console.log( testNode.childNodes.length );
  3824. *
  3825. * </script>
  3826. * ```
  3827. */
  3828. fillNode:function (doc, node) {
  3829. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3830. node.innerHTML = '';
  3831. node.appendChild(tmpNode);
  3832. },
  3833. /**
  3834. * 把节点src的所有子节点追加到另一个节点tag上去
  3835. * @method moveChild
  3836. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3837. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3838. * @example
  3839. * ```html
  3840. * <div id="test1">
  3841. * <span></span>
  3842. * </div>
  3843. * <div id="test2">
  3844. * <div></div>
  3845. * </div>
  3846. *
  3847. * <script>
  3848. *
  3849. * var test1 = document.getElementById("test1"),
  3850. * test2 = document.getElementById("test2");
  3851. *
  3852. * UE.dom.domUtils.moveChild( test1, test2 );
  3853. *
  3854. * //output: ""(空字符串)
  3855. * console.log( test1.innerHTML );
  3856. *
  3857. * //output: "<div></div><span></span>"
  3858. * console.log( test2.innerHTML );
  3859. *
  3860. * </script>
  3861. * ```
  3862. */
  3863. /**
  3864. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3865. * @method moveChild
  3866. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3867. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3868. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3869. * @example
  3870. * ```html
  3871. * <div id="test1">
  3872. * <span></span>
  3873. * </div>
  3874. * <div id="test2">
  3875. * <div></div>
  3876. * </div>
  3877. *
  3878. * <script>
  3879. *
  3880. * var test1 = document.getElementById("test1"),
  3881. * test2 = document.getElementById("test2");
  3882. *
  3883. * UE.dom.domUtils.moveChild( test1, test2, true );
  3884. *
  3885. * //output: ""(空字符串)
  3886. * console.log( test1.innerHTML );
  3887. *
  3888. * //output: "<span></span><div></div>"
  3889. * console.log( test2.innerHTML );
  3890. *
  3891. * </script>
  3892. * ```
  3893. */
  3894. moveChild:function (src, tag, dir) {
  3895. while (src.firstChild) {
  3896. if (dir && tag.firstChild) {
  3897. tag.insertBefore(src.lastChild, tag.firstChild);
  3898. } else {
  3899. tag.appendChild(src.firstChild);
  3900. }
  3901. }
  3902. },
  3903. /**
  3904. * 判断节点的标签上是否不存在任何属性
  3905. * @method hasNoAttributes
  3906. * @private
  3907. * @param { Node } node 需要检测的节点对象
  3908. * @return { Boolean } 节点是否不包含任何属性
  3909. * @example
  3910. * ```html
  3911. * <div id="test"><span>xxxx</span></div>
  3912. *
  3913. * <script>
  3914. *
  3915. * //output: false
  3916. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3917. *
  3918. * //output: true
  3919. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3920. *
  3921. * </script>
  3922. * ```
  3923. */
  3924. hasNoAttributes:function (node) {
  3925. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3926. },
  3927. /**
  3928. * 检测节点是否是UEditor所使用的辅助节点
  3929. * @method isCustomeNode
  3930. * @private
  3931. * @param { Node } node 需要检测的节点
  3932. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3933. * @return { Boolean } 给定的节点是否是一个辅助节点
  3934. */
  3935. isCustomeNode:function (node) {
  3936. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3937. },
  3938. /**
  3939. * 检测节点的标签是否是给定的标签
  3940. * @method isTagNode
  3941. * @param { Node } node 需要检测的节点对象
  3942. * @param { String } tagName 标签
  3943. * @return { Boolean } 节点的标签是否是给定的标签
  3944. * @example
  3945. * ```html
  3946. * <div id="test"></div>
  3947. *
  3948. * <script>
  3949. *
  3950. * //output: true
  3951. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3952. *
  3953. * </script>
  3954. * ```
  3955. */
  3956. isTagNode:function (node, tagNames) {
  3957. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3958. },
  3959. /**
  3960. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3961. * @method filterNodeList
  3962. * @param { Array } nodeList 需要过滤的节点数组
  3963. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3964. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3965. * @example
  3966. * ```javascript
  3967. * var divNodes = document.getElementsByTagName("div");
  3968. * divNodes = [].slice.call( divNodes, 0 );
  3969. *
  3970. * //output: null
  3971. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3972. * return node.tagName.toLowerCase() !== 'div';
  3973. * } ) );
  3974. * ```
  3975. */
  3976. /**
  3977. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3978. * @method filterNodeList
  3979. * @param { Array } nodeList 需要过滤的节点数组
  3980. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3981. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3982. * @example
  3983. * ```javascript
  3984. * var divNodes = document.getElementsByTagName("div");
  3985. * divNodes = [].slice.call( divNodes, 0 );
  3986. *
  3987. * //output: null
  3988. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3989. * ```
  3990. */
  3991. /**
  3992. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3993. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3994. * @method filterNodeList
  3995. * @param { Array } nodeList 需要过滤的节点数组
  3996. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3997. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3998. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3999. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  4000. * @example
  4001. * ```javascript
  4002. * var divNodes = document.getElementsByTagName("div");
  4003. * divNodes = [].slice.call( divNodes, 0 );
  4004. *
  4005. * //output: 3(假定有3个div)
  4006. * console.log( divNodes.length );
  4007. *
  4008. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4009. * return node.tagName.toLowerCase() === 'div';
  4010. * }, true );
  4011. *
  4012. * //output: 3
  4013. * console.log( nodes.length );
  4014. *
  4015. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4016. * return node.tagName.toLowerCase() === 'div';
  4017. * }, false );
  4018. *
  4019. * //output: div
  4020. * console.log( node.nodeName );
  4021. * ```
  4022. */
  4023. filterNodeList : function(nodelist,filter,forAll){
  4024. var results = [];
  4025. if(!utils .isFunction(filter)){
  4026. var str = filter;
  4027. filter = function(n){
  4028. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  4029. };
  4030. }
  4031. utils.each(nodelist,function(n){
  4032. filter(n) && results.push(n)
  4033. });
  4034. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4035. },
  4036. /**
  4037. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4038. * @method isInNodeEndBoundary
  4039. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4040. * @param node 需要检测的节点对象
  4041. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4042. */
  4043. isInNodeEndBoundary : function (rng,node){
  4044. var start = rng.startContainer;
  4045. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  4046. return 0;
  4047. }
  4048. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  4049. return 0;
  4050. }
  4051. while(start !== node){
  4052. if(start.nextSibling){
  4053. return 0
  4054. };
  4055. start = start.parentNode;
  4056. }
  4057. return 1;
  4058. },
  4059. isBoundaryNode : function (node,dir){
  4060. var tmp;
  4061. while(!domUtils.isBody(node)){
  4062. tmp = node;
  4063. node = node.parentNode;
  4064. if(tmp !== node[dir]){
  4065. return false;
  4066. }
  4067. }
  4068. return true;
  4069. },
  4070. fillHtml : browser.ie11below ? '&nbsp;' : '<br/>'
  4071. };
  4072. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4073. // core/Range.js
  4074. /**
  4075. * Range封装
  4076. * @file
  4077. * @module UE.dom
  4078. * @class Range
  4079. * @since 1.2.6.1
  4080. */
  4081. /**
  4082. * dom操作封装
  4083. * @unfile
  4084. * @module UE.dom
  4085. */
  4086. /**
  4087. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4088. * @unfile
  4089. * @module UE.dom
  4090. * @class Range
  4091. */
  4092. (function () {
  4093. var guid = 0,
  4094. fillChar = domUtils.fillChar,
  4095. fillData;
  4096. /**
  4097. * 更新range的collapse状态
  4098. * @param {Range} range range对象
  4099. */
  4100. function updateCollapse(range) {
  4101. range.collapsed =
  4102. range.startContainer && range.endContainer &&
  4103. range.startContainer === range.endContainer &&
  4104. range.startOffset == range.endOffset;
  4105. }
  4106. function selectOneNode(rng){
  4107. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4108. }
  4109. function setEndPoint(toStart, node, offset, range) {
  4110. //如果node是自闭合标签要处理
  4111. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4112. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4113. node = node.parentNode;
  4114. }
  4115. if (toStart) {
  4116. range.startContainer = node;
  4117. range.startOffset = offset;
  4118. if (!range.endContainer) {
  4119. range.collapse(true);
  4120. }
  4121. } else {
  4122. range.endContainer = node;
  4123. range.endOffset = offset;
  4124. if (!range.startContainer) {
  4125. range.collapse(false);
  4126. }
  4127. }
  4128. updateCollapse(range);
  4129. return range;
  4130. }
  4131. function execContentsAction(range, action) {
  4132. //调整边界
  4133. //range.includeBookmark();
  4134. var start = range.startContainer,
  4135. end = range.endContainer,
  4136. startOffset = range.startOffset,
  4137. endOffset = range.endOffset,
  4138. doc = range.document,
  4139. frag = doc.createDocumentFragment(),
  4140. tmpStart, tmpEnd;
  4141. if (start.nodeType == 1) {
  4142. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4143. }
  4144. if (end.nodeType == 1) {
  4145. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4146. }
  4147. if (start === end && start.nodeType == 3) {
  4148. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4149. //is not clone
  4150. if (action) {
  4151. start.deleteData(startOffset, endOffset - startOffset);
  4152. range.collapse(true);
  4153. }
  4154. return frag;
  4155. }
  4156. var current, currentLevel, clone = frag,
  4157. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4158. for (var i = 0; startParents[i] == endParents[i];) {
  4159. i++;
  4160. }
  4161. for (var j = i, si; si = startParents[j]; j++) {
  4162. current = si.nextSibling;
  4163. if (si == start) {
  4164. if (!tmpStart) {
  4165. if (range.startContainer.nodeType == 3) {
  4166. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4167. //is not clone
  4168. if (action) {
  4169. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4170. }
  4171. } else {
  4172. clone.appendChild(!action ? start.cloneNode(true) : start);
  4173. }
  4174. }
  4175. } else {
  4176. currentLevel = si.cloneNode(false);
  4177. clone.appendChild(currentLevel);
  4178. }
  4179. while (current) {
  4180. if (current === end || current === endParents[j]) {
  4181. break;
  4182. }
  4183. si = current.nextSibling;
  4184. clone.appendChild(!action ? current.cloneNode(true) : current);
  4185. current = si;
  4186. }
  4187. clone = currentLevel;
  4188. }
  4189. clone = frag;
  4190. if (!startParents[i]) {
  4191. clone.appendChild(startParents[i - 1].cloneNode(false));
  4192. clone = clone.firstChild;
  4193. }
  4194. for (var j = i, ei; ei = endParents[j]; j++) {
  4195. current = ei.previousSibling;
  4196. if (ei == end) {
  4197. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4198. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4199. //is not clone
  4200. if (action) {
  4201. end.deleteData(0, endOffset);
  4202. }
  4203. }
  4204. } else {
  4205. currentLevel = ei.cloneNode(false);
  4206. clone.appendChild(currentLevel);
  4207. }
  4208. //如果两端同级,右边第一次已经被开始做了
  4209. if (j != i || !startParents[i]) {
  4210. while (current) {
  4211. if (current === start) {
  4212. break;
  4213. }
  4214. ei = current.previousSibling;
  4215. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4216. current = ei;
  4217. }
  4218. }
  4219. clone = currentLevel;
  4220. }
  4221. if (action) {
  4222. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4223. }
  4224. tmpStart && domUtils.remove(tmpStart);
  4225. tmpEnd && domUtils.remove(tmpEnd);
  4226. return frag;
  4227. }
  4228. /**
  4229. * 创建一个跟document绑定的空的Range实例
  4230. * @constructor
  4231. * @param { Document } document 新建的选区所属的文档对象
  4232. */
  4233. /**
  4234. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4235. */
  4236. /**
  4237. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4238. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4239. */
  4240. /**
  4241. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4242. */
  4243. /**
  4244. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4245. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4246. */
  4247. /**
  4248. * @property { Boolean } collapsed 当前Range是否闭合
  4249. * @default true
  4250. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4251. */
  4252. /**
  4253. * @property { Document } document 当前Range所属的Document对象
  4254. * @remind 不同range的的document属性可以是不同的
  4255. */
  4256. var Range = dom.Range = function (document) {
  4257. var me = this;
  4258. me.startContainer =
  4259. me.startOffset =
  4260. me.endContainer =
  4261. me.endOffset = null;
  4262. me.document = document;
  4263. me.collapsed = true;
  4264. };
  4265. /**
  4266. * 删除fillData
  4267. * @param doc
  4268. * @param excludeNode
  4269. */
  4270. function removeFillData(doc, excludeNode) {
  4271. try {
  4272. if (fillData && domUtils.inDoc(fillData, doc)) {
  4273. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4274. var tmpNode = fillData.parentNode;
  4275. domUtils.remove(fillData);
  4276. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4277. //safari的contains有bug
  4278. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4279. ) {
  4280. fillData = tmpNode.parentNode;
  4281. domUtils.remove(tmpNode);
  4282. tmpNode = fillData;
  4283. }
  4284. } else {
  4285. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4286. }
  4287. }
  4288. } catch (e) {
  4289. }
  4290. }
  4291. /**
  4292. * @param node
  4293. * @param dir
  4294. */
  4295. function mergeSibling(node, dir) {
  4296. var tmpNode;
  4297. node = node[dir];
  4298. while (node && domUtils.isFillChar(node)) {
  4299. tmpNode = node[dir];
  4300. domUtils.remove(node);
  4301. node = tmpNode;
  4302. }
  4303. }
  4304. Range.prototype = {
  4305. /**
  4306. * 克隆选区的内容到一个DocumentFragment里
  4307. * @method cloneContents
  4308. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4309. * @example
  4310. * ```html
  4311. * <body>
  4312. * <!-- 中括号表示选区 -->
  4313. * <b>x<i>x[x</i>xx]x</b>
  4314. *
  4315. * <script>
  4316. * //range是已选中的选区
  4317. * var fragment = range.cloneContents(),
  4318. * node = document.createElement("div");
  4319. *
  4320. * node.appendChild( fragment );
  4321. *
  4322. * //output: <i>x</i>xx
  4323. * console.log( node.innerHTML );
  4324. *
  4325. * </script>
  4326. * </body>
  4327. * ```
  4328. */
  4329. cloneContents:function () {
  4330. return this.collapsed ? null : execContentsAction(this, 0);
  4331. },
  4332. /**
  4333. * 删除当前选区范围中的所有内容
  4334. * @method deleteContents
  4335. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4336. * @return { UE.dom.Range } 当前操作的Range对象
  4337. * @example
  4338. * ```html
  4339. * <body>
  4340. * <!-- 中括号表示选区 -->
  4341. * <b>x<i>x[x</i>xx]x</b>
  4342. *
  4343. * <script>
  4344. * //range是已选中的选区
  4345. * range.deleteContents();
  4346. *
  4347. * //竖线表示闭合后的选区位置
  4348. * //output: <b>x<i>x</i>|x</b>
  4349. * console.log( document.body.innerHTML );
  4350. *
  4351. * //此时, range的各项属性为
  4352. * //output: B
  4353. * console.log( range.startContainer.tagName );
  4354. * //output: 2
  4355. * console.log( range.startOffset );
  4356. * //output: B
  4357. * console.log( range.endContainer.tagName );
  4358. * //output: 2
  4359. * console.log( range.endOffset );
  4360. * //output: true
  4361. * console.log( range.collapsed );
  4362. *
  4363. * </script>
  4364. * </body>
  4365. * ```
  4366. */
  4367. deleteContents:function () {
  4368. var txt;
  4369. if (!this.collapsed) {
  4370. execContentsAction(this, 1);
  4371. }
  4372. if (browser.webkit) {
  4373. txt = this.startContainer;
  4374. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4375. this.setStartBefore(txt).collapse(true);
  4376. domUtils.remove(txt);
  4377. }
  4378. }
  4379. return this;
  4380. },
  4381. /**
  4382. * 将当前选区的内容提取到一个DocumentFragment里
  4383. * @method extractContents
  4384. * @remind 执行该操作后, 选区将变成闭合状态
  4385. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4386. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4387. * @example
  4388. * ```html
  4389. * <body>
  4390. * <!-- 中括号表示选区 -->
  4391. * <b>x<i>x[x</i>xx]x</b>
  4392. *
  4393. * <script>
  4394. * //range是已选中的选区
  4395. * var fragment = range.extractContents(),
  4396. * node = document.createElement( "div" );
  4397. *
  4398. * node.appendChild( fragment );
  4399. *
  4400. * //竖线表示闭合后的选区位置
  4401. *
  4402. * //output: <b>x<i>x</i>|x</b>
  4403. * console.log( document.body.innerHTML );
  4404. * //output: <i>x</i>xx
  4405. * console.log( node.innerHTML );
  4406. *
  4407. * //此时, range的各项属性为
  4408. * //output: B
  4409. * console.log( range.startContainer.tagName );
  4410. * //output: 2
  4411. * console.log( range.startOffset );
  4412. * //output: B
  4413. * console.log( range.endContainer.tagName );
  4414. * //output: 2
  4415. * console.log( range.endOffset );
  4416. * //output: true
  4417. * console.log( range.collapsed );
  4418. *
  4419. * </script>
  4420. * </body>
  4421. */
  4422. extractContents:function () {
  4423. return this.collapsed ? null : execContentsAction(this, 2);
  4424. },
  4425. /**
  4426. * 设置Range的开始容器节点和偏移量
  4427. * @method setStart
  4428. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4429. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4430. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4431. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4432. * 中的索引
  4433. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4434. * @param { int } offset 选区的开始位置偏移量
  4435. * @return { UE.dom.Range } 当前range对象
  4436. * @example
  4437. * ```html
  4438. * <!-- 选区 -->
  4439. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4440. *
  4441. * <script>
  4442. *
  4443. * //执行操作
  4444. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4445. *
  4446. * //此时, 选区变成了
  4447. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4448. *
  4449. * </script>
  4450. * ```
  4451. * @example
  4452. * ```html
  4453. * <!-- 选区 -->
  4454. * <b>xxx<img>[xx]x</b>
  4455. *
  4456. * <script>
  4457. *
  4458. * //执行操作
  4459. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4460. *
  4461. * //此时, 选区变成了
  4462. * //<b>xxx[<img>xx]x</b>
  4463. *
  4464. * </script>
  4465. * ```
  4466. */
  4467. setStart:function (node, offset) {
  4468. return setEndPoint(true, node, offset, this);
  4469. },
  4470. /**
  4471. * 设置Range的结束容器和偏移量
  4472. * @method setEnd
  4473. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4474. * @param { int } offset 结束边界的偏移量
  4475. * @see UE.dom.Range:setStart(Node,int)
  4476. * @return { UE.dom.Range } 当前range对象
  4477. */
  4478. setEnd:function (node, offset) {
  4479. return setEndPoint(false, node, offset, this);
  4480. },
  4481. /**
  4482. * 将Range开始位置设置到node节点之后
  4483. * @method setStartAfter
  4484. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4485. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4486. * @return { UE.dom.Range } 当前range对象
  4487. * @example
  4488. * ```html
  4489. * <!-- 选区示例 -->
  4490. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4491. *
  4492. * <script>
  4493. *
  4494. * //执行操作
  4495. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4496. *
  4497. * //结果选区
  4498. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4499. *
  4500. * </script>
  4501. * ```
  4502. */
  4503. setStartAfter:function (node) {
  4504. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4505. },
  4506. /**
  4507. * 将Range开始位置设置到node节点之前
  4508. * @method setStartBefore
  4509. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4510. * @param { Node } node 新的选区开始位置在该节点之前
  4511. * @see UE.dom.Range:setStartAfter(Node)
  4512. * @return { UE.dom.Range } 当前range对象
  4513. */
  4514. setStartBefore:function (node) {
  4515. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4516. },
  4517. /**
  4518. * 将Range结束位置设置到node节点之后
  4519. * @method setEndAfter
  4520. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4521. * @param { Node } node 目标节点
  4522. * @see UE.dom.Range:setStartAfter(Node)
  4523. * @return { UE.dom.Range } 当前range对象
  4524. * @example
  4525. * ```html
  4526. * <!-- 选区示例 -->
  4527. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4528. *
  4529. * <script>
  4530. *
  4531. * //执行操作
  4532. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4533. *
  4534. * //结果选区
  4535. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4536. *
  4537. * </script>
  4538. * ```
  4539. */
  4540. setEndAfter:function (node) {
  4541. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4542. },
  4543. /**
  4544. * 将Range结束位置设置到node节点之前
  4545. * @method setEndBefore
  4546. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4547. * @param { Node } node 目标节点
  4548. * @see UE.dom.Range:setEndAfter(Node)
  4549. * @return { UE.dom.Range } 当前range对象
  4550. */
  4551. setEndBefore:function (node) {
  4552. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4553. },
  4554. /**
  4555. * 设置Range的开始位置到node节点内的第一个子节点之前
  4556. * @method setStartAtFirst
  4557. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4558. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4559. * @param { Node } node 目标节点
  4560. * @see UE.dom.Range:setStartBefore(Node)
  4561. * @return { UE.dom.Range } 当前range对象
  4562. * @example
  4563. * ```html
  4564. * <!-- 选区示例 -->
  4565. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4566. *
  4567. * <script>
  4568. *
  4569. * //执行操作
  4570. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4571. *
  4572. * //结果选区
  4573. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4574. *
  4575. * </script>
  4576. * ```
  4577. */
  4578. setStartAtFirst:function (node) {
  4579. return this.setStart(node, 0);
  4580. },
  4581. /**
  4582. * 设置Range的开始位置到node节点内的最后一个节点之后
  4583. * @method setStartAtLast
  4584. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4585. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4586. * @param { Node } node 目标节点
  4587. * @see UE.dom.Range:setStartAtFirst(Node)
  4588. * @return { UE.dom.Range } 当前range对象
  4589. */
  4590. setStartAtLast:function (node) {
  4591. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4592. },
  4593. /**
  4594. * 设置Range的结束位置到node节点内的第一个节点之前
  4595. * @method setEndAtFirst
  4596. * @param { Node } node 目标节点
  4597. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4598. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4599. * @see UE.dom.Range:setStartAtFirst(Node)
  4600. * @return { UE.dom.Range } 当前range对象
  4601. */
  4602. setEndAtFirst:function (node) {
  4603. return this.setEnd(node, 0);
  4604. },
  4605. /**
  4606. * 设置Range的结束位置到node节点内的最后一个节点之后
  4607. * @method setEndAtLast
  4608. * @param { Node } node 目标节点
  4609. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4610. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4611. * @see UE.dom.Range:setStartAtFirst(Node)
  4612. * @return { UE.dom.Range } 当前range对象
  4613. */
  4614. setEndAtLast:function (node) {
  4615. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4616. },
  4617. /**
  4618. * 选中给定节点
  4619. * @method selectNode
  4620. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4621. * 而endOffset为startOffset+1
  4622. * @param { Node } node 需要选中的节点
  4623. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4624. * @example
  4625. * ```html
  4626. * <!-- 选区示例 -->
  4627. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4628. *
  4629. * <script>
  4630. *
  4631. * //执行操作
  4632. * range.selectNode( document.getElementsByTagName("i")[0] );
  4633. *
  4634. * //结果选区
  4635. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4636. *
  4637. * </script>
  4638. * ```
  4639. */
  4640. selectNode:function (node) {
  4641. return this.setStartBefore(node).setEndAfter(node);
  4642. },
  4643. /**
  4644. * 选中给定节点内部的所有节点
  4645. * @method selectNodeContents
  4646. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4647. * 而endOffset是该节点的子节点数。
  4648. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4649. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4650. * @example
  4651. * ```html
  4652. * <!-- 选区示例 -->
  4653. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4654. *
  4655. * <script>
  4656. *
  4657. * //执行操作
  4658. * range.selectNode( document.getElementsByTagName("b")[0] );
  4659. *
  4660. * //结果选区
  4661. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4662. *
  4663. * </script>
  4664. * ```
  4665. */
  4666. selectNodeContents:function (node) {
  4667. return this.setStart(node, 0).setEndAtLast(node);
  4668. },
  4669. /**
  4670. * clone当前Range对象
  4671. * @method cloneRange
  4672. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4673. * @return { UE.dom.Range } 当前range对象的一个副本
  4674. */
  4675. cloneRange:function () {
  4676. var me = this;
  4677. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4678. },
  4679. /**
  4680. * 向当前选区的结束处闭合选区
  4681. * @method collapse
  4682. * @return { UE.dom.Range } 当前range对象
  4683. * @example
  4684. * ```html
  4685. * <!-- 选区示例 -->
  4686. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4687. *
  4688. * <script>
  4689. *
  4690. * //执行操作
  4691. * range.collapse();
  4692. *
  4693. * //结果选区
  4694. * //“|”表示选区已闭合
  4695. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4696. *
  4697. * </script>
  4698. * ```
  4699. */
  4700. /**
  4701. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4702. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4703. * @method collapse
  4704. * @param { Boolean } toStart 是否向选区开始处闭合
  4705. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4706. * @see UE.dom.Range:collapse()
  4707. * @example
  4708. * ```html
  4709. * <!-- 选区示例 -->
  4710. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4711. *
  4712. * <script>
  4713. *
  4714. * //执行操作
  4715. * range.collapse( true );
  4716. *
  4717. * //结果选区
  4718. * //“|”表示选区已闭合
  4719. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4720. *
  4721. * </script>
  4722. * ```
  4723. */
  4724. collapse:function (toStart) {
  4725. var me = this;
  4726. if (toStart) {
  4727. me.endContainer = me.startContainer;
  4728. me.endOffset = me.startOffset;
  4729. } else {
  4730. me.startContainer = me.endContainer;
  4731. me.startOffset = me.endOffset;
  4732. }
  4733. me.collapsed = true;
  4734. return me;
  4735. },
  4736. /**
  4737. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4738. * @method shrinkBoundary
  4739. * @return { UE.dom.Range } 当前range对象
  4740. * @example
  4741. * ```html
  4742. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4743. * ```
  4744. *
  4745. * @example
  4746. * ```html
  4747. * <!-- 选区示例 -->
  4748. * <b>x[xx</b><i>]xxx</i>
  4749. *
  4750. * <script>
  4751. *
  4752. * //执行收缩
  4753. * range.shrinkBoundary();
  4754. *
  4755. * //结果选区
  4756. * //<b>x[xx]</b><i>xxx</i>
  4757. * </script>
  4758. * ```
  4759. *
  4760. * @example
  4761. * ```html
  4762. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4763. * ```
  4764. */
  4765. /**
  4766. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4767. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4768. * @method shrinkBoundary
  4769. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4770. * @return { UE.dom.Range } 当前range对象
  4771. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4772. */
  4773. shrinkBoundary:function (ignoreEnd) {
  4774. var me = this, child,
  4775. collapsed = me.collapsed;
  4776. function check(node){
  4777. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4778. }
  4779. while (me.startContainer.nodeType == 1 //是element
  4780. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4781. && check(child)) {
  4782. me.setStart(child, 0);
  4783. }
  4784. if (collapsed) {
  4785. return me.collapse(true);
  4786. }
  4787. if (!ignoreEnd) {
  4788. while (me.endContainer.nodeType == 1//是element
  4789. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4790. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4791. && check(child)) {
  4792. me.setEnd(child, child.childNodes.length);
  4793. }
  4794. }
  4795. return me;
  4796. },
  4797. /**
  4798. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4799. * @method getCommonAncestor
  4800. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4801. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4802. * @example
  4803. * ```html
  4804. * //选区示例
  4805. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4806. * <script>
  4807. *
  4808. * var node = range.getCommonAncestor();
  4809. *
  4810. * //公共祖先节点是: b节点
  4811. * //输出: B
  4812. * console.log(node.tagName);
  4813. *
  4814. * </script>
  4815. * ```
  4816. */
  4817. /**
  4818. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4819. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4820. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4821. * @method getCommonAncestor
  4822. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4823. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4824. * @see UE.dom.Range:getCommonAncestor()
  4825. * @example
  4826. * ```html
  4827. * <body>
  4828. *
  4829. * <!-- 选区示例 -->
  4830. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4831. *
  4832. * <script>
  4833. *
  4834. * var node = range.getCommonAncestor( false );
  4835. *
  4836. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4837. * //output: B
  4838. * console.log( node.tagName );
  4839. *
  4840. * </script>
  4841. *
  4842. * </body>
  4843. * ```
  4844. */
  4845. /**
  4846. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4847. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4848. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4849. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4850. * @method getCommonAncestor
  4851. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4852. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4853. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4854. * @see UE.dom.Range:getCommonAncestor()
  4855. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4856. * @example
  4857. * ```html
  4858. * <body>
  4859. *
  4860. * <!-- 选区示例 -->
  4861. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4862. *
  4863. * <script>
  4864. *
  4865. * var node = range.getCommonAncestor( true, false );
  4866. *
  4867. * //output: SPAN
  4868. * console.log( node.tagName );
  4869. *
  4870. * </script>
  4871. *
  4872. * </body>
  4873. * ```
  4874. */
  4875. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4876. var me = this,
  4877. start = me.startContainer,
  4878. end = me.endContainer;
  4879. if (start === end) {
  4880. if (includeSelf && selectOneNode(this)) {
  4881. start = start.childNodes[me.startOffset];
  4882. if(start.nodeType == 1)
  4883. return start;
  4884. }
  4885. //只有在上来就相等的情况下才会出现是文本的情况
  4886. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4887. }
  4888. return domUtils.getCommonAncestor(start, end);
  4889. },
  4890. /**
  4891. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4892. * @method trimBoundary
  4893. * @remind 该操作有可能会引起文本节点被切开
  4894. * @return { UE.dom.Range } 当前range对象
  4895. * @example
  4896. * ```html
  4897. *
  4898. * //选区示例
  4899. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4900. *
  4901. * <script>
  4902. * //未调整前, 选区的开始容器和结束都是文本节点
  4903. * //执行调整
  4904. * range.trimBoundary();
  4905. *
  4906. * //调整之后, 容器节点变成了i节点
  4907. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4908. * </script>
  4909. * ```
  4910. */
  4911. /**
  4912. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4913. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4914. * @method trimBoundary
  4915. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4916. * @return { UE.dom.Range } 当前range对象
  4917. * @example
  4918. * ```html
  4919. *
  4920. * //选区示例
  4921. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4922. *
  4923. * <script>
  4924. * //未调整前, 选区的开始容器和结束都是文本节点
  4925. * //执行调整
  4926. * range.trimBoundary( true );
  4927. *
  4928. * //调整之后, 开始容器节点变成了i节点
  4929. * //但是, 结束容器没有发生变化
  4930. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4931. * </script>
  4932. * ```
  4933. */
  4934. trimBoundary:function (ignoreEnd) {
  4935. this.txtToElmBoundary();
  4936. var start = this.startContainer,
  4937. offset = this.startOffset,
  4938. collapsed = this.collapsed,
  4939. end = this.endContainer;
  4940. if (start.nodeType == 3) {
  4941. if (offset == 0) {
  4942. this.setStartBefore(start);
  4943. } else {
  4944. if (offset >= start.nodeValue.length) {
  4945. this.setStartAfter(start);
  4946. } else {
  4947. var textNode = domUtils.split(start, offset);
  4948. //跟新结束边界
  4949. if (start === end) {
  4950. this.setEnd(textNode, this.endOffset - offset);
  4951. } else if (start.parentNode === end) {
  4952. this.endOffset += 1;
  4953. }
  4954. this.setStartBefore(textNode);
  4955. }
  4956. }
  4957. if (collapsed) {
  4958. return this.collapse(true);
  4959. }
  4960. }
  4961. if (!ignoreEnd) {
  4962. offset = this.endOffset;
  4963. end = this.endContainer;
  4964. if (end.nodeType == 3) {
  4965. if (offset == 0) {
  4966. this.setEndBefore(end);
  4967. } else {
  4968. offset < end.nodeValue.length && domUtils.split(end, offset);
  4969. this.setEndAfter(end);
  4970. }
  4971. }
  4972. }
  4973. return this;
  4974. },
  4975. /**
  4976. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4977. * @method txtToElmBoundary
  4978. * @remind 该操作不会修改dom节点
  4979. * @return { UE.dom.Range } 当前range对象
  4980. */
  4981. /**
  4982. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4983. * ignoreCollapsed 的值决定是否执行该调整
  4984. * @method txtToElmBoundary
  4985. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4986. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4987. * @return { UE.dom.Range } 当前range对象
  4988. */
  4989. txtToElmBoundary:function (ignoreCollapsed) {
  4990. function adjust(r, c) {
  4991. var container = r[c + 'Container'],
  4992. offset = r[c + 'Offset'];
  4993. if (container.nodeType == 3) {
  4994. if (!offset) {
  4995. r['set' + c.replace(/(\w)/, function (a) {
  4996. return a.toUpperCase();
  4997. }) + 'Before'](container);
  4998. } else if (offset >= container.nodeValue.length) {
  4999. r['set' + c.replace(/(\w)/, function (a) {
  5000. return a.toUpperCase();
  5001. }) + 'After' ](container);
  5002. }
  5003. }
  5004. }
  5005. if (ignoreCollapsed || !this.collapsed) {
  5006. adjust(this, 'start');
  5007. adjust(this, 'end');
  5008. }
  5009. return this;
  5010. },
  5011. /**
  5012. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  5013. * @method insertNode
  5014. * @param { Node } node 需要插入的节点
  5015. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  5016. * @return { UE.dom.Range } 当前range对象
  5017. */
  5018. insertNode:function (node) {
  5019. var first = node, length = 1;
  5020. if (node.nodeType == 11) {
  5021. first = node.firstChild;
  5022. length = node.childNodes.length;
  5023. }
  5024. this.trimBoundary(true);
  5025. var start = this.startContainer,
  5026. offset = this.startOffset;
  5027. var nextNode = start.childNodes[ offset ];
  5028. if (nextNode) {
  5029. start.insertBefore(node, nextNode);
  5030. } else {
  5031. start.appendChild(node);
  5032. }
  5033. if (first.parentNode === this.endContainer) {
  5034. this.endOffset = this.endOffset + length;
  5035. }
  5036. return this.setStartBefore(first);
  5037. },
  5038. /**
  5039. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5040. * @method setCursor
  5041. * @return { UE.dom.Range } 当前range对象
  5042. * @see UE.dom.Range:collapse()
  5043. */
  5044. /**
  5045. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5046. * @method setCursor
  5047. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5048. * 反之,则向开始容器方向闭合
  5049. * @return { UE.dom.Range } 当前range对象
  5050. * @see UE.dom.Range:collapse(Boolean)
  5051. */
  5052. setCursor:function (toEnd, noFillData) {
  5053. return this.collapse(!toEnd).select(noFillData);
  5054. },
  5055. /**
  5056. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5057. * @method createBookmark
  5058. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5059. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5060. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5061. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5062. * 返回的记录的类型为ID, 反之则为引用
  5063. */
  5064. createBookmark:function (serialize, same) {
  5065. var endNode,
  5066. startNode = this.document.createElement('span');
  5067. startNode.style.cssText = 'display:none;line-height:0px;';
  5068. startNode.appendChild(this.document.createTextNode('\u200D'));
  5069. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5070. if (!this.collapsed) {
  5071. endNode = startNode.cloneNode(true);
  5072. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5073. }
  5074. this.insertNode(startNode);
  5075. if (endNode) {
  5076. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5077. }
  5078. this.setStartAfter(startNode);
  5079. return {
  5080. start:serialize ? startNode.id : startNode,
  5081. end:endNode ? serialize ? endNode.id : endNode : null,
  5082. id:serialize
  5083. }
  5084. },
  5085. /**
  5086. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5087. * @method moveToBookmark
  5088. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5089. * @return { UE.dom.Range } 当前range对象
  5090. * @see UE.dom.Range:createBookmark(Boolean)
  5091. */
  5092. moveToBookmark:function (bookmark) {
  5093. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5094. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5095. this.setStartBefore(start);
  5096. domUtils.remove(start);
  5097. if (end) {
  5098. this.setEndBefore(end);
  5099. domUtils.remove(end);
  5100. } else {
  5101. this.collapse(true);
  5102. }
  5103. return this;
  5104. },
  5105. /**
  5106. * 调整range的边界,使其"放大"到最近的父节点
  5107. * @method enlarge
  5108. * @remind 会引起选区的变化
  5109. * @return { UE.dom.Range } 当前range对象
  5110. */
  5111. /**
  5112. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5113. * 要求扩大之后的父节点是block节点
  5114. * @method enlarge
  5115. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5116. * @return { UE.dom.Range } 当前range对象
  5117. */
  5118. enlarge:function (toBlock, stopFn) {
  5119. var isBody = domUtils.isBody,
  5120. pre, node, tmp = this.document.createTextNode('');
  5121. if (toBlock) {
  5122. node = this.startContainer;
  5123. if (node.nodeType == 1) {
  5124. if (node.childNodes[this.startOffset]) {
  5125. pre = node = node.childNodes[this.startOffset]
  5126. } else {
  5127. node.appendChild(tmp);
  5128. pre = node = tmp;
  5129. }
  5130. } else {
  5131. pre = node;
  5132. }
  5133. while (1) {
  5134. if (domUtils.isBlockElm(node)) {
  5135. node = pre;
  5136. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5137. node = pre;
  5138. }
  5139. this.setStartBefore(node);
  5140. break;
  5141. }
  5142. pre = node;
  5143. node = node.parentNode;
  5144. }
  5145. node = this.endContainer;
  5146. if (node.nodeType == 1) {
  5147. if (pre = node.childNodes[this.endOffset]) {
  5148. node.insertBefore(tmp, pre);
  5149. } else {
  5150. node.appendChild(tmp);
  5151. }
  5152. pre = node = tmp;
  5153. } else {
  5154. pre = node;
  5155. }
  5156. while (1) {
  5157. if (domUtils.isBlockElm(node)) {
  5158. node = pre;
  5159. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5160. node = pre;
  5161. }
  5162. this.setEndAfter(node);
  5163. break;
  5164. }
  5165. pre = node;
  5166. node = node.parentNode;
  5167. }
  5168. if (tmp.parentNode === this.endContainer) {
  5169. this.endOffset--;
  5170. }
  5171. domUtils.remove(tmp);
  5172. }
  5173. // 扩展边界到最大
  5174. if (!this.collapsed) {
  5175. while (this.startOffset == 0) {
  5176. if (stopFn && stopFn(this.startContainer)) {
  5177. break;
  5178. }
  5179. if (isBody(this.startContainer)) {
  5180. break;
  5181. }
  5182. this.setStartBefore(this.startContainer);
  5183. }
  5184. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5185. if (stopFn && stopFn(this.endContainer)) {
  5186. break;
  5187. }
  5188. if (isBody(this.endContainer)) {
  5189. break;
  5190. }
  5191. this.setEndAfter(this.endContainer);
  5192. }
  5193. }
  5194. return this;
  5195. },
  5196. enlargeToBlockElm:function(ignoreEnd){
  5197. while(!domUtils.isBlockElm(this.startContainer)){
  5198. this.setStartBefore(this.startContainer);
  5199. }
  5200. if(!ignoreEnd){
  5201. while(!domUtils.isBlockElm(this.endContainer)){
  5202. this.setEndAfter(this.endContainer);
  5203. }
  5204. }
  5205. return this;
  5206. },
  5207. /**
  5208. * 调整Range的边界,使其"缩小"到最合适的位置
  5209. * @method adjustmentBoundary
  5210. * @return { UE.dom.Range } 当前range对象
  5211. * @see UE.dom.Range:shrinkBoundary()
  5212. */
  5213. adjustmentBoundary:function () {
  5214. if (!this.collapsed) {
  5215. while (!domUtils.isBody(this.startContainer) &&
  5216. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5217. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5218. ) {
  5219. this.setStartAfter(this.startContainer);
  5220. }
  5221. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5222. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5223. ) {
  5224. this.setEndBefore(this.endContainer);
  5225. }
  5226. }
  5227. return this;
  5228. },
  5229. /**
  5230. * 给range选区中的内容添加给定的inline标签
  5231. * @method applyInlineStyle
  5232. * @param { String } tagName 需要添加的标签名
  5233. * @example
  5234. * ```html
  5235. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5236. * ```
  5237. */
  5238. /**
  5239. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5240. * @method applyInlineStyle
  5241. * @param { String } tagName 需要添加的标签名
  5242. * @param { Object } attrs 跟随新添加的标签的属性
  5243. * @return { UE.dom.Range } 当前选区
  5244. * @example
  5245. * ```html
  5246. * <p>xxxx[xxxx]x</p>
  5247. *
  5248. * ==>
  5249. *
  5250. * <!-- 执行操作 -->
  5251. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5252. *
  5253. * ==>
  5254. *
  5255. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5256. * ```
  5257. */
  5258. applyInlineStyle:function (tagName, attrs, list) {
  5259. if (this.collapsed)return this;
  5260. this.trimBoundary().enlarge(false,
  5261. function (node) {
  5262. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5263. }).adjustmentBoundary();
  5264. var bookmark = this.createBookmark(),
  5265. end = bookmark.end,
  5266. filterFn = function (node) {
  5267. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5268. },
  5269. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5270. node,
  5271. pre,
  5272. range = this.cloneRange();
  5273. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5274. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5275. range.setStartBefore(current);
  5276. node = current;
  5277. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5278. pre = node;
  5279. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5280. return dtd[tagName][parent.tagName];
  5281. });
  5282. }
  5283. var frag = range.setEndAfter(pre).extractContents(), elm;
  5284. if (list && list.length > 0) {
  5285. var level, top;
  5286. top = level = list[0].cloneNode(false);
  5287. for (var i = 1, ci; ci = list[i++];) {
  5288. level.appendChild(ci.cloneNode(false));
  5289. level = level.firstChild;
  5290. }
  5291. elm = level;
  5292. } else {
  5293. elm = range.document.createElement(tagName);
  5294. }
  5295. if (attrs) {
  5296. domUtils.setAttributes(elm, attrs);
  5297. }
  5298. elm.appendChild(frag);
  5299. range.insertNode(list ? top : elm);
  5300. //处理下滑线在a上的情况
  5301. var aNode;
  5302. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5303. domUtils.setAttributes(aNode, attrs);
  5304. domUtils.remove(elm, true);
  5305. elm = aNode;
  5306. } else {
  5307. domUtils.mergeSibling(elm);
  5308. domUtils.clearEmptySibling(elm);
  5309. }
  5310. //去除子节点相同的
  5311. domUtils.mergeChild(elm, attrs);
  5312. current = domUtils.getNextDomNode(elm, false, filterFn);
  5313. domUtils.mergeToParent(elm);
  5314. if (node === end) {
  5315. break;
  5316. }
  5317. } else {
  5318. current = domUtils.getNextDomNode(current, true, filterFn);
  5319. }
  5320. }
  5321. return this.moveToBookmark(bookmark);
  5322. },
  5323. /**
  5324. * 移除当前选区内指定的inline标签,但保留其中的内容
  5325. * @method removeInlineStyle
  5326. * @param { String } tagName 需要移除的标签名
  5327. * @return { UE.dom.Range } 当前的range对象
  5328. * @example
  5329. * ```html
  5330. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5331. * ```
  5332. */
  5333. /**
  5334. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5335. * @method removeInlineStyle
  5336. * @param { Array } tagNameArr 需要移除的标签名的数组
  5337. * @return { UE.dom.Range } 当前的range对象
  5338. * @see UE.dom.Range:removeInlineStyle(String)
  5339. */
  5340. removeInlineStyle:function (tagNames) {
  5341. if (this.collapsed)return this;
  5342. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5343. this.shrinkBoundary().adjustmentBoundary();
  5344. var start = this.startContainer, end = this.endContainer;
  5345. while (1) {
  5346. if (start.nodeType == 1) {
  5347. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5348. break;
  5349. }
  5350. if (start.tagName.toLowerCase() == 'body') {
  5351. start = null;
  5352. break;
  5353. }
  5354. }
  5355. start = start.parentNode;
  5356. }
  5357. while (1) {
  5358. if (end.nodeType == 1) {
  5359. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5360. break;
  5361. }
  5362. if (end.tagName.toLowerCase() == 'body') {
  5363. end = null;
  5364. break;
  5365. }
  5366. }
  5367. end = end.parentNode;
  5368. }
  5369. var bookmark = this.createBookmark(),
  5370. frag,
  5371. tmpRange;
  5372. if (start) {
  5373. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5374. frag = tmpRange.extractContents();
  5375. tmpRange.insertNode(frag);
  5376. domUtils.clearEmptySibling(start, true);
  5377. start.parentNode.insertBefore(bookmark.start, start);
  5378. }
  5379. if (end) {
  5380. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5381. frag = tmpRange.extractContents();
  5382. tmpRange.insertNode(frag);
  5383. domUtils.clearEmptySibling(end, false, true);
  5384. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5385. }
  5386. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5387. return node.nodeType == 1;
  5388. }), next;
  5389. while (current && current !== bookmark.end) {
  5390. next = domUtils.getNextDomNode(current, true, function (node) {
  5391. return node.nodeType == 1;
  5392. });
  5393. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5394. domUtils.remove(current, true);
  5395. }
  5396. current = next;
  5397. }
  5398. return this.moveToBookmark(bookmark);
  5399. },
  5400. /**
  5401. * 获取当前选中的自闭合的节点
  5402. * @method getClosedNode
  5403. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5404. */
  5405. getClosedNode:function () {
  5406. var node;
  5407. if (!this.collapsed) {
  5408. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5409. if (selectOneNode(range)) {
  5410. var child = range.startContainer.childNodes[range.startOffset];
  5411. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5412. node = child;
  5413. }
  5414. }
  5415. }
  5416. return node;
  5417. },
  5418. /**
  5419. * 在页面上高亮range所表示的选区
  5420. * @method select
  5421. * @return { UE.dom.Range } 返回当前Range对象
  5422. */
  5423. //这里不区分ie9以上,trace:3824
  5424. select:browser.ie ? function (noFillData, textRange) {
  5425. var nativeRange;
  5426. if (!this.collapsed)
  5427. this.shrinkBoundary();
  5428. var node = this.getClosedNode();
  5429. if (node && !textRange) {
  5430. try {
  5431. nativeRange = this.document.body.createControlRange();
  5432. nativeRange.addElement(node);
  5433. nativeRange.select();
  5434. } catch (e) {}
  5435. return this;
  5436. }
  5437. var bookmark = this.createBookmark(),
  5438. start = bookmark.start,
  5439. end;
  5440. nativeRange = this.document.body.createTextRange();
  5441. nativeRange.moveToElementText(start);
  5442. nativeRange.moveStart('character', 1);
  5443. if (!this.collapsed) {
  5444. var nativeRangeEnd = this.document.body.createTextRange();
  5445. end = bookmark.end;
  5446. nativeRangeEnd.moveToElementText(end);
  5447. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5448. } else {
  5449. if (!noFillData && this.startContainer.nodeType != 3) {
  5450. //使用<span>|x<span>固定住光标
  5451. var tmpText = this.document.createTextNode(fillChar),
  5452. tmp = this.document.createElement('span');
  5453. tmp.appendChild(this.document.createTextNode(fillChar));
  5454. start.parentNode.insertBefore(tmp, start);
  5455. start.parentNode.insertBefore(tmpText, start);
  5456. //当点b,i,u时,不能清除i上边的b
  5457. removeFillData(this.document, tmpText);
  5458. fillData = tmpText;
  5459. mergeSibling(tmp, 'previousSibling');
  5460. mergeSibling(start, 'nextSibling');
  5461. nativeRange.moveStart('character', -1);
  5462. nativeRange.collapse(true);
  5463. }
  5464. }
  5465. this.moveToBookmark(bookmark);
  5466. tmp && domUtils.remove(tmp);
  5467. //IE在隐藏状态下不支持range操作,catch一下
  5468. try {
  5469. nativeRange.select();
  5470. } catch (e) {
  5471. }
  5472. return this;
  5473. } : function (notInsertFillData) {
  5474. function checkOffset(rng){
  5475. function check(node,offset,dir){
  5476. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5477. rng[dir + 'Offset'] = node.nodeValue.length
  5478. }
  5479. }
  5480. check(rng.startContainer,rng.startOffset,'start');
  5481. check(rng.endContainer,rng.endOffset,'end');
  5482. }
  5483. var win = domUtils.getWindow(this.document),
  5484. sel = win.getSelection(),
  5485. txtNode;
  5486. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5487. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5488. browser.gecko ? this.document.body.focus() : win.focus();
  5489. if (sel) {
  5490. sel.removeAllRanges();
  5491. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5492. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5493. if (this.collapsed && !notInsertFillData) {
  5494. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5495. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5496. // var tmp = this.document.createTextNode('');
  5497. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5498. // }
  5499. //
  5500. //处理光标落在文本节点的情况
  5501. //处理以下的情况
  5502. //<b>|xxxx</b>
  5503. //<b>xxxx</b>|xxxx
  5504. //xxxx<b>|</b>
  5505. var start = this.startContainer,child = start;
  5506. if(start.nodeType == 1){
  5507. child = start.childNodes[this.startOffset];
  5508. }
  5509. if( !(start.nodeType == 3 && this.startOffset) &&
  5510. (child ?
  5511. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5512. :
  5513. (!start.lastChild || start.lastChild.nodeType != 3)
  5514. )
  5515. ){
  5516. txtNode = this.document.createTextNode(fillChar);
  5517. //跟着前边走
  5518. this.insertNode(txtNode);
  5519. removeFillData(this.document, txtNode);
  5520. mergeSibling(txtNode, 'previousSibling');
  5521. mergeSibling(txtNode, 'nextSibling');
  5522. fillData = txtNode;
  5523. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5524. }
  5525. }
  5526. var nativeRange = this.document.createRange();
  5527. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5528. var child = this.startContainer.childNodes[this.startOffset];
  5529. if(!child){
  5530. //往前靠拢
  5531. child = this.startContainer.lastChild;
  5532. if( child && domUtils.isBr(child)){
  5533. this.setStartBefore(child).collapse(true);
  5534. }
  5535. }else{
  5536. //向后靠拢
  5537. while(child && domUtils.isBlockElm(child)){
  5538. if(child.nodeType == 1 && child.childNodes[0]){
  5539. child = child.childNodes[0]
  5540. }else{
  5541. break;
  5542. }
  5543. }
  5544. child && this.setStartBefore(child).collapse(true)
  5545. }
  5546. }
  5547. //是createAddress最后一位算的不准,现在这里进行微调
  5548. checkOffset(this);
  5549. nativeRange.setStart(this.startContainer, this.startOffset);
  5550. nativeRange.setEnd(this.endContainer, this.endOffset);
  5551. sel.addRange(nativeRange);
  5552. }
  5553. return this;
  5554. },
  5555. /**
  5556. * 滚动到当前range开始的位置
  5557. * @method scrollToView
  5558. * @param { Window } win 当前range对象所属的window对象
  5559. * @return { UE.dom.Range } 当前Range对象
  5560. */
  5561. /**
  5562. * 滚动到距离当前range开始位置 offset 的位置处
  5563. * @method scrollToView
  5564. * @param { Window } win 当前range对象所属的window对象
  5565. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5566. * @return { UE.dom.Range } 当前Range对象
  5567. */
  5568. scrollToView:function (win, offset) {
  5569. win = win ? window : domUtils.getWindow(this.document);
  5570. var me = this,
  5571. span = me.document.createElement('span');
  5572. //trace:717
  5573. span.innerHTML = '&nbsp;';
  5574. me.cloneRange().insertNode(span);
  5575. domUtils.scrollToView(span, win, offset);
  5576. domUtils.remove(span);
  5577. return me;
  5578. },
  5579. /**
  5580. * 判断当前选区内容是否占位符
  5581. * @private
  5582. * @method inFillChar
  5583. * @return { Boolean } 如果是占位符返回true,否则返回false
  5584. */
  5585. inFillChar : function(){
  5586. var start = this.startContainer;
  5587. if(this.collapsed && start.nodeType == 3
  5588. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5589. ){
  5590. return true;
  5591. }
  5592. return false;
  5593. },
  5594. /**
  5595. * 保存
  5596. * @method createAddress
  5597. * @private
  5598. * @return { Boolean } 返回开始和结束的位置
  5599. * @example
  5600. * ```html
  5601. * <body>
  5602. * <p>
  5603. * aaaa
  5604. * <em>
  5605. * <!-- 选区开始 -->
  5606. * bbbb
  5607. * <!-- 选区结束 -->
  5608. * </em>
  5609. * </p>
  5610. *
  5611. * <script>
  5612. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5613. * console.log( range.createAddress() );
  5614. * </script>
  5615. * </body>
  5616. * ```
  5617. */
  5618. createAddress : function(ignoreEnd,ignoreTxt){
  5619. var addr = {},me = this;
  5620. function getAddress(isStart){
  5621. var node = isStart ? me.startContainer : me.endContainer;
  5622. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5623. addrs = [];
  5624. for(var i = 0,ci;ci = parents[i++];){
  5625. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5626. }
  5627. var firstIndex = 0;
  5628. if(ignoreTxt){
  5629. if(node.nodeType == 3){
  5630. var tmpNode = node.previousSibling;
  5631. while(tmpNode && tmpNode.nodeType == 3){
  5632. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5633. tmpNode = tmpNode.previousSibling;
  5634. }
  5635. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5636. }else{
  5637. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5638. if(node){
  5639. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5640. }else{
  5641. node = isStart ? me.startContainer : me.endContainer;
  5642. var first = node.firstChild;
  5643. while(first){
  5644. if(domUtils.isFillChar(first)){
  5645. first = first.nextSibling;
  5646. continue;
  5647. }
  5648. firstIndex++;
  5649. if(first.nodeType == 3){
  5650. while( first && first.nodeType == 3){
  5651. first = first.nextSibling;
  5652. }
  5653. }else{
  5654. first = first.nextSibling;
  5655. }
  5656. }
  5657. }
  5658. }
  5659. }else{
  5660. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5661. }
  5662. if(firstIndex < 0){
  5663. firstIndex = 0;
  5664. }
  5665. addrs.push(firstIndex);
  5666. return addrs;
  5667. }
  5668. addr.startAddress = getAddress(true);
  5669. if(!ignoreEnd){
  5670. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5671. }
  5672. return addr;
  5673. },
  5674. /**
  5675. * 保存
  5676. * @method createAddress
  5677. * @private
  5678. * @return { Boolean } 返回开始和结束的位置
  5679. * @example
  5680. * ```html
  5681. * <body>
  5682. * <p>
  5683. * aaaa
  5684. * <em>
  5685. * <!-- 选区开始 -->
  5686. * bbbb
  5687. * <!-- 选区结束 -->
  5688. * </em>
  5689. * </p>
  5690. *
  5691. * <script>
  5692. * var range = editor.selection.getRange();
  5693. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5694. * range.select();
  5695. * //output: 'bbbb'
  5696. * console.log(editor.selection.getText());
  5697. * </script>
  5698. * </body>
  5699. * ```
  5700. */
  5701. moveToAddress : function(addr,ignoreEnd){
  5702. var me = this;
  5703. function getNode(address,isStart){
  5704. var tmpNode = me.document.body,
  5705. parentNode,offset;
  5706. for(var i= 0,ci,l=address.length;i<l;i++){
  5707. ci = address[i];
  5708. parentNode = tmpNode;
  5709. tmpNode = tmpNode.childNodes[ci];
  5710. if(!tmpNode){
  5711. offset = ci;
  5712. break;
  5713. }
  5714. }
  5715. if(isStart){
  5716. if(tmpNode){
  5717. me.setStartBefore(tmpNode)
  5718. }else{
  5719. me.setStart(parentNode,offset)
  5720. }
  5721. }else{
  5722. if(tmpNode){
  5723. me.setEndBefore(tmpNode)
  5724. }else{
  5725. me.setEnd(parentNode,offset)
  5726. }
  5727. }
  5728. }
  5729. getNode(addr.startAddress,true);
  5730. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5731. return me;
  5732. },
  5733. /**
  5734. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5735. * @method equals
  5736. * @param { UE.dom.Range } 需要判断的Range对象
  5737. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5738. */
  5739. equals : function(rng){
  5740. for(var p in this){
  5741. if(this.hasOwnProperty(p)){
  5742. if(this[p] !== rng[p])
  5743. return false
  5744. }
  5745. }
  5746. return true;
  5747. },
  5748. /**
  5749. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5750. * 作为其参数。
  5751. * @method traversal
  5752. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5753. * @return { UE.dom.Range } 当前range对象
  5754. * @example
  5755. * ```html
  5756. *
  5757. * <body>
  5758. *
  5759. * <!-- 选区开始 -->
  5760. * <span></span>
  5761. * <a></a>
  5762. * <!-- 选区结束 -->
  5763. * </body>
  5764. *
  5765. * <script>
  5766. *
  5767. * //output: <span></span><a></a>
  5768. * console.log( range.cloneContents() );
  5769. *
  5770. * range.traversal( function ( node ) {
  5771. *
  5772. * if ( node.nodeType === 1 ) {
  5773. * node.className = "test";
  5774. * }
  5775. *
  5776. * } );
  5777. *
  5778. * //output: <span class="test"></span><a class="test"></a>
  5779. * console.log( range.cloneContents() );
  5780. *
  5781. * </script>
  5782. * ```
  5783. */
  5784. /**
  5785. * 遍历range内的节点。
  5786. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5787. * 作为其参数。
  5788. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5789. * 发doFn函数的执行
  5790. * @method traversal
  5791. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5792. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5793. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5794. * 会触发doFn。
  5795. * @return { UE.dom.Range } 当前range对象
  5796. * @see UE.dom.Range:traversal(Function)
  5797. * @example
  5798. * ```html
  5799. *
  5800. * <body>
  5801. *
  5802. * <!-- 选区开始 -->
  5803. * <span></span>
  5804. * <a></a>
  5805. * <!-- 选区结束 -->
  5806. * </body>
  5807. *
  5808. * <script>
  5809. *
  5810. * //output: <span></span><a></a>
  5811. * console.log( range.cloneContents() );
  5812. *
  5813. * range.traversal( function ( node ) {
  5814. *
  5815. * node.className = "test";
  5816. *
  5817. * }, function ( node ) {
  5818. * return node.nodeType === 1;
  5819. * } );
  5820. *
  5821. * //output: <span class="test"></span><a class="test"></a>
  5822. * console.log( range.cloneContents() );
  5823. *
  5824. * </script>
  5825. * ```
  5826. */
  5827. traversal:function(doFn,filterFn){
  5828. if (this.collapsed)
  5829. return this;
  5830. var bookmark = this.createBookmark(),
  5831. end = bookmark.end,
  5832. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5833. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5834. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5835. doFn(current);
  5836. current = tmpNode;
  5837. }
  5838. return this.moveToBookmark(bookmark);
  5839. }
  5840. };
  5841. })();
  5842. // core/Selection.js
  5843. /**
  5844. * 选集
  5845. * @file
  5846. * @module UE.dom
  5847. * @class Selection
  5848. * @since 1.2.6.1
  5849. */
  5850. /**
  5851. * 选区集合
  5852. * @unfile
  5853. * @module UE.dom
  5854. * @class Selection
  5855. */
  5856. (function () {
  5857. function getBoundaryInformation( range, start ) {
  5858. var getIndex = domUtils.getNodeIndex;
  5859. range = range.duplicate();
  5860. range.collapse( start );
  5861. var parent = range.parentElement();
  5862. //如果节点里没有子节点,直接退出
  5863. if ( !parent.hasChildNodes() ) {
  5864. return {container:parent, offset:0};
  5865. }
  5866. var siblings = parent.children,
  5867. child,
  5868. testRange = range.duplicate(),
  5869. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5870. distance;
  5871. while ( startIndex <= endIndex ) {
  5872. index = Math.floor( (startIndex + endIndex) / 2 );
  5873. child = siblings[index];
  5874. testRange.moveToElementText( child );
  5875. var position = testRange.compareEndPoints( 'StartToStart', range );
  5876. if ( position > 0 ) {
  5877. endIndex = index - 1;
  5878. } else if ( position < 0 ) {
  5879. startIndex = index + 1;
  5880. } else {
  5881. //trace:1043
  5882. return {container:parent, offset:getIndex( child )};
  5883. }
  5884. }
  5885. if ( index == -1 ) {
  5886. testRange.moveToElementText( parent );
  5887. testRange.setEndPoint( 'StartToStart', range );
  5888. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5889. siblings = parent.childNodes;
  5890. if ( !distance ) {
  5891. child = siblings[siblings.length - 1];
  5892. return {container:child, offset:child.nodeValue.length};
  5893. }
  5894. var i = siblings.length;
  5895. while ( distance > 0 ){
  5896. distance -= siblings[ --i ].nodeValue.length;
  5897. }
  5898. return {container:siblings[i], offset:-distance};
  5899. }
  5900. testRange.collapse( position > 0 );
  5901. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5902. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5903. if ( !distance ) {
  5904. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5905. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5906. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5907. }
  5908. while ( distance > 0 ) {
  5909. try {
  5910. var pre = child;
  5911. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5912. distance -= child.nodeValue.length;
  5913. } catch ( e ) {
  5914. return {container:parent, offset:getIndex( pre )};
  5915. }
  5916. }
  5917. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5918. }
  5919. /**
  5920. * 将ieRange转换为Range对象
  5921. * @param {Range} ieRange ieRange对象
  5922. * @param {Range} range Range对象
  5923. * @return {Range} range 返回转换后的Range对象
  5924. */
  5925. function transformIERangeToRange( ieRange, range ) {
  5926. if ( ieRange.item ) {
  5927. range.selectNode( ieRange.item( 0 ) );
  5928. } else {
  5929. var bi = getBoundaryInformation( ieRange, true );
  5930. range.setStart( bi.container, bi.offset );
  5931. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5932. bi = getBoundaryInformation( ieRange, false );
  5933. range.setEnd( bi.container, bi.offset );
  5934. }
  5935. }
  5936. return range;
  5937. }
  5938. /**
  5939. * 获得ieRange
  5940. * @param {Selection} sel Selection对象
  5941. * @return {ieRange} 得到ieRange
  5942. */
  5943. function _getIERange( sel ) {
  5944. var ieRange;
  5945. //ie下有可能报错
  5946. try {
  5947. ieRange = sel.getNative().createRange();
  5948. } catch ( e ) {
  5949. return null;
  5950. }
  5951. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5952. if ( ( el.ownerDocument || el ) === sel.document ) {
  5953. return ieRange;
  5954. }
  5955. return null;
  5956. }
  5957. var Selection = dom.Selection = function ( doc ) {
  5958. var me = this, iframe;
  5959. me.document = doc;
  5960. if ( browser.ie9below ) {
  5961. iframe = domUtils.getWindow( doc ).frameElement;
  5962. domUtils.on( iframe, 'beforedeactivate', function () {
  5963. me._bakIERange = me.getIERange();
  5964. } );
  5965. domUtils.on( iframe, 'activate', function () {
  5966. try {
  5967. if ( !_getIERange( me ) && me._bakIERange ) {
  5968. me._bakIERange.select();
  5969. }
  5970. } catch ( ex ) {
  5971. }
  5972. me._bakIERange = null;
  5973. } );
  5974. }
  5975. iframe = doc = null;
  5976. };
  5977. Selection.prototype = {
  5978. rangeInBody : function(rng,txtRange){
  5979. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5980. return node === this.document.body || domUtils.inDoc(node,this.document);
  5981. },
  5982. /**
  5983. * 获取原生seleciton对象
  5984. * @method getNative
  5985. * @return { Object } 获得selection对象
  5986. * @example
  5987. * ```javascript
  5988. * editor.selection.getNative();
  5989. * ```
  5990. */
  5991. getNative:function () {
  5992. var doc = this.document;
  5993. try {
  5994. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5995. } catch ( e ) {
  5996. return null;
  5997. }
  5998. },
  5999. /**
  6000. * 获得ieRange
  6001. * @method getIERange
  6002. * @return { Object } 返回ie原生的Range
  6003. * @example
  6004. * ```javascript
  6005. * editor.selection.getIERange();
  6006. * ```
  6007. */
  6008. getIERange:function () {
  6009. var ieRange = _getIERange( this );
  6010. if ( !ieRange ) {
  6011. if ( this._bakIERange ) {
  6012. return this._bakIERange;
  6013. }
  6014. }
  6015. return ieRange;
  6016. },
  6017. /**
  6018. * 缓存当前选区的range和选区的开始节点
  6019. * @method cache
  6020. */
  6021. cache:function () {
  6022. this.clear();
  6023. this._cachedRange = this.getRange();
  6024. this._cachedStartElement = this.getStart();
  6025. this._cachedStartElementPath = this.getStartElementPath();
  6026. },
  6027. /**
  6028. * 获取选区开始位置的父节点到body
  6029. * @method getStartElementPath
  6030. * @return { Array } 返回父节点集合
  6031. * @example
  6032. * ```javascript
  6033. * editor.selection.getStartElementPath();
  6034. * ```
  6035. */
  6036. getStartElementPath:function () {
  6037. if ( this._cachedStartElementPath ) {
  6038. return this._cachedStartElementPath;
  6039. }
  6040. var start = this.getStart();
  6041. if ( start ) {
  6042. return domUtils.findParents( start, true, null, true )
  6043. }
  6044. return [];
  6045. },
  6046. /**
  6047. * 清空缓存
  6048. * @method clear
  6049. */
  6050. clear:function () {
  6051. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6052. },
  6053. /**
  6054. * 编辑器是否得到了选区
  6055. * @method isFocus
  6056. */
  6057. isFocus:function () {
  6058. try {
  6059. if(browser.ie9below){
  6060. var nativeRange = _getIERange(this);
  6061. return !!(nativeRange && this.rangeInBody(nativeRange));
  6062. }else{
  6063. return !!this.getNative().rangeCount;
  6064. }
  6065. } catch ( e ) {
  6066. return false;
  6067. }
  6068. },
  6069. /**
  6070. * 获取选区对应的Range
  6071. * @method getRange
  6072. * @return { Object } 得到Range对象
  6073. * @example
  6074. * ```javascript
  6075. * editor.selection.getRange();
  6076. * ```
  6077. */
  6078. getRange:function () {
  6079. var me = this;
  6080. function optimze( range ) {
  6081. var child = me.document.body.firstChild,
  6082. collapsed = range.collapsed;
  6083. while ( child && child.firstChild ) {
  6084. range.setStart( child, 0 );
  6085. child = child.firstChild;
  6086. }
  6087. if ( !range.startContainer ) {
  6088. range.setStart( me.document.body, 0 )
  6089. }
  6090. if ( collapsed ) {
  6091. range.collapse( true );
  6092. }
  6093. }
  6094. if ( me._cachedRange != null ) {
  6095. return this._cachedRange;
  6096. }
  6097. var range = new baidu.editor.dom.Range( me.document );
  6098. if ( browser.ie9below ) {
  6099. var nativeRange = me.getIERange();
  6100. if ( nativeRange ) {
  6101. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6102. try{
  6103. transformIERangeToRange( nativeRange, range );
  6104. }catch(e){
  6105. optimze( range );
  6106. }
  6107. } else {
  6108. optimze( range );
  6109. }
  6110. } else {
  6111. var sel = me.getNative();
  6112. if ( sel && sel.rangeCount ) {
  6113. var firstRange = sel.getRangeAt( 0 );
  6114. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  6115. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  6116. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  6117. optimze( range );
  6118. }
  6119. } else {
  6120. //trace:1734 有可能已经不在dom树上了,标识的节点
  6121. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  6122. return this._bakRange;
  6123. }
  6124. optimze( range );
  6125. }
  6126. }
  6127. return this._bakRange = range;
  6128. },
  6129. /**
  6130. * 获取开始元素,用于状态反射
  6131. * @method getStart
  6132. * @return { Element } 获得开始元素
  6133. * @example
  6134. * ```javascript
  6135. * editor.selection.getStart();
  6136. * ```
  6137. */
  6138. getStart:function () {
  6139. if ( this._cachedStartElement ) {
  6140. return this._cachedStartElement;
  6141. }
  6142. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6143. tmpRange,
  6144. start, tmp, parent;
  6145. if ( browser.ie9below ) {
  6146. if ( !range ) {
  6147. //todo 给第一个值可能会有问题
  6148. return this.document.body.firstChild;
  6149. }
  6150. //control元素
  6151. if ( range.item ){
  6152. return range.item( 0 );
  6153. }
  6154. tmpRange = range.duplicate();
  6155. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6156. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  6157. tmpRange.collapse( 1 );
  6158. start = tmpRange.parentElement();
  6159. parent = tmp = range.parentElement();
  6160. while ( tmp = tmp.parentNode ) {
  6161. if ( tmp == start ) {
  6162. start = parent;
  6163. break;
  6164. }
  6165. }
  6166. } else {
  6167. range.shrinkBoundary();
  6168. start = range.startContainer;
  6169. if ( start.nodeType == 1 && start.hasChildNodes() ){
  6170. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  6171. }
  6172. if ( start.nodeType == 3 ){
  6173. return start.parentNode;
  6174. }
  6175. }
  6176. return start;
  6177. },
  6178. /**
  6179. * 得到选区中的文本
  6180. * @method getText
  6181. * @return { String } 选区中包含的文本
  6182. * @example
  6183. * ```javascript
  6184. * editor.selection.getText();
  6185. * ```
  6186. */
  6187. getText:function () {
  6188. var nativeSel, nativeRange;
  6189. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  6190. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  6191. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6192. }
  6193. return '';
  6194. },
  6195. /**
  6196. * 清除选区
  6197. * @method clearRange
  6198. * @example
  6199. * ```javascript
  6200. * editor.selection.clearRange();
  6201. * ```
  6202. */
  6203. clearRange : function(){
  6204. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6205. }
  6206. };
  6207. })();
  6208. // core/Editor.js
  6209. /**
  6210. * 编辑器主类,包含编辑器提供的大部分公用接口
  6211. * @file
  6212. * @module UE
  6213. * @class Editor
  6214. * @since 1.2.6.1
  6215. */
  6216. /**
  6217. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6218. * @unfile
  6219. * @module UE
  6220. */
  6221. /**
  6222. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6223. * @unfile
  6224. * @module UE
  6225. * @class Editor
  6226. */
  6227. (function () {
  6228. var uid = 0, _selectionChangeTimer;
  6229. /**
  6230. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6231. * @private
  6232. * @method setValue
  6233. * @param { UE.Editor } editor 编辑器事例
  6234. */
  6235. function setValue(form, editor) {
  6236. var textarea;
  6237. if (editor.textarea) {
  6238. if (utils.isString(editor.textarea)) {
  6239. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6240. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6241. textarea = ti;
  6242. break;
  6243. }
  6244. }
  6245. } else {
  6246. textarea = editor.textarea;
  6247. }
  6248. }
  6249. if (!textarea) {
  6250. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6251. 'name': editor.options.textarea,
  6252. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6253. 'style': "display:none"
  6254. }));
  6255. //不要产生多个textarea
  6256. editor.textarea = textarea;
  6257. }
  6258. !textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea );
  6259. textarea.value = editor.hasContents() ?
  6260. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6261. ''
  6262. }
  6263. function loadPlugins(me){
  6264. //初始化插件
  6265. for (var pi in UE.plugins) {
  6266. UE.plugins[pi].call(me);
  6267. }
  6268. }
  6269. function checkCurLang(I18N){
  6270. for(var lang in I18N){
  6271. return lang
  6272. }
  6273. }
  6274. function langReadied(me){
  6275. me.langIsReady = true;
  6276. me.fireEvent("langReady");
  6277. }
  6278. /**
  6279. * 编辑器准备就绪后会触发该事件
  6280. * @module UE
  6281. * @class Editor
  6282. * @event ready
  6283. * @remind render方法执行完成之后,会触发该事件
  6284. * @remind
  6285. * @example
  6286. * ```javascript
  6287. * editor.addListener( 'ready', function( editor ) {
  6288. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6289. * } );
  6290. * ```
  6291. */
  6292. /**
  6293. * 执行destroy方法,会触发该事件
  6294. * @module UE
  6295. * @class Editor
  6296. * @event destroy
  6297. * @see UE.Editor:destroy()
  6298. */
  6299. /**
  6300. * 执行reset方法,会触发该事件
  6301. * @module UE
  6302. * @class Editor
  6303. * @event reset
  6304. * @see UE.Editor:reset()
  6305. */
  6306. /**
  6307. * 执行focus方法,会触发该事件
  6308. * @module UE
  6309. * @class Editor
  6310. * @event focus
  6311. * @see UE.Editor:focus(Boolean)
  6312. */
  6313. /**
  6314. * 语言加载完成会触发该事件
  6315. * @module UE
  6316. * @class Editor
  6317. * @event langReady
  6318. */
  6319. /**
  6320. * 运行命令之后会触发该命令
  6321. * @module UE
  6322. * @class Editor
  6323. * @event beforeExecCommand
  6324. */
  6325. /**
  6326. * 运行命令之后会触发该命令
  6327. * @module UE
  6328. * @class Editor
  6329. * @event afterExecCommand
  6330. */
  6331. /**
  6332. * 运行命令之前会触发该命令
  6333. * @module UE
  6334. * @class Editor
  6335. * @event firstBeforeExecCommand
  6336. */
  6337. /**
  6338. * 在getContent方法执行之前会触发该事件
  6339. * @module UE
  6340. * @class Editor
  6341. * @event beforeGetContent
  6342. * @see UE.Editor:getContent()
  6343. */
  6344. /**
  6345. * 在getContent方法执行之后会触发该事件
  6346. * @module UE
  6347. * @class Editor
  6348. * @event afterGetContent
  6349. * @see UE.Editor:getContent()
  6350. */
  6351. /**
  6352. * 在getAllHtml方法执行时会触发该事件
  6353. * @module UE
  6354. * @class Editor
  6355. * @event getAllHtml
  6356. * @see UE.Editor:getAllHtml()
  6357. */
  6358. /**
  6359. * 在setContent方法执行之前会触发该事件
  6360. * @module UE
  6361. * @class Editor
  6362. * @event beforeSetContent
  6363. * @see UE.Editor:setContent(String)
  6364. */
  6365. /**
  6366. * 在setContent方法执行之后会触发该事件
  6367. * @module UE
  6368. * @class Editor
  6369. * @event afterSetContent
  6370. * @see UE.Editor:setContent(String)
  6371. */
  6372. /**
  6373. * 每当编辑器内部选区发生改变时,将触发该事件
  6374. * @event selectionchange
  6375. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6376. * @example
  6377. * ```javascript
  6378. * editor.addListener( 'selectionchange', function( editor ) {
  6379. * console.log('选区发生改变');
  6380. * }
  6381. */
  6382. /**
  6383. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6384. * @module UE
  6385. * @class Editor
  6386. * @event beforeSelectionChange
  6387. * @see UE.Editor:selectionchange
  6388. */
  6389. /**
  6390. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6391. * @module UE
  6392. * @class Editor
  6393. * @event afterSelectionChange
  6394. * @see UE.Editor:selectionchange
  6395. */
  6396. /**
  6397. * 编辑器内容发生改变时会触发该事件
  6398. * @module UE
  6399. * @class Editor
  6400. * @event contentChange
  6401. */
  6402. /**
  6403. * 以默认参数构建一个编辑器实例
  6404. * @constructor
  6405. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6406. * @example
  6407. * ```javascript
  6408. * var editor = new UE.Editor();
  6409. * editor.execCommand('blod');
  6410. * ```
  6411. * @see UE.Config
  6412. */
  6413. /**
  6414. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6415. * @constructor
  6416. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6417. * @param { Object } setting 创建编辑器的参数
  6418. * @example
  6419. * ```javascript
  6420. * var editor = new UE.Editor();
  6421. * editor.execCommand('blod');
  6422. * ```
  6423. * @see UE.Config
  6424. */
  6425. var Editor = UE.Editor = function (options) {
  6426. var me = this;
  6427. me.uid = uid++;
  6428. EventBase.call(me);
  6429. me.commands = {};
  6430. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6431. me.shortcutkeys = {};
  6432. me.inputRules = [];
  6433. me.outputRules = [];
  6434. //设置默认的常用属性
  6435. me.setOpt(Editor.defaultOptions(me));
  6436. /* 尝试异步加载后台配置 */
  6437. me.loadServerConfig();
  6438. if(!utils.isEmptyObject(UE.I18N)){
  6439. //修改默认的语言类型
  6440. me.options.lang = checkCurLang(UE.I18N);
  6441. UE.plugin.load(me);
  6442. langReadied(me);
  6443. }else{
  6444. utils.loadFile(document, {
  6445. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6446. tag: "script",
  6447. type: "text/javascript",
  6448. defer: "defer"
  6449. }, function () {
  6450. UE.plugin.load(me);
  6451. langReadied(me);
  6452. });
  6453. }
  6454. UE.instants['ueditorInstant' + me.uid] = me;
  6455. };
  6456. Editor.prototype = {
  6457. registerCommand : function(name,obj){
  6458. this.commands[name] = obj;
  6459. },
  6460. /**
  6461. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6462. * @method ready
  6463. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6464. * 立即触发该回调。
  6465. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6466. * @example
  6467. * ```javascript
  6468. * editor.ready( function( editor ) {
  6469. * editor.setContent('初始化完毕');
  6470. * } );
  6471. * ```
  6472. * @see UE.Editor.event:ready
  6473. */
  6474. ready: function (fn) {
  6475. var me = this;
  6476. if (fn) {
  6477. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6478. }
  6479. },
  6480. /**
  6481. * 该方法是提供给插件里面使用,设置配置项默认值
  6482. * @method setOpt
  6483. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6484. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6485. * @param { String } key 编辑器的可接受的选项名称
  6486. * @param { * } val 该选项可接受的值
  6487. * @example
  6488. * ```javascript
  6489. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6490. * ```
  6491. */
  6492. /**
  6493. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6494. * @method setOpt
  6495. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6496. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6497. * @param { Object } options 将要设置的选项的键值对对象
  6498. * @example
  6499. * ```javascript
  6500. * editor.setOpt( {
  6501. * 'initContent': '欢迎使用编辑器'
  6502. * } );
  6503. * ```
  6504. */
  6505. setOpt: function (key, val) {
  6506. var obj = {};
  6507. if (utils.isString(key)) {
  6508. obj[key] = val
  6509. } else {
  6510. obj = key;
  6511. }
  6512. utils.extend(this.options, obj, true);
  6513. },
  6514. getOpt:function(key){
  6515. return this.options[key]
  6516. },
  6517. /**
  6518. * 销毁编辑器实例,使用textarea代替
  6519. * @method destroy
  6520. * @example
  6521. * ```javascript
  6522. * editor.destroy();
  6523. * ```
  6524. */
  6525. destroy: function () {
  6526. var me = this;
  6527. me.fireEvent('destroy');
  6528. var container = me.container.parentNode;
  6529. var textarea = me.textarea;
  6530. if (!textarea) {
  6531. textarea = document.createElement('textarea');
  6532. container.parentNode.insertBefore(textarea, container);
  6533. } else {
  6534. textarea.style.display = ''
  6535. }
  6536. textarea.style.width = me.iframe.offsetWidth + 'px';
  6537. textarea.style.height = me.iframe.offsetHeight + 'px';
  6538. textarea.value = me.getContent();
  6539. textarea.id = me.key;
  6540. container.innerHTML = '';
  6541. domUtils.remove(container);
  6542. var key = me.key;
  6543. //trace:2004
  6544. for (var p in me) {
  6545. if (me.hasOwnProperty(p)) {
  6546. delete this[p];
  6547. }
  6548. }
  6549. UE.delEditor(key);
  6550. },
  6551. /**
  6552. * 渲染编辑器的DOM到指定容器
  6553. * @method render
  6554. * @param { String } containerId 指定一个容器ID
  6555. * @remind 执行该方法,会触发ready事件
  6556. * @warning 必须且只能调用一次
  6557. */
  6558. /**
  6559. * 渲染编辑器的DOM到指定容器
  6560. * @method render
  6561. * @param { Element } containerDom 直接指定容器对象
  6562. * @remind 执行该方法,会触发ready事件
  6563. * @warning 必须且只能调用一次
  6564. */
  6565. render: function (container) {
  6566. var me = this,
  6567. options = me.options,
  6568. getStyleValue=function(attr){
  6569. return parseInt(domUtils.getComputedStyle(container,attr));
  6570. };
  6571. if (utils.isString(container)) {
  6572. container = document.getElementById(container);
  6573. }
  6574. if (container) {
  6575. if(options.initialFrameWidth){
  6576. options.minFrameWidth = options.initialFrameWidth
  6577. }else{
  6578. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6579. }
  6580. if(options.initialFrameHeight){
  6581. options.minFrameHeight = options.initialFrameHeight
  6582. }else{
  6583. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6584. }
  6585. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6586. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6587. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6588. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6589. container.style.zIndex = options.zIndex;
  6590. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6591. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6592. '<style type=\'text/css\'>' +
  6593. //设置四周的留边
  6594. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6595. //设置默认字体和字号
  6596. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6597. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6598. //设置段落间距
  6599. 'p{margin:5px 0;}</style>' +
  6600. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6601. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6602. '</head><body class=\'view\' ></body>' +
  6603. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6604. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6605. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6606. container.appendChild(domUtils.createElement(document, 'iframe', {
  6607. id: 'ueditor_' + me.uid,
  6608. width: "100%",
  6609. height: "100%",
  6610. frameborder: "0",
  6611. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6612. // scrolling :'no',
  6613. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6614. 'document.write("' + html + '");document.close();}())'
  6615. }));
  6616. container.style.overflow = 'hidden';
  6617. //解决如果是给定的百分比,会导致高度算不对的问题
  6618. setTimeout(function(){
  6619. if( /%$/.test(options.initialFrameWidth)){
  6620. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6621. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6622. // container.style.width = options.initialFrameWidth + 'px';
  6623. }
  6624. if(/%$/.test(options.initialFrameHeight)){
  6625. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6626. container.style.height = options.initialFrameHeight + 'px';
  6627. }
  6628. })
  6629. }
  6630. },
  6631. /**
  6632. * 编辑器初始化
  6633. * @method _setup
  6634. * @private
  6635. * @param { Element } doc 编辑器Iframe中的文档对象
  6636. */
  6637. _setup: function (doc) {
  6638. var me = this,
  6639. options = me.options;
  6640. if (ie) {
  6641. doc.body.disabled = true;
  6642. doc.body.contentEditable = true;
  6643. doc.body.disabled = false;
  6644. } else {
  6645. doc.body.contentEditable = true;
  6646. }
  6647. doc.body.spellcheck = false;
  6648. me.document = doc;
  6649. me.window = doc.defaultView || doc.parentWindow;
  6650. me.iframe = me.window.frameElement;
  6651. me.body = doc.body;
  6652. me.selection = new dom.Selection(doc);
  6653. //gecko初始化就能得到range,无法判断isFocus了
  6654. var geckoSel;
  6655. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6656. geckoSel.removeAllRanges();
  6657. }
  6658. this._initEvents();
  6659. //为form提交提供一个隐藏的textarea
  6660. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6661. if (form.tagName == 'FORM') {
  6662. me.form = form;
  6663. if(me.options.autoSyncData){
  6664. domUtils.on(me.window,'blur',function(){
  6665. setValue(form,me);
  6666. });
  6667. }else{
  6668. domUtils.on(form, 'submit', function () {
  6669. setValue(this, me);
  6670. });
  6671. }
  6672. break;
  6673. }
  6674. }
  6675. if (options.initialContent) {
  6676. if (options.autoClearinitialContent) {
  6677. var oldExecCommand = me.execCommand;
  6678. me.execCommand = function () {
  6679. me.fireEvent('firstBeforeExecCommand');
  6680. return oldExecCommand.apply(me, arguments);
  6681. };
  6682. this._setDefaultContent(options.initialContent);
  6683. } else
  6684. this.setContent(options.initialContent, false, true);
  6685. }
  6686. //编辑器不能为空内容
  6687. if (domUtils.isEmptyNode(me.body)) {
  6688. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6689. }
  6690. //如果要求focus, 就把光标定位到内容开始
  6691. if (options.focus) {
  6692. setTimeout(function () {
  6693. me.focus(me.options.focusInEnd);
  6694. //如果自动清除开着,就不需要做selectionchange;
  6695. !me.options.autoClearinitialContent && me._selectionChange();
  6696. }, 0);
  6697. }
  6698. if (!me.container) {
  6699. me.container = this.iframe.parentNode;
  6700. }
  6701. if (options.fullscreen && me.ui) {
  6702. me.ui.setFullScreen(true);
  6703. }
  6704. try {
  6705. me.document.execCommand('2D-position', false, false);
  6706. } catch (e) {
  6707. }
  6708. try {
  6709. me.document.execCommand('enableInlineTableEditing', false, false);
  6710. } catch (e) {
  6711. }
  6712. try {
  6713. me.document.execCommand('enableObjectResizing', false, false);
  6714. } catch (e) {
  6715. }
  6716. //挂接快捷键
  6717. me._bindshortcutKeys();
  6718. me.isReady = 1;
  6719. me.fireEvent('ready');
  6720. options.onready && options.onready.call(me);
  6721. if (!browser.ie9below) {
  6722. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6723. //chrome下会出现alt+tab切换时,导致选区位置不对
  6724. if (e.type == 'blur') {
  6725. me._bakRange = me.selection.getRange();
  6726. try {
  6727. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6728. me.selection.getNative().removeAllRanges();
  6729. } catch (e) {
  6730. me._bakNativeRange = null;
  6731. }
  6732. } else {
  6733. try {
  6734. me._bakRange && me._bakRange.select();
  6735. } catch (e) {
  6736. }
  6737. }
  6738. });
  6739. }
  6740. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6741. if (browser.gecko && browser.version <= 10902) {
  6742. //修复ff3.6初始化进来,不能点击获得焦点
  6743. me.body.contentEditable = false;
  6744. setTimeout(function () {
  6745. me.body.contentEditable = true;
  6746. }, 100);
  6747. setInterval(function () {
  6748. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6749. }, 100)
  6750. }
  6751. !options.isShow && me.setHide();
  6752. options.readonly && me.setDisabled();
  6753. },
  6754. /**
  6755. * 同步数据到编辑器所在的form
  6756. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6757. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6758. * @method sync
  6759. * @example
  6760. * ```javascript
  6761. * editor.sync();
  6762. * form.sumbit(); //form变量已经指向了form元素
  6763. * ```
  6764. */
  6765. /**
  6766. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6767. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6768. * @method sync
  6769. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6770. */
  6771. sync: function (formId) {
  6772. var me = this,
  6773. form = formId ? document.getElementById(formId) :
  6774. domUtils.findParent(me.iframe.parentNode, function (node) {
  6775. return node.tagName == 'FORM'
  6776. }, true);
  6777. form && setValue(form, me);
  6778. },
  6779. /**
  6780. * 设置编辑器高度
  6781. * @method setHeight
  6782. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6783. * @param { Number } number 设置的高度值,纯数值,不带单位
  6784. * @example
  6785. * ```javascript
  6786. * editor.setHeight(number);
  6787. * ```
  6788. */
  6789. setHeight: function (height,notSetHeight) {
  6790. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6791. this.iframe.parentNode.style.height = height + 'px';
  6792. }
  6793. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6794. this.body.style.height = height + 'px';
  6795. !notSetHeight && this.trigger('setHeight')
  6796. },
  6797. /**
  6798. * 为编辑器的编辑命令提供快捷键
  6799. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6800. * @method addshortcutkey
  6801. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6802. * @example
  6803. * ```javascript
  6804. * editor.addshortcutkey({
  6805. * "Bold" : "ctrl+66",//^B
  6806. * "Italic" : "ctrl+73", //^I
  6807. * });
  6808. * ```
  6809. */
  6810. /**
  6811. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6812. * @method addshortcutkey
  6813. * @param { String } cmd 触发快捷键时,响应的命令
  6814. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6815. * @example
  6816. * ```javascript
  6817. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6818. * ```
  6819. */
  6820. addshortcutkey: function (cmd, keys) {
  6821. var obj = {};
  6822. if (keys) {
  6823. obj[cmd] = keys
  6824. } else {
  6825. obj = cmd;
  6826. }
  6827. utils.extend(this.shortcutkeys, obj)
  6828. },
  6829. /**
  6830. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6831. * @method _bindshortcutKeys
  6832. * @private
  6833. */
  6834. _bindshortcutKeys: function () {
  6835. var me = this, shortcutkeys = this.shortcutkeys;
  6836. me.addListener('keydown', function (type, e) {
  6837. var keyCode = e.keyCode || e.which;
  6838. for (var i in shortcutkeys) {
  6839. var tmp = shortcutkeys[i].split(',');
  6840. for (var t = 0, ti; ti = tmp[t++];) {
  6841. ti = ti.split(':');
  6842. var key = ti[0], param = ti[1];
  6843. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6844. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6845. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6846. && keyCode == RegExp.$3
  6847. ) ||
  6848. keyCode == RegExp.$1
  6849. ) {
  6850. if (me.queryCommandState(i,param) != -1)
  6851. me.execCommand(i, param);
  6852. domUtils.preventDefault(e);
  6853. }
  6854. }
  6855. }
  6856. }
  6857. });
  6858. },
  6859. /**
  6860. * 获取编辑器的内容
  6861. * @method getContent
  6862. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6863. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6864. * @example
  6865. * ```javascript
  6866. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6867. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6868. * ```
  6869. */
  6870. /**
  6871. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6872. * @method getContent
  6873. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6874. * 代表当前编辑器的内容是否空,
  6875. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6876. * 经过内置过滤规则处理后的内容。
  6877. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6878. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6879. * @return { String } 编辑器的内容字符串
  6880. * @example
  6881. * ```javascript
  6882. * // editor 是一个编辑器的实例
  6883. * var content = editor.getContent( function ( editor ) {
  6884. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6885. * } );
  6886. * ```
  6887. */
  6888. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6889. var me = this;
  6890. if (cmd && utils.isFunction(cmd)) {
  6891. fn = cmd;
  6892. cmd = '';
  6893. }
  6894. if (fn ? !fn() : !this.hasContents()) {
  6895. return '';
  6896. }
  6897. me.fireEvent('beforegetcontent');
  6898. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6899. me.filterOutputRule(root);
  6900. me.fireEvent('aftergetcontent', cmd,root);
  6901. return root.toHtml(formatter);
  6902. },
  6903. /**
  6904. * 取得完整的html代码,可以直接显示成完整的html文档
  6905. * @method getAllHtml
  6906. * @return { String } 编辑器的内容html文档字符串
  6907. * @eaxmple
  6908. * ```javascript
  6909. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6910. * ```
  6911. */
  6912. getAllHtml: function () {
  6913. var me = this,
  6914. headHtml = [],
  6915. html = '';
  6916. me.fireEvent('getAllHtml', headHtml);
  6917. if (browser.ie && browser.version > 8) {
  6918. var headHtmlForIE9 = '';
  6919. utils.each(me.document.styleSheets, function (si) {
  6920. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6921. });
  6922. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6923. headHtmlForIE9 += si.outerHTML;
  6924. });
  6925. }
  6926. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6927. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6928. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6929. },
  6930. /**
  6931. * 得到编辑器的纯文本内容,但会保留段落格式
  6932. * @method getPlainTxt
  6933. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6934. * @example
  6935. * ```javascript
  6936. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6937. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6938. * ```
  6939. */
  6940. getPlainTxt: function () {
  6941. var reg = new RegExp(domUtils.fillChar, 'g'),
  6942. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6943. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6944. .replace(/<br\/?>/gi, '\n')
  6945. .replace(/<[^>/]+>/g, '')
  6946. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6947. return dtd.$block[c] ? '\n' : b ? b : '';
  6948. });
  6949. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6950. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6951. },
  6952. /**
  6953. * 获取编辑器中的纯文本内容,没有段落格式
  6954. * @method getContentTxt
  6955. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6956. * @example
  6957. * ```javascript
  6958. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6959. * console.log(editor.getPlainTxt()); //输出:"12
  6960. * ```
  6961. */
  6962. getContentTxt: function () {
  6963. var reg = new RegExp(domUtils.fillChar, 'g');
  6964. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6965. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6966. },
  6967. /**
  6968. * 设置编辑器的内容,可修改编辑器当前的html内容
  6969. * @method setContent
  6970. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6971. * @warning 该方法会触发selectionchange事件
  6972. * @param { String } html 要插入的html内容
  6973. * @example
  6974. * ```javascript
  6975. * editor.getContent('<p>test</p>');
  6976. * ```
  6977. */
  6978. /**
  6979. * 设置编辑器的内容,可修改编辑器当前的html内容
  6980. * @method setContent
  6981. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6982. * @warning 该方法会触发selectionchange事件
  6983. * @param { String } html 要插入的html内容
  6984. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6985. * @example
  6986. * ```javascript
  6987. * //假设设置前的编辑器内容是 <p>old text</p>
  6988. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6989. * ```
  6990. */
  6991. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6992. var me = this;
  6993. me.fireEvent('beforesetcontent', html);
  6994. var root = UE.htmlparser(html);
  6995. me.filterInputRule(root);
  6996. html = root.toHtml();
  6997. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6998. function isCdataDiv(node){
  6999. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  7000. }
  7001. //给文本或者inline节点套p标签
  7002. if (me.options.enterTag == 'p') {
  7003. var child = this.body.firstChild, tmpNode;
  7004. if (!child || child.nodeType == 1 &&
  7005. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  7006. domUtils.isCustomeNode(child)
  7007. )
  7008. && child === this.body.lastChild) {
  7009. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  7010. } else {
  7011. var p = me.document.createElement('p');
  7012. while (child) {
  7013. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  7014. tmpNode = child.nextSibling;
  7015. p.appendChild(child);
  7016. child = tmpNode;
  7017. }
  7018. if (p.firstChild) {
  7019. if (!child) {
  7020. me.body.appendChild(p);
  7021. break;
  7022. } else {
  7023. child.parentNode.insertBefore(p, child);
  7024. p = me.document.createElement('p');
  7025. }
  7026. }
  7027. child = child.nextSibling;
  7028. }
  7029. }
  7030. }
  7031. me.fireEvent('aftersetcontent');
  7032. me.fireEvent('contentchange');
  7033. !notFireSelectionchange && me._selectionChange();
  7034. //清除保存的选区
  7035. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7036. //trace:1742 setContent后gecko能得到焦点问题
  7037. var geckoSel;
  7038. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7039. geckoSel.removeAllRanges();
  7040. }
  7041. if(me.options.autoSyncData){
  7042. me.form && setValue(me.form,me);
  7043. }
  7044. },
  7045. /**
  7046. * 让编辑器获得焦点,默认focus到编辑器头部
  7047. * @method focus
  7048. * @example
  7049. * ```javascript
  7050. * editor.focus()
  7051. * ```
  7052. */
  7053. /**
  7054. * 让编辑器获得焦点,toEnd确定focus位置
  7055. * @method focus
  7056. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7057. * @example
  7058. * ```javascript
  7059. * editor.focus(true)
  7060. * ```
  7061. */
  7062. focus: function (toEnd) {
  7063. try {
  7064. var me = this,
  7065. rng = me.selection.getRange();
  7066. if (toEnd) {
  7067. var node = me.body.lastChild;
  7068. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7069. if(domUtils.isEmptyBlock(node)){
  7070. rng.setStartAtFirst(node)
  7071. }else{
  7072. rng.setStartAtLast(node)
  7073. }
  7074. rng.collapse(true);
  7075. }
  7076. rng.setCursor(true);
  7077. } else {
  7078. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  7079. var node = me.body.firstChild;
  7080. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7081. rng.setStartAtFirst(node).collapse(true);
  7082. }
  7083. }
  7084. rng.select(true);
  7085. }
  7086. this.fireEvent('focus selectionchange');
  7087. } catch (e) {
  7088. }
  7089. },
  7090. isFocus:function(){
  7091. return this.selection.isFocus();
  7092. },
  7093. blur:function(){
  7094. var sel = this.selection.getNative();
  7095. if(sel.empty && browser.ie){
  7096. var nativeRng = document.body.createTextRange();
  7097. nativeRng.moveToElementText(document.body);
  7098. nativeRng.collapse(true);
  7099. nativeRng.select();
  7100. sel.empty()
  7101. }else{
  7102. sel.removeAllRanges()
  7103. }
  7104. //this.fireEvent('blur selectionchange');
  7105. },
  7106. /**
  7107. * 初始化UE事件及部分事件代理
  7108. * @method _initEvents
  7109. * @private
  7110. */
  7111. _initEvents: function () {
  7112. var me = this,
  7113. doc = me.document,
  7114. win = me.window;
  7115. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7116. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7117. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7118. domUtils.on(me.body,'drop',function(e){
  7119. //阻止ff下默认的弹出新页面打开图片
  7120. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  7121. me.fireEvent('contentchange')
  7122. });
  7123. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7124. //特殊键不触发selectionchange
  7125. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7126. return;
  7127. }
  7128. if (evt.button == 2)return;
  7129. me._selectionChange(250, evt);
  7130. });
  7131. },
  7132. /**
  7133. * 触发事件代理
  7134. * @method _proxyDomEvent
  7135. * @private
  7136. * @return { * } fireEvent的返回值
  7137. * @see UE.EventBase:fireEvent(String)
  7138. */
  7139. _proxyDomEvent: function (evt) {
  7140. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  7141. return false;
  7142. }
  7143. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  7144. return false;
  7145. }
  7146. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7147. },
  7148. /**
  7149. * 变化选区
  7150. * @method _selectionChange
  7151. * @private
  7152. */
  7153. _selectionChange: function (delay, evt) {
  7154. var me = this;
  7155. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7156. // if ( !me.selection.isFocus() ){
  7157. // return;
  7158. // }
  7159. var hackForMouseUp = false;
  7160. var mouseX, mouseY;
  7161. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7162. var range = this.selection.getRange();
  7163. if (!range.collapsed) {
  7164. hackForMouseUp = true;
  7165. mouseX = evt.clientX;
  7166. mouseY = evt.clientY;
  7167. }
  7168. }
  7169. clearTimeout(_selectionChangeTimer);
  7170. _selectionChangeTimer = setTimeout(function () {
  7171. if (!me.selection || !me.selection.getNative()) {
  7172. return;
  7173. }
  7174. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7175. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7176. var ieRange;
  7177. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7178. ieRange = me.document.body.createTextRange();
  7179. try {
  7180. ieRange.moveToPoint(mouseX, mouseY);
  7181. } catch (ex) {
  7182. ieRange = null;
  7183. }
  7184. }
  7185. var bakGetIERange;
  7186. if (ieRange) {
  7187. bakGetIERange = me.selection.getIERange;
  7188. me.selection.getIERange = function () {
  7189. return ieRange;
  7190. };
  7191. }
  7192. me.selection.cache();
  7193. if (bakGetIERange) {
  7194. me.selection.getIERange = bakGetIERange;
  7195. }
  7196. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7197. me.fireEvent('beforeselectionchange');
  7198. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7199. me.fireEvent('selectionchange', !!evt);
  7200. me.fireEvent('afterselectionchange');
  7201. me.selection.clear();
  7202. }
  7203. }, delay || 50);
  7204. },
  7205. /**
  7206. * 执行编辑命令
  7207. * @method _callCmdFn
  7208. * @private
  7209. * @param { String } fnName 函数名称
  7210. * @param { * } args 传给命令函数的参数
  7211. * @return { * } 返回命令函数运行的返回值
  7212. */
  7213. _callCmdFn: function (fnName, args) {
  7214. var cmdName = args[0].toLowerCase(),
  7215. cmd, cmdFn;
  7216. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7217. cmdFn = cmd && cmd[fnName];
  7218. //没有querycommandstate或者没有command的都默认返回0
  7219. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7220. return 0;
  7221. } else if (cmdFn) {
  7222. return cmdFn.apply(this, args);
  7223. }
  7224. },
  7225. /**
  7226. * 执行编辑命令cmdName,完成富文本编辑效果
  7227. * @method execCommand
  7228. * @param { String } cmdName 需要执行的命令
  7229. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7230. * @return { * } 返回命令函数运行的返回值
  7231. * @example
  7232. * ```javascript
  7233. * editor.execCommand(cmdName);
  7234. * ```
  7235. */
  7236. execCommand: function (cmdName) {
  7237. cmdName = cmdName.toLowerCase();
  7238. var me = this,
  7239. result,
  7240. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7241. if (!cmd || !cmd.execCommand) {
  7242. return null;
  7243. }
  7244. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7245. me.__hasEnterExecCommand = true;
  7246. if (me.queryCommandState.apply(me,arguments) != -1) {
  7247. me.fireEvent('saveScene');
  7248. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7249. result = this._callCmdFn('execCommand', arguments);
  7250. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7251. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7252. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7253. me.fireEvent('saveScene');
  7254. }
  7255. me.__hasEnterExecCommand = false;
  7256. } else {
  7257. result = this._callCmdFn('execCommand', arguments);
  7258. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7259. }
  7260. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7261. return result;
  7262. },
  7263. /**
  7264. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7265. * @method queryCommandState
  7266. * @param { String } cmdName 需要查询的命令名称
  7267. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7268. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7269. * @example
  7270. * ```javascript
  7271. * editor.queryCommandState(cmdName) => (-1|0|1)
  7272. * ```
  7273. * @see COMMAND.LIST
  7274. */
  7275. queryCommandState: function (cmdName) {
  7276. return this._callCmdFn('queryCommandState', arguments);
  7277. },
  7278. /**
  7279. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7280. * @method queryCommandValue
  7281. * @param { String } cmdName 需要查询的命令名称
  7282. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7283. * @remind 只有部分插件有此方法
  7284. * @return { * } 返回每个命令特定的当前状态值
  7285. * @grammar editor.queryCommandValue(cmdName) => {*}
  7286. * @see COMMAND.LIST
  7287. */
  7288. queryCommandValue: function (cmdName) {
  7289. return this._callCmdFn('queryCommandValue', arguments);
  7290. },
  7291. /**
  7292. * 检查编辑区域中是否有内容
  7293. * @method hasContents
  7294. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7295. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7296. * @return { Boolean } 检查有内容返回true,否则返回false
  7297. * @example
  7298. * ```javascript
  7299. * editor.hasContents()
  7300. * ```
  7301. */
  7302. /**
  7303. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7304. * @method hasContents
  7305. * @param { Array } tags 传入数组判断时用到的节点类型
  7306. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7307. * @example
  7308. * ```javascript
  7309. * editor.hasContents(['span']);
  7310. * ```
  7311. */
  7312. hasContents: function (tags) {
  7313. if (tags) {
  7314. for (var i = 0, ci; ci = tags[i++];) {
  7315. if (this.document.getElementsByTagName(ci).length > 0) {
  7316. return true;
  7317. }
  7318. }
  7319. }
  7320. if (!domUtils.isEmptyBlock(this.body)) {
  7321. return true
  7322. }
  7323. //随时添加,定义的特殊标签如果存在,不能认为是空
  7324. tags = ['div'];
  7325. for (i = 0; ci = tags[i++];) {
  7326. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7327. for (var n = 0, cn; cn = nodes[n++];) {
  7328. if (domUtils.isCustomeNode(cn)) {
  7329. return true;
  7330. }
  7331. }
  7332. }
  7333. return false;
  7334. },
  7335. /**
  7336. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7337. * @method reset
  7338. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7339. * @example
  7340. * ```javascript
  7341. * editor.reset()
  7342. * ```
  7343. */
  7344. reset: function () {
  7345. this.fireEvent('reset');
  7346. },
  7347. /**
  7348. * 设置当前编辑区域可以编辑
  7349. * @method setEnabled
  7350. * @example
  7351. * ```javascript
  7352. * editor.setEnabled()
  7353. * ```
  7354. */
  7355. setEnabled: function () {
  7356. var me = this, range;
  7357. if (me.body.contentEditable == 'false') {
  7358. me.body.contentEditable = true;
  7359. range = me.selection.getRange();
  7360. //有可能内容丢失了
  7361. try {
  7362. range.moveToBookmark(me.lastBk);
  7363. delete me.lastBk
  7364. } catch (e) {
  7365. range.setStartAtFirst(me.body).collapse(true)
  7366. }
  7367. range.select(true);
  7368. if (me.bkqueryCommandState) {
  7369. me.queryCommandState = me.bkqueryCommandState;
  7370. delete me.bkqueryCommandState;
  7371. }
  7372. if (me.bkqueryCommandValue) {
  7373. me.queryCommandValue = me.bkqueryCommandValue;
  7374. delete me.bkqueryCommandValue;
  7375. }
  7376. me.fireEvent('selectionchange');
  7377. }
  7378. },
  7379. enable: function () {
  7380. return this.setEnabled();
  7381. },
  7382. /** 设置当前编辑区域不可编辑
  7383. * @method setDisabled
  7384. */
  7385. /** 设置当前编辑区域不可编辑,except中的命令除外
  7386. * @method setDisabled
  7387. * @param { String } except 例外命令的字符串
  7388. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7389. * @example
  7390. * ```javascript
  7391. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7392. * ```
  7393. */
  7394. /** 设置当前编辑区域不可编辑,except中的命令除外
  7395. * @method setDisabled
  7396. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7397. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7398. * @example
  7399. * ```javascript
  7400. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7401. * ```
  7402. */
  7403. setDisabled: function (except) {
  7404. var me = this;
  7405. except = except ? utils.isArray(except) ? except : [except] : [];
  7406. if (me.body.contentEditable == 'true') {
  7407. if (!me.lastBk) {
  7408. me.lastBk = me.selection.getRange().createBookmark(true);
  7409. }
  7410. me.body.contentEditable = false;
  7411. me.bkqueryCommandState = me.queryCommandState;
  7412. me.bkqueryCommandValue = me.queryCommandValue;
  7413. me.queryCommandState = function (type) {
  7414. if (utils.indexOf(except, type) != -1) {
  7415. return me.bkqueryCommandState.apply(me, arguments);
  7416. }
  7417. return -1;
  7418. };
  7419. me.queryCommandValue = function (type) {
  7420. if (utils.indexOf(except, type) != -1) {
  7421. return me.bkqueryCommandValue.apply(me, arguments);
  7422. }
  7423. return null;
  7424. };
  7425. me.fireEvent('selectionchange');
  7426. }
  7427. },
  7428. disable: function (except) {
  7429. return this.setDisabled(except);
  7430. },
  7431. /**
  7432. * 设置默认内容
  7433. * @method _setDefaultContent
  7434. * @private
  7435. * @param { String } cont 要存入的内容
  7436. */
  7437. _setDefaultContent: function () {
  7438. function clear() {
  7439. var me = this;
  7440. if (me.document.getElementById('initContent')) {
  7441. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7442. me.removeListener('firstBeforeExecCommand focus', clear);
  7443. setTimeout(function () {
  7444. me.focus();
  7445. me._selectionChange();
  7446. }, 0)
  7447. }
  7448. }
  7449. return function (cont) {
  7450. var me = this;
  7451. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7452. me.addListener('firstBeforeExecCommand focus', clear);
  7453. }
  7454. }(),
  7455. /**
  7456. * 显示编辑器
  7457. * @method setShow
  7458. * @example
  7459. * ```javascript
  7460. * editor.setShow()
  7461. * ```
  7462. */
  7463. setShow: function () {
  7464. var me = this, range = me.selection.getRange();
  7465. if (me.container.style.display == 'none') {
  7466. //有可能内容丢失了
  7467. try {
  7468. range.moveToBookmark(me.lastBk);
  7469. delete me.lastBk
  7470. } catch (e) {
  7471. range.setStartAtFirst(me.body).collapse(true)
  7472. }
  7473. //ie下focus实效,所以做了个延迟
  7474. setTimeout(function () {
  7475. range.select(true);
  7476. }, 100);
  7477. me.container.style.display = '';
  7478. }
  7479. },
  7480. show: function () {
  7481. return this.setShow();
  7482. },
  7483. /**
  7484. * 隐藏编辑器
  7485. * @method setHide
  7486. * @example
  7487. * ```javascript
  7488. * editor.setHide()
  7489. * ```
  7490. */
  7491. setHide: function () {
  7492. var me = this;
  7493. if (!me.lastBk) {
  7494. me.lastBk = me.selection.getRange().createBookmark(true);
  7495. }
  7496. me.container.style.display = 'none'
  7497. },
  7498. hide: function () {
  7499. return this.setHide();
  7500. },
  7501. /**
  7502. * 根据指定的路径,获取对应的语言资源
  7503. * @method getLang
  7504. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7505. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7506. * @example
  7507. * ```javascript
  7508. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7509. * ```
  7510. */
  7511. getLang: function (path) {
  7512. // HaoChuan9421
  7513. if(!this.options){
  7514. return '';
  7515. }
  7516. var lang = UE.I18N[this.options.lang];
  7517. if (!lang) {
  7518. throw Error("not import language file");
  7519. }
  7520. path = (path || "").split(".");
  7521. for (var i = 0, ci; ci = path[i++];) {
  7522. lang = lang[ci];
  7523. if (!lang)break;
  7524. }
  7525. return lang;
  7526. },
  7527. /**
  7528. * 计算编辑器html内容字符串的长度
  7529. * @method getContentLength
  7530. * @return { Number } 返回计算的长度
  7531. * @example
  7532. * ```javascript
  7533. * //编辑器html内容<p><strong>132</strong></p>
  7534. * editor.getContentLength() //返回27
  7535. * ```
  7536. */
  7537. /**
  7538. * 计算编辑器当前纯文本内容的长度
  7539. * @method getContentLength
  7540. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7541. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7542. * @example
  7543. * ```javascript
  7544. * //编辑器html内容<p><strong>132</strong></p>
  7545. * editor.getContentLength() //返回3
  7546. * ```
  7547. */
  7548. getContentLength: function (ingoneHtml, tagNames) {
  7549. var count = this.getContent(false,false,true).length;
  7550. if (ingoneHtml) {
  7551. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7552. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7553. for (var i = 0, ci; ci = tagNames[i++];) {
  7554. count += this.document.getElementsByTagName(ci).length;
  7555. }
  7556. }
  7557. return count;
  7558. },
  7559. /**
  7560. * 注册输入过滤规则
  7561. * @method addInputRule
  7562. * @param { Function } rule 要添加的过滤规则
  7563. * @example
  7564. * ```javascript
  7565. * editor.addInputRule(function(root){
  7566. * $.each(root.getNodesByTagName('div'),function(i,node){
  7567. * node.tagName="p";
  7568. * });
  7569. * });
  7570. * ```
  7571. */
  7572. addInputRule: function (rule) {
  7573. this.inputRules.push(rule);
  7574. },
  7575. /**
  7576. * 执行注册的过滤规则
  7577. * @method filterInputRule
  7578. * @param { UE.uNode } root 要过滤的uNode节点
  7579. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7580. * @example
  7581. * ```javascript
  7582. * editor.filterInputRule(editor.body);
  7583. * ```
  7584. * @see UE.Editor:addInputRule
  7585. */
  7586. filterInputRule: function (root) {
  7587. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7588. ci.call(this, root)
  7589. }
  7590. },
  7591. /**
  7592. * 注册输出过滤规则
  7593. * @method addOutputRule
  7594. * @param { Function } rule 要添加的过滤规则
  7595. * @example
  7596. * ```javascript
  7597. * editor.addOutputRule(function(root){
  7598. * $.each(root.getNodesByTagName('p'),function(i,node){
  7599. * node.tagName="div";
  7600. * });
  7601. * });
  7602. * ```
  7603. */
  7604. addOutputRule: function (rule) {
  7605. this.outputRules.push(rule)
  7606. },
  7607. /**
  7608. * 根据输出过滤规则,过滤编辑器内容
  7609. * @method filterOutputRule
  7610. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7611. * @param { UE.uNode } root 要过滤的uNode节点
  7612. * @example
  7613. * ```javascript
  7614. * editor.filterOutputRule(editor.body);
  7615. * ```
  7616. * @see UE.Editor:addOutputRule
  7617. */
  7618. filterOutputRule: function (root) {
  7619. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7620. ci.call(this, root)
  7621. }
  7622. },
  7623. /**
  7624. * 根据action名称获取请求的路径
  7625. * @method getActionUrl
  7626. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7627. * @param { String } action action名称
  7628. * @example
  7629. * ```javascript
  7630. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7631. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7632. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7633. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7634. * ```
  7635. */
  7636. getActionUrl: function(action){
  7637. var actionName = this.getOpt(action) || action,
  7638. imageUrl = this.getOpt('imageUrl'),
  7639. serverUrl = this.getOpt('serverUrl');
  7640. if(!serverUrl && imageUrl) {
  7641. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7642. }
  7643. if(serverUrl) {
  7644. serverUrl = serverUrl + (serverUrl.indexOf('?') == -1 ? '?':'&') + 'action=' + (actionName || '');
  7645. return utils.formatUrl(serverUrl);
  7646. } else {
  7647. return '';
  7648. }
  7649. }
  7650. };
  7651. utils.inherits(Editor, EventBase);
  7652. })();
  7653. // core/Editor.defaultoptions.js
  7654. //维护编辑器一下默认的不在插件中的配置项
  7655. UE.Editor.defaultOptions = function(editor){
  7656. var _url = editor.options.UEDITOR_HOME_URL;
  7657. return {
  7658. isShow: true,
  7659. initialContent: '',
  7660. initialStyle:'',
  7661. autoClearinitialContent: false,
  7662. iframeCssUrl: _url + 'themes/iframe.css',
  7663. textarea: 'editorValue',
  7664. focus: false,
  7665. focusInEnd: true,
  7666. autoClearEmptyNode: true,
  7667. fullscreen: false,
  7668. readonly: false,
  7669. zIndex: 999,
  7670. imagePopup: true,
  7671. enterTag: 'p',
  7672. customDomain: false,
  7673. lang: 'zh-cn',
  7674. langPath: _url + 'lang/',
  7675. theme: 'default',
  7676. themePath: _url + 'themes/',
  7677. allHtmlEnabled: false,
  7678. scaleEnabled: false,
  7679. tableNativeEditInFF: false,
  7680. autoSyncData : true,
  7681. fileNameFormat: '{time}{rand:6}'
  7682. }
  7683. };
  7684. // core/loadconfig.js
  7685. (function(){
  7686. UE.Editor.prototype.loadServerConfig = function(){
  7687. var me = this;
  7688. setTimeout(function(){
  7689. try{
  7690. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  7691. var configUrl = me.getActionUrl('config'),
  7692. isJsonp = utils.isCrossDomainUrl(configUrl);
  7693. /* 发出ajax请求 */
  7694. me._serverConfigLoaded = false;
  7695. configUrl && UE.ajax.request(configUrl,{
  7696. 'method': 'GET',
  7697. 'dataType': isJsonp ? 'jsonp':'',
  7698. 'onsuccess':function(r){
  7699. try {
  7700. var config = isJsonp ? r:eval("("+r.responseText+")");
  7701. utils.extend(me.options, config);
  7702. me.fireEvent('serverConfigLoaded');
  7703. me._serverConfigLoaded = true;
  7704. } catch (e) {
  7705. showErrorMsg(me.getLang('loadconfigFormatError'));
  7706. }
  7707. },
  7708. 'onerror':function(){
  7709. showErrorMsg(me.getLang('loadconfigHttpError'));
  7710. }
  7711. });
  7712. } catch(e){
  7713. showErrorMsg(me.getLang('loadconfigError'));
  7714. }
  7715. });
  7716. function showErrorMsg(msg) {
  7717. console && console.error(msg);
  7718. //me.fireEvent('showMessage', {
  7719. // 'title': msg,
  7720. // 'type': 'error'
  7721. //});
  7722. }
  7723. };
  7724. UE.Editor.prototype.isServerConfigLoaded = function(){
  7725. var me = this;
  7726. return me._serverConfigLoaded || false;
  7727. };
  7728. UE.Editor.prototype.afterConfigReady = function(handler){
  7729. if (!handler || !utils.isFunction(handler)) return;
  7730. var me = this;
  7731. var readyHandler = function(){
  7732. handler.apply(me, arguments);
  7733. me.removeListener('serverConfigLoaded', readyHandler);
  7734. };
  7735. if (me.isServerConfigLoaded()) {
  7736. handler.call(me, 'serverConfigLoaded');
  7737. } else {
  7738. me.addListener('serverConfigLoaded', readyHandler);
  7739. }
  7740. };
  7741. })();
  7742. // core/ajax.js
  7743. /**
  7744. * @file
  7745. * @module UE.ajax
  7746. * @since 1.2.6.1
  7747. */
  7748. /**
  7749. * 提供对ajax请求的支持
  7750. * @module UE.ajax
  7751. */
  7752. UE.ajax = function() {
  7753. //创建一个ajaxRequest对象
  7754. var fnStr = 'XMLHttpRequest()';
  7755. try {
  7756. new ActiveXObject("Msxml2.XMLHTTP");
  7757. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7758. } catch (e) {
  7759. try {
  7760. new ActiveXObject("Microsoft.XMLHTTP");
  7761. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7762. } catch (e) {
  7763. }
  7764. }
  7765. var creatAjaxRequest = new Function('return new ' + fnStr);
  7766. /**
  7767. * 将json参数转化成适合ajax提交的参数列表
  7768. * @param json
  7769. */
  7770. function json2str(json) {
  7771. var strArr = [];
  7772. for (var i in json) {
  7773. //忽略默认的几个参数
  7774. if(i=="method" || i=="timeout" || i=="async" || i=="dataType" || i=="callback") continue;
  7775. //忽略控制
  7776. if(json[i] == undefined || json[i] == null) continue;
  7777. //传递过来的对象和函数不在提交之列
  7778. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7779. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7780. } else if (utils.isArray(json[i])) {
  7781. //支持传数组内容
  7782. for(var j = 0; j < json[i].length; j++) {
  7783. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  7784. }
  7785. }
  7786. }
  7787. return strArr.join("&");
  7788. }
  7789. function doAjax(url, ajaxOptions) {
  7790. var xhr = creatAjaxRequest(),
  7791. //是否超时
  7792. timeIsOut = false,
  7793. //默认参数
  7794. defaultAjaxOptions = {
  7795. method:"POST",
  7796. timeout:5000,
  7797. async:true,
  7798. data:{},//需要传递对象的话只能覆盖
  7799. onsuccess:function() {
  7800. },
  7801. onerror:function() {
  7802. }
  7803. };
  7804. if (typeof url === "object") {
  7805. ajaxOptions = url;
  7806. url = ajaxOptions.url;
  7807. }
  7808. if (!xhr || !url) return;
  7809. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7810. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7811. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7812. if (!utils.isEmptyObject(ajaxOpts.data)){
  7813. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7814. }
  7815. //超时检测
  7816. var timerID = setTimeout(function() {
  7817. if (xhr.readyState != 4) {
  7818. timeIsOut = true;
  7819. xhr.abort();
  7820. clearTimeout(timerID);
  7821. }
  7822. }, ajaxOpts.timeout);
  7823. var method = ajaxOpts.method.toUpperCase();
  7824. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7825. xhr.open(method, str, ajaxOpts.async);
  7826. xhr.onreadystatechange = function() {
  7827. if (xhr.readyState == 4) {
  7828. if (!timeIsOut && xhr.status == 200) {
  7829. ajaxOpts.onsuccess(xhr);
  7830. } else {
  7831. ajaxOpts.onerror(xhr);
  7832. }
  7833. }
  7834. };
  7835. if (method == "POST") {
  7836. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7837. xhr.send(submitStr);
  7838. } else {
  7839. xhr.send(null);
  7840. }
  7841. }
  7842. function doJsonp(url, opts) {
  7843. var successhandler = opts.onsuccess || function(){},
  7844. scr = document.createElement('SCRIPT'),
  7845. options = opts || {},
  7846. charset = options['charset'],
  7847. callbackField = options['jsonp'] || 'callback',
  7848. callbackFnName,
  7849. timeOut = options['timeOut'] || 0,
  7850. timer,
  7851. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  7852. matches;
  7853. if (utils.isFunction(successhandler)) {
  7854. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  7855. window[callbackFnName] = getCallBack(0);
  7856. } else if(utils.isString(successhandler)){
  7857. callbackFnName = successhandler;
  7858. } else {
  7859. if (matches = reg.exec(url)) {
  7860. callbackFnName = matches[2];
  7861. }
  7862. }
  7863. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  7864. if (url.search(reg) < 0) {
  7865. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  7866. }
  7867. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7868. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7869. if (!utils.isEmptyObject(opts.data)){
  7870. queryStr += (queryStr? "&":"") + json2str(opts.data);
  7871. }
  7872. if (queryStr) {
  7873. url = url.replace(/\?/, '?' + queryStr + '&');
  7874. }
  7875. scr.onerror = getCallBack(1);
  7876. if( timeOut ){
  7877. timer = setTimeout(getCallBack(1), timeOut);
  7878. }
  7879. createScriptTag(scr, url, charset);
  7880. function createScriptTag(scr, url, charset) {
  7881. scr.setAttribute('type', 'text/javascript');
  7882. scr.setAttribute('defer', 'defer');
  7883. charset && scr.setAttribute('charset', charset);
  7884. scr.setAttribute('src', url);
  7885. document.getElementsByTagName('head')[0].appendChild(scr);
  7886. }
  7887. function getCallBack(onTimeOut){
  7888. return function(){
  7889. try {
  7890. if(onTimeOut){
  7891. options.onerror && options.onerror();
  7892. }else{
  7893. try{
  7894. clearTimeout(timer);
  7895. successhandler.apply(window, arguments);
  7896. } catch (e){}
  7897. }
  7898. } catch (exception) {
  7899. options.onerror && options.onerror.call(window, exception);
  7900. } finally {
  7901. options.oncomplete && options.oncomplete.apply(window, arguments);
  7902. scr.parentNode && scr.parentNode.removeChild(scr);
  7903. window[callbackFnName] = null;
  7904. try {
  7905. delete window[callbackFnName];
  7906. }catch(e){}
  7907. }
  7908. }
  7909. }
  7910. }
  7911. return {
  7912. /**
  7913. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7914. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7915. * @method request
  7916. * @param { URLString } url ajax请求的url地址
  7917. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7918. * @example
  7919. * ```javascript
  7920. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7921. * UE.ajax.requeset( 'sayhello.php', {
  7922. *
  7923. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7924. * method: 'GET',
  7925. *
  7926. * //超时时间。 默认为5000, 单位是ms
  7927. * timeout: 10000,
  7928. *
  7929. * //是否是异步请求。 true为异步请求, false为同步请求
  7930. * async: true,
  7931. *
  7932. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7933. * data: {
  7934. * name: 'ueditor'
  7935. * },
  7936. *
  7937. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7938. * onsuccess: function ( xhr ) {
  7939. * console.log( xhr.responseText );
  7940. * },
  7941. *
  7942. * //请求失败或者超时后的回调。
  7943. * onerror: function ( xhr ) {
  7944. * alert( 'Ajax请求失败' );
  7945. * }
  7946. *
  7947. * } );
  7948. * ```
  7949. */
  7950. /**
  7951. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7952. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7953. * @method request
  7954. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7955. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7956. * @example
  7957. * ```javascript
  7958. *
  7959. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7960. * UE.ajax.requeset( 'sayhello.php', {
  7961. *
  7962. * //请求的地址, 该项是必须的。
  7963. * url: 'sayhello.php'
  7964. *
  7965. * } );
  7966. * ```
  7967. */
  7968. request:function(url, opts) {
  7969. if (opts && opts.dataType == 'jsonp') {
  7970. doJsonp(url, opts);
  7971. } else {
  7972. doAjax(url, opts);
  7973. }
  7974. },
  7975. getJSONP:function(url, data, fn) {
  7976. var opts = {
  7977. 'data': data,
  7978. 'oncomplete': fn
  7979. };
  7980. doJsonp(url, opts);
  7981. }
  7982. };
  7983. }();
  7984. // core/filterword.js
  7985. /**
  7986. * UE过滤word的静态方法
  7987. * @file
  7988. */
  7989. /**
  7990. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7991. * @module UE
  7992. */
  7993. /**
  7994. * 根据传入html字符串过滤word
  7995. * @module UE
  7996. * @since 1.2.6.1
  7997. * @method filterWord
  7998. * @param { String } html html字符串
  7999. * @return { String } 已过滤后的结果字符串
  8000. * @example
  8001. * ```javascript
  8002. * UE.filterWord(html);
  8003. * ```
  8004. */
  8005. var filterWord = UE.filterWord = function () {
  8006. //是否是word过来的内容
  8007. function isWordDocument( str ) {
  8008. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  8009. }
  8010. //去掉小数
  8011. function transUnit( v ) {
  8012. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  8013. return utils.transUnitToPx(m);
  8014. } );
  8015. return v;
  8016. }
  8017. function filterPasteWord( str ) {
  8018. return str.replace(/[\t\r\n]+/g,' ')
  8019. .replace( /<!--[\s\S]*?-->/ig, "" )
  8020. //转换图片
  8021. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  8022. //opera能自己解析出image所这里直接返回空
  8023. if(browser.opera){
  8024. return '';
  8025. }
  8026. try{
  8027. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  8028. if(/Bitmap/i.test(str)){
  8029. return '';
  8030. }
  8031. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  8032. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  8033. src = str.match(/src=\s*"([^"]*)"/i)[1];
  8034. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  8035. } catch(e){
  8036. return '';
  8037. }
  8038. })
  8039. //针对wps添加的多余标签处理
  8040. .replace(/<\/?div[^>]*>/g,'')
  8041. //去掉多余的属性
  8042. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  8043. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  8044. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  8045. //去掉多余的属性
  8046. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  8047. //保留list的标示
  8048. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8049. })
  8050. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8051. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  8052. return c.replace(/[\t\r\n ]+/g,' ')
  8053. })
  8054. //处理style的问题
  8055. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  8056. var n = [],
  8057. s = style.replace( /^\s+|\s+$/, '' )
  8058. .replace(/&#39;/g,'\'')
  8059. .replace( /&quot;/gi, "'" )
  8060. .replace(/[\d.]+(cm|pt)/g,function(str){
  8061. return utils.transUnitToPx(str)
  8062. })
  8063. .split( /;\s*/g );
  8064. for ( var i = 0,v; v = s[i];i++ ) {
  8065. var name, value,
  8066. parts = v.split( ":" );
  8067. if ( parts.length == 2 ) {
  8068. name = parts[0].toLowerCase();
  8069. value = parts[1].toLowerCase();
  8070. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  8071. ||
  8072. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8073. ){
  8074. continue;
  8075. }
  8076. switch ( name ) {
  8077. case "mso-padding-alt":
  8078. case "mso-padding-top-alt":
  8079. case "mso-padding-right-alt":
  8080. case "mso-padding-bottom-alt":
  8081. case "mso-padding-left-alt":
  8082. case "mso-margin-alt":
  8083. case "mso-margin-top-alt":
  8084. case "mso-margin-right-alt":
  8085. case "mso-margin-bottom-alt":
  8086. case "mso-margin-left-alt":
  8087. //ie下会出现挤到一起的情况
  8088. //case "mso-table-layout-alt":
  8089. case "mso-height":
  8090. case "mso-width":
  8091. case "mso-vertical-align-alt":
  8092. //trace:1819 ff下会解析出padding在table上
  8093. if(!/<table/.test(tag))
  8094. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  8095. continue;
  8096. case "horiz-align":
  8097. n[i] = "text-align:" + value;
  8098. continue;
  8099. case "vert-align":
  8100. n[i] = "vertical-align:" + value;
  8101. continue;
  8102. case "font-color":
  8103. case "mso-foreground":
  8104. n[i] = "color:" + value;
  8105. continue;
  8106. case "mso-background":
  8107. case "mso-highlight":
  8108. n[i] = "background:" + value;
  8109. continue;
  8110. case "mso-default-height":
  8111. n[i] = "min-height:" + transUnit( value );
  8112. continue;
  8113. case "mso-default-width":
  8114. n[i] = "min-width:" + transUnit( value );
  8115. continue;
  8116. case "mso-padding-between-alt":
  8117. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  8118. continue;
  8119. case "text-line-through":
  8120. if ( (value == "single") || (value == "double") ) {
  8121. n[i] = "text-decoration:line-through";
  8122. }
  8123. continue;
  8124. case "mso-zero-height":
  8125. if ( value == "yes" ) {
  8126. n[i] = "display:none";
  8127. }
  8128. continue;
  8129. // case 'background':
  8130. // break;
  8131. case 'margin':
  8132. if ( !/[1-9]/.test( value ) ) {
  8133. continue;
  8134. }
  8135. }
  8136. 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 )
  8137. ||
  8138. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8139. ) {
  8140. continue;
  8141. }
  8142. n[i] = name + ":" + parts[1];
  8143. }
  8144. }
  8145. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  8146. })
  8147. }
  8148. return function ( html ) {
  8149. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  8150. };
  8151. }();
  8152. // core/node.js
  8153. /**
  8154. * 编辑器模拟的节点类
  8155. * @file
  8156. * @module UE
  8157. * @class uNode
  8158. * @since 1.2.6.1
  8159. */
  8160. /**
  8161. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8162. * @unfile
  8163. * @module UE
  8164. */
  8165. (function () {
  8166. /**
  8167. * 编辑器模拟的节点类
  8168. * @unfile
  8169. * @module UE
  8170. * @class uNode
  8171. */
  8172. /**
  8173. * 通过一个键值对,创建一个uNode对象
  8174. * @constructor
  8175. * @param { Object } attr 传入要创建的uNode的初始属性
  8176. * @example
  8177. * ```javascript
  8178. * var node = new uNode({
  8179. * type:'element',
  8180. * tagName:'span',
  8181. * attrs:{style:'font-size:14px;'}
  8182. * }
  8183. * ```
  8184. */
  8185. var uNode = UE.uNode = function (obj) {
  8186. this.type = obj.type;
  8187. this.data = obj.data;
  8188. this.tagName = obj.tagName;
  8189. this.parentNode = obj.parentNode;
  8190. this.attrs = obj.attrs || {};
  8191. this.children = obj.children;
  8192. };
  8193. var notTransAttrs = {
  8194. 'href':1,
  8195. 'src':1,
  8196. '_src':1,
  8197. '_href':1,
  8198. 'cdata_data':1
  8199. };
  8200. var notTransTagName = {
  8201. style:1,
  8202. script:1
  8203. };
  8204. var indentChar = ' ',
  8205. breakChar = '\n';
  8206. function insertLine(arr, current, begin) {
  8207. arr.push(breakChar);
  8208. return current + (begin ? 1 : -1);
  8209. }
  8210. function insertIndent(arr, current) {
  8211. //插入缩进
  8212. for (var i = 0; i < current; i++) {
  8213. arr.push(indentChar);
  8214. }
  8215. }
  8216. //创建uNode的静态方法
  8217. //支持标签和html
  8218. uNode.createElement = function (html) {
  8219. if (/[<>]/.test(html)) {
  8220. return UE.htmlparser(html).children[0]
  8221. } else {
  8222. return new uNode({
  8223. type:'element',
  8224. children:[],
  8225. tagName:html
  8226. })
  8227. }
  8228. };
  8229. uNode.createText = function (data,noTrans) {
  8230. return new UE.uNode({
  8231. type:'text',
  8232. 'data':noTrans ? data : utils.unhtml(data || '')
  8233. })
  8234. };
  8235. function nodeToHtml(node, arr, formatter, current) {
  8236. switch (node.type) {
  8237. case 'root':
  8238. for (var i = 0, ci; ci = node.children[i++];) {
  8239. //插入新行
  8240. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8241. insertLine(arr, current, true);
  8242. insertIndent(arr, current)
  8243. }
  8244. nodeToHtml(ci, arr, formatter, current)
  8245. }
  8246. break;
  8247. case 'text':
  8248. isText(node, arr);
  8249. break;
  8250. case 'element':
  8251. isElement(node, arr, formatter, current);
  8252. break;
  8253. case 'comment':
  8254. isComment(node, arr, formatter);
  8255. }
  8256. return arr;
  8257. }
  8258. function isText(node, arr) {
  8259. if(node.parentNode.tagName == 'pre'){
  8260. //源码模式下输入html标签,不能做转换处理,直接输出
  8261. arr.push(node.data)
  8262. }else{
  8263. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  8264. }
  8265. }
  8266. function isElement(node, arr, formatter, current) {
  8267. var attrhtml = '';
  8268. if (node.attrs) {
  8269. attrhtml = [];
  8270. var attrs = node.attrs;
  8271. for (var a in attrs) {
  8272. //这里就针对
  8273. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8274. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8275. //有可能做的不够
  8276. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8277. return '&quot;'
  8278. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8279. }
  8280. attrhtml = attrhtml.join(' ');
  8281. }
  8282. arr.push('<' + node.tagName +
  8283. (attrhtml ? ' ' + attrhtml : '') +
  8284. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  8285. );
  8286. //插入新行
  8287. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8288. if(node.children && node.children.length){
  8289. current = insertLine(arr, current, true);
  8290. insertIndent(arr, current)
  8291. }
  8292. }
  8293. if (node.children && node.children.length) {
  8294. for (var i = 0, ci; ci = node.children[i++];) {
  8295. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8296. insertLine(arr, current);
  8297. insertIndent(arr, current)
  8298. }
  8299. nodeToHtml(ci, arr, formatter, current)
  8300. }
  8301. }
  8302. if (!dtd.$empty[node.tagName]) {
  8303. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8304. if(node.children && node.children.length){
  8305. current = insertLine(arr, current);
  8306. insertIndent(arr, current)
  8307. }
  8308. }
  8309. arr.push('<\/' + node.tagName + '>');
  8310. }
  8311. }
  8312. function isComment(node, arr) {
  8313. arr.push('<!--' + node.data + '-->');
  8314. }
  8315. function getNodeById(root, id) {
  8316. var node;
  8317. if (root.type == 'element' && root.getAttr('id') == id) {
  8318. return root;
  8319. }
  8320. if (root.children && root.children.length) {
  8321. for (var i = 0, ci; ci = root.children[i++];) {
  8322. if (node = getNodeById(ci, id)) {
  8323. return node;
  8324. }
  8325. }
  8326. }
  8327. }
  8328. function getNodesByTagName(node, tagName, arr) {
  8329. if (node.type == 'element' && node.tagName == tagName) {
  8330. arr.push(node);
  8331. }
  8332. if (node.children && node.children.length) {
  8333. for (var i = 0, ci; ci = node.children[i++];) {
  8334. getNodesByTagName(ci, tagName, arr)
  8335. }
  8336. }
  8337. }
  8338. function nodeTraversal(root,fn){
  8339. if(root.children && root.children.length){
  8340. for(var i= 0,ci;ci=root.children[i];){
  8341. nodeTraversal(ci,fn);
  8342. //ci被替换的情况,这里就不再走 fn了
  8343. if(ci.parentNode ){
  8344. if(ci.children && ci.children.length){
  8345. fn(ci)
  8346. }
  8347. if(ci.parentNode) i++
  8348. }
  8349. }
  8350. }else{
  8351. fn(root)
  8352. }
  8353. }
  8354. uNode.prototype = {
  8355. /**
  8356. * 当前节点对象,转换成html文本
  8357. * @method toHtml
  8358. * @return { String } 返回转换后的html字符串
  8359. * @example
  8360. * ```javascript
  8361. * node.toHtml();
  8362. * ```
  8363. */
  8364. /**
  8365. * 当前节点对象,转换成html文本
  8366. * @method toHtml
  8367. * @param { Boolean } formatter 是否格式化返回值
  8368. * @return { String } 返回转换后的html字符串
  8369. * @example
  8370. * ```javascript
  8371. * node.toHtml( true );
  8372. * ```
  8373. */
  8374. toHtml:function (formatter) {
  8375. var arr = [];
  8376. nodeToHtml(this, arr, formatter, 0);
  8377. return arr.join('')
  8378. },
  8379. /**
  8380. * 获取节点的html内容
  8381. * @method innerHTML
  8382. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8383. * @return { String } 返回节点的html内容
  8384. * @example
  8385. * ```javascript
  8386. * var htmlstr = node.innerHTML();
  8387. * ```
  8388. */
  8389. /**
  8390. * 设置节点的html内容
  8391. * @method innerHTML
  8392. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8393. * @param { String } htmlstr 传入要设置的html内容
  8394. * @return { UE.uNode } 返回节点本身
  8395. * @example
  8396. * ```javascript
  8397. * node.innerHTML('<span>text</span>');
  8398. * ```
  8399. */
  8400. innerHTML:function (htmlstr) {
  8401. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8402. return this;
  8403. }
  8404. if (utils.isString(htmlstr)) {
  8405. if(this.children){
  8406. for (var i = 0, ci; ci = this.children[i++];) {
  8407. ci.parentNode = null;
  8408. }
  8409. }
  8410. this.children = [];
  8411. var tmpRoot = UE.htmlparser(htmlstr);
  8412. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8413. this.children.push(ci);
  8414. ci.parentNode = this;
  8415. }
  8416. return this;
  8417. } else {
  8418. var tmpRoot = new UE.uNode({
  8419. type:'root',
  8420. children:this.children
  8421. });
  8422. return tmpRoot.toHtml();
  8423. }
  8424. },
  8425. /**
  8426. * 获取节点的纯文本内容
  8427. * @method innerText
  8428. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8429. * @return { String } 返回节点的存文本内容
  8430. * @example
  8431. * ```javascript
  8432. * var textStr = node.innerText();
  8433. * ```
  8434. */
  8435. /**
  8436. * 设置节点的纯文本内容
  8437. * @method innerText
  8438. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8439. * @param { String } textStr 传入要设置的文本内容
  8440. * @return { UE.uNode } 返回节点本身
  8441. * @example
  8442. * ```javascript
  8443. * node.innerText('<span>text</span>');
  8444. * ```
  8445. */
  8446. innerText:function (textStr,noTrans) {
  8447. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8448. return this;
  8449. }
  8450. if (textStr) {
  8451. if(this.children){
  8452. for (var i = 0, ci; ci = this.children[i++];) {
  8453. ci.parentNode = null;
  8454. }
  8455. }
  8456. this.children = [];
  8457. this.appendChild(uNode.createText(textStr,noTrans));
  8458. return this;
  8459. } else {
  8460. return this.toHtml().replace(/<[^>]+>/g, '');
  8461. }
  8462. },
  8463. /**
  8464. * 获取当前对象的data属性
  8465. * @method getData
  8466. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8467. * @example
  8468. * ```javascript
  8469. * node.getData();
  8470. * ```
  8471. */
  8472. getData:function () {
  8473. if (this.type == 'element')
  8474. return '';
  8475. return this.data
  8476. },
  8477. /**
  8478. * 获取当前节点下的第一个子节点
  8479. * @method firstChild
  8480. * @return { UE.uNode } 返回第一个子节点
  8481. * @example
  8482. * ```javascript
  8483. * node.firstChild(); //返回第一个子节点
  8484. * ```
  8485. */
  8486. firstChild:function () {
  8487. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8488. // return this;
  8489. // }
  8490. return this.children ? this.children[0] : null;
  8491. },
  8492. /**
  8493. * 获取当前节点下的最后一个子节点
  8494. * @method lastChild
  8495. * @return { UE.uNode } 返回最后一个子节点
  8496. * @example
  8497. * ```javascript
  8498. * node.lastChild(); //返回最后一个子节点
  8499. * ```
  8500. */
  8501. lastChild:function () {
  8502. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8503. // return this;
  8504. // }
  8505. return this.children ? this.children[this.children.length - 1] : null;
  8506. },
  8507. /**
  8508. * 获取和当前节点有相同父亲节点的前一个节点
  8509. * @method previousSibling
  8510. * @return { UE.uNode } 返回前一个节点
  8511. * @example
  8512. * ```javascript
  8513. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8514. * ```
  8515. */
  8516. previousSibling : function(){
  8517. var parent = this.parentNode;
  8518. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8519. if (ci === this) {
  8520. return i == 0 ? null : parent.children[i-1];
  8521. }
  8522. }
  8523. },
  8524. /**
  8525. * 获取和当前节点有相同父亲节点的后一个节点
  8526. * @method nextSibling
  8527. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8528. * @example
  8529. * ```javascript
  8530. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8531. * ```
  8532. */
  8533. nextSibling : function(){
  8534. var parent = this.parentNode;
  8535. for (var i = 0, ci; ci = parent.children[i++];) {
  8536. if (ci === this) {
  8537. return parent.children[i];
  8538. }
  8539. }
  8540. },
  8541. /**
  8542. * 用新的节点替换当前节点
  8543. * @method replaceChild
  8544. * @param { UE.uNode } target 要替换成该节点参数
  8545. * @param { UE.uNode } source 要被替换掉的节点
  8546. * @return { UE.uNode } 返回替换之后的节点对象
  8547. * @example
  8548. * ```javascript
  8549. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8550. * ```
  8551. */
  8552. replaceChild:function (target, source) {
  8553. if (this.children) {
  8554. if(target.parentNode){
  8555. target.parentNode.removeChild(target);
  8556. }
  8557. for (var i = 0, ci; ci = this.children[i]; i++) {
  8558. if (ci === source) {
  8559. this.children.splice(i, 1, target);
  8560. source.parentNode = null;
  8561. target.parentNode = this;
  8562. return target;
  8563. }
  8564. }
  8565. }
  8566. },
  8567. /**
  8568. * 在节点的子节点列表最后位置插入一个节点
  8569. * @method appendChild
  8570. * @param { UE.uNode } node 要插入的节点
  8571. * @return { UE.uNode } 返回刚插入的子节点
  8572. * @example
  8573. * ```javascript
  8574. * node.appendChild( newNode ); //在node内插入子节点newNode
  8575. * ```
  8576. */
  8577. appendChild:function (node) {
  8578. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8579. if (!this.children) {
  8580. this.children = []
  8581. }
  8582. if(node.parentNode){
  8583. node.parentNode.removeChild(node);
  8584. }
  8585. for (var i = 0, ci; ci = this.children[i]; i++) {
  8586. if (ci === node) {
  8587. this.children.splice(i, 1);
  8588. break;
  8589. }
  8590. }
  8591. this.children.push(node);
  8592. node.parentNode = this;
  8593. return node;
  8594. }
  8595. },
  8596. /**
  8597. * 在传入节点的前面插入一个节点
  8598. * @method insertBefore
  8599. * @param { UE.uNode } target 要插入的节点
  8600. * @param { UE.uNode } source 在该参数节点前面插入
  8601. * @return { UE.uNode } 返回刚插入的子节点
  8602. * @example
  8603. * ```javascript
  8604. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8605. * ```
  8606. */
  8607. insertBefore:function (target, source) {
  8608. if (this.children) {
  8609. if(target.parentNode){
  8610. target.parentNode.removeChild(target);
  8611. }
  8612. for (var i = 0, ci; ci = this.children[i]; i++) {
  8613. if (ci === source) {
  8614. this.children.splice(i, 0, target);
  8615. target.parentNode = this;
  8616. return target;
  8617. }
  8618. }
  8619. }
  8620. },
  8621. /**
  8622. * 在传入节点的后面插入一个节点
  8623. * @method insertAfter
  8624. * @param { UE.uNode } target 要插入的节点
  8625. * @param { UE.uNode } source 在该参数节点后面插入
  8626. * @return { UE.uNode } 返回刚插入的子节点
  8627. * @example
  8628. * ```javascript
  8629. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8630. * ```
  8631. */
  8632. insertAfter:function (target, source) {
  8633. if (this.children) {
  8634. if(target.parentNode){
  8635. target.parentNode.removeChild(target);
  8636. }
  8637. for (var i = 0, ci; ci = this.children[i]; i++) {
  8638. if (ci === source) {
  8639. this.children.splice(i + 1, 0, target);
  8640. target.parentNode = this;
  8641. return target;
  8642. }
  8643. }
  8644. }
  8645. },
  8646. /**
  8647. * 从当前节点的子节点列表中,移除节点
  8648. * @method removeChild
  8649. * @param { UE.uNode } node 要移除的节点引用
  8650. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8651. * @return { * } 返回刚移除的子节点
  8652. * @example
  8653. * ```javascript
  8654. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8655. * ```
  8656. */
  8657. removeChild:function (node,keepChildren) {
  8658. if (this.children) {
  8659. for (var i = 0, ci; ci = this.children[i]; i++) {
  8660. if (ci === node) {
  8661. this.children.splice(i, 1);
  8662. ci.parentNode = null;
  8663. if(keepChildren && ci.children && ci.children.length){
  8664. for(var j= 0,cj;cj=ci.children[j];j++){
  8665. this.children.splice(i+j,0,cj);
  8666. cj.parentNode = this;
  8667. }
  8668. }
  8669. return ci;
  8670. }
  8671. }
  8672. }
  8673. },
  8674. /**
  8675. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8676. * @method getAttr
  8677. * @param { String } attrName 要获取的属性名称
  8678. * @return { * } 返回attrs对象下的属性值
  8679. * @example
  8680. * ```javascript
  8681. * node.getAttr('title');
  8682. * ```
  8683. */
  8684. getAttr:function (attrName) {
  8685. return this.attrs && this.attrs[attrName.toLowerCase()]
  8686. },
  8687. /**
  8688. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8689. * @method setAttr
  8690. * @param { String } attrName 要设置的属性名称
  8691. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8692. * @return { * } 返回attrs对象下的属性值
  8693. * @example
  8694. * ```javascript
  8695. * node.setAttr('title','标题');
  8696. * ```
  8697. */
  8698. setAttr:function (attrName, attrVal) {
  8699. if (!attrName) {
  8700. delete this.attrs;
  8701. return;
  8702. }
  8703. if(!this.attrs){
  8704. this.attrs = {};
  8705. }
  8706. if (utils.isObject(attrName)) {
  8707. for (var a in attrName) {
  8708. if (!attrName[a]) {
  8709. delete this.attrs[a]
  8710. } else {
  8711. this.attrs[a.toLowerCase()] = attrName[a];
  8712. }
  8713. }
  8714. } else {
  8715. if (!attrVal) {
  8716. delete this.attrs[attrName]
  8717. } else {
  8718. this.attrs[attrName.toLowerCase()] = attrVal;
  8719. }
  8720. }
  8721. },
  8722. /**
  8723. * 获取当前节点在父节点下的位置索引
  8724. * @method getIndex
  8725. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8726. * @example
  8727. * ```javascript
  8728. * node.getIndex();
  8729. * ```
  8730. */
  8731. getIndex:function(){
  8732. var parent = this.parentNode;
  8733. for(var i= 0,ci;ci=parent.children[i];i++){
  8734. if(ci === this){
  8735. return i;
  8736. }
  8737. }
  8738. return -1;
  8739. },
  8740. /**
  8741. * 在当前节点下,根据id查找节点
  8742. * @method getNodeById
  8743. * @param { String } id 要查找的id
  8744. * @return { UE.uNode } 返回找到的节点
  8745. * @example
  8746. * ```javascript
  8747. * node.getNodeById('textId');
  8748. * ```
  8749. */
  8750. getNodeById:function (id) {
  8751. var node;
  8752. if (this.children && this.children.length) {
  8753. for (var i = 0, ci; ci = this.children[i++];) {
  8754. if (node = getNodeById(ci, id)) {
  8755. return node;
  8756. }
  8757. }
  8758. }
  8759. },
  8760. /**
  8761. * 在当前节点下,根据元素名称查找节点列表
  8762. * @method getNodesByTagName
  8763. * @param { String } tagNames 要查找的元素名称
  8764. * @return { Array } 返回找到的节点列表
  8765. * @example
  8766. * ```javascript
  8767. * node.getNodesByTagName('span');
  8768. * ```
  8769. */
  8770. getNodesByTagName:function (tagNames) {
  8771. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8772. var arr = [], me = this;
  8773. utils.each(tagNames, function (tagName) {
  8774. if (me.children && me.children.length) {
  8775. for (var i = 0, ci; ci = me.children[i++];) {
  8776. getNodesByTagName(ci, tagName, arr)
  8777. }
  8778. }
  8779. });
  8780. return arr;
  8781. },
  8782. /**
  8783. * 根据样式名称,获取节点的样式值
  8784. * @method getStyle
  8785. * @param { String } name 要获取的样式名称
  8786. * @return { String } 返回样式值
  8787. * @example
  8788. * ```javascript
  8789. * node.getStyle('font-size');
  8790. * ```
  8791. */
  8792. getStyle:function (name) {
  8793. var cssStyle = this.getAttr('style');
  8794. if (!cssStyle) {
  8795. return ''
  8796. }
  8797. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8798. var match = cssStyle.match(reg);
  8799. if (match && match[0]) {
  8800. return match[2]
  8801. }
  8802. return '';
  8803. },
  8804. /**
  8805. * 给节点设置样式
  8806. * @method setStyle
  8807. * @param { String } name 要设置的的样式名称
  8808. * @param { String } val 要设置的的样值
  8809. * @example
  8810. * ```javascript
  8811. * node.setStyle('font-size', '12px');
  8812. * ```
  8813. */
  8814. setStyle:function (name, val) {
  8815. function exec(name, val) {
  8816. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8817. cssStyle = cssStyle.replace(reg, '$1');
  8818. if (val) {
  8819. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8820. }
  8821. }
  8822. var cssStyle = this.getAttr('style');
  8823. if (!cssStyle) {
  8824. cssStyle = '';
  8825. }
  8826. if (utils.isObject(name)) {
  8827. for (var a in name) {
  8828. exec(a, name[a])
  8829. }
  8830. } else {
  8831. exec(name, val)
  8832. }
  8833. this.setAttr('style', utils.trim(cssStyle))
  8834. },
  8835. /**
  8836. * 传入一个函数,递归遍历当前节点下的所有节点
  8837. * @method traversal
  8838. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8839. * @example
  8840. * ```javascript
  8841. * traversal(node, function(){
  8842. * console.log(node.type);
  8843. * });
  8844. * ```
  8845. */
  8846. traversal:function(fn){
  8847. if(this.children && this.children.length){
  8848. nodeTraversal(this,fn);
  8849. }
  8850. return this;
  8851. }
  8852. }
  8853. })();
  8854. // core/htmlparser.js
  8855. /**
  8856. * html字符串转换成uNode节点
  8857. * @file
  8858. * @module UE
  8859. * @since 1.2.6.1
  8860. */
  8861. /**
  8862. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8863. * @unfile
  8864. * @module UE
  8865. */
  8866. /**
  8867. * html字符串转换成uNode节点的静态方法
  8868. * @method htmlparser
  8869. * @param { String } htmlstr 要转换的html代码
  8870. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8871. * @return { uNode } 给定的html片段转换形成的uNode对象
  8872. * @example
  8873. * ```javascript
  8874. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8875. * ```
  8876. */
  8877. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8878. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8879. //先去掉了,加上的原因忘了,这里先记录
  8880. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8881. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8882. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8883. var allowEmptyTags = {
  8884. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8885. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8886. };
  8887. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8888. if(!ignoreBlank){
  8889. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8890. //br暂时单独处理
  8891. if(b && allowEmptyTags[b.toLowerCase()]){
  8892. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8893. }
  8894. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8895. });
  8896. }
  8897. var notTransAttrs = {
  8898. 'href':1,
  8899. 'src':1
  8900. };
  8901. var uNode = UE.uNode,
  8902. needParentNode = {
  8903. 'td':'tr',
  8904. 'tr':['tbody','thead','tfoot'],
  8905. 'tbody':'table',
  8906. 'th':'tr',
  8907. 'thead':'table',
  8908. 'tfoot':'table',
  8909. 'caption':'table',
  8910. 'li':['ul', 'ol'],
  8911. 'dt':'dl',
  8912. 'dd':'dl',
  8913. 'option':'select'
  8914. },
  8915. needChild = {
  8916. 'ol':'li',
  8917. 'ul':'li'
  8918. };
  8919. function text(parent, data) {
  8920. if(needChild[parent.tagName]){
  8921. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8922. parent.appendChild(tmpNode);
  8923. tmpNode.appendChild(uNode.createText(data));
  8924. parent = tmpNode;
  8925. }else{
  8926. parent.appendChild(uNode.createText(data));
  8927. }
  8928. }
  8929. function element(parent, tagName, htmlattr) {
  8930. var needParentTag;
  8931. if (needParentTag = needParentNode[tagName]) {
  8932. var tmpParent = parent,hasParent;
  8933. while(tmpParent.type != 'root'){
  8934. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8935. parent = tmpParent;
  8936. hasParent = true;
  8937. break;
  8938. }
  8939. tmpParent = tmpParent.parentNode;
  8940. }
  8941. if(!hasParent){
  8942. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8943. }
  8944. }
  8945. //按dtd处理嵌套
  8946. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8947. // parent = parent.parentNode;
  8948. var elm = new uNode({
  8949. parentNode:parent,
  8950. type:'element',
  8951. tagName:tagName.toLowerCase(),
  8952. //是自闭合的处理一下
  8953. children:dtd.$empty[tagName] ? null : []
  8954. });
  8955. //如果属性存在,处理属性
  8956. if (htmlattr) {
  8957. var attrs = {}, match;
  8958. while (match = re_attr.exec(htmlattr)) {
  8959. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8960. }
  8961. elm.attrs = attrs;
  8962. }
  8963. //trace:3970
  8964. // //如果parent下不能放elm
  8965. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  8966. // parent = parent.parentNode;
  8967. // elm.parentNode = parent;
  8968. // }
  8969. parent.children.push(elm);
  8970. //如果是自闭合节点返回父亲节点
  8971. return dtd.$empty[tagName] ? parent : elm
  8972. }
  8973. function comment(parent, data) {
  8974. parent.children.push(new uNode({
  8975. type:'comment',
  8976. data:data,
  8977. parentNode:parent
  8978. }));
  8979. }
  8980. var match, currentIndex = 0, nextIndex = 0;
  8981. //设置根节点
  8982. var root = new uNode({
  8983. type:'root',
  8984. children:[]
  8985. });
  8986. var currentParent = root;
  8987. while (match = re_tag.exec(htmlstr)) {
  8988. currentIndex = match.index;
  8989. try{
  8990. if (currentIndex > nextIndex) {
  8991. //text node
  8992. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8993. }
  8994. if (match[3]) {
  8995. if(dtd.$cdata[currentParent.tagName]){
  8996. text(currentParent, match[0]);
  8997. }else{
  8998. //start tag
  8999. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  9000. }
  9001. } else if (match[1]) {
  9002. if(currentParent.type != 'root'){
  9003. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  9004. text(currentParent, match[0]);
  9005. }else{
  9006. var tmpParent = currentParent;
  9007. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  9008. currentParent = currentParent.parentNode;
  9009. if(currentParent.type == 'root'){
  9010. currentParent = tmpParent;
  9011. throw 'break'
  9012. }
  9013. }
  9014. //end tag
  9015. currentParent = currentParent.parentNode;
  9016. }
  9017. }
  9018. } else if (match[2]) {
  9019. //comment
  9020. comment(currentParent, match[2])
  9021. }
  9022. }catch(e){}
  9023. nextIndex = re_tag.lastIndex;
  9024. }
  9025. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  9026. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  9027. if (nextIndex < htmlstr.length) {
  9028. text(currentParent, htmlstr.slice(nextIndex));
  9029. }
  9030. return root;
  9031. };
  9032. // core/filternode.js
  9033. /**
  9034. * UE过滤节点的静态方法
  9035. * @file
  9036. */
  9037. /**
  9038. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9039. * @module UE
  9040. */
  9041. /**
  9042. * 根据传入节点和过滤规则过滤相应节点
  9043. * @module UE
  9044. * @since 1.2.6.1
  9045. * @method filterNode
  9046. * @param { Object } root 指定root节点
  9047. * @param { Object } rules 过滤规则json对象
  9048. * @example
  9049. * ```javascript
  9050. * UE.filterNode(root,editor.options.filterRules);
  9051. * ```
  9052. */
  9053. var filterNode = UE.filterNode = function () {
  9054. function filterNode(node,rules){
  9055. switch (node.type) {
  9056. case 'text':
  9057. break;
  9058. case 'element':
  9059. var val;
  9060. if(val = rules[node.tagName]){
  9061. if(val === '-'){
  9062. node.parentNode.removeChild(node)
  9063. }else if(utils.isFunction(val)){
  9064. var parentNode = node.parentNode,
  9065. index = node.getIndex();
  9066. val(node);
  9067. if(node.parentNode){
  9068. if(node.children){
  9069. for(var i = 0,ci;ci=node.children[i];){
  9070. filterNode(ci,rules);
  9071. if(ci.parentNode){
  9072. i++;
  9073. }
  9074. }
  9075. }
  9076. }else{
  9077. for(var i = index,ci;ci=parentNode.children[i];){
  9078. filterNode(ci,rules);
  9079. if(ci.parentNode){
  9080. i++;
  9081. }
  9082. }
  9083. }
  9084. }else{
  9085. var attrs = val['$'];
  9086. if(attrs && node.attrs){
  9087. var tmpAttrs = {},tmpVal;
  9088. for(var a in attrs){
  9089. tmpVal = node.getAttr(a);
  9090. //todo 只先对style单独处理
  9091. if(a == 'style' && utils.isArray(attrs[a])){
  9092. var tmpCssStyle = [];
  9093. utils.each(attrs[a],function(v){
  9094. var tmp;
  9095. if(tmp = node.getStyle(v)){
  9096. tmpCssStyle.push(v + ':' + tmp);
  9097. }
  9098. });
  9099. tmpVal = tmpCssStyle.join(';')
  9100. }
  9101. if(tmpVal){
  9102. tmpAttrs[a] = tmpVal;
  9103. }
  9104. }
  9105. node.attrs = tmpAttrs;
  9106. }
  9107. if(node.children){
  9108. for(var i = 0,ci;ci=node.children[i];){
  9109. filterNode(ci,rules);
  9110. if(ci.parentNode){
  9111. i++;
  9112. }
  9113. }
  9114. }
  9115. }
  9116. }else{
  9117. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9118. if(dtd.$cdata[node.tagName]){
  9119. node.parentNode.removeChild(node)
  9120. }else{
  9121. var parentNode = node.parentNode,
  9122. index = node.getIndex();
  9123. node.parentNode.removeChild(node,true);
  9124. for(var i = index,ci;ci=parentNode.children[i];){
  9125. filterNode(ci,rules);
  9126. if(ci.parentNode){
  9127. i++;
  9128. }
  9129. }
  9130. }
  9131. }
  9132. break;
  9133. case 'comment':
  9134. node.parentNode.removeChild(node)
  9135. }
  9136. }
  9137. return function(root,rules){
  9138. if(utils.isEmptyObject(rules)){
  9139. return root;
  9140. }
  9141. var val;
  9142. if(val = rules['-']){
  9143. utils.each(val.split(' '),function(k){
  9144. rules[k] = '-'
  9145. })
  9146. }
  9147. for(var i= 0,ci;ci=root.children[i];){
  9148. filterNode(ci,rules);
  9149. if(ci.parentNode){
  9150. i++;
  9151. }
  9152. }
  9153. return root;
  9154. }
  9155. }();
  9156. // core/plugin.js
  9157. /**
  9158. * Created with JetBrains PhpStorm.
  9159. * User: campaign
  9160. * Date: 10/8/13
  9161. * Time: 6:15 PM
  9162. * To change this template use File | Settings | File Templates.
  9163. */
  9164. UE.plugin = function(){
  9165. var _plugins = {};
  9166. return {
  9167. register : function(pluginName,fn,oldOptionName,afterDisabled){
  9168. if(oldOptionName && utils.isFunction(oldOptionName)){
  9169. afterDisabled = oldOptionName;
  9170. oldOptionName = null
  9171. }
  9172. _plugins[pluginName] = {
  9173. optionName : oldOptionName || pluginName,
  9174. execFn : fn,
  9175. //当插件被禁用时执行
  9176. afterDisabled : afterDisabled
  9177. }
  9178. },
  9179. load : function(editor){
  9180. utils.each(_plugins,function(plugin){
  9181. var _export = plugin.execFn.call(editor);
  9182. if(editor.options[plugin.optionName] !== false){
  9183. if(_export){
  9184. //后边需要再做扩展
  9185. utils.each(_export,function(v,k){
  9186. switch(k.toLowerCase()){
  9187. case 'shortcutkey':
  9188. editor.addshortcutkey(v);
  9189. break;
  9190. case 'bindevents':
  9191. utils.each(v,function(fn,eventName){
  9192. editor.addListener(eventName,fn);
  9193. });
  9194. break;
  9195. case 'bindmultievents':
  9196. utils.each(utils.isArray(v) ? v:[v],function(event){
  9197. var types = utils.trim(event.type).split(/\s+/);
  9198. utils.each(types,function(eventName){
  9199. editor.addListener(eventName, event.handler);
  9200. });
  9201. });
  9202. break;
  9203. case 'commands':
  9204. utils.each(v,function(execFn,execName){
  9205. editor.commands[execName] = execFn
  9206. });
  9207. break;
  9208. case 'outputrule':
  9209. editor.addOutputRule(v);
  9210. break;
  9211. case 'inputrule':
  9212. editor.addInputRule(v);
  9213. break;
  9214. case 'defaultoptions':
  9215. editor.setOpt(v)
  9216. }
  9217. })
  9218. }
  9219. }else if(plugin.afterDisabled){
  9220. plugin.afterDisabled.call(editor)
  9221. }
  9222. });
  9223. //向下兼容
  9224. utils.each(UE.plugins,function(plugin){
  9225. plugin.call(editor);
  9226. });
  9227. },
  9228. run : function(pluginName,editor){
  9229. var plugin = _plugins[pluginName];
  9230. if(plugin){
  9231. plugin.exeFn.call(editor)
  9232. }
  9233. }
  9234. }
  9235. }();
  9236. // core/keymap.js
  9237. var keymap = UE.keymap = {
  9238. 'Backspace' : 8,
  9239. 'Tab' : 9,
  9240. 'Enter' : 13,
  9241. 'Shift':16,
  9242. 'Control':17,
  9243. 'Alt':18,
  9244. 'CapsLock':20,
  9245. 'Esc':27,
  9246. 'Spacebar':32,
  9247. 'PageUp':33,
  9248. 'PageDown':34,
  9249. 'End':35,
  9250. 'Home':36,
  9251. 'Left':37,
  9252. 'Up':38,
  9253. 'Right':39,
  9254. 'Down':40,
  9255. 'Insert':45,
  9256. 'Del':46,
  9257. 'NumLock':144,
  9258. 'Cmd':91,
  9259. '=':187,
  9260. '-':189,
  9261. "b":66,
  9262. 'i':73,
  9263. //回退
  9264. 'z':90,
  9265. 'y':89,
  9266. //粘贴
  9267. 'v' : 86,
  9268. 'x' : 88,
  9269. 's' : 83,
  9270. 'n' : 78
  9271. };
  9272. // core/localstorage.js
  9273. //存储媒介封装
  9274. var LocalStorage = UE.LocalStorage = (function () {
  9275. var storage = window.localStorage || getUserData() || null,
  9276. LOCAL_FILE = 'localStorage';
  9277. return {
  9278. saveLocalData: function (key, data) {
  9279. if (storage && data) {
  9280. storage.setItem(key, data);
  9281. return true;
  9282. }
  9283. return false;
  9284. },
  9285. getLocalData: function (key) {
  9286. if (storage) {
  9287. return storage.getItem(key);
  9288. }
  9289. return null;
  9290. },
  9291. removeItem: function (key) {
  9292. storage && storage.removeItem(key);
  9293. }
  9294. };
  9295. function getUserData() {
  9296. var container = document.createElement("div");
  9297. container.style.display = "none";
  9298. if (!container.addBehavior) {
  9299. return null;
  9300. }
  9301. container.addBehavior("#default#userdata");
  9302. return {
  9303. getItem: function (key) {
  9304. var result = null;
  9305. try {
  9306. document.body.appendChild(container);
  9307. container.load(LOCAL_FILE);
  9308. result = container.getAttribute(key);
  9309. document.body.removeChild(container);
  9310. } catch (e) {
  9311. }
  9312. return result;
  9313. },
  9314. setItem: function (key, value) {
  9315. document.body.appendChild(container);
  9316. container.setAttribute(key, value);
  9317. container.save(LOCAL_FILE);
  9318. document.body.removeChild(container);
  9319. },
  9320. //// 暂时没有用到
  9321. //clear: function () {
  9322. //
  9323. // var expiresTime = new Date();
  9324. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9325. // document.body.appendChild(container);
  9326. // container.expires = expiresTime.toUTCString();
  9327. // container.save(LOCAL_FILE);
  9328. // document.body.removeChild(container);
  9329. //
  9330. //},
  9331. removeItem: function (key) {
  9332. document.body.appendChild(container);
  9333. container.removeAttribute(key);
  9334. container.save(LOCAL_FILE);
  9335. document.body.removeChild(container);
  9336. }
  9337. };
  9338. }
  9339. })();
  9340. (function () {
  9341. var ROOTKEY = 'ueditor_preference';
  9342. UE.Editor.prototype.setPreferences = function(key,value){
  9343. var obj = {};
  9344. if (utils.isString(key)) {
  9345. obj[ key ] = value;
  9346. } else {
  9347. obj = key;
  9348. }
  9349. var data = LocalStorage.getLocalData(ROOTKEY);
  9350. if (data && (data = utils.str2json(data))) {
  9351. utils.extend(data, obj);
  9352. } else {
  9353. data = obj;
  9354. }
  9355. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9356. };
  9357. UE.Editor.prototype.getPreferences = function(key){
  9358. var data = LocalStorage.getLocalData(ROOTKEY);
  9359. if (data && (data = utils.str2json(data))) {
  9360. return key ? data[key] : data
  9361. }
  9362. return null;
  9363. };
  9364. UE.Editor.prototype.removePreferences = function (key) {
  9365. var data = LocalStorage.getLocalData(ROOTKEY);
  9366. if (data && (data = utils.str2json(data))) {
  9367. data[key] = undefined;
  9368. delete data[key]
  9369. }
  9370. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9371. };
  9372. })();
  9373. // plugins/defaultfilter.js
  9374. ///import core
  9375. ///plugin 编辑器默认的过滤转换机制
  9376. UE.plugins['defaultfilter'] = function () {
  9377. var me = this;
  9378. me.setOpt({
  9379. 'allowDivTransToP':true,
  9380. 'disabledTableInTable':true
  9381. });
  9382. //默认的过滤处理
  9383. //进入编辑器的内容处理
  9384. me.addInputRule(function (root) {
  9385. var allowDivTransToP = this.options.allowDivTransToP;
  9386. var val;
  9387. function tdParent(node){
  9388. while(node && node.type == 'element'){
  9389. if(node.tagName == 'td'){
  9390. return true;
  9391. }
  9392. node = node.parentNode;
  9393. }
  9394. return false;
  9395. }
  9396. //进行默认的处理
  9397. root.traversal(function (node) {
  9398. if (node.type == 'element') {
  9399. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9400. if (!node.firstChild()) node.parentNode.removeChild(node);
  9401. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9402. node.parentNode.removeChild(node, true)
  9403. }
  9404. return;
  9405. }
  9406. switch (node.tagName) {
  9407. case 'style':
  9408. case 'script':
  9409. node.setAttr({
  9410. cdata_tag: node.tagName,
  9411. cdata_data: (node.innerHTML() || ''),
  9412. '_ue_custom_node_':'true'
  9413. });
  9414. node.tagName = 'div';
  9415. node.innerHTML('');
  9416. break;
  9417. case 'a':
  9418. if (val = node.getAttr('href')) {
  9419. node.setAttr('_href', val)
  9420. }
  9421. break;
  9422. case 'img':
  9423. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9424. if (val = node.getAttr('src')) {
  9425. if (/^data:/.test(val)) {
  9426. node.parentNode.removeChild(node);
  9427. break;
  9428. }
  9429. }
  9430. node.setAttr('_src', node.getAttr('src'));
  9431. break;
  9432. case 'span':
  9433. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9434. if (/nowrap|normal/.test(val)) {
  9435. node.setStyle('white-space', '');
  9436. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9437. node.parentNode.removeChild(node, true)
  9438. }
  9439. }
  9440. }
  9441. val = node.getAttr('id');
  9442. if(val && /^_baidu_bookmark_/i.test(val)){
  9443. node.parentNode.removeChild(node)
  9444. }
  9445. break;
  9446. case 'p':
  9447. if (val = node.getAttr('align')) {
  9448. node.setAttr('align');
  9449. node.setStyle('text-align', val)
  9450. }
  9451. //trace:3431
  9452. // var cssStyle = node.getAttr('style');
  9453. // if (cssStyle) {
  9454. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9455. // node.setAttr('style', cssStyle)
  9456. //
  9457. // }
  9458. //p标签不允许嵌套
  9459. utils.each(node.children,function(n){
  9460. if(n.type == 'element' && n.tagName == 'p'){
  9461. var next = n.nextSibling();
  9462. node.parentNode.insertAfter(n,node);
  9463. var last = n;
  9464. while(next){
  9465. var tmp = next.nextSibling();
  9466. node.parentNode.insertAfter(next,last);
  9467. last = next;
  9468. next = tmp;
  9469. }
  9470. return false;
  9471. }
  9472. });
  9473. if (!node.firstChild()) {
  9474. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9475. }
  9476. break;
  9477. case 'div':
  9478. if(node.getAttr('cdata_tag')){
  9479. break;
  9480. }
  9481. //针对代码这里不处理插入代码的div
  9482. val = node.getAttr('class');
  9483. if(val && /^line number\d+/.test(val)){
  9484. break;
  9485. }
  9486. if(!allowDivTransToP){
  9487. break;
  9488. }
  9489. var tmpNode, p = UE.uNode.createElement('p');
  9490. while (tmpNode = node.firstChild()) {
  9491. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9492. p.appendChild(tmpNode);
  9493. } else {
  9494. if (p.firstChild()) {
  9495. node.parentNode.insertBefore(p, node);
  9496. p = UE.uNode.createElement('p');
  9497. } else {
  9498. node.parentNode.insertBefore(tmpNode, node);
  9499. }
  9500. }
  9501. }
  9502. if (p.firstChild()) {
  9503. node.parentNode.insertBefore(p, node);
  9504. }
  9505. node.parentNode.removeChild(node);
  9506. break;
  9507. case 'dl':
  9508. node.tagName = 'ul';
  9509. break;
  9510. case 'dt':
  9511. case 'dd':
  9512. node.tagName = 'li';
  9513. break;
  9514. case 'li':
  9515. var className = node.getAttr('class');
  9516. if (!className || !/list\-/.test(className)) {
  9517. node.setAttr()
  9518. }
  9519. var tmpNodes = node.getNodesByTagName('ol ul');
  9520. UE.utils.each(tmpNodes, function (n) {
  9521. node.parentNode.insertAfter(n, node);
  9522. });
  9523. break;
  9524. case 'td':
  9525. case 'th':
  9526. case 'caption':
  9527. if(!node.children || !node.children.length){
  9528. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9529. }
  9530. break;
  9531. case 'table':
  9532. if(me.options.disabledTableInTable && tdParent(node)){
  9533. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  9534. node.parentNode.removeChild(node)
  9535. }
  9536. }
  9537. }
  9538. // if(node.type == 'comment'){
  9539. // node.parentNode.removeChild(node);
  9540. // }
  9541. })
  9542. });
  9543. //从编辑器出去的内容处理
  9544. me.addOutputRule(function (root) {
  9545. var val;
  9546. root.traversal(function (node) {
  9547. if (node.type == 'element') {
  9548. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9549. if (!node.firstChild()) node.parentNode.removeChild(node);
  9550. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9551. node.parentNode.removeChild(node, true)
  9552. }
  9553. return;
  9554. }
  9555. switch (node.tagName) {
  9556. case 'div':
  9557. if (val = node.getAttr('cdata_tag')) {
  9558. node.tagName = val;
  9559. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9560. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9561. }
  9562. break;
  9563. case 'a':
  9564. if (val = node.getAttr('_href')) {
  9565. node.setAttr({
  9566. 'href': utils.html(val),
  9567. '_href': ''
  9568. })
  9569. }
  9570. break;
  9571. break;
  9572. case 'span':
  9573. val = node.getAttr('id');
  9574. if(val && /^_baidu_bookmark_/i.test(val)){
  9575. node.parentNode.removeChild(node)
  9576. }
  9577. break;
  9578. case 'img':
  9579. if (val = node.getAttr('_src')) {
  9580. node.setAttr({
  9581. 'src': node.getAttr('_src'),
  9582. '_src': ''
  9583. })
  9584. }
  9585. }
  9586. }
  9587. })
  9588. });
  9589. };
  9590. // plugins/inserthtml.js
  9591. /**
  9592. * 插入html字符串插件
  9593. * @file
  9594. * @since 1.2.6.1
  9595. */
  9596. /**
  9597. * 插入html代码
  9598. * @command inserthtml
  9599. * @method execCommand
  9600. * @param { String } cmd 命令字符串
  9601. * @param { String } html 插入的html字符串
  9602. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9603. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9604. * @example
  9605. * ```javascript
  9606. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9607. * //执行命令,插入<b>CC</b>
  9608. * //插入后的效果 xxx<b>CC</b>xxx
  9609. * //<p>xx|xxx</p> 当前选区为闭合状态
  9610. * //插入<p>CC</p>
  9611. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9612. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9613. * //插入 xxxx
  9614. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9615. * ```
  9616. */
  9617. UE.commands['inserthtml'] = {
  9618. execCommand: function (command,html,notNeedFilter){
  9619. var me = this,
  9620. range,
  9621. div;
  9622. if(!html){
  9623. return;
  9624. }
  9625. if(me.fireEvent('beforeinserthtml',html) === true){
  9626. return;
  9627. }
  9628. range = me.selection.getRange();
  9629. div = range.document.createElement( 'div' );
  9630. div.style.display = 'inline';
  9631. if (!notNeedFilter) {
  9632. var root = UE.htmlparser(html);
  9633. //如果给了过滤规则就先进行过滤
  9634. if(me.options.filterRules){
  9635. UE.filterNode(root,me.options.filterRules);
  9636. }
  9637. //执行默认的处理
  9638. me.filterInputRule(root);
  9639. html = root.toHtml()
  9640. }
  9641. div.innerHTML = utils.trim( html );
  9642. if ( !range.collapsed ) {
  9643. var tmpNode = range.startContainer;
  9644. if(domUtils.isFillChar(tmpNode)){
  9645. range.setStartBefore(tmpNode)
  9646. }
  9647. tmpNode = range.endContainer;
  9648. if(domUtils.isFillChar(tmpNode)){
  9649. range.setEndAfter(tmpNode)
  9650. }
  9651. range.txtToElmBoundary();
  9652. //结束边界可能放到了br的前边,要把br包含进来
  9653. // x[xxx]<br/>
  9654. if(range.endContainer && range.endContainer.nodeType == 1){
  9655. tmpNode = range.endContainer.childNodes[range.endOffset];
  9656. if(tmpNode && domUtils.isBr(tmpNode)){
  9657. range.setEndAfter(tmpNode);
  9658. }
  9659. }
  9660. if(range.startOffset == 0){
  9661. tmpNode = range.startContainer;
  9662. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9663. tmpNode = range.endContainer;
  9664. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9665. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9666. range.setStart(me.body.firstChild,0).collapse(true)
  9667. }
  9668. }
  9669. }
  9670. !range.collapsed && range.deleteContents();
  9671. if(range.startContainer.nodeType == 1){
  9672. var child = range.startContainer.childNodes[range.startOffset],pre;
  9673. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9674. range.setEnd(pre,pre.childNodes.length).collapse();
  9675. while(child.firstChild){
  9676. pre.appendChild(child.firstChild);
  9677. }
  9678. domUtils.remove(child);
  9679. }
  9680. }
  9681. }
  9682. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9683. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9684. if(range.inFillChar()){
  9685. child = range.startContainer;
  9686. if(domUtils.isFillChar(child)){
  9687. range.setStartBefore(child).collapse(true);
  9688. domUtils.remove(child);
  9689. }else if(domUtils.isFillChar(child,true)){
  9690. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9691. range.startOffset--;
  9692. range.collapsed && range.collapse(true)
  9693. }
  9694. }
  9695. //列表单独处理
  9696. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9697. if(li){
  9698. var next,last;
  9699. while(child = div.firstChild){
  9700. //针对hr单独处理一下先
  9701. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9702. next = child.nextSibling;
  9703. range.insertNode( child).collapse();
  9704. last = child;
  9705. child = next;
  9706. }
  9707. if(child){
  9708. if(/^(ol|ul)$/i.test(child.tagName)){
  9709. while(child.firstChild){
  9710. last = child.firstChild;
  9711. domUtils.insertAfter(li,child.firstChild);
  9712. li = li.nextSibling;
  9713. }
  9714. domUtils.remove(child)
  9715. }else{
  9716. var tmpLi;
  9717. next = child.nextSibling;
  9718. tmpLi = me.document.createElement('li');
  9719. domUtils.insertAfter(li,tmpLi);
  9720. tmpLi.appendChild(child);
  9721. last = child;
  9722. child = next;
  9723. li = tmpLi;
  9724. }
  9725. }
  9726. }
  9727. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9728. if(domUtils.isEmptyBlock(li)){
  9729. domUtils.remove(li)
  9730. }
  9731. if(last){
  9732. range.setStartAfter(last).collapse(true).select(true)
  9733. }
  9734. }else{
  9735. while ( child = div.firstChild ) {
  9736. if(hadBreak){
  9737. var p = me.document.createElement('p');
  9738. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9739. nextNode = child.nextSibling;
  9740. p.appendChild(child);
  9741. child = nextNode;
  9742. }
  9743. if(p.firstChild){
  9744. child = p
  9745. }
  9746. }
  9747. range.insertNode( child );
  9748. nextNode = child.nextSibling;
  9749. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9750. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9751. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9752. if(!dtd[parent.tagName][child.nodeName]){
  9753. pre = parent;
  9754. }else{
  9755. tmp = child.parentNode;
  9756. while (tmp !== parent){
  9757. pre = tmp;
  9758. tmp = tmp.parentNode;
  9759. }
  9760. }
  9761. domUtils.breakParent( child, pre || tmp );
  9762. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9763. var pre = child.previousSibling;
  9764. domUtils.trimWhiteTextNode(pre);
  9765. if(!pre.childNodes.length){
  9766. domUtils.remove(pre);
  9767. }
  9768. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9769. if(!browser.ie &&
  9770. (next = child.nextSibling) &&
  9771. domUtils.isBlockElm(next) &&
  9772. next.lastChild &&
  9773. !domUtils.isBr(next.lastChild)){
  9774. next.appendChild(me.document.createElement('br'));
  9775. }
  9776. hadBreak = 1;
  9777. }
  9778. }
  9779. var next = child.nextSibling;
  9780. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9781. range.setStart(next,0).collapse(true);
  9782. break;
  9783. }
  9784. range.setEndAfter( child ).collapse();
  9785. }
  9786. child = range.startContainer;
  9787. if(nextNode && domUtils.isBr(nextNode)){
  9788. domUtils.remove(nextNode)
  9789. }
  9790. //用chrome可能有空白展位符
  9791. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9792. if(nextNode = child.nextSibling){
  9793. domUtils.remove(child);
  9794. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9795. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9796. }
  9797. }else{
  9798. try{
  9799. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9800. }catch(e){
  9801. range.setStartBefore(child);
  9802. domUtils.remove(child)
  9803. }
  9804. }
  9805. }
  9806. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9807. try{
  9808. range.select(true);
  9809. }catch(e){}
  9810. }
  9811. setTimeout(function(){
  9812. range = me.selection.getRange();
  9813. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9814. me.fireEvent('afterinserthtml', html);
  9815. },200);
  9816. }
  9817. };
  9818. // plugins/autotypeset.js
  9819. /**
  9820. * 自动排版
  9821. * @file
  9822. * @since 1.2.6.1
  9823. */
  9824. /**
  9825. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9826. * @command autotypeset
  9827. * @method execCommand
  9828. * @param { String } cmd 命令字符串
  9829. * @example
  9830. * ```javascript
  9831. * editor.execCommand( 'autotypeset' );
  9832. * ```
  9833. */
  9834. UE.plugins['autotypeset'] = function(){
  9835. this.setOpt({'autotypeset': {
  9836. mergeEmptyline: true, //合并空行
  9837. removeClass: true, //去掉冗余的class
  9838. removeEmptyline: false, //去掉空行
  9839. textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9840. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9841. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  9842. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9843. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9844. removeEmptyNode: false, // 去掉空节点
  9845. //可以去掉的标签
  9846. removeTagNames: utils.extend({div:1},dtd.$removeEmpty),
  9847. indent: false, // 行首缩进
  9848. indentValue : '2em', //行首缩进的大小
  9849. bdc2sb: false,
  9850. tobdc: false
  9851. }});
  9852. var me = this,
  9853. opt = me.options.autotypeset,
  9854. remainClass = {
  9855. 'selectTdClass':1,
  9856. 'pagebreak':1,
  9857. 'anchorclass':1
  9858. },
  9859. remainTag = {
  9860. 'li':1
  9861. },
  9862. tags = {
  9863. div:1,
  9864. p:1,
  9865. //trace:2183 这些也认为是行
  9866. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9867. span:1
  9868. },
  9869. highlightCont;
  9870. //升级了版本,但配置项目里没有autotypeset
  9871. if(!opt){
  9872. return;
  9873. }
  9874. readLocalOpts();
  9875. function isLine(node,notEmpty){
  9876. if(!node || node.nodeType == 3)
  9877. return 0;
  9878. if(domUtils.isBr(node))
  9879. return 1;
  9880. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9881. if(highlightCont && highlightCont.contains(node)
  9882. ||
  9883. node.getAttribute('pagebreak')
  9884. ){
  9885. return 0;
  9886. }
  9887. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9888. +']','g'));
  9889. }
  9890. }
  9891. function removeNotAttributeSpan(node){
  9892. if(!node.style.cssText){
  9893. domUtils.removeAttributes(node,['style']);
  9894. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9895. domUtils.remove(node,true);
  9896. }
  9897. }
  9898. }
  9899. function autotype(type,html){
  9900. var me = this,cont;
  9901. if(html){
  9902. if(!opt.pasteFilter){
  9903. return;
  9904. }
  9905. cont = me.document.createElement('div');
  9906. cont.innerHTML = html.html;
  9907. }else{
  9908. cont = me.document.body;
  9909. }
  9910. var nodes = domUtils.getElementsByTagName(cont,'*');
  9911. // 行首缩进,段落方向,段间距,段内间距
  9912. for(var i=0,ci;ci=nodes[i++];){
  9913. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9914. continue;
  9915. }
  9916. //font-size
  9917. if(opt.clearFontSize && ci.style.fontSize){
  9918. domUtils.removeStyle(ci,'font-size');
  9919. removeNotAttributeSpan(ci);
  9920. }
  9921. //font-family
  9922. if(opt.clearFontFamily && ci.style.fontFamily){
  9923. domUtils.removeStyle(ci,'font-family');
  9924. removeNotAttributeSpan(ci);
  9925. }
  9926. if(isLine(ci)){
  9927. //合并空行
  9928. if(opt.mergeEmptyline ){
  9929. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9930. while(isLine(next)){
  9931. tmpNode = next;
  9932. next = tmpNode.nextSibling;
  9933. if(isBr && (!next || next && !domUtils.isBr(next))){
  9934. break;
  9935. }
  9936. domUtils.remove(tmpNode);
  9937. }
  9938. }
  9939. //去掉空行,保留占位的空行
  9940. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9941. if(domUtils.isBr(ci)){
  9942. next = ci.nextSibling;
  9943. if(next && !domUtils.isBr(next)){
  9944. continue;
  9945. }
  9946. }
  9947. domUtils.remove(ci);
  9948. continue;
  9949. }
  9950. }
  9951. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9952. if(opt.indent){
  9953. ci.style.textIndent = opt.indentValue;
  9954. }
  9955. if(opt.textAlign){
  9956. ci.style.textAlign = opt.textAlign;
  9957. }
  9958. // if(opt.lineHeight)
  9959. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9960. }
  9961. //去掉class,保留的class不去掉
  9962. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9963. if(highlightCont && highlightCont.contains(ci)){
  9964. continue;
  9965. }
  9966. domUtils.removeAttributes(ci,['class']);
  9967. }
  9968. //表情不处理
  9969. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9970. if(html){
  9971. var img = ci;
  9972. switch (opt.imageBlockLine){
  9973. case 'left':
  9974. case 'right':
  9975. case 'none':
  9976. var pN = img.parentNode,tmpNode,pre,next;
  9977. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9978. pN = pN.parentNode;
  9979. }
  9980. tmpNode = pN;
  9981. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9982. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9983. pre = tmpNode.previousSibling;
  9984. next = tmpNode.nextSibling;
  9985. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9986. pre.appendChild(tmpNode.firstChild);
  9987. while(next.firstChild){
  9988. pre.appendChild(next.firstChild);
  9989. }
  9990. domUtils.remove(tmpNode);
  9991. domUtils.remove(next);
  9992. }else{
  9993. domUtils.setStyle(tmpNode,'text-align','');
  9994. }
  9995. }
  9996. }
  9997. domUtils.setStyle(img,'float', opt.imageBlockLine);
  9998. break;
  9999. case 'center':
  10000. if(me.queryCommandValue('imagefloat') != 'center'){
  10001. pN = img.parentNode;
  10002. domUtils.setStyle(img,'float','none');
  10003. tmpNode = img;
  10004. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  10005. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  10006. tmpNode = pN;
  10007. pN = pN.parentNode;
  10008. }
  10009. var pNode = me.document.createElement('p');
  10010. domUtils.setAttributes(pNode,{
  10011. style:'text-align:center'
  10012. });
  10013. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  10014. pNode.appendChild(tmpNode);
  10015. domUtils.setStyle(tmpNode,'float','');
  10016. }
  10017. }
  10018. } else {
  10019. var range = me.selection.getRange();
  10020. range.selectNode(ci).select();
  10021. me.execCommand('imagefloat', opt.imageBlockLine);
  10022. }
  10023. }
  10024. //去掉冗余的标签
  10025. if(opt.removeEmptyNode){
  10026. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  10027. domUtils.remove(ci);
  10028. }
  10029. }
  10030. }
  10031. if(opt.tobdc){
  10032. var root = UE.htmlparser(cont.innerHTML);
  10033. root.traversal(function(node){
  10034. if(node.type == 'text'){
  10035. node.data = ToDBC(node.data)
  10036. }
  10037. });
  10038. cont.innerHTML = root.toHtml()
  10039. }
  10040. if(opt.bdc2sb){
  10041. var root = UE.htmlparser(cont.innerHTML);
  10042. root.traversal(function(node){
  10043. if(node.type == 'text'){
  10044. node.data = DBC2SB(node.data)
  10045. }
  10046. });
  10047. cont.innerHTML = root.toHtml()
  10048. }
  10049. if(html){
  10050. html.html = cont.innerHTML;
  10051. }
  10052. }
  10053. if(opt.pasteFilter){
  10054. me.addListener('beforepaste',autotype);
  10055. }
  10056. function DBC2SB(str) {
  10057. var result = '';
  10058. for (var i = 0; i < str.length; i++) {
  10059. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10060. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10061. {
  10062. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10063. } else if (code == 12288)//空格
  10064. {
  10065. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10066. } else {
  10067. result += str.charAt(i);
  10068. }
  10069. }
  10070. return result;
  10071. }
  10072. function ToDBC(txtstring) {
  10073. txtstring = utils.html(txtstring);
  10074. var tmp = "";
  10075. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10076. for (var i = 0; i < txtstring.length; i++) {
  10077. if (txtstring.charCodeAt(i) == 32) {
  10078. tmp = tmp + String.fromCharCode(12288);
  10079. }
  10080. else if (txtstring.charCodeAt(i) < 127) {
  10081. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10082. }
  10083. else {
  10084. tmp += txtstring.charAt(i);
  10085. }
  10086. }
  10087. return tmp;
  10088. }
  10089. function readLocalOpts() {
  10090. var cookieOpt = me.getPreferences('autotypeset');
  10091. utils.extend(me.options.autotypeset, cookieOpt);
  10092. }
  10093. me.commands['autotypeset'] = {
  10094. execCommand:function () {
  10095. me.removeListener('beforepaste',autotype);
  10096. if(opt.pasteFilter){
  10097. me.addListener('beforepaste',autotype);
  10098. }
  10099. autotype.call(me)
  10100. }
  10101. };
  10102. };
  10103. // plugins/autosubmit.js
  10104. /**
  10105. * 快捷键提交
  10106. * @file
  10107. * @since 1.2.6.1
  10108. */
  10109. /**
  10110. * 提交表单
  10111. * @command autosubmit
  10112. * @method execCommand
  10113. * @param { String } cmd 命令字符串
  10114. * @example
  10115. * ```javascript
  10116. * editor.execCommand( 'autosubmit' );
  10117. * ```
  10118. */
  10119. UE.plugin.register('autosubmit',function(){
  10120. return {
  10121. shortcutkey:{
  10122. "autosubmit":"ctrl+13" //手动提交
  10123. },
  10124. commands:{
  10125. 'autosubmit':{
  10126. execCommand:function () {
  10127. var me=this,
  10128. form = domUtils.findParentByTagName(me.iframe,"form", false);
  10129. if (form){
  10130. if(me.fireEvent("beforesubmit")===false){
  10131. return;
  10132. }
  10133. me.sync();
  10134. form.submit();
  10135. }
  10136. }
  10137. }
  10138. }
  10139. }
  10140. });
  10141. // plugins/background.js
  10142. /**
  10143. * 背景插件,为UEditor提供设置背景功能
  10144. * @file
  10145. * @since 1.2.6.1
  10146. */
  10147. UE.plugin.register('background', function () {
  10148. var me = this,
  10149. cssRuleId = 'editor_background',
  10150. isSetColored,
  10151. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10152. function stringToObj(str) {
  10153. var obj = {}, styles = str.split(';');
  10154. utils.each(styles, function (v) {
  10155. var index = v.indexOf(':'),
  10156. key = utils.trim(v.substr(0, index)).toLowerCase();
  10157. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10158. });
  10159. return obj;
  10160. }
  10161. function setBackground(obj) {
  10162. if (obj) {
  10163. var styles = [];
  10164. for (var name in obj) {
  10165. if (obj.hasOwnProperty(name)) {
  10166. styles.push(name + ":" + obj[name] + '; ');
  10167. }
  10168. }
  10169. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10170. } else {
  10171. utils.cssRule(cssRuleId, '', me.document)
  10172. }
  10173. }
  10174. //重写editor.hasContent方法
  10175. var orgFn = me.hasContents;
  10176. me.hasContents = function(){
  10177. if(me.queryCommandValue('background')){
  10178. return true
  10179. }
  10180. return orgFn.apply(me,arguments);
  10181. };
  10182. return {
  10183. bindEvents: {
  10184. 'getAllHtml': function (type, headHtml) {
  10185. var body = this.body,
  10186. su = domUtils.getComputedStyle(body, "background-image"),
  10187. url = "";
  10188. if (su.indexOf(me.options.imagePath) > 0) {
  10189. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10190. } else {
  10191. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10192. }
  10193. var html = '<style type="text/css">body{';
  10194. var bgObj = {
  10195. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10196. 'background-image': url ? 'url(' + url + ')' : '',
  10197. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10198. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10199. 'height': domUtils.getComputedStyle(body, "height")
  10200. };
  10201. for (var name in bgObj) {
  10202. if (bgObj.hasOwnProperty(name)) {
  10203. html += name + ":" + bgObj[name] + "; ";
  10204. }
  10205. }
  10206. html += '}</style> ';
  10207. headHtml.push(html);
  10208. },
  10209. 'aftersetcontent': function () {
  10210. if(isSetColored == false) setBackground();
  10211. }
  10212. },
  10213. inputRule: function (root) {
  10214. isSetColored = false;
  10215. utils.each(root.getNodesByTagName('p'), function (p) {
  10216. var styles = p.getAttr('data-background');
  10217. if (styles) {
  10218. isSetColored = true;
  10219. setBackground(stringToObj(styles));
  10220. p.parentNode.removeChild(p);
  10221. }
  10222. })
  10223. },
  10224. outputRule: function (root) {
  10225. var me = this,
  10226. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10227. if (styles) {
  10228. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10229. }
  10230. },
  10231. commands: {
  10232. 'background': {
  10233. execCommand: function (cmd, obj) {
  10234. setBackground(obj);
  10235. },
  10236. queryCommandValue: function () {
  10237. var me = this,
  10238. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10239. return styles ? stringToObj(styles[1]) : null;
  10240. },
  10241. notNeedUndo: true
  10242. }
  10243. }
  10244. }
  10245. });
  10246. // plugins/image.js
  10247. /**
  10248. * 图片插入、排版插件
  10249. * @file
  10250. * @since 1.2.6.1
  10251. */
  10252. /**
  10253. * 图片对齐方式
  10254. * @command imagefloat
  10255. * @method execCommand
  10256. * @remind 值center为独占一行居中
  10257. * @param { String } cmd 命令字符串
  10258. * @param { String } align 对齐方式,可传left、right、none、center
  10259. * @remaind center表示图片独占一行
  10260. * @example
  10261. * ```javascript
  10262. * editor.execCommand( 'imagefloat', 'center' );
  10263. * ```
  10264. */
  10265. /**
  10266. * 如果选区所在位置是图片区域
  10267. * @command imagefloat
  10268. * @method queryCommandValue
  10269. * @param { String } cmd 命令字符串
  10270. * @return { String } 返回图片对齐方式
  10271. * @example
  10272. * ```javascript
  10273. * editor.queryCommandValue( 'imagefloat' );
  10274. * ```
  10275. */
  10276. UE.commands['imagefloat'] = {
  10277. execCommand:function (cmd, align) {
  10278. var me = this,
  10279. range = me.selection.getRange();
  10280. if (!range.collapsed) {
  10281. var img = range.getClosedNode();
  10282. if (img && img.tagName == 'IMG') {
  10283. switch (align) {
  10284. case 'left':
  10285. case 'right':
  10286. case 'none':
  10287. var pN = img.parentNode, tmpNode, pre, next;
  10288. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10289. pN = pN.parentNode;
  10290. }
  10291. tmpNode = pN;
  10292. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10293. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10294. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10295. }) == 1) {
  10296. pre = tmpNode.previousSibling;
  10297. next = tmpNode.nextSibling;
  10298. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10299. pre.appendChild(tmpNode.firstChild);
  10300. while (next.firstChild) {
  10301. pre.appendChild(next.firstChild);
  10302. }
  10303. domUtils.remove(tmpNode);
  10304. domUtils.remove(next);
  10305. } else {
  10306. domUtils.setStyle(tmpNode, 'text-align', '');
  10307. }
  10308. }
  10309. range.selectNode(img).select();
  10310. }
  10311. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10312. if(align == 'none'){
  10313. domUtils.removeAttributes(img,'align');
  10314. }
  10315. break;
  10316. case 'center':
  10317. if (me.queryCommandValue('imagefloat') != 'center') {
  10318. pN = img.parentNode;
  10319. domUtils.setStyle(img, 'float', '');
  10320. domUtils.removeAttributes(img,'align');
  10321. tmpNode = img;
  10322. while (pN && domUtils.getChildCount(pN, function (node) {
  10323. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10324. }) == 1
  10325. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10326. tmpNode = pN;
  10327. pN = pN.parentNode;
  10328. }
  10329. range.setStartBefore(tmpNode).setCursor(false);
  10330. pN = me.document.createElement('div');
  10331. pN.appendChild(tmpNode);
  10332. domUtils.setStyle(tmpNode, 'float', '');
  10333. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10334. tmpNode = me.document.getElementById('_img_parent_tmp');
  10335. tmpNode.removeAttribute('id');
  10336. tmpNode = tmpNode.firstChild;
  10337. range.selectNode(tmpNode).select();
  10338. //去掉后边多余的元素
  10339. next = tmpNode.parentNode.nextSibling;
  10340. if (next && domUtils.isEmptyNode(next)) {
  10341. domUtils.remove(next);
  10342. }
  10343. }
  10344. break;
  10345. }
  10346. }
  10347. }
  10348. },
  10349. queryCommandValue:function () {
  10350. var range = this.selection.getRange(),
  10351. startNode, floatStyle;
  10352. if (range.collapsed) {
  10353. return 'none';
  10354. }
  10355. startNode = range.getClosedNode();
  10356. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10357. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10358. if (floatStyle == 'none') {
  10359. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10360. }
  10361. return {
  10362. left:1,
  10363. right:1,
  10364. center:1
  10365. }[floatStyle] ? floatStyle : 'none';
  10366. }
  10367. return 'none';
  10368. },
  10369. queryCommandState:function () {
  10370. var range = this.selection.getRange(),
  10371. startNode;
  10372. if (range.collapsed) return -1;
  10373. startNode = range.getClosedNode();
  10374. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10375. return 0;
  10376. }
  10377. return -1;
  10378. }
  10379. };
  10380. /**
  10381. * 插入图片
  10382. * @command insertimage
  10383. * @method execCommand
  10384. * @param { String } cmd 命令字符串
  10385. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10386. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10387. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10388. * @example
  10389. * ```javascript
  10390. * editor.execCommand( 'insertimage', {
  10391. * src:'a/b/c.jpg',
  10392. * width:'100',
  10393. * height:'100'
  10394. * } );
  10395. * ```
  10396. * @example
  10397. * ```javascript
  10398. * editor.execCommand( 'insertimage', [{
  10399. * src:'a/b/c.jpg',
  10400. * width:'100',
  10401. * height:'100'
  10402. * },{
  10403. * src:'a/b/d.jpg',
  10404. * width:'100',
  10405. * height:'100'
  10406. * }] );
  10407. * ```
  10408. */
  10409. UE.commands['insertimage'] = {
  10410. execCommand:function (cmd, opt) {
  10411. opt = utils.isArray(opt) ? opt : [opt];
  10412. if (!opt.length) {
  10413. return;
  10414. }
  10415. var me = this,
  10416. range = me.selection.getRange(),
  10417. img = range.getClosedNode();
  10418. if(me.fireEvent('beforeinsertimage', opt) === true){
  10419. return;
  10420. }
  10421. function unhtmlData(imgCi) {
  10422. utils.each('width,height,border,hspace,vspace'.split(','), function (item) {
  10423. if (imgCi[item]) {
  10424. imgCi[item] = parseInt(imgCi[item], 10) || 0;
  10425. }
  10426. });
  10427. utils.each('src,_src'.split(','), function (item) {
  10428. if (imgCi[item]) {
  10429. imgCi[item] = utils.unhtmlForUrl(imgCi[item]);
  10430. }
  10431. });
  10432. utils.each('title,alt'.split(','), function (item) {
  10433. if (imgCi[item]) {
  10434. imgCi[item] = utils.unhtml(imgCi[item]);
  10435. }
  10436. });
  10437. }
  10438. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  10439. var first = opt.shift();
  10440. var floatStyle = first['floatStyle'];
  10441. delete first['floatStyle'];
  10442. //// img.style.border = (first.border||0) +"px solid #000";
  10443. //// img.style.margin = (first.margin||0) +"px";
  10444. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10445. domUtils.setAttributes(img, first);
  10446. me.execCommand('imagefloat', floatStyle);
  10447. if (opt.length > 0) {
  10448. range.setStartAfter(img).setCursor(false, true);
  10449. me.execCommand('insertimage', opt);
  10450. }
  10451. } else {
  10452. var html = [], str = '', ci;
  10453. ci = opt[0];
  10454. if (opt.length == 1) {
  10455. unhtmlData(ci);
  10456. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10457. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10458. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10459. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10460. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10461. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10462. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10463. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10464. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10465. if (ci['floatStyle'] == 'center') {
  10466. str = '<p style="text-align: center">' + str + '</p>';
  10467. }
  10468. html.push(str);
  10469. } else {
  10470. for (var i = 0; ci = opt[i++];) {
  10471. unhtmlData(ci);
  10472. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10473. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10474. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10475. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10476. (ci.border || '') + '" ' +
  10477. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10478. html.push(str);
  10479. }
  10480. }
  10481. me.execCommand('insertHtml', html.join(''));
  10482. }
  10483. me.fireEvent('afterinsertimage', opt)
  10484. }
  10485. };
  10486. // plugins/justify.js
  10487. /**
  10488. * 段落格式
  10489. * @file
  10490. * @since 1.2.6.1
  10491. */
  10492. /**
  10493. * 段落对齐方式
  10494. * @command justify
  10495. * @method execCommand
  10496. * @param { String } cmd 命令字符串
  10497. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10498. * @example
  10499. * ```javascript
  10500. * editor.execCommand( 'justify', 'center' );
  10501. * ```
  10502. */
  10503. /**
  10504. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10505. * @command justify
  10506. * @method queryCommandValue
  10507. * @param { String } cmd 命令字符串
  10508. * @return { String } 返回段落对齐方式
  10509. * @example
  10510. * ```javascript
  10511. * editor.queryCommandValue( 'justify' );
  10512. * ```
  10513. */
  10514. UE.plugins['justify']=function(){
  10515. var me=this,
  10516. block = domUtils.isBlockElm,
  10517. defaultValue = {
  10518. left:1,
  10519. right:1,
  10520. center:1,
  10521. justify:1
  10522. },
  10523. doJustify = function (range, style) {
  10524. var bookmark = range.createBookmark(),
  10525. filterFn = function (node) {
  10526. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10527. };
  10528. range.enlarge(true);
  10529. var bookmark2 = range.createBookmark(),
  10530. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10531. tmpRange = range.cloneRange(),
  10532. tmpNode;
  10533. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10534. if (current.nodeType == 3 || !block(current)) {
  10535. tmpRange.setStartBefore(current);
  10536. while (current && current !== bookmark2.end && !block(current)) {
  10537. tmpNode = current;
  10538. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10539. return !block(node);
  10540. });
  10541. }
  10542. tmpRange.setEndAfter(tmpNode);
  10543. var common = tmpRange.getCommonAncestor();
  10544. if (!domUtils.isBody(common) && block(common)) {
  10545. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  10546. current = common;
  10547. } else {
  10548. var p = range.document.createElement('p');
  10549. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  10550. var frag = tmpRange.extractContents();
  10551. p.appendChild(frag);
  10552. tmpRange.insertNode(p);
  10553. current = p;
  10554. }
  10555. current = domUtils.getNextDomNode(current, false, filterFn);
  10556. } else {
  10557. current = domUtils.getNextDomNode(current, true, filterFn);
  10558. }
  10559. }
  10560. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10561. };
  10562. UE.commands['justify'] = {
  10563. execCommand:function (cmdName, align) {
  10564. var range = this.selection.getRange(),
  10565. txt;
  10566. //闭合时单独处理
  10567. if (range.collapsed) {
  10568. txt = this.document.createTextNode('p');
  10569. range.insertNode(txt);
  10570. }
  10571. doJustify(range, align);
  10572. if (txt) {
  10573. range.setStartBefore(txt).collapse(true);
  10574. domUtils.remove(txt);
  10575. }
  10576. range.select();
  10577. return true;
  10578. },
  10579. queryCommandValue:function () {
  10580. var startNode = this.selection.getStart(),
  10581. value = domUtils.getComputedStyle(startNode, 'text-align');
  10582. return defaultValue[value] ? value : 'left';
  10583. },
  10584. queryCommandState:function () {
  10585. var start = this.selection.getStart(),
  10586. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  10587. return cell? -1:0;
  10588. }
  10589. };
  10590. };
  10591. // plugins/font.js
  10592. /**
  10593. * 字体颜色,背景色,字号,字体,下划线,删除线
  10594. * @file
  10595. * @since 1.2.6.1
  10596. */
  10597. /**
  10598. * 字体颜色
  10599. * @command forecolor
  10600. * @method execCommand
  10601. * @param { String } cmd 命令字符串
  10602. * @param { String } value 色值(必须十六进制)
  10603. * @example
  10604. * ```javascript
  10605. * editor.execCommand( 'forecolor', '#000' );
  10606. * ```
  10607. */
  10608. /**
  10609. * 返回选区字体颜色
  10610. * @command forecolor
  10611. * @method queryCommandValue
  10612. * @param { String } cmd 命令字符串
  10613. * @return { String } 返回字体颜色
  10614. * @example
  10615. * ```javascript
  10616. * editor.queryCommandValue( 'forecolor' );
  10617. * ```
  10618. */
  10619. /**
  10620. * 字体背景颜色
  10621. * @command backcolor
  10622. * @method execCommand
  10623. * @param { String } cmd 命令字符串
  10624. * @param { String } value 色值(必须十六进制)
  10625. * @example
  10626. * ```javascript
  10627. * editor.execCommand( 'backcolor', '#000' );
  10628. * ```
  10629. */
  10630. /**
  10631. * 返回选区字体颜色
  10632. * @command backcolor
  10633. * @method queryCommandValue
  10634. * @param { String } cmd 命令字符串
  10635. * @return { String } 返回字体背景颜色
  10636. * @example
  10637. * ```javascript
  10638. * editor.queryCommandValue( 'backcolor' );
  10639. * ```
  10640. */
  10641. /**
  10642. * 字体大小
  10643. * @command fontsize
  10644. * @method execCommand
  10645. * @param { String } cmd 命令字符串
  10646. * @param { String } value 字体大小
  10647. * @example
  10648. * ```javascript
  10649. * editor.execCommand( 'fontsize', '14px' );
  10650. * ```
  10651. */
  10652. /**
  10653. * 返回选区字体大小
  10654. * @command fontsize
  10655. * @method queryCommandValue
  10656. * @param { String } cmd 命令字符串
  10657. * @return { String } 返回字体大小
  10658. * @example
  10659. * ```javascript
  10660. * editor.queryCommandValue( 'fontsize' );
  10661. * ```
  10662. */
  10663. /**
  10664. * 字体样式
  10665. * @command fontfamily
  10666. * @method execCommand
  10667. * @param { String } cmd 命令字符串
  10668. * @param { String } value 字体样式
  10669. * @example
  10670. * ```javascript
  10671. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10672. * ```
  10673. */
  10674. /**
  10675. * 返回选区字体样式
  10676. * @command fontfamily
  10677. * @method queryCommandValue
  10678. * @param { String } cmd 命令字符串
  10679. * @return { String } 返回字体样式
  10680. * @example
  10681. * ```javascript
  10682. * editor.queryCommandValue( 'fontfamily' );
  10683. * ```
  10684. */
  10685. /**
  10686. * 字体下划线,与删除线互斥
  10687. * @command underline
  10688. * @method execCommand
  10689. * @param { String } cmd 命令字符串
  10690. * @example
  10691. * ```javascript
  10692. * editor.execCommand( 'underline' );
  10693. * ```
  10694. */
  10695. /**
  10696. * 字体删除线,与下划线互斥
  10697. * @command strikethrough
  10698. * @method execCommand
  10699. * @param { String } cmd 命令字符串
  10700. * @example
  10701. * ```javascript
  10702. * editor.execCommand( 'strikethrough' );
  10703. * ```
  10704. */
  10705. /**
  10706. * 字体边框
  10707. * @command fontborder
  10708. * @method execCommand
  10709. * @param { String } cmd 命令字符串
  10710. * @example
  10711. * ```javascript
  10712. * editor.execCommand( 'fontborder' );
  10713. * ```
  10714. */
  10715. UE.plugins['font'] = function () {
  10716. var me = this,
  10717. fonts = {
  10718. 'forecolor': 'color',
  10719. 'backcolor': 'background-color',
  10720. 'fontsize': 'font-size',
  10721. 'fontfamily': 'font-family',
  10722. 'underline': 'text-decoration',
  10723. 'strikethrough': 'text-decoration',
  10724. 'fontborder': 'border'
  10725. },
  10726. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10727. needSetChild = {
  10728. 'forecolor': 'color',
  10729. 'backcolor': 'background-color',
  10730. 'fontsize': 'font-size',
  10731. 'fontfamily': 'font-family'
  10732. };
  10733. me.setOpt({
  10734. 'fontfamily': [
  10735. { name: 'songti', val: '宋体,SimSun'},
  10736. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10737. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10738. { name: 'heiti', val: '黑体, SimHei'},
  10739. { name: 'lishu', val: '隶书, SimLi'},
  10740. { name: 'andaleMono', val: 'andale mono'},
  10741. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10742. { name: 'arialBlack', val: 'arial black,avant garde'},
  10743. { name: 'comicSansMs', val: 'comic sans ms'},
  10744. { name: 'impact', val: 'impact,chicago'},
  10745. { name: 'timesNewRoman', val: 'times new roman'}
  10746. ],
  10747. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10748. });
  10749. function mergeWithParent(node){
  10750. var parent;
  10751. while(parent = node.parentNode){
  10752. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10753. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10754. }) == 1) {
  10755. parent.style.cssText += node.style.cssText;
  10756. domUtils.remove(node,true);
  10757. node = parent;
  10758. }else{
  10759. break;
  10760. }
  10761. }
  10762. }
  10763. function mergeChild(rng,cmdName,value){
  10764. if(needSetChild[cmdName]){
  10765. rng.adjustmentBoundary();
  10766. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10767. var start = rng.startContainer.childNodes[rng.startOffset];
  10768. if(start && domUtils.isTagNode(start,'span')){
  10769. var bk = rng.createBookmark();
  10770. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10771. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10772. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10773. return;
  10774. }
  10775. domUtils.removeStyle(span,needSetChild[cmdName]);
  10776. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10777. domUtils.remove(span,true)
  10778. }
  10779. });
  10780. rng.moveToBookmark(bk)
  10781. }
  10782. }
  10783. }
  10784. }
  10785. function mergesibling(rng,cmdName,value) {
  10786. var collapsed = rng.collapsed,
  10787. bk = rng.createBookmark(), common;
  10788. if (collapsed) {
  10789. common = bk.start.parentNode;
  10790. while (dtd.$inline[common.tagName]) {
  10791. common = common.parentNode;
  10792. }
  10793. } else {
  10794. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10795. }
  10796. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10797. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10798. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10799. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10800. domUtils.remove(span, true);
  10801. }else{
  10802. domUtils.removeStyle(span,'border');
  10803. }
  10804. return
  10805. }
  10806. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10807. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10808. }
  10809. if(!(cmdName=='fontborder' && value=='none')){
  10810. var next = span.nextSibling;
  10811. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10812. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10813. span.appendChild(next);
  10814. next = span.nextSibling;
  10815. continue;
  10816. }
  10817. if (next.style.cssText == span.style.cssText) {
  10818. domUtils.moveChild(next, span);
  10819. domUtils.remove(next);
  10820. }
  10821. if (span.nextSibling === next)
  10822. break;
  10823. next = span.nextSibling;
  10824. }
  10825. }
  10826. mergeWithParent(span);
  10827. if(browser.ie && browser.version > 8 ){
  10828. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10829. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10830. if(parent && !/background-color/.test(span.style.cssText)){
  10831. span.style.backgroundColor = parent.style.backgroundColor;
  10832. }
  10833. }
  10834. });
  10835. rng.moveToBookmark(bk);
  10836. mergeChild(rng,cmdName,value)
  10837. }
  10838. me.addInputRule(function (root) {
  10839. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10840. if (node.tagName == 'font') {
  10841. var cssStyle = [];
  10842. for (var p in node.attrs) {
  10843. switch (p) {
  10844. case 'size':
  10845. cssStyle.push('font-size:' +
  10846. ({
  10847. '1':'10',
  10848. '2':'12',
  10849. '3':'16',
  10850. '4':'18',
  10851. '5':'24',
  10852. '6':'32',
  10853. '7':'48'
  10854. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10855. break;
  10856. case 'color':
  10857. cssStyle.push('color:' + node.attrs[p]);
  10858. break;
  10859. case 'face':
  10860. cssStyle.push('font-family:' + node.attrs[p]);
  10861. break;
  10862. case 'style':
  10863. cssStyle.push(node.attrs[p]);
  10864. }
  10865. }
  10866. node.attrs = {
  10867. 'style': cssStyle.join(';')
  10868. };
  10869. } else {
  10870. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10871. node.attrs = {
  10872. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10873. }
  10874. }
  10875. node.tagName = 'span';
  10876. });
  10877. // utils.each(root.getNodesByTagName('span'), function (node) {
  10878. // var val;
  10879. // if(val = node.getAttr('class')){
  10880. // if(/fontstrikethrough/.test(val)){
  10881. // node.setStyle('text-decoration','line-through');
  10882. // if(node.attrs['class']){
  10883. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10884. // }else{
  10885. // node.setAttr('class')
  10886. // }
  10887. // }
  10888. // if(/fontborder/.test(val)){
  10889. // node.setStyle('border','1px solid #000');
  10890. // if(node.attrs['class']){
  10891. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10892. // }else{
  10893. // node.setAttr('class')
  10894. // }
  10895. // }
  10896. // }
  10897. // });
  10898. });
  10899. // me.addOutputRule(function(root){
  10900. // utils.each(root.getNodesByTagName('span'), function (node) {
  10901. // var val;
  10902. // if(val = node.getStyle('text-decoration')){
  10903. // if(/line-through/.test(val)){
  10904. // if(node.attrs['class']){
  10905. // node.attrs['class'] += ' fontstrikethrough';
  10906. // }else{
  10907. // node.setAttr('class','fontstrikethrough')
  10908. // }
  10909. // }
  10910. //
  10911. // node.setStyle('text-decoration')
  10912. // }
  10913. // if(val = node.getStyle('border')){
  10914. // if(/1px/.test(val) && /solid/.test(val)){
  10915. // if(node.attrs['class']){
  10916. // node.attrs['class'] += ' fontborder';
  10917. //
  10918. // }else{
  10919. // node.setAttr('class','fontborder')
  10920. // }
  10921. // }
  10922. // node.setStyle('border')
  10923. //
  10924. // }
  10925. // });
  10926. // });
  10927. for (var p in fonts) {
  10928. (function (cmd, style) {
  10929. UE.commands[cmd] = {
  10930. execCommand: function (cmdName, value) {
  10931. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10932. cmdName == 'fontborder' ? '1px solid #000' :
  10933. 'line-through');
  10934. var me = this,
  10935. range = this.selection.getRange(),
  10936. text;
  10937. if (value == 'default') {
  10938. if (range.collapsed) {
  10939. text = me.document.createTextNode('font');
  10940. range.insertNode(text).select();
  10941. }
  10942. me.execCommand('removeFormat', 'span,a', style);
  10943. if (text) {
  10944. range.setStartBefore(text).collapse(true);
  10945. domUtils.remove(text);
  10946. }
  10947. mergesibling(range,cmdName,value);
  10948. range.select()
  10949. } else {
  10950. if (!range.collapsed) {
  10951. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10952. me.execCommand('removeFormat', 'span,a', style);
  10953. }
  10954. range = me.selection.getRange();
  10955. range.applyInlineStyle('span', {'style': style + ':' + value});
  10956. mergesibling(range, cmdName,value);
  10957. range.select();
  10958. } else {
  10959. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10960. text = me.document.createTextNode('font');
  10961. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10962. //for ie hack when enter
  10963. range.insertNode(text);
  10964. if (needCmd[cmd]) {
  10965. range.selectNode(text).select();
  10966. me.execCommand('removeFormat', 'span,a', style, null);
  10967. span = domUtils.findParentByTagName(text, 'span', true);
  10968. range.setStartBefore(text);
  10969. }
  10970. span && (span.style.cssText += ';' + style + ':' + value);
  10971. range.collapse(true).select();
  10972. } else {
  10973. range.insertNode(text);
  10974. range.selectNode(text).select();
  10975. span = range.document.createElement('span');
  10976. if (needCmd[cmd]) {
  10977. //a标签内的不处理跳过
  10978. if (domUtils.findParentByTagName(text, 'a', true)) {
  10979. range.setStartBefore(text).setCursor();
  10980. domUtils.remove(text);
  10981. return;
  10982. }
  10983. me.execCommand('removeFormat', 'span,a', style);
  10984. }
  10985. span.style.cssText = style + ':' + value;
  10986. text.parentNode.insertBefore(span, text);
  10987. //修复,span套span 但样式不继承的问题
  10988. if (!browser.ie || browser.ie && browser.version == 9) {
  10989. var spanParent = span.parentNode;
  10990. while (!domUtils.isBlockElm(spanParent)) {
  10991. if (spanParent.tagName == 'SPAN') {
  10992. //opera合并style不会加入";"
  10993. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10994. }
  10995. spanParent = spanParent.parentNode;
  10996. }
  10997. }
  10998. if (opera) {
  10999. setTimeout(function () {
  11000. range.setStart(span, 0).collapse(true);
  11001. mergesibling(range, cmdName,value);
  11002. range.select();
  11003. });
  11004. } else {
  11005. range.setStart(span, 0).collapse(true);
  11006. mergesibling(range,cmdName,value);
  11007. range.select();
  11008. }
  11009. //trace:981
  11010. //domUtils.mergeToParent(span)
  11011. }
  11012. domUtils.remove(text);
  11013. }
  11014. }
  11015. return true;
  11016. },
  11017. queryCommandValue: function (cmdName) {
  11018. var startNode = this.selection.getStart();
  11019. //trace:946
  11020. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  11021. var tmpNode = startNode, value;
  11022. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  11023. if (tmpNode.nodeType == 1) {
  11024. value = domUtils.getComputedStyle(tmpNode, style);
  11025. if (value != 'none') {
  11026. return value;
  11027. }
  11028. }
  11029. tmpNode = tmpNode.parentNode;
  11030. }
  11031. return 'none';
  11032. }
  11033. if (cmdName == 'fontborder') {
  11034. var tmp = startNode, val;
  11035. while (tmp && dtd.$inline[tmp.tagName]) {
  11036. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  11037. if (/1px/.test(val) && /solid/.test(val)) {
  11038. return val;
  11039. }
  11040. }
  11041. tmp = tmp.parentNode;
  11042. }
  11043. return ''
  11044. }
  11045. if( cmdName == 'FontSize' ) {
  11046. var styleVal = domUtils.getComputedStyle(startNode, style),
  11047. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  11048. if( tmp ) {
  11049. return Math.floor( tmp[1] ) + tmp[2];
  11050. }
  11051. return styleVal;
  11052. }
  11053. return domUtils.getComputedStyle(startNode, style);
  11054. },
  11055. queryCommandState: function (cmdName) {
  11056. if (!needCmd[cmdName])
  11057. return 0;
  11058. var val = this.queryCommandValue(cmdName);
  11059. if (cmdName == 'fontborder') {
  11060. return /1px/.test(val) && /solid/.test(val)
  11061. } else {
  11062. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11063. }
  11064. }
  11065. };
  11066. })(p, fonts[p]);
  11067. }
  11068. };
  11069. // plugins/link.js
  11070. /**
  11071. * 超链接
  11072. * @file
  11073. * @since 1.2.6.1
  11074. */
  11075. /**
  11076. * 插入超链接
  11077. * @command link
  11078. * @method execCommand
  11079. * @param { String } cmd 命令字符串
  11080. * @param { Object } options 设置自定义属性,例如:url、title、target
  11081. * @example
  11082. * ```javascript
  11083. * editor.execCommand( 'link', '{
  11084. * url:'ueditor.baidu.com',
  11085. * title:'ueditor',
  11086. * target:'_blank'
  11087. * }' );
  11088. * ```
  11089. */
  11090. /**
  11091. * 返回当前选中的第一个超链接节点
  11092. * @command link
  11093. * @method queryCommandValue
  11094. * @param { String } cmd 命令字符串
  11095. * @return { Element } 超链接节点
  11096. * @example
  11097. * ```javascript
  11098. * editor.queryCommandValue( 'link' );
  11099. * ```
  11100. */
  11101. /**
  11102. * 取消超链接
  11103. * @command unlink
  11104. * @method execCommand
  11105. * @param { String } cmd 命令字符串
  11106. * @example
  11107. * ```javascript
  11108. * editor.execCommand( 'unlink');
  11109. * ```
  11110. */
  11111. UE.plugins['link'] = function(){
  11112. function optimize( range ) {
  11113. var start = range.startContainer,end = range.endContainer;
  11114. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  11115. range.setStartBefore( start );
  11116. }
  11117. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  11118. range.setEndAfter( end );
  11119. }
  11120. }
  11121. UE.commands['unlink'] = {
  11122. execCommand : function() {
  11123. var range = this.selection.getRange(),
  11124. bookmark;
  11125. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  11126. return;
  11127. }
  11128. bookmark = range.createBookmark();
  11129. optimize( range );
  11130. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  11131. },
  11132. queryCommandState : function(){
  11133. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11134. }
  11135. };
  11136. function doLink(range,opt,me){
  11137. var rngClone = range.cloneRange(),
  11138. link = me.queryCommandValue('link');
  11139. optimize( range = range.adjustmentBoundary() );
  11140. var start = range.startContainer;
  11141. if(start.nodeType == 1 && link){
  11142. start = start.childNodes[range.startOffset];
  11143. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  11144. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  11145. }
  11146. }
  11147. if( !rngClone.collapsed || link){
  11148. range.removeInlineStyle( 'a' );
  11149. rngClone = range.cloneRange();
  11150. }
  11151. if ( rngClone.collapsed ) {
  11152. var a = range.document.createElement( 'a'),
  11153. text = '';
  11154. if(opt.textValue){
  11155. text = utils.html(opt.textValue);
  11156. delete opt.textValue;
  11157. }else{
  11158. text = utils.html(opt.href);
  11159. }
  11160. domUtils.setAttributes( a, opt );
  11161. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  11162. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  11163. range.setStartAfter(start).collapse(true);
  11164. }
  11165. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11166. range.insertNode(a).selectNode( a );
  11167. } else {
  11168. range.applyInlineStyle( 'a', opt );
  11169. }
  11170. }
  11171. UE.commands['link'] = {
  11172. execCommand : function( cmdName, opt ) {
  11173. var range;
  11174. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  11175. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  11176. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  11177. doLink(range=this.selection.getRange(),opt,this);
  11178. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11179. range.collapse().select(true);
  11180. },
  11181. queryCommandValue : function() {
  11182. var range = this.selection.getRange(),
  11183. node;
  11184. if ( range.collapsed ) {
  11185. // node = this.selection.getStart();
  11186. //在ie下getstart()取值偏上了
  11187. node = range.startContainer;
  11188. node = node.nodeType == 1 ? node : node.parentNode;
  11189. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  11190. return node;
  11191. }
  11192. } else {
  11193. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11194. range.shrinkBoundary();
  11195. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11196. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  11197. common = range.getCommonAncestor();
  11198. node = domUtils.findParentByTagName( common, 'a', true );
  11199. if ( !node && common.nodeType == 1){
  11200. var as = common.getElementsByTagName( 'a' ),
  11201. ps,pe;
  11202. for ( var i = 0,ci; ci = as[i++]; ) {
  11203. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  11204. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11205. &&
  11206. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11207. ) {
  11208. node = ci;
  11209. break;
  11210. }
  11211. }
  11212. }
  11213. return node;
  11214. }
  11215. },
  11216. queryCommandState : function() {
  11217. //判断如果是视频的话连接不可用
  11218. //fix 853
  11219. var img = this.selection.getRange().getClosedNode(),
  11220. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  11221. return flag ? -1 : 0;
  11222. }
  11223. };
  11224. };
  11225. // plugins/iframe.js
  11226. ///import core
  11227. ///import plugins\inserthtml.js
  11228. ///commands 插入框架
  11229. ///commandsName InsertFrame
  11230. ///commandsTitle 插入Iframe
  11231. ///commandsDialog dialogs\insertframe
  11232. UE.plugins['insertframe'] = function() {
  11233. var me =this;
  11234. function deleteIframe(){
  11235. me._iframe && delete me._iframe;
  11236. }
  11237. me.addListener("selectionchange",function(){
  11238. deleteIframe();
  11239. });
  11240. };
  11241. // plugins/scrawl.js
  11242. ///import core
  11243. ///commands 涂鸦
  11244. ///commandsName Scrawl
  11245. ///commandsTitle 涂鸦
  11246. ///commandsDialog dialogs\scrawl
  11247. UE.commands['scrawl'] = {
  11248. queryCommandState : function(){
  11249. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  11250. }
  11251. };
  11252. // plugins/removeformat.js
  11253. /**
  11254. * 清除格式
  11255. * @file
  11256. * @since 1.2.6.1
  11257. */
  11258. /**
  11259. * 清除文字样式
  11260. * @command removeformat
  11261. * @method execCommand
  11262. * @param { String } cmd 命令字符串
  11263. * @param {String} tags 以逗号隔开的标签。如:strong
  11264. * @param {String} style 样式如:color
  11265. * @param {String} attrs 属性如:width
  11266. * @example
  11267. * ```javascript
  11268. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11269. * ```
  11270. */
  11271. UE.plugins['removeformat'] = function(){
  11272. var me = this;
  11273. me.setOpt({
  11274. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11275. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  11276. });
  11277. me.commands['removeformat'] = {
  11278. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  11279. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  11280. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  11281. range = new dom.Range( this.document ),
  11282. bookmark,node,parent,
  11283. filter = function( node ) {
  11284. return node.nodeType == 1;
  11285. };
  11286. function isRedundantSpan (node) {
  11287. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  11288. return 0;
  11289. }
  11290. if (browser.ie) {
  11291. //ie 下判断实效,所以只能简单用style来判断
  11292. //return node.style.cssText == '' ? 1 : 0;
  11293. var attrs = node.attributes;
  11294. if ( attrs.length ) {
  11295. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  11296. if ( attrs[i].specified ) {
  11297. return 0;
  11298. }
  11299. }
  11300. return 1;
  11301. }
  11302. }
  11303. return !node.attributes.length;
  11304. }
  11305. function doRemove( range ) {
  11306. var bookmark1 = range.createBookmark();
  11307. if ( range.collapsed ) {
  11308. range.enlarge( true );
  11309. }
  11310. //不能把a标签切了
  11311. if(!notIncludeA){
  11312. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  11313. if(aNode){
  11314. range.setStartBefore(aNode);
  11315. }
  11316. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  11317. if(aNode){
  11318. range.setEndAfter(aNode);
  11319. }
  11320. }
  11321. bookmark = range.createBookmark();
  11322. node = bookmark.start;
  11323. //切开始
  11324. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11325. domUtils.breakParent( node, parent );
  11326. domUtils.clearEmptySibling( node );
  11327. }
  11328. if ( bookmark.end ) {
  11329. //切结束
  11330. node = bookmark.end;
  11331. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11332. domUtils.breakParent( node, parent );
  11333. domUtils.clearEmptySibling( node );
  11334. }
  11335. //开始去除样式
  11336. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  11337. next;
  11338. while ( current ) {
  11339. if ( current == bookmark.end ) {
  11340. break;
  11341. }
  11342. next = domUtils.getNextDomNode( current, true, filter );
  11343. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  11344. if ( tagReg.test( current.tagName ) ) {
  11345. if ( style ) {
  11346. domUtils.removeStyle( current, style );
  11347. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  11348. domUtils.remove( current, true );
  11349. }
  11350. } else {
  11351. domUtils.remove( current, true );
  11352. }
  11353. } else {
  11354. //trace:939 不能把list上的样式去掉
  11355. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  11356. domUtils.removeAttributes( current, removeFormatAttributes );
  11357. if ( isRedundantSpan( current ) ){
  11358. domUtils.remove( current, true );
  11359. }
  11360. }
  11361. }
  11362. }
  11363. current = next;
  11364. }
  11365. }
  11366. //trace:1035
  11367. //trace:1096 不能把td上的样式去掉,比如边框
  11368. var pN = bookmark.start.parentNode;
  11369. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  11370. domUtils.removeAttributes( pN,removeFormatAttributes );
  11371. }
  11372. pN = bookmark.end.parentNode;
  11373. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  11374. domUtils.removeAttributes( pN,removeFormatAttributes );
  11375. }
  11376. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  11377. //清除冗余的代码 <b><bookmark></b>
  11378. var node = range.startContainer,
  11379. tmp,
  11380. collapsed = range.collapsed;
  11381. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11382. tmp = node.parentNode;
  11383. range.setStartBefore(node);
  11384. //trace:937
  11385. //更新结束边界
  11386. if(range.startContainer === range.endContainer){
  11387. range.endOffset--;
  11388. }
  11389. domUtils.remove(node);
  11390. node = tmp;
  11391. }
  11392. if(!collapsed){
  11393. node = range.endContainer;
  11394. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11395. tmp = node.parentNode;
  11396. range.setEndBefore(node);
  11397. domUtils.remove(node);
  11398. node = tmp;
  11399. }
  11400. }
  11401. }
  11402. range = this.selection.getRange();
  11403. doRemove( range );
  11404. range.select();
  11405. }
  11406. };
  11407. };
  11408. // plugins/blockquote.js
  11409. /**
  11410. * 添加引用
  11411. * @file
  11412. * @since 1.2.6.1
  11413. */
  11414. /**
  11415. * 添加引用
  11416. * @command blockquote
  11417. * @method execCommand
  11418. * @param { String } cmd 命令字符串
  11419. * @example
  11420. * ```javascript
  11421. * editor.execCommand( 'blockquote' );
  11422. * ```
  11423. */
  11424. /**
  11425. * 添加引用
  11426. * @command blockquote
  11427. * @method execCommand
  11428. * @param { String } cmd 命令字符串
  11429. * @param { Object } attrs 节点属性
  11430. * @example
  11431. * ```javascript
  11432. * editor.execCommand( 'blockquote',{
  11433. * style: "color: red;"
  11434. * } );
  11435. * ```
  11436. */
  11437. UE.plugins['blockquote'] = function(){
  11438. var me = this;
  11439. function getObj(editor){
  11440. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  11441. }
  11442. me.commands['blockquote'] = {
  11443. execCommand : function( cmdName, attrs ) {
  11444. var range = this.selection.getRange(),
  11445. obj = getObj(this),
  11446. blockquote = dtd.blockquote,
  11447. bookmark = range.createBookmark();
  11448. if ( obj ) {
  11449. var start = range.startContainer,
  11450. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  11451. end = range.endContainer,
  11452. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  11453. //处理一下li
  11454. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  11455. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  11456. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  11457. domUtils.remove(obj,true);
  11458. }else{
  11459. domUtils.breakParent(startBlock,obj);
  11460. }
  11461. if(startBlock !== endBlock){
  11462. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  11463. if(obj){
  11464. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  11465. obj.parentNode && domUtils.remove(obj,true);
  11466. }else{
  11467. domUtils.breakParent(endBlock,obj);
  11468. }
  11469. }
  11470. }
  11471. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  11472. for(var i=0,bi;bi=blockquotes[i++];){
  11473. if(!bi.childNodes.length){
  11474. domUtils.remove(bi);
  11475. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  11476. domUtils.remove(bi,true);
  11477. }
  11478. }
  11479. } else {
  11480. var tmpRange = range.cloneRange(),
  11481. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11482. preNode = node,
  11483. doEnd = 1;
  11484. //调整开始
  11485. while ( 1 ) {
  11486. if ( domUtils.isBody(node) ) {
  11487. if ( preNode !== node ) {
  11488. if ( range.collapsed ) {
  11489. tmpRange.selectNode( preNode );
  11490. doEnd = 0;
  11491. } else {
  11492. tmpRange.setStartBefore( preNode );
  11493. }
  11494. }else{
  11495. tmpRange.setStart(node,0);
  11496. }
  11497. break;
  11498. }
  11499. if ( !blockquote[node.tagName] ) {
  11500. if ( range.collapsed ) {
  11501. tmpRange.selectNode( preNode );
  11502. } else{
  11503. tmpRange.setStartBefore( preNode);
  11504. }
  11505. break;
  11506. }
  11507. preNode = node;
  11508. node = node.parentNode;
  11509. }
  11510. //调整结束
  11511. if ( doEnd ) {
  11512. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11513. while ( 1 ) {
  11514. if ( domUtils.isBody( node ) ) {
  11515. if ( preNode !== node ) {
  11516. tmpRange.setEndAfter( preNode );
  11517. } else {
  11518. tmpRange.setEnd( node, node.childNodes.length );
  11519. }
  11520. break;
  11521. }
  11522. if ( !blockquote[node.tagName] ) {
  11523. tmpRange.setEndAfter( preNode );
  11524. break;
  11525. }
  11526. preNode = node;
  11527. node = node.parentNode;
  11528. }
  11529. }
  11530. node = range.document.createElement( 'blockquote' );
  11531. domUtils.setAttributes( node, attrs );
  11532. node.appendChild( tmpRange.extractContents() );
  11533. tmpRange.insertNode( node );
  11534. //去除重复的
  11535. var childs = domUtils.getElementsByTagName(node,'blockquote');
  11536. for(var i=0,ci;ci=childs[i++];){
  11537. if(ci.parentNode){
  11538. domUtils.remove(ci,true);
  11539. }
  11540. }
  11541. }
  11542. range.moveToBookmark( bookmark ).select();
  11543. },
  11544. queryCommandState : function() {
  11545. return getObj(this) ? 1 : 0;
  11546. }
  11547. };
  11548. };
  11549. // plugins/convertcase.js
  11550. /**
  11551. * 大小写转换
  11552. * @file
  11553. * @since 1.2.6.1
  11554. */
  11555. /**
  11556. * 把选区内文本变大写,与“tolowercase”命令互斥
  11557. * @command touppercase
  11558. * @method execCommand
  11559. * @param { String } cmd 命令字符串
  11560. * @example
  11561. * ```javascript
  11562. * editor.execCommand( 'touppercase' );
  11563. * ```
  11564. */
  11565. /**
  11566. * 把选区内文本变小写,与“touppercase”命令互斥
  11567. * @command tolowercase
  11568. * @method execCommand
  11569. * @param { String } cmd 命令字符串
  11570. * @example
  11571. * ```javascript
  11572. * editor.execCommand( 'tolowercase' );
  11573. * ```
  11574. */
  11575. UE.commands['touppercase'] =
  11576. UE.commands['tolowercase'] = {
  11577. execCommand:function (cmd) {
  11578. var me = this;
  11579. var rng = me.selection.getRange();
  11580. if(rng.collapsed){
  11581. return rng;
  11582. }
  11583. var bk = rng.createBookmark(),
  11584. bkEnd = bk.end,
  11585. filterFn = function( node ) {
  11586. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  11587. },
  11588. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  11589. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  11590. if ( curNode.nodeType == 3 ) {
  11591. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11592. }
  11593. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  11594. if(curNode === bkEnd){
  11595. break;
  11596. }
  11597. }
  11598. rng.moveToBookmark(bk).select();
  11599. }
  11600. };
  11601. // plugins/indent.js
  11602. /**
  11603. * 首行缩进
  11604. * @file
  11605. * @since 1.2.6.1
  11606. */
  11607. /**
  11608. * 缩进
  11609. * @command indent
  11610. * @method execCommand
  11611. * @param { String } cmd 命令字符串
  11612. * @example
  11613. * ```javascript
  11614. * editor.execCommand( 'indent' );
  11615. * ```
  11616. */
  11617. UE.commands['indent'] = {
  11618. execCommand : function() {
  11619. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11620. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  11621. },
  11622. queryCommandState : function() {
  11623. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11624. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11625. }
  11626. };
  11627. // plugins/print.js
  11628. /**
  11629. * 打印
  11630. * @file
  11631. * @since 1.2.6.1
  11632. */
  11633. /**
  11634. * 打印
  11635. * @command print
  11636. * @method execCommand
  11637. * @param { String } cmd 命令字符串
  11638. * @example
  11639. * ```javascript
  11640. * editor.execCommand( 'print' );
  11641. * ```
  11642. */
  11643. UE.commands['print'] = {
  11644. execCommand : function(){
  11645. this.window.print();
  11646. },
  11647. notNeedUndo : 1
  11648. };
  11649. // plugins/preview.js
  11650. /**
  11651. * 预览
  11652. * @file
  11653. * @since 1.2.6.1
  11654. */
  11655. /**
  11656. * 预览
  11657. * @command preview
  11658. * @method execCommand
  11659. * @param { String } cmd 命令字符串
  11660. * @example
  11661. * ```javascript
  11662. * editor.execCommand( 'preview' );
  11663. * ```
  11664. */
  11665. UE.commands['preview'] = {
  11666. execCommand : function(){
  11667. var w = window.open('', '_blank', ''),
  11668. d = w.document;
  11669. d.open();
  11670. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  11671. "setTimeout(function(){uParse('div',{rootPath: '"+ this.options.UEDITOR_HOME_URL +"'})},300)" +
  11672. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  11673. d.close();
  11674. },
  11675. notNeedUndo : 1
  11676. };
  11677. // plugins/selectall.js
  11678. /**
  11679. * 全选
  11680. * @file
  11681. * @since 1.2.6.1
  11682. */
  11683. /**
  11684. * 选中所有内容
  11685. * @command selectall
  11686. * @method execCommand
  11687. * @param { String } cmd 命令字符串
  11688. * @example
  11689. * ```javascript
  11690. * editor.execCommand( 'selectall' );
  11691. * ```
  11692. */
  11693. UE.plugins['selectall'] = function(){
  11694. var me = this;
  11695. me.commands['selectall'] = {
  11696. execCommand : function(){
  11697. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11698. var me = this,body = me.body,
  11699. range = me.selection.getRange();
  11700. range.selectNodeContents(body);
  11701. if(domUtils.isEmptyBlock(body)){
  11702. //opera不能自动合并到元素的里边,要手动处理一下
  11703. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11704. range.setStartAtFirst(body.firstChild);
  11705. }
  11706. range.collapse(true);
  11707. }
  11708. range.select(true);
  11709. },
  11710. notNeedUndo : 1
  11711. };
  11712. //快捷键
  11713. me.addshortcutkey({
  11714. "selectAll" : "ctrl+65"
  11715. });
  11716. };
  11717. // plugins/paragraph.js
  11718. /**
  11719. * 段落样式
  11720. * @file
  11721. * @since 1.2.6.1
  11722. */
  11723. /**
  11724. * 段落格式
  11725. * @command paragraph
  11726. * @method execCommand
  11727. * @param { String } cmd 命令字符串
  11728. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11729. * @param {Object} attrs 标签的属性
  11730. * @example
  11731. * ```javascript
  11732. * editor.execCommand( 'Paragraph','h1','{
  11733. * class:'test'
  11734. * }' );
  11735. * ```
  11736. */
  11737. /**
  11738. * 返回选区内节点标签名
  11739. * @command paragraph
  11740. * @method queryCommandValue
  11741. * @param { String } cmd 命令字符串
  11742. * @return { String } 节点标签名
  11743. * @example
  11744. * ```javascript
  11745. * editor.queryCommandValue( 'Paragraph' );
  11746. * ```
  11747. */
  11748. UE.plugins['paragraph'] = function() {
  11749. var me = this,
  11750. block = domUtils.isBlockElm,
  11751. notExchange = ['TD','LI','PRE'],
  11752. doParagraph = function(range,style,attrs,sourceCmdName){
  11753. var bookmark = range.createBookmark(),
  11754. filterFn = function( node ) {
  11755. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11756. },
  11757. para;
  11758. range.enlarge( true );
  11759. var bookmark2 = range.createBookmark(),
  11760. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11761. tmpRange = range.cloneRange(),
  11762. tmpNode;
  11763. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11764. if ( current.nodeType == 3 || !block( current ) ) {
  11765. tmpRange.setStartBefore( current );
  11766. while ( current && current !== bookmark2.end && !block( current ) ) {
  11767. tmpNode = current;
  11768. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11769. return !block( node );
  11770. } );
  11771. }
  11772. tmpRange.setEndAfter( tmpNode );
  11773. para = range.document.createElement( style );
  11774. if(attrs){
  11775. domUtils.setAttributes(para,attrs);
  11776. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11777. para.style.cssText = attrs.style;
  11778. }
  11779. }
  11780. para.appendChild( tmpRange.extractContents() );
  11781. //需要内容占位
  11782. if(domUtils.isEmptyNode(para)){
  11783. domUtils.fillChar(range.document,para);
  11784. }
  11785. tmpRange.insertNode( para );
  11786. var parent = para.parentNode;
  11787. //如果para上一级是一个block元素且不是body,td就删除它
  11788. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11789. //存储dir,style
  11790. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11791. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11792. //trace:1070
  11793. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11794. //trace:1030
  11795. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11796. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11797. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11798. }
  11799. //trace:1706 选择的就是h1-6要删除
  11800. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11801. domUtils.setAttributes(parent,attrs);
  11802. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11803. parent.style.cssText = attrs.style;
  11804. }
  11805. domUtils.remove(para,true);
  11806. para = parent;
  11807. }else{
  11808. domUtils.remove( para.parentNode, true );
  11809. }
  11810. }
  11811. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11812. current = parent;
  11813. }else{
  11814. current = para;
  11815. }
  11816. current = domUtils.getNextDomNode( current, false, filterFn );
  11817. } else {
  11818. current = domUtils.getNextDomNode( current, true, filterFn );
  11819. }
  11820. }
  11821. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11822. };
  11823. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11824. me.commands['paragraph'] = {
  11825. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11826. var range = this.selection.getRange();
  11827. //闭合时单独处理
  11828. if(range.collapsed){
  11829. var txt = this.document.createTextNode('p');
  11830. range.insertNode(txt);
  11831. //去掉冗余的fillchar
  11832. if(browser.ie){
  11833. var node = txt.previousSibling;
  11834. if(node && domUtils.isWhitespace(node)){
  11835. domUtils.remove(node);
  11836. }
  11837. node = txt.nextSibling;
  11838. if(node && domUtils.isWhitespace(node)){
  11839. domUtils.remove(node);
  11840. }
  11841. }
  11842. }
  11843. range = doParagraph(range,style,attrs,sourceCmdName);
  11844. if(txt){
  11845. range.setStartBefore(txt).collapse(true);
  11846. var pN = txt.parentNode;
  11847. domUtils.remove(txt);
  11848. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11849. domUtils.fillNode(this.document,pN);
  11850. }
  11851. }
  11852. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11853. var child = range.startContainer.childNodes[range.startOffset];
  11854. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11855. range.setStart(child,0).collapse(true);
  11856. }
  11857. }
  11858. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11859. range.select();
  11860. return true;
  11861. },
  11862. queryCommandValue : function() {
  11863. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11864. return node ? node.tagName.toLowerCase() : '';
  11865. }
  11866. };
  11867. };
  11868. // plugins/directionality.js
  11869. /**
  11870. * 设置文字输入的方向的插件
  11871. * @file
  11872. * @since 1.2.6.1
  11873. */
  11874. (function() {
  11875. var block = domUtils.isBlockElm ,
  11876. getObj = function(editor){
  11877. // var startNode = editor.selection.getStart(),
  11878. // parents;
  11879. // if ( startNode ) {
  11880. // //查找所有的是block的父亲节点
  11881. // parents = domUtils.findParents( startNode, true, block, true );
  11882. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11883. // if ( ci.getAttribute( 'dir' ) ) {
  11884. // return ci;
  11885. // }
  11886. // }
  11887. // }
  11888. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n && n.nodeType == 1 && n.getAttribute('dir')});
  11889. },
  11890. doDirectionality = function(range,editor,forward){
  11891. var bookmark,
  11892. filterFn = function( node ) {
  11893. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11894. },
  11895. obj = getObj( editor );
  11896. if ( obj && range.collapsed ) {
  11897. obj.setAttribute( 'dir', forward );
  11898. return range;
  11899. }
  11900. bookmark = range.createBookmark();
  11901. range.enlarge( true );
  11902. var bookmark2 = range.createBookmark(),
  11903. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11904. tmpRange = range.cloneRange(),
  11905. tmpNode;
  11906. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11907. if ( current.nodeType == 3 || !block( current ) ) {
  11908. tmpRange.setStartBefore( current );
  11909. while ( current && current !== bookmark2.end && !block( current ) ) {
  11910. tmpNode = current;
  11911. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11912. return !block( node );
  11913. } );
  11914. }
  11915. tmpRange.setEndAfter( tmpNode );
  11916. var common = tmpRange.getCommonAncestor();
  11917. if ( !domUtils.isBody( common ) && block( common ) ) {
  11918. //遍历到了block节点
  11919. common.setAttribute( 'dir', forward );
  11920. current = common;
  11921. } else {
  11922. //没有遍历到,添加一个block节点
  11923. var p = range.document.createElement( 'p' );
  11924. p.setAttribute( 'dir', forward );
  11925. var frag = tmpRange.extractContents();
  11926. p.appendChild( frag );
  11927. tmpRange.insertNode( p );
  11928. current = p;
  11929. }
  11930. current = domUtils.getNextDomNode( current, false, filterFn );
  11931. } else {
  11932. current = domUtils.getNextDomNode( current, true, filterFn );
  11933. }
  11934. }
  11935. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11936. };
  11937. /**
  11938. * 文字输入方向
  11939. * @command directionality
  11940. * @method execCommand
  11941. * @param { String } cmdName 命令字符串
  11942. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11943. * @example
  11944. * ```javascript
  11945. * editor.execCommand( 'directionality', 'ltr');
  11946. * ```
  11947. */
  11948. /**
  11949. * 查询当前选区的文字输入方向
  11950. * @command directionality
  11951. * @method queryCommandValue
  11952. * @param { String } cmdName 命令字符串
  11953. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11954. * @example
  11955. * ```javascript
  11956. * editor.queryCommandValue( 'directionality');
  11957. * ```
  11958. */
  11959. UE.commands['directionality'] = {
  11960. execCommand : function( cmdName,forward ) {
  11961. var range = this.selection.getRange();
  11962. //闭合时单独处理
  11963. if(range.collapsed){
  11964. var txt = this.document.createTextNode('d');
  11965. range.insertNode(txt);
  11966. }
  11967. doDirectionality(range,this,forward);
  11968. if(txt){
  11969. range.setStartBefore(txt).collapse(true);
  11970. domUtils.remove(txt);
  11971. }
  11972. range.select();
  11973. return true;
  11974. },
  11975. queryCommandValue : function() {
  11976. var node = getObj(this);
  11977. return node ? node.getAttribute('dir') : 'ltr';
  11978. }
  11979. };
  11980. })();
  11981. // plugins/horizontal.js
  11982. /**
  11983. * 插入分割线插件
  11984. * @file
  11985. * @since 1.2.6.1
  11986. */
  11987. /**
  11988. * 插入分割线
  11989. * @command horizontal
  11990. * @method execCommand
  11991. * @param { String } cmdName 命令字符串
  11992. * @example
  11993. * ```javascript
  11994. * editor.execCommand( 'horizontal' );
  11995. * ```
  11996. */
  11997. UE.plugins['horizontal'] = function(){
  11998. var me = this;
  11999. me.commands['horizontal'] = {
  12000. execCommand : function( cmdName ) {
  12001. var me = this;
  12002. if(me.queryCommandState(cmdName)!==-1){
  12003. me.execCommand('insertHtml','<hr>');
  12004. var range = me.selection.getRange(),
  12005. start = range.startContainer;
  12006. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  12007. var tmp;
  12008. if(tmp = start.childNodes[range.startOffset - 1]){
  12009. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  12010. if(me.options.enterTag == 'p'){
  12011. tmp = me.document.createElement('p');
  12012. range.insertNode(tmp);
  12013. range.setStart(tmp,0).setCursor();
  12014. }else{
  12015. tmp = me.document.createElement('br');
  12016. range.insertNode(tmp);
  12017. range.setStartBefore(tmp).setCursor();
  12018. }
  12019. }
  12020. }
  12021. }
  12022. return true;
  12023. }
  12024. },
  12025. //边界在table里不能加分隔线
  12026. queryCommandState : function() {
  12027. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  12028. }
  12029. };
  12030. // me.addListener('delkeyup',function(){
  12031. // var rng = this.selection.getRange();
  12032. // if(browser.ie && browser.version > 8){
  12033. // rng.txtToElmBoundary(true);
  12034. // if(domUtils.isStartInblock(rng)){
  12035. // var tmpNode = rng.startContainer;
  12036. // var pre = tmpNode.previousSibling;
  12037. // if(pre && domUtils.isTagNode(pre,'hr')){
  12038. // domUtils.remove(pre);
  12039. // rng.select();
  12040. // return;
  12041. // }
  12042. // }
  12043. // }
  12044. // if(domUtils.isBody(rng.startContainer)){
  12045. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  12046. // if(hr && hr.nodeName == 'HR'){
  12047. // var next = hr.nextSibling;
  12048. // if(next){
  12049. // rng.setStart(next,0)
  12050. // }else if(hr.previousSibling){
  12051. // rng.setStartAtLast(hr.previousSibling)
  12052. // }else{
  12053. // var p = this.document.createElement('p');
  12054. // hr.parentNode.insertBefore(p,hr);
  12055. // domUtils.fillNode(this.document,p);
  12056. // rng.setStart(p,0);
  12057. // }
  12058. // domUtils.remove(hr);
  12059. // rng.setCursor(false,true);
  12060. // }
  12061. // }
  12062. // })
  12063. me.addListener('delkeydown',function(name,evt){
  12064. var rng = this.selection.getRange();
  12065. rng.txtToElmBoundary(true);
  12066. if(domUtils.isStartInblock(rng)){
  12067. var tmpNode = rng.startContainer;
  12068. var pre = tmpNode.previousSibling;
  12069. if(pre && domUtils.isTagNode(pre,'hr')){
  12070. domUtils.remove(pre);
  12071. rng.select();
  12072. domUtils.preventDefault(evt);
  12073. return true;
  12074. }
  12075. }
  12076. })
  12077. };
  12078. // plugins/time.js
  12079. /**
  12080. * 插入时间和日期
  12081. * @file
  12082. * @since 1.2.6.1
  12083. */
  12084. /**
  12085. * 插入时间,默认格式:12:59:59
  12086. * @command time
  12087. * @method execCommand
  12088. * @param { String } cmd 命令字符串
  12089. * @example
  12090. * ```javascript
  12091. * editor.execCommand( 'time');
  12092. * ```
  12093. */
  12094. /**
  12095. * 插入日期,默认格式:2013-08-30
  12096. * @command date
  12097. * @method execCommand
  12098. * @param { String } cmd 命令字符串
  12099. * @example
  12100. * ```javascript
  12101. * editor.execCommand( 'date');
  12102. * ```
  12103. */
  12104. UE.commands['time'] = UE.commands["date"] = {
  12105. execCommand : function(cmd, format){
  12106. var date = new Date;
  12107. function formatTime(date, format) {
  12108. var hh = ('0' + date.getHours()).slice(-2),
  12109. ii = ('0' + date.getMinutes()).slice(-2),
  12110. ss = ('0' + date.getSeconds()).slice(-2);
  12111. format = format || 'hh:ii:ss';
  12112. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12113. }
  12114. function formatDate(date, format) {
  12115. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12116. yy = yyyy.slice(-2),
  12117. mm = ('0' + (date.getMonth()+1)).slice(-2),
  12118. dd = ('0' + date.getDate()).slice(-2);
  12119. format = format || 'yyyy-mm-dd';
  12120. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12121. }
  12122. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  12123. }
  12124. };
  12125. // plugins/rowspacing.js
  12126. /**
  12127. * 段前段后间距插件
  12128. * @file
  12129. * @since 1.2.6.1
  12130. */
  12131. /**
  12132. * 设置段间距
  12133. * @command rowspacing
  12134. * @method execCommand
  12135. * @param { String } cmd 命令字符串
  12136. * @param { String } value 段间距的值,以px为单位
  12137. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12138. * @example
  12139. * ```javascript
  12140. * editor.execCommand( 'rowspacing', '10', 'top' );
  12141. * ```
  12142. */
  12143. UE.plugins['rowspacing'] = function(){
  12144. var me = this;
  12145. me.setOpt({
  12146. 'rowspacingtop':['5', '10', '15', '20', '25'],
  12147. 'rowspacingbottom':['5', '10', '15', '20', '25']
  12148. });
  12149. me.commands['rowspacing'] = {
  12150. execCommand : function( cmdName,value,dir ) {
  12151. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  12152. return true;
  12153. },
  12154. queryCommandValue : function(cmdName,dir) {
  12155. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  12156. value;
  12157. //trace:1026
  12158. if(pN){
  12159. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  12160. return !value ? 0 : value;
  12161. }
  12162. return 0;
  12163. }
  12164. };
  12165. };
  12166. // plugins/lineheight.js
  12167. /**
  12168. * 设置行内间距
  12169. * @file
  12170. * @since 1.2.6.1
  12171. */
  12172. UE.plugins['lineheight'] = function(){
  12173. var me = this;
  12174. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  12175. /**
  12176. * 行距
  12177. * @command lineheight
  12178. * @method execCommand
  12179. * @param { String } cmdName 命令字符串
  12180. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12181. * @example
  12182. * ```javascript
  12183. * editor.execCommand( 'lineheight', 1.5);
  12184. * ```
  12185. */
  12186. /**
  12187. * 查询当前选区内容的行高大小
  12188. * @command lineheight
  12189. * @method queryCommandValue
  12190. * @param { String } cmd 命令字符串
  12191. * @return { String } 返回当前行高大小
  12192. * @example
  12193. * ```javascript
  12194. * editor.queryCommandValue( 'lineheight' );
  12195. * ```
  12196. */
  12197. me.commands['lineheight'] = {
  12198. execCommand : function( cmdName,value ) {
  12199. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  12200. return true;
  12201. },
  12202. queryCommandValue : function() {
  12203. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  12204. if(pN){
  12205. var value = domUtils.getComputedStyle(pN,'line-height');
  12206. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  12207. }
  12208. }
  12209. };
  12210. };
  12211. // plugins/insertcode.js
  12212. /**
  12213. * 插入代码插件
  12214. * @file
  12215. * @since 1.2.6.1
  12216. */
  12217. UE.plugins['insertcode'] = function() {
  12218. var me = this;
  12219. me.ready(function(){
  12220. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12221. me.document)
  12222. });
  12223. me.setOpt('insertcode',{
  12224. 'as3':'ActionScript3',
  12225. 'bash':'Bash/Shell',
  12226. 'cpp':'C/C++',
  12227. 'css':'Css',
  12228. 'cf':'CodeFunction',
  12229. 'c#':'C#',
  12230. 'delphi':'Delphi',
  12231. 'diff':'Diff',
  12232. 'erlang':'Erlang',
  12233. 'groovy':'Groovy',
  12234. 'html':'Html',
  12235. 'java':'Java',
  12236. 'jfx':'JavaFx',
  12237. 'js':'Javascript',
  12238. 'pl':'Perl',
  12239. 'php':'Php',
  12240. 'plain':'Plain Text',
  12241. 'ps':'PowerShell',
  12242. 'python':'Python',
  12243. 'ruby':'Ruby',
  12244. 'scala':'Scala',
  12245. 'sql':'Sql',
  12246. 'vb':'Vb',
  12247. 'xml':'Xml'
  12248. });
  12249. /**
  12250. * 插入代码
  12251. * @command insertcode
  12252. * @method execCommand
  12253. * @param { String } cmd 命令字符串
  12254. * @param { String } lang 插入代码的语言
  12255. * @example
  12256. * ```javascript
  12257. * editor.execCommand( 'insertcode', 'javascript' );
  12258. * ```
  12259. */
  12260. /**
  12261. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12262. * @command insertcode
  12263. * @method queryCommandValue
  12264. * @param { String } cmd 命令字符串
  12265. * @return { String } 返回代码的语言
  12266. * @example
  12267. * ```javascript
  12268. * editor.queryCommandValue( 'insertcode' );
  12269. * ```
  12270. */
  12271. me.commands['insertcode'] = {
  12272. execCommand : function(cmd,lang){
  12273. var me = this,
  12274. rng = me.selection.getRange(),
  12275. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12276. if(pre){
  12277. pre.className = 'brush:'+lang+';toolbar:false;';
  12278. }else{
  12279. var code = '';
  12280. if(rng.collapsed){
  12281. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;':''):'<br/>';
  12282. }else{
  12283. var frag = rng.extractContents();
  12284. var div = me.document.createElement('div');
  12285. div.appendChild(frag);
  12286. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  12287. if(browser.ie && browser.ie11below && browser.version > 8){
  12288. if(node.type =='element'){
  12289. if(node.tagName == 'br'){
  12290. code += '\n'
  12291. }else if(!dtd.$empty[node.tagName]){
  12292. utils.each(node.children,function(cn){
  12293. if(cn.type =='element'){
  12294. if(cn.tagName == 'br'){
  12295. code += '\n'
  12296. }else if(!dtd.$empty[node.tagName]){
  12297. code += cn.innerText();
  12298. }
  12299. }else{
  12300. code += cn.data
  12301. }
  12302. })
  12303. if(!/\n$/.test(code)){
  12304. code += '\n';
  12305. }
  12306. }
  12307. }else{
  12308. code += node.data + '\n'
  12309. }
  12310. if(!node.nextSibling() && /\n$/.test(code)){
  12311. code = code.replace(/\n$/,'');
  12312. }
  12313. }else{
  12314. if(browser.ie && browser.ie11below){
  12315. if(node.type =='element'){
  12316. if(node.tagName == 'br'){
  12317. code += '<br>'
  12318. }else if(!dtd.$empty[node.tagName]){
  12319. utils.each(node.children,function(cn){
  12320. if(cn.type =='element'){
  12321. if(cn.tagName == 'br'){
  12322. code += '<br>'
  12323. }else if(!dtd.$empty[node.tagName]){
  12324. code += cn.innerText();
  12325. }
  12326. }else{
  12327. code += cn.data
  12328. }
  12329. });
  12330. if(!/br>$/.test(code)){
  12331. code += '<br>';
  12332. }
  12333. }
  12334. }else{
  12335. code += node.data + '<br>'
  12336. }
  12337. if(!node.nextSibling() && /<br>$/.test(code)){
  12338. code = code.replace(/<br>$/,'');
  12339. }
  12340. }else{
  12341. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12342. if(!/br\/?\s*>$/.test(code)){
  12343. if(!node.nextSibling())
  12344. return;
  12345. code += '<br>'
  12346. }
  12347. }
  12348. }
  12349. });
  12350. }
  12351. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  12352. pre = me.document.getElementById('coder');
  12353. domUtils.removeAttributes(pre,'id');
  12354. var tmpNode = pre.previousSibling;
  12355. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  12356. domUtils.remove(tmpNode)
  12357. }
  12358. var rng = me.selection.getRange();
  12359. if(domUtils.isEmptyBlock(pre)){
  12360. rng.setStart(pre,0).setCursor(false,true)
  12361. }else{
  12362. rng.selectNodeContents(pre).select()
  12363. }
  12364. }
  12365. },
  12366. queryCommandValue : function(){
  12367. var path = this.selection.getStartElementPath();
  12368. var lang = '';
  12369. utils.each(path,function(node){
  12370. if(node.nodeName =='PRE'){
  12371. var match = node.className.match(/brush:([^;]+)/);
  12372. lang = match && match[1] ? match[1] : '';
  12373. return false;
  12374. }
  12375. });
  12376. return lang;
  12377. }
  12378. };
  12379. me.addInputRule(function(root){
  12380. utils.each(root.getNodesByTagName('pre'),function(pre){
  12381. var brs = pre.getNodesByTagName('br');
  12382. if(brs.length){
  12383. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs,function(br){
  12384. var txt = UE.uNode.createText('\n');
  12385. br.parentNode.insertBefore(txt,br);
  12386. br.parentNode.removeChild(br);
  12387. });
  12388. return;
  12389. }
  12390. if(browser.ie && browser.ie11below && browser.version > 8)
  12391. return;
  12392. var code = pre.innerText().split(/\n/);
  12393. pre.innerHTML('');
  12394. utils.each(code,function(c){
  12395. if(c.length){
  12396. pre.appendChild(UE.uNode.createText(c));
  12397. }
  12398. pre.appendChild(UE.uNode.createElement('br'))
  12399. })
  12400. })
  12401. });
  12402. me.addOutputRule(function(root){
  12403. utils.each(root.getNodesByTagName('pre'),function(pre){
  12404. var code = '';
  12405. utils.each(pre.children,function(n){
  12406. if(n.type == 'text'){
  12407. //在ie下文本内容有可能末尾带有\n要去掉
  12408. //trace:3396
  12409. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  12410. }else{
  12411. if(n.tagName == 'br'){
  12412. code += '\n'
  12413. }else{
  12414. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12415. }
  12416. }
  12417. });
  12418. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  12419. })
  12420. });
  12421. //不需要判断highlight的command列表
  12422. me.notNeedCodeQuery ={
  12423. help:1,
  12424. undo:1,
  12425. redo:1,
  12426. source:1,
  12427. print:1,
  12428. searchreplace:1,
  12429. fullscreen:1,
  12430. preview:1,
  12431. insertparagraph:1,
  12432. elementpath:1,
  12433. insertcode:1,
  12434. inserthtml:1,
  12435. selectall:1
  12436. };
  12437. //将queyCommamndState重置
  12438. var orgQuery = me.queryCommandState;
  12439. me.queryCommandState = function(cmd){
  12440. var me = this;
  12441. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  12442. return -1;
  12443. }
  12444. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  12445. };
  12446. me.addListener('beforeenterkeydown',function(){
  12447. var rng = me.selection.getRange();
  12448. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12449. if(pre){
  12450. me.fireEvent('saveScene');
  12451. if(!rng.collapsed){
  12452. rng.deleteContents();
  12453. }
  12454. if(!browser.ie || browser.ie9above){
  12455. var tmpNode = me.document.createElement('br'),pre;
  12456. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12457. var next = tmpNode.nextSibling;
  12458. if(!next && (!browser.ie || browser.version > 10)){
  12459. rng.insertNode(tmpNode.cloneNode(false));
  12460. }else{
  12461. rng.setStartAfter(tmpNode);
  12462. }
  12463. pre = tmpNode.previousSibling;
  12464. var tmp;
  12465. while(pre ){
  12466. tmp = pre;
  12467. pre = pre.previousSibling;
  12468. if(!pre || pre.nodeName == 'BR'){
  12469. pre = tmp;
  12470. break;
  12471. }
  12472. }
  12473. if(pre){
  12474. var str = '';
  12475. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12476. str += pre.nodeValue;
  12477. pre = pre.nextSibling;
  12478. }
  12479. if(pre.nodeName != 'BR'){
  12480. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  12481. if(match && match[1]){
  12482. str += match[1]
  12483. }
  12484. }
  12485. if(str){
  12486. str = me.document.createTextNode(str);
  12487. rng.insertNode(str).setStartAfter(str);
  12488. }
  12489. }
  12490. rng.collapse(true).select(true);
  12491. }else{
  12492. if(browser.version > 8){
  12493. var txt = me.document.createTextNode('\n');
  12494. var start = rng.startContainer;
  12495. if(rng.startOffset == 0){
  12496. var preNode = start.previousSibling;
  12497. if(preNode){
  12498. rng.insertNode(txt);
  12499. var fillchar = me.document.createTextNode(' ');
  12500. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12501. }
  12502. }else{
  12503. rng.insertNode(txt).setStartAfter(txt);
  12504. var fillchar = me.document.createTextNode(' ');
  12505. start = rng.startContainer.childNodes[rng.startOffset];
  12506. if(start && !/^\n/.test(start.nodeValue)){
  12507. rng.setStartBefore(txt)
  12508. }
  12509. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12510. }
  12511. }else{
  12512. var tmpNode = me.document.createElement('br');
  12513. rng.insertNode(tmpNode);
  12514. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12515. rng.setStartAfter(tmpNode);
  12516. pre = tmpNode.previousSibling;
  12517. var tmp;
  12518. while(pre ){
  12519. tmp = pre;
  12520. pre = pre.previousSibling;
  12521. if(!pre || pre.nodeName == 'BR'){
  12522. pre = tmp;
  12523. break;
  12524. }
  12525. }
  12526. if(pre){
  12527. var str = '';
  12528. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12529. str += pre.nodeValue;
  12530. pre = pre.nextSibling;
  12531. }
  12532. if(pre.nodeName != 'BR'){
  12533. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  12534. if(match && match[1]){
  12535. str += match[1]
  12536. }
  12537. }
  12538. str = me.document.createTextNode(str);
  12539. rng.insertNode(str).setStartAfter(str);
  12540. }
  12541. rng.collapse(true).select();
  12542. }
  12543. }
  12544. me.fireEvent('saveScene');
  12545. return true;
  12546. }
  12547. });
  12548. me.addListener('tabkeydown',function(cmd,evt){
  12549. var rng = me.selection.getRange();
  12550. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12551. if(pre){
  12552. me.fireEvent('saveScene');
  12553. if(evt.shiftKey){
  12554. }else{
  12555. if(!rng.collapsed){
  12556. var bk = rng.createBookmark();
  12557. var start = bk.start.previousSibling;
  12558. while(start){
  12559. if(pre.firstChild === start && !domUtils.isBr(start)){
  12560. pre.insertBefore(me.document.createTextNode(' '),start);
  12561. break;
  12562. }
  12563. if(domUtils.isBr(start)){
  12564. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  12565. break;
  12566. }
  12567. start = start.previousSibling;
  12568. }
  12569. var end = bk.end;
  12570. start = bk.start.nextSibling;
  12571. if(pre.firstChild === bk.start){
  12572. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12573. }
  12574. while(start && start !== end){
  12575. if(domUtils.isBr(start) && start.nextSibling){
  12576. if(start.nextSibling === end){
  12577. break;
  12578. }
  12579. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12580. }
  12581. start = start.nextSibling;
  12582. }
  12583. rng.moveToBookmark(bk).select();
  12584. }else{
  12585. var tmpNode = me.document.createTextNode(' ');
  12586. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12587. }
  12588. }
  12589. me.fireEvent('saveScene');
  12590. return true;
  12591. }
  12592. });
  12593. me.addListener('beforeinserthtml',function(evtName,html){
  12594. var me = this,
  12595. rng = me.selection.getRange(),
  12596. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12597. if(pre){
  12598. if(!rng.collapsed){
  12599. rng.deleteContents()
  12600. }
  12601. var htmlstr = '';
  12602. if(browser.ie && browser.version > 8){
  12603. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12604. if(node.type =='element'){
  12605. if(node.tagName == 'br'){
  12606. htmlstr += '\n'
  12607. }else if(!dtd.$empty[node.tagName]){
  12608. utils.each(node.children,function(cn){
  12609. if(cn.type =='element'){
  12610. if(cn.tagName == 'br'){
  12611. htmlstr += '\n'
  12612. }else if(!dtd.$empty[node.tagName]){
  12613. htmlstr += cn.innerText();
  12614. }
  12615. }else{
  12616. htmlstr += cn.data
  12617. }
  12618. })
  12619. if(!/\n$/.test(htmlstr)){
  12620. htmlstr += '\n';
  12621. }
  12622. }
  12623. }else{
  12624. htmlstr += node.data + '\n'
  12625. }
  12626. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  12627. htmlstr = htmlstr.replace(/\n$/,'');
  12628. }
  12629. });
  12630. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  12631. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  12632. }else{
  12633. var frag = me.document.createDocumentFragment();
  12634. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12635. if(node.type =='element'){
  12636. if(node.tagName == 'br'){
  12637. frag.appendChild(me.document.createElement('br'))
  12638. }else if(!dtd.$empty[node.tagName]){
  12639. utils.each(node.children,function(cn){
  12640. if(cn.type =='element'){
  12641. if(cn.tagName == 'br'){
  12642. frag.appendChild(me.document.createElement('br'))
  12643. }else if(!dtd.$empty[node.tagName]){
  12644. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  12645. }
  12646. }else{
  12647. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  12648. }
  12649. })
  12650. if(frag.lastChild.nodeName != 'BR'){
  12651. frag.appendChild(me.document.createElement('br'))
  12652. }
  12653. }
  12654. }else{
  12655. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  12656. }
  12657. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  12658. frag.removeChild(frag.lastChild)
  12659. }
  12660. });
  12661. rng.insertNode(frag).select();
  12662. }
  12663. return true;
  12664. }
  12665. });
  12666. //方向键的处理
  12667. me.addListener('keydown',function(cmd,evt){
  12668. var me = this,keyCode = evt.keyCode || evt.which;
  12669. if(keyCode == 40){
  12670. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  12671. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  12672. var last = pre.lastChild
  12673. while(last && last.nodeName == 'BR'){
  12674. last = last.previousSibling;
  12675. }
  12676. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  12677. me.execCommand('insertparagraph');
  12678. domUtils.preventDefault(evt)
  12679. }
  12680. }
  12681. }
  12682. });
  12683. //trace:3395
  12684. me.addListener('delkeydown',function(type,evt){
  12685. var rng = this.selection.getRange();
  12686. rng.txtToElmBoundary(true);
  12687. var start = rng.startContainer;
  12688. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  12689. var p = me.document.createElement('p');
  12690. domUtils.fillNode(me.document,p);
  12691. start.parentNode.insertBefore(p,start);
  12692. domUtils.remove(start);
  12693. rng.setStart(p,0).setCursor(false,true);
  12694. domUtils.preventDefault(evt);
  12695. return true;
  12696. }
  12697. })
  12698. };
  12699. // plugins/cleardoc.js
  12700. /**
  12701. * 清空文档插件
  12702. * @file
  12703. * @since 1.2.6.1
  12704. */
  12705. /**
  12706. * 清空文档
  12707. * @command cleardoc
  12708. * @method execCommand
  12709. * @param { String } cmd 命令字符串
  12710. * @example
  12711. * ```javascript
  12712. * //editor 是编辑器实例
  12713. * editor.execCommand('cleardoc');
  12714. * ```
  12715. */
  12716. UE.commands['cleardoc'] = {
  12717. execCommand : function( cmdName) {
  12718. var me = this,
  12719. enterTag = me.options.enterTag,
  12720. range = me.selection.getRange();
  12721. if(enterTag == "br"){
  12722. me.body.innerHTML = "<br/>";
  12723. range.setStart(me.body,0).setCursor();
  12724. }else{
  12725. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12726. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12727. }
  12728. setTimeout(function(){
  12729. me.fireEvent("clearDoc");
  12730. },0);
  12731. }
  12732. };
  12733. // plugins/anchor.js
  12734. /**
  12735. * 锚点插件,为UEditor提供插入锚点支持
  12736. * @file
  12737. * @since 1.2.6.1
  12738. */
  12739. UE.plugin.register('anchor', function (){
  12740. return {
  12741. bindEvents:{
  12742. 'ready':function(){
  12743. utils.cssRule('anchor',
  12744. '.anchorclass{background: url(\''
  12745. + this.options.themePath
  12746. + this.options.theme +'/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12747. this.document);
  12748. }
  12749. },
  12750. outputRule: function(root){
  12751. utils.each(root.getNodesByTagName('img'),function(a){
  12752. var val;
  12753. if(val = a.getAttr('anchorname')){
  12754. a.tagName = 'a';
  12755. a.setAttr({
  12756. anchorname : '',
  12757. name : val,
  12758. 'class' : ''
  12759. })
  12760. }
  12761. })
  12762. },
  12763. inputRule:function(root){
  12764. utils.each(root.getNodesByTagName('a'),function(a){
  12765. var val;
  12766. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12767. a.tagName = 'img';
  12768. a.setAttr({
  12769. anchorname :a.getAttr('name'),
  12770. 'class' : 'anchorclass'
  12771. });
  12772. a.setAttr('name')
  12773. }
  12774. })
  12775. },
  12776. commands:{
  12777. /**
  12778. * 插入锚点
  12779. * @command anchor
  12780. * @method execCommand
  12781. * @param { String } cmd 命令字符串
  12782. * @param { String } name 锚点名称字符串
  12783. * @example
  12784. * ```javascript
  12785. * //editor 是编辑器实例
  12786. * editor.execCommand('anchor', 'anchor1');
  12787. * ```
  12788. */
  12789. 'anchor':{
  12790. execCommand:function (cmd, name) {
  12791. var range = this.selection.getRange(),img = range.getClosedNode();
  12792. if (img && img.getAttribute('anchorname')) {
  12793. if (name) {
  12794. img.setAttribute('anchorname', name);
  12795. } else {
  12796. range.setStartBefore(img).setCursor();
  12797. domUtils.remove(img);
  12798. }
  12799. } else {
  12800. if (name) {
  12801. //只在选区的开始插入
  12802. var anchor = this.document.createElement('img');
  12803. range.collapse(true);
  12804. domUtils.setAttributes(anchor,{
  12805. 'anchorname':name,
  12806. 'class':'anchorclass'
  12807. });
  12808. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12809. }
  12810. }
  12811. }
  12812. }
  12813. }
  12814. }
  12815. });
  12816. // plugins/wordcount.js
  12817. ///import core
  12818. ///commands 字数统计
  12819. ///commandsName WordCount,wordCount
  12820. ///commandsTitle 字数统计
  12821. /*
  12822. * Created by JetBrains WebStorm.
  12823. * User: taoqili
  12824. * Date: 11-9-7
  12825. * Time: 下午8:18
  12826. * To change this template use File | Settings | File Templates.
  12827. */
  12828. UE.plugins['wordcount'] = function(){
  12829. var me = this;
  12830. me.setOpt('wordCount',true);
  12831. me.addListener('contentchange',function(){
  12832. me.fireEvent('wordcount');
  12833. });
  12834. var timer;
  12835. me.addListener('ready',function(){
  12836. var me = this;
  12837. domUtils.on(me.body,"keyup",function(evt){
  12838. var code = evt.keyCode||evt.which,
  12839. //忽略的按键,ctr,alt,shift,方向键
  12840. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12841. if(code in ignores) return;
  12842. clearTimeout(timer);
  12843. timer = setTimeout(function(){
  12844. me.fireEvent('wordcount');
  12845. },200)
  12846. })
  12847. });
  12848. };
  12849. // plugins/pagebreak.js
  12850. /**
  12851. * 分页功能插件
  12852. * @file
  12853. * @since 1.2.6.1
  12854. */
  12855. UE.plugins['pagebreak'] = function () {
  12856. var me = this,
  12857. notBreakTags = ['td'];
  12858. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12859. function fillNode(node){
  12860. if(domUtils.isEmptyBlock(node)){
  12861. var firstChild = node.firstChild,tmpNode;
  12862. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12863. tmpNode = firstChild;
  12864. firstChild = firstChild.firstChild;
  12865. }
  12866. !tmpNode && (tmpNode = node);
  12867. domUtils.fillNode(me.document,tmpNode);
  12868. }
  12869. }
  12870. //分页符样式添加
  12871. me.ready(function(){
  12872. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12873. });
  12874. function isHr(node){
  12875. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12876. }
  12877. me.addInputRule(function(root){
  12878. root.traversal(function(node){
  12879. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12880. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12881. node.parentNode.insertBefore(hr,node);
  12882. node.parentNode.removeChild(node)
  12883. }
  12884. })
  12885. });
  12886. me.addOutputRule(function(node){
  12887. utils.each(node.getNodesByTagName('hr'),function(n){
  12888. if(n.getAttr('class') == 'pagebreak'){
  12889. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12890. n.parentNode.insertBefore(txt,n);
  12891. n.parentNode.removeChild(n);
  12892. }
  12893. })
  12894. });
  12895. /**
  12896. * 插入分页符
  12897. * @command pagebreak
  12898. * @method execCommand
  12899. * @param { String } cmd 命令字符串
  12900. * @remind 在表格中插入分页符会把表格切分成两部分
  12901. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12902. * 以便于提交数据到服务器端后处理分页。
  12903. * @example
  12904. * ```javascript
  12905. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12906. * ```
  12907. */
  12908. me.commands['pagebreak'] = {
  12909. execCommand:function () {
  12910. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12911. domUtils.setAttributes(hr,{
  12912. 'class' : 'pagebreak',
  12913. noshade:"noshade",
  12914. size:"5"
  12915. });
  12916. domUtils.unSelectable(hr);
  12917. //table单独处理
  12918. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12919. parents = [], pN;
  12920. if (node) {
  12921. switch (node.tagName) {
  12922. case 'TD':
  12923. pN = node.parentNode;
  12924. if (!pN.previousSibling) {
  12925. var table = domUtils.findParentByTagName(pN, 'table');
  12926. // var tableWrapDiv = table.parentNode;
  12927. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12928. // && tableWrapDiv.tagName == 'DIV'
  12929. // && tableWrapDiv.getAttribute('dropdrag')
  12930. // ){
  12931. // domUtils.remove(tableWrapDiv,true);
  12932. // }
  12933. table.parentNode.insertBefore(hr, table);
  12934. parents = domUtils.findParents(hr, true);
  12935. } else {
  12936. pN.parentNode.insertBefore(hr, pN);
  12937. parents = domUtils.findParents(hr);
  12938. }
  12939. pN = parents[1];
  12940. if (hr !== pN) {
  12941. domUtils.breakParent(hr, pN);
  12942. }
  12943. //table要重写绑定一下拖拽
  12944. me.fireEvent('afteradjusttable',me.document);
  12945. }
  12946. } else {
  12947. if (!range.collapsed) {
  12948. range.deleteContents();
  12949. var start = range.startContainer;
  12950. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12951. range.setStartBefore(start).collapse(true);
  12952. domUtils.remove(start);
  12953. start = range.startContainer;
  12954. }
  12955. }
  12956. range.insertNode(hr);
  12957. var pN = hr.parentNode, nextNode;
  12958. while (!domUtils.isBody(pN)) {
  12959. domUtils.breakParent(hr, pN);
  12960. nextNode = hr.nextSibling;
  12961. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12962. domUtils.remove(nextNode);
  12963. }
  12964. pN = hr.parentNode;
  12965. }
  12966. nextNode = hr.nextSibling;
  12967. var pre = hr.previousSibling;
  12968. if(isHr(pre)){
  12969. domUtils.remove(pre);
  12970. }else{
  12971. pre && fillNode(pre);
  12972. }
  12973. if(!nextNode){
  12974. var p = me.document.createElement('p');
  12975. hr.parentNode.appendChild(p);
  12976. domUtils.fillNode(me.document,p);
  12977. range.setStart(p,0).collapse(true);
  12978. }else{
  12979. if(isHr(nextNode)){
  12980. domUtils.remove(nextNode);
  12981. }else{
  12982. fillNode(nextNode);
  12983. }
  12984. range.setEndAfter(hr).collapse(false);
  12985. }
  12986. range.select(true);
  12987. }
  12988. }
  12989. };
  12990. };
  12991. // plugins/wordimage.js
  12992. ///import core
  12993. ///commands 本地图片引导上传
  12994. ///commandsName WordImage
  12995. ///commandsTitle 本地图片引导上传
  12996. ///commandsDialog dialogs\wordimage
  12997. UE.plugin.register('wordimage',function(){
  12998. var me = this,
  12999. images = [];
  13000. return {
  13001. commands : {
  13002. 'wordimage':{
  13003. execCommand:function () {
  13004. var images = domUtils.getElementsByTagName(me.body, "img");
  13005. var urlList = [];
  13006. for (var i = 0, ci; ci = images[i++];) {
  13007. var url = ci.getAttribute("word_img");
  13008. url && urlList.push(url);
  13009. }
  13010. return urlList;
  13011. },
  13012. queryCommandState:function () {
  13013. images = domUtils.getElementsByTagName(me.body, "img");
  13014. for (var i = 0, ci; ci = images[i++];) {
  13015. if (ci.getAttribute("word_img")) {
  13016. return 1;
  13017. }
  13018. }
  13019. return -1;
  13020. },
  13021. notNeedUndo:true
  13022. }
  13023. },
  13024. inputRule : function (root) {
  13025. utils.each(root.getNodesByTagName('img'), function (img) {
  13026. var attrs = img.attrs,
  13027. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  13028. opt = me.options,
  13029. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  13030. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  13031. img.setAttr({
  13032. width:attrs.width,
  13033. height:attrs.height,
  13034. alt:attrs.alt,
  13035. word_img: attrs.src,
  13036. src:src,
  13037. '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'
  13038. })
  13039. }
  13040. })
  13041. }
  13042. }
  13043. });
  13044. // plugins/dragdrop.js
  13045. UE.plugins['dragdrop'] = function (){
  13046. var me = this;
  13047. me.ready(function(){
  13048. domUtils.on(this.body,'dragend',function(){
  13049. var rng = me.selection.getRange();
  13050. var node = rng.getClosedNode()||me.selection.getStart();
  13051. if(node && node.tagName == 'IMG'){
  13052. var pre = node.previousSibling,next;
  13053. while(next = node.nextSibling){
  13054. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  13055. domUtils.remove(next)
  13056. }else{
  13057. break;
  13058. }
  13059. }
  13060. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  13061. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  13062. pre.appendChild(node);
  13063. domUtils.moveChild(next,pre);
  13064. domUtils.remove(next);
  13065. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  13066. next.insertBefore(node,next.firstChild);
  13067. }
  13068. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  13069. domUtils.remove(pre)
  13070. }
  13071. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  13072. domUtils.remove(next)
  13073. }
  13074. rng.selectNode(node).select();
  13075. me.fireEvent('saveScene');
  13076. }
  13077. }
  13078. })
  13079. });
  13080. me.addListener('keyup', function(type, evt) {
  13081. var keyCode = evt.keyCode || evt.which;
  13082. if (keyCode == 13) {
  13083. var rng = me.selection.getRange(),node;
  13084. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  13085. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  13086. domUtils.removeStyle(node,'text-align')
  13087. }
  13088. }
  13089. }
  13090. })
  13091. };
  13092. // plugins/undo.js
  13093. /**
  13094. * undo redo
  13095. * @file
  13096. * @since 1.2.6.1
  13097. */
  13098. /**
  13099. * 撤销上一次执行的命令
  13100. * @command undo
  13101. * @method execCommand
  13102. * @param { String } cmd 命令字符串
  13103. * @example
  13104. * ```javascript
  13105. * editor.execCommand( 'undo' );
  13106. * ```
  13107. */
  13108. /**
  13109. * 重做上一次执行的命令
  13110. * @command redo
  13111. * @method execCommand
  13112. * @param { String } cmd 命令字符串
  13113. * @example
  13114. * ```javascript
  13115. * editor.execCommand( 'redo' );
  13116. * ```
  13117. */
  13118. UE.plugins['undo'] = function () {
  13119. var saveSceneTimer;
  13120. var me = this,
  13121. maxUndoCount = me.options.maxUndoCount || 20,
  13122. maxInputCount = me.options.maxInputCount || 20,
  13123. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13124. var noNeedFillCharTags = {
  13125. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  13126. };
  13127. var orgState = me.options.autoClearEmptyNode;
  13128. function compareAddr(indexA, indexB) {
  13129. if (indexA.length != indexB.length)
  13130. return 0;
  13131. for (var i = 0, l = indexA.length; i < l; i++) {
  13132. if (indexA[i] != indexB[i])
  13133. return 0
  13134. }
  13135. return 1;
  13136. }
  13137. function compareRangeAddress(rngAddrA, rngAddrB) {
  13138. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13139. return 0;
  13140. }
  13141. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13142. return 0;
  13143. }
  13144. return 1;
  13145. }
  13146. function UndoManager() {
  13147. this.list = [];
  13148. this.index = 0;
  13149. this.hasUndo = false;
  13150. this.hasRedo = false;
  13151. this.undo = function () {
  13152. if (this.hasUndo) {
  13153. if (!this.list[this.index - 1] && this.list.length == 1) {
  13154. this.reset();
  13155. return;
  13156. }
  13157. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13158. this.index--;
  13159. if (this.index == 0) {
  13160. return this.restore(0);
  13161. }
  13162. }
  13163. this.restore(--this.index);
  13164. }
  13165. };
  13166. this.redo = function () {
  13167. if (this.hasRedo) {
  13168. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13169. this.index++;
  13170. if (this.index == this.list.length - 1) {
  13171. return this.restore(this.index);
  13172. }
  13173. }
  13174. this.restore(++this.index);
  13175. }
  13176. };
  13177. this.restore = function () {
  13178. var me = this.editor;
  13179. var scene = this.list[this.index];
  13180. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13181. me.options.autoClearEmptyNode = false;
  13182. me.filterInputRule(root);
  13183. me.options.autoClearEmptyNode = orgState;
  13184. //trace:873
  13185. //去掉展位符
  13186. me.document.body.innerHTML = root.toHtml();
  13187. me.fireEvent('afterscencerestore');
  13188. //处理undo后空格不展位的问题
  13189. if (browser.ie) {
  13190. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  13191. if(domUtils.isEmptyNode(node)){
  13192. domUtils.fillNode(me.document, node);
  13193. }
  13194. })
  13195. }
  13196. try{
  13197. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13198. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13199. }catch(e){}
  13200. this.update();
  13201. this.clearKey();
  13202. //不能把自己reset了
  13203. me.fireEvent('reset', true);
  13204. };
  13205. this.getScene = function () {
  13206. var me = this.editor;
  13207. var rng = me.selection.getRange(),
  13208. rngAddress = rng.createAddress(false,true);
  13209. me.fireEvent('beforegetscene');
  13210. var root = UE.htmlparser(me.body.innerHTML);
  13211. me.options.autoClearEmptyNode = false;
  13212. me.filterOutputRule(root);
  13213. me.options.autoClearEmptyNode = orgState;
  13214. var cont = root.toHtml();
  13215. //trace:3461
  13216. //这个会引起回退时导致空格丢失的情况
  13217. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13218. me.fireEvent('aftergetscene');
  13219. return {
  13220. address:rngAddress,
  13221. content:cont
  13222. }
  13223. };
  13224. this.save = function (notCompareRange,notSetCursor) {
  13225. clearTimeout(saveSceneTimer);
  13226. var currentScene = this.getScene(notSetCursor),
  13227. lastScene = this.list[this.index];
  13228. if(lastScene && lastScene.content != currentScene.content){
  13229. me.trigger('contentchange')
  13230. }
  13231. //内容相同位置相同不存
  13232. if (lastScene && lastScene.content == currentScene.content &&
  13233. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  13234. ) {
  13235. return;
  13236. }
  13237. this.list = this.list.slice(0, this.index + 1);
  13238. this.list.push(currentScene);
  13239. //如果大于最大数量了,就把最前的剔除
  13240. if (this.list.length > maxUndoCount) {
  13241. this.list.shift();
  13242. }
  13243. this.index = this.list.length - 1;
  13244. this.clearKey();
  13245. //跟新undo/redo状态
  13246. this.update();
  13247. };
  13248. this.update = function () {
  13249. this.hasRedo = !!this.list[this.index + 1];
  13250. this.hasUndo = !!this.list[this.index - 1];
  13251. };
  13252. this.reset = function () {
  13253. this.list = [];
  13254. this.index = 0;
  13255. this.hasUndo = false;
  13256. this.hasRedo = false;
  13257. this.clearKey();
  13258. };
  13259. this.clearKey = function () {
  13260. keycont = 0;
  13261. lastKeyCode = null;
  13262. };
  13263. }
  13264. me.undoManger = new UndoManager();
  13265. me.undoManger.editor = me;
  13266. function saveScene() {
  13267. this.undoManger.save();
  13268. }
  13269. me.addListener('saveScene', function () {
  13270. var args = Array.prototype.splice.call(arguments,1);
  13271. this.undoManger.save.apply(this.undoManger,args);
  13272. });
  13273. // me.addListener('beforeexeccommand', saveScene);
  13274. // me.addListener('afterexeccommand', saveScene);
  13275. me.addListener('reset', function (type, exclude) {
  13276. if (!exclude) {
  13277. this.undoManger.reset();
  13278. }
  13279. });
  13280. me.commands['redo'] = me.commands['undo'] = {
  13281. execCommand:function (cmdName) {
  13282. this.undoManger[cmdName]();
  13283. },
  13284. queryCommandState:function (cmdName) {
  13285. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13286. },
  13287. notNeedUndo:1
  13288. };
  13289. var keys = {
  13290. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13291. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  13292. 37:1, 38:1, 39:1, 40:1
  13293. },
  13294. keycont = 0,
  13295. lastKeyCode;
  13296. //输入法状态下不计算字符数
  13297. var inputType = false;
  13298. me.addListener('ready', function () {
  13299. domUtils.on(this.body, 'compositionstart', function () {
  13300. inputType = true;
  13301. });
  13302. domUtils.on(this.body, 'compositionend', function () {
  13303. inputType = false;
  13304. })
  13305. });
  13306. //快捷键
  13307. me.addshortcutkey({
  13308. "Undo":"ctrl+90", //undo
  13309. "Redo":"ctrl+89" //redo
  13310. });
  13311. var isCollapsed = true;
  13312. me.addListener('keydown', function (type, evt) {
  13313. var me = this;
  13314. var keyCode = evt.keyCode || evt.which;
  13315. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13316. if (inputType)
  13317. return;
  13318. if(!me.selection.getRange().collapsed){
  13319. me.undoManger.save(false,true);
  13320. isCollapsed = false;
  13321. return;
  13322. }
  13323. if (me.undoManger.list.length == 0) {
  13324. me.undoManger.save(true);
  13325. }
  13326. clearTimeout(saveSceneTimer);
  13327. function save(cont){
  13328. cont.undoManger.save(false,true);
  13329. cont.fireEvent('selectionchange');
  13330. }
  13331. saveSceneTimer = setTimeout(function(){
  13332. if(inputType){
  13333. var interalTimer = setInterval(function(){
  13334. if(!inputType){
  13335. save(me);
  13336. clearInterval(interalTimer)
  13337. }
  13338. },300)
  13339. return;
  13340. }
  13341. save(me);
  13342. },200);
  13343. lastKeyCode = keyCode;
  13344. keycont++;
  13345. if (keycont >= maxInputCount ) {
  13346. save(me)
  13347. }
  13348. }
  13349. });
  13350. me.addListener('keyup', function (type, evt) {
  13351. var keyCode = evt.keyCode || evt.which;
  13352. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13353. if (inputType)
  13354. return;
  13355. if(!isCollapsed){
  13356. this.undoManger.save(false,true);
  13357. isCollapsed = true;
  13358. }
  13359. }
  13360. });
  13361. //扩展实例,添加关闭和开启命令undo
  13362. me.stopCmdUndo = function(){
  13363. me.__hasEnterExecCommand = true;
  13364. };
  13365. me.startCmdUndo = function(){
  13366. me.__hasEnterExecCommand = false;
  13367. }
  13368. };
  13369. // plugins/copy.js
  13370. UE.plugin.register('copy', function () {
  13371. var me = this;
  13372. function initZeroClipboard() {
  13373. ZeroClipboard.config({
  13374. debug: false,
  13375. swfPath: me.options.UEDITOR_HOME_URL + 'third-party/zeroclipboard/ZeroClipboard.swf'
  13376. });
  13377. var client = me.zeroclipboard = new ZeroClipboard();
  13378. // 复制内容
  13379. client.on('copy', function (e) {
  13380. var client = e.client,
  13381. rng = me.selection.getRange(),
  13382. div = document.createElement('div');
  13383. div.appendChild(rng.cloneContents());
  13384. client.setText(div.innerText || div.textContent);
  13385. client.setHtml(div.innerHTML);
  13386. rng.select();
  13387. });
  13388. // hover事件传递到target
  13389. client.on('mouseover mouseout', function (e) {
  13390. var target = e.target;
  13391. if (e.type == 'mouseover') {
  13392. domUtils.addClass(target, 'edui-state-hover');
  13393. } else if (e.type == 'mouseout') {
  13394. domUtils.removeClasses(target, 'edui-state-hover');
  13395. }
  13396. });
  13397. // flash加载不成功
  13398. client.on('wrongflash noflash', function () {
  13399. ZeroClipboard.destroy();
  13400. });
  13401. }
  13402. return {
  13403. bindEvents: {
  13404. 'ready': function () {
  13405. if (!browser.ie) {
  13406. if (window.ZeroClipboard) {
  13407. initZeroClipboard();
  13408. } else {
  13409. utils.loadFile(document, {
  13410. src: me.options.UEDITOR_HOME_URL + "third-party/zeroclipboard/ZeroClipboard.js",
  13411. tag: "script",
  13412. type: "text/javascript",
  13413. defer: "defer"
  13414. }, function () {
  13415. initZeroClipboard();
  13416. });
  13417. }
  13418. }
  13419. }
  13420. },
  13421. commands: {
  13422. 'copy': {
  13423. execCommand: function (cmd) {
  13424. if (!me.document.execCommand('copy')) {
  13425. alert(me.getLang('copymsg'));
  13426. }
  13427. }
  13428. }
  13429. }
  13430. }
  13431. });
  13432. // plugins/paste.js
  13433. ///import core
  13434. ///import plugins/inserthtml.js
  13435. ///import plugins/undo.js
  13436. ///import plugins/serialize.js
  13437. ///commands 粘贴
  13438. ///commandsName PastePlain
  13439. ///commandsTitle 纯文本粘贴模式
  13440. /**
  13441. * @description 粘贴
  13442. * @author zhanyi
  13443. */
  13444. UE.plugins['paste'] = function () {
  13445. function getClipboardData(callback) {
  13446. var doc = this.document;
  13447. if (doc.getElementById('baidu_pastebin')) {
  13448. return;
  13449. }
  13450. var range = this.selection.getRange(),
  13451. bk = range.createBookmark(),
  13452. //创建剪贴的容器div
  13453. pastebin = doc.createElement('div');
  13454. pastebin.id = 'baidu_pastebin';
  13455. // Safari 要求div必须有内容,才能粘贴内容进来
  13456. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13457. doc.body.appendChild(pastebin);
  13458. //trace:717 隐藏的span不能得到top
  13459. //bk.start.innerHTML = '&nbsp;';
  13460. bk.start.style.display = '';
  13461. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13462. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13463. domUtils.getXY(bk.start).y + 'px';
  13464. range.selectNodeContents(pastebin).select(true);
  13465. setTimeout(function () {
  13466. if (browser.webkit) {
  13467. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13468. if (domUtils.isEmptyNode(pi)) {
  13469. domUtils.remove(pi);
  13470. } else {
  13471. pastebin = pi;
  13472. break;
  13473. }
  13474. }
  13475. }
  13476. try {
  13477. pastebin.parentNode.removeChild(pastebin);
  13478. } catch (e) {
  13479. }
  13480. range.moveToBookmark(bk).select(true);
  13481. callback(pastebin);
  13482. }, 0);
  13483. }
  13484. var me = this;
  13485. me.setOpt({
  13486. retainOnlyLabelPasted : false
  13487. });
  13488. var txtContent, htmlContent, address;
  13489. function getPureHtml(html){
  13490. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13491. tagName = tagName.toLowerCase();
  13492. if ({img: 1}[tagName]) {
  13493. return a;
  13494. }
  13495. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13496. if ({
  13497. 'src': 1,
  13498. 'href': 1,
  13499. 'name': 1
  13500. }[atr.toLowerCase()]) {
  13501. return atr + '=' + val + ' '
  13502. }
  13503. return ''
  13504. });
  13505. if ({
  13506. 'span': 1,
  13507. 'div': 1
  13508. }[tagName]) {
  13509. return ''
  13510. } else {
  13511. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13512. }
  13513. });
  13514. }
  13515. function filter(div) {
  13516. var html;
  13517. if (div.firstChild) {
  13518. //去掉cut中添加的边界值
  13519. var nodes = domUtils.getElementsByTagName(div, 'span');
  13520. for (var i = 0, ni; ni = nodes[i++];) {
  13521. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13522. domUtils.remove(ni);
  13523. }
  13524. }
  13525. if (browser.webkit) {
  13526. var brs = div.querySelectorAll('div br');
  13527. for (var i = 0, bi; bi = brs[i++];) {
  13528. var pN = bi.parentNode;
  13529. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13530. pN.innerHTML = '<p><br/></p>';
  13531. domUtils.remove(pN);
  13532. }
  13533. }
  13534. var divs = div.querySelectorAll('#baidu_pastebin');
  13535. for (var i = 0, di; di = divs[i++];) {
  13536. var tmpP = me.document.createElement('p');
  13537. di.parentNode.insertBefore(tmpP, di);
  13538. while (di.firstChild) {
  13539. tmpP.appendChild(di.firstChild);
  13540. }
  13541. domUtils.remove(di);
  13542. }
  13543. var metas = div.querySelectorAll('meta');
  13544. for (var i = 0, ci; ci = metas[i++];) {
  13545. domUtils.remove(ci);
  13546. }
  13547. var brs = div.querySelectorAll('br');
  13548. for (i = 0; ci = brs[i++];) {
  13549. if (/^apple-/i.test(ci.className)) {
  13550. domUtils.remove(ci);
  13551. }
  13552. }
  13553. }
  13554. if (browser.gecko) {
  13555. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13556. for (i = 0; ci = dirtyNodes[i++];) {
  13557. ci.removeAttribute('_moz_dirty');
  13558. }
  13559. }
  13560. if (!browser.ie) {
  13561. var spans = div.querySelectorAll('span.Apple-style-span');
  13562. for (var i = 0, ci; ci = spans[i++];) {
  13563. domUtils.remove(ci, true);
  13564. }
  13565. }
  13566. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13567. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  13568. //过滤word粘贴过来的冗余属性
  13569. html = UE.filterWord(html);
  13570. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  13571. var root = UE.htmlparser(html);
  13572. //如果给了过滤规则就先进行过滤
  13573. if (me.options.filterRules) {
  13574. UE.filterNode(root, me.options.filterRules);
  13575. }
  13576. //执行默认的处理
  13577. me.filterInputRule(root);
  13578. //针对chrome的处理
  13579. if (browser.webkit) {
  13580. var br = root.lastChild();
  13581. if (br && br.type == 'element' && br.tagName == 'br') {
  13582. root.removeChild(br)
  13583. }
  13584. utils.each(me.body.querySelectorAll('div'), function (node) {
  13585. if (domUtils.isEmptyBlock(node)) {
  13586. domUtils.remove(node,true)
  13587. }
  13588. })
  13589. }
  13590. html = {'html': root.toHtml()};
  13591. me.fireEvent('beforepaste', html, root);
  13592. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  13593. if(!html.html){
  13594. return;
  13595. }
  13596. root = UE.htmlparser(html.html,true);
  13597. //如果开启了纯文本模式
  13598. if (me.queryCommandState('pasteplain') === 1) {
  13599. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  13600. } else {
  13601. //文本模式
  13602. UE.filterNode(root, me.options.filterTxtRules);
  13603. txtContent = root.toHtml();
  13604. //完全模式
  13605. htmlContent = html.html;
  13606. address = me.selection.getRange().createAddress(true);
  13607. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  13608. }
  13609. me.fireEvent("afterpaste", html);
  13610. }
  13611. }
  13612. me.addListener('pasteTransfer', function (cmd, plainType) {
  13613. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  13614. var range = me.selection.getRange();
  13615. range.moveToAddress(address, true);
  13616. if (!range.collapsed) {
  13617. while (!domUtils.isBody(range.startContainer)
  13618. ) {
  13619. var start = range.startContainer;
  13620. if(start.nodeType == 1){
  13621. start = start.childNodes[range.startOffset];
  13622. if(!start){
  13623. range.setStartBefore(range.startContainer);
  13624. continue;
  13625. }
  13626. var pre = start.previousSibling;
  13627. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  13628. range.setStartBefore(pre)
  13629. }
  13630. }
  13631. if(range.startOffset == 0){
  13632. range.setStartBefore(range.startContainer);
  13633. }else{
  13634. break;
  13635. }
  13636. }
  13637. while (!domUtils.isBody(range.endContainer)
  13638. ) {
  13639. var end = range.endContainer;
  13640. if(end.nodeType == 1){
  13641. end = end.childNodes[range.endOffset];
  13642. if(!end){
  13643. range.setEndAfter(range.endContainer);
  13644. continue;
  13645. }
  13646. var next = end.nextSibling;
  13647. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  13648. range.setEndAfter(next)
  13649. }
  13650. }
  13651. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  13652. range.setEndAfter(range.endContainer);
  13653. }else{
  13654. break;
  13655. }
  13656. }
  13657. }
  13658. range.deleteContents();
  13659. range.select(true);
  13660. me.__hasEnterExecCommand = true;
  13661. var html = htmlContent;
  13662. if (plainType === 2 ) {
  13663. html = getPureHtml(html);
  13664. } else if (plainType) {
  13665. html = txtContent;
  13666. }
  13667. me.execCommand('inserthtml', html, true);
  13668. me.__hasEnterExecCommand = false;
  13669. var rng = me.selection.getRange();
  13670. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  13671. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  13672. ) {
  13673. rng.setStartBefore(rng.startContainer);
  13674. }
  13675. var tmpAddress = rng.createAddress(true);
  13676. address.endAddress = tmpAddress.startAddress;
  13677. }
  13678. });
  13679. me.addListener('ready', function () {
  13680. domUtils.on(me.body, 'cut', function () {
  13681. var range = me.selection.getRange();
  13682. if (!range.collapsed && me.undoManger) {
  13683. me.undoManger.save();
  13684. }
  13685. });
  13686. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  13687. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  13688. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  13689. return;
  13690. }
  13691. getClipboardData.call(me, function (div) {
  13692. filter(div);
  13693. });
  13694. });
  13695. });
  13696. me.commands['paste'] = {
  13697. execCommand: function (cmd) {
  13698. if (browser.ie) {
  13699. getClipboardData.call(me, function (div) {
  13700. filter(div);
  13701. });
  13702. me.document.execCommand('paste');
  13703. } else {
  13704. alert(me.getLang('pastemsg'));
  13705. }
  13706. }
  13707. }
  13708. };
  13709. // plugins/puretxtpaste.js
  13710. /**
  13711. * 纯文本粘贴插件
  13712. * @file
  13713. * @since 1.2.6.1
  13714. */
  13715. UE.plugins['pasteplain'] = function(){
  13716. var me = this;
  13717. me.setOpt({
  13718. 'pasteplain':false,
  13719. 'filterTxtRules' : function(){
  13720. function transP(node){
  13721. node.tagName = 'p';
  13722. node.setStyle();
  13723. }
  13724. function removeNode(node){
  13725. node.parentNode.removeChild(node,true)
  13726. }
  13727. return {
  13728. //直接删除及其字节点内容
  13729. '-' : 'script style object iframe embed input select',
  13730. 'p': {$:{}},
  13731. 'br':{$:{}},
  13732. div: function (node) {
  13733. var tmpNode, p = UE.uNode.createElement('p');
  13734. while (tmpNode = node.firstChild()) {
  13735. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  13736. p.appendChild(tmpNode);
  13737. } else {
  13738. if (p.firstChild()) {
  13739. node.parentNode.insertBefore(p, node);
  13740. p = UE.uNode.createElement('p');
  13741. } else {
  13742. node.parentNode.insertBefore(tmpNode, node);
  13743. }
  13744. }
  13745. }
  13746. if (p.firstChild()) {
  13747. node.parentNode.insertBefore(p, node);
  13748. }
  13749. node.parentNode.removeChild(node);
  13750. },
  13751. ol: removeNode,
  13752. ul: removeNode,
  13753. dl:removeNode,
  13754. dt:removeNode,
  13755. dd:removeNode,
  13756. 'li':removeNode,
  13757. 'caption':transP,
  13758. 'th':transP,
  13759. 'tr':transP,
  13760. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  13761. 'td':function(node){
  13762. //没有内容的td直接删掉
  13763. var txt = !!node.innerText();
  13764. if(txt){
  13765. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  13766. }
  13767. node.parentNode.removeChild(node,node.innerText())
  13768. }
  13769. }
  13770. }()
  13771. });
  13772. //暂时这里支持一下老版本的属性
  13773. var pasteplain = me.options.pasteplain;
  13774. /**
  13775. * 启用或取消纯文本粘贴模式
  13776. * @command pasteplain
  13777. * @method execCommand
  13778. * @param { String } cmd 命令字符串
  13779. * @example
  13780. * ```javascript
  13781. * editor.queryCommandState( 'pasteplain' );
  13782. * ```
  13783. */
  13784. /**
  13785. * 查询当前是否处于纯文本粘贴模式
  13786. * @command pasteplain
  13787. * @method queryCommandState
  13788. * @param { String } cmd 命令字符串
  13789. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  13790. * @example
  13791. * ```javascript
  13792. * editor.queryCommandState( 'pasteplain' );
  13793. * ```
  13794. */
  13795. me.commands['pasteplain'] = {
  13796. queryCommandState: function (){
  13797. return pasteplain ? 1 : 0;
  13798. },
  13799. execCommand: function (){
  13800. pasteplain = !pasteplain|0;
  13801. },
  13802. notNeedUndo : 1
  13803. };
  13804. };
  13805. // plugins/list.js
  13806. /**
  13807. * 有序列表,无序列表插件
  13808. * @file
  13809. * @since 1.2.6.1
  13810. */
  13811. UE.plugins['list'] = function () {
  13812. var me = this,
  13813. notExchange = {
  13814. 'TD':1,
  13815. 'PRE':1,
  13816. 'BLOCKQUOTE':1
  13817. };
  13818. var customStyle = {
  13819. 'cn' : 'cn-1-',
  13820. 'cn1' : 'cn-2-',
  13821. 'cn2' : 'cn-3-',
  13822. 'num': 'num-1-',
  13823. 'num1' : 'num-2-',
  13824. 'num2' : 'num-3-',
  13825. 'dash' : 'dash',
  13826. 'dot':'dot'
  13827. };
  13828. me.setOpt( {
  13829. 'autoTransWordToList':false,
  13830. 'insertorderedlist':{
  13831. 'num':'',
  13832. 'num1':'',
  13833. 'num2':'',
  13834. 'cn':'',
  13835. 'cn1':'',
  13836. 'cn2':'',
  13837. 'decimal':'',
  13838. 'lower-alpha':'',
  13839. 'lower-roman':'',
  13840. 'upper-alpha':'',
  13841. 'upper-roman':''
  13842. },
  13843. 'insertunorderedlist':{
  13844. 'circle':'',
  13845. 'disc':'',
  13846. 'square':'',
  13847. 'dash' : '',
  13848. 'dot':''
  13849. },
  13850. listDefaultPaddingLeft : '30',
  13851. listiconpath : 'http://bs.baidu.com/listicon/',
  13852. maxListLevel : -1,//-1不限制
  13853. disablePInList:false
  13854. } );
  13855. function listToArray(list){
  13856. var arr = [];
  13857. for(var p in list){
  13858. arr.push(p)
  13859. }
  13860. return arr;
  13861. }
  13862. var listStyle = {
  13863. 'OL':listToArray(me.options.insertorderedlist),
  13864. 'UL':listToArray(me.options.insertunorderedlist)
  13865. };
  13866. var liiconpath = me.options.listiconpath;
  13867. //根据用户配置,调整customStyle
  13868. for(var s in customStyle){
  13869. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  13870. delete customStyle[s];
  13871. }
  13872. }
  13873. me.ready(function () {
  13874. var customCss = [];
  13875. for(var p in customStyle){
  13876. if(p == 'dash' || p == 'dot'){
  13877. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  13878. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13879. }else{
  13880. for(var i= 0;i<99;i++){
  13881. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  13882. }
  13883. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13884. }
  13885. switch(p){
  13886. case 'cn':
  13887. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13888. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13889. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13890. break;
  13891. case 'cn1':
  13892. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13893. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13894. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13895. break;
  13896. case 'cn2':
  13897. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13898. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13899. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13900. break;
  13901. case 'num':
  13902. case 'num1':
  13903. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13904. break;
  13905. case 'num2':
  13906. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13907. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13908. break;
  13909. case 'dash':
  13910. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13911. break;
  13912. case 'dot':
  13913. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13914. }
  13915. }
  13916. customCss.push('.list-paddingleft-1{padding-left:0}');
  13917. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13918. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13919. //如果不给宽度会在自定应样式里出现滚动条
  13920. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13921. });
  13922. //单独处理剪切的问题
  13923. me.ready(function(){
  13924. domUtils.on(me.body,'cut',function(){
  13925. setTimeout(function(){
  13926. var rng = me.selection.getRange(),li;
  13927. //trace:3416
  13928. if(!rng.collapsed){
  13929. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13930. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13931. var pn = li.parentNode,node;
  13932. if(node = pn.previousSibling){
  13933. domUtils.remove(pn);
  13934. rng.setStartAtLast(node).collapse(true);
  13935. rng.select(true);
  13936. }else if(node = pn.nextSibling){
  13937. domUtils.remove(pn);
  13938. rng.setStartAtFirst(node).collapse(true);
  13939. rng.select(true);
  13940. }else{
  13941. var tmpNode = me.document.createElement('p');
  13942. domUtils.fillNode(me.document,tmpNode);
  13943. pn.parentNode.insertBefore(tmpNode,pn);
  13944. domUtils.remove(pn);
  13945. rng.setStart(tmpNode,0).collapse(true);
  13946. rng.select(true);
  13947. }
  13948. }
  13949. }
  13950. }
  13951. })
  13952. })
  13953. });
  13954. function getStyle(node){
  13955. var cls = node.className;
  13956. if(domUtils.hasClass(node,/custom_/)){
  13957. return cls.match(/custom_(\w+)/)[1]
  13958. }
  13959. return domUtils.getStyle(node, 'list-style-type')
  13960. }
  13961. me.addListener('beforepaste',function(type,html){
  13962. var me = this,
  13963. rng = me.selection.getRange(),li;
  13964. var root = UE.htmlparser(html.html,true);
  13965. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13966. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13967. utils.each(root.getNodesByTagName(tagName),function(n){
  13968. n.tagName = list.tagName;
  13969. n.setAttr();
  13970. if(n.parentNode === root){
  13971. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13972. }else{
  13973. var className = n.parentNode.getAttr('class');
  13974. if(className && /custom_/.test(className)){
  13975. type = className.match(/custom_(\w+)/)[1]
  13976. }else{
  13977. type = n.parentNode.getStyle('list-style-type');
  13978. }
  13979. if(!type){
  13980. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13981. }
  13982. }
  13983. var index = utils.indexOf(listStyle[list.tagName], type);
  13984. if(n.parentNode !== root)
  13985. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13986. var currentStyle = listStyle[list.tagName][index];
  13987. if(customStyle[currentStyle]){
  13988. n.setAttr('class', 'custom_' + currentStyle)
  13989. }else{
  13990. n.setStyle('list-style-type',currentStyle)
  13991. }
  13992. })
  13993. }
  13994. html.html = root.toHtml();
  13995. });
  13996. //导出时,去掉p标签
  13997. me.getOpt('disablePInList') === true && me.addOutputRule(function(root){
  13998. utils.each(root.getNodesByTagName('li'),function(li){
  13999. var newChildrens = [],index=0;
  14000. utils.each(li.children,function(n){
  14001. if(n.tagName == 'p'){
  14002. var tmpNode;
  14003. while(tmpNode = n.children.pop()) {
  14004. newChildrens.splice(index,0,tmpNode);
  14005. tmpNode.parentNode = li;
  14006. lastNode = tmpNode;
  14007. }
  14008. tmpNode = newChildrens[newChildrens.length-1];
  14009. if(!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br'){
  14010. var br = UE.uNode.createElement('br');
  14011. br.parentNode = li;
  14012. newChildrens.push(br);
  14013. }
  14014. index = newChildrens.length;
  14015. }
  14016. });
  14017. if(newChildrens.length){
  14018. li.children = newChildrens;
  14019. }
  14020. });
  14021. });
  14022. //进入编辑器的li要套p标签
  14023. me.addInputRule(function(root){
  14024. utils.each(root.getNodesByTagName('li'),function(li){
  14025. var tmpP = UE.uNode.createElement('p');
  14026. for(var i= 0,ci;ci=li.children[i];){
  14027. if(ci.type == 'text' || dtd.p[ci.tagName]){
  14028. tmpP.appendChild(ci);
  14029. }else{
  14030. if(tmpP.firstChild()){
  14031. li.insertBefore(tmpP,ci);
  14032. tmpP = UE.uNode.createElement('p');
  14033. i = i + 2;
  14034. }else{
  14035. i++;
  14036. }
  14037. }
  14038. }
  14039. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  14040. li.appendChild(tmpP);
  14041. }
  14042. //trace:3357
  14043. //p不能为空
  14044. if (!tmpP.firstChild()) {
  14045. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  14046. }
  14047. //去掉末尾的空白
  14048. var p = li.firstChild();
  14049. var lastChild = p.lastChild();
  14050. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  14051. p.removeChild(lastChild)
  14052. }
  14053. });
  14054. if(me.options.autoTransWordToList){
  14055. var orderlisttype = {
  14056. 'num1':/^\d+\)/,
  14057. 'decimal':/^\d+\./,
  14058. 'lower-alpha':/^[a-z]+\)/,
  14059. 'upper-alpha':/^[A-Z]+\./,
  14060. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14061. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14062. },
  14063. unorderlisttype = {
  14064. 'square':'n'
  14065. };
  14066. function checkListType(content,container){
  14067. var span = container.firstChild();
  14068. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  14069. for(var p in unorderlisttype){
  14070. if(unorderlisttype[p] == span.data){
  14071. return p
  14072. }
  14073. }
  14074. return 'disc'
  14075. }
  14076. for(var p in orderlisttype){
  14077. if(orderlisttype[p].test(content)){
  14078. return p;
  14079. }
  14080. }
  14081. }
  14082. utils.each(root.getNodesByTagName('p'),function(node){
  14083. if(node.getAttr('class') != 'MsoListParagraph'){
  14084. return
  14085. }
  14086. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14087. node.setStyle('margin','');
  14088. node.setStyle('margin-left','');
  14089. node.setAttr('class','');
  14090. function appendLi(list,p,type){
  14091. if(list.tagName == 'ol'){
  14092. if(browser.ie){
  14093. var first = p.firstChild();
  14094. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  14095. p.removeChild(first);
  14096. }
  14097. }else{
  14098. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  14099. }
  14100. }else{
  14101. p.removeChild(p.firstChild())
  14102. }
  14103. var li = UE.uNode.createElement('li');
  14104. li.appendChild(p);
  14105. list.appendChild(li);
  14106. }
  14107. var tmp = node,type,cacheNode = node;
  14108. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  14109. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14110. if(customStyle[type]){
  14111. list.setAttr('class','custom_'+type)
  14112. }else{
  14113. list.setStyle('list-style-type',type)
  14114. }
  14115. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  14116. tmp = node.nextSibling();
  14117. if(!tmp){
  14118. node.parentNode.insertBefore(list,node)
  14119. }
  14120. appendLi(list,node,type);
  14121. node = tmp;
  14122. }
  14123. if(!list.parentNode && node && node.parentNode){
  14124. node.parentNode.insertBefore(list,node)
  14125. }
  14126. }
  14127. var span = cacheNode.firstChild();
  14128. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  14129. span.parentNode.removeChild(span)
  14130. }
  14131. })
  14132. }
  14133. });
  14134. //调整索引标签
  14135. me.addListener('contentchange',function(){
  14136. adjustListStyle(me.document)
  14137. });
  14138. function adjustListStyle(doc,ignore){
  14139. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  14140. if(!domUtils.inDoc(node,doc))
  14141. return;
  14142. var parent = node.parentNode;
  14143. if(parent.tagName == node.tagName){
  14144. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14145. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14146. if(nodeStyleType == parentStyleType){
  14147. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14148. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14149. setListStyle(node,listStyle[node.tagName][styleIndex])
  14150. }
  14151. }
  14152. var index = 0,type = 2;
  14153. if( domUtils.hasClass(node,/custom_/)){
  14154. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  14155. type = 1;
  14156. }
  14157. }else{
  14158. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  14159. type = 3;
  14160. }
  14161. }
  14162. var style = domUtils.getStyle(node, 'list-style-type');
  14163. style && (node.style.cssText = 'list-style-type:' + style);
  14164. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  14165. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  14166. li.style.cssText && (li.style.cssText = '');
  14167. if(!li.firstChild){
  14168. domUtils.remove(li);
  14169. return;
  14170. }
  14171. if(li.parentNode !== node){
  14172. return;
  14173. }
  14174. index++;
  14175. if(domUtils.hasClass(node,/custom_/) ){
  14176. var paddingLeft = 1,currentStyle = getStyle(node);
  14177. if(node.tagName == 'OL'){
  14178. if(currentStyle){
  14179. switch(currentStyle){
  14180. case 'cn' :
  14181. case 'cn1':
  14182. case 'cn2':
  14183. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  14184. paddingLeft = 2
  14185. }else if(index > 20){
  14186. paddingLeft = 3
  14187. }
  14188. break;
  14189. case 'num2' :
  14190. if(index > 9){
  14191. paddingLeft = 2
  14192. }
  14193. }
  14194. }
  14195. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  14196. }else{
  14197. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  14198. }
  14199. }else{
  14200. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  14201. }
  14202. var className = li.getAttribute('class');
  14203. if(className !== null && !className.replace(/\s/g,'')){
  14204. domUtils.removeAttributes(li,'class')
  14205. }
  14206. });
  14207. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  14208. })
  14209. }
  14210. function adjustList(list, tag, style,ignoreEmpty) {
  14211. var nextList = list.nextSibling;
  14212. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14213. domUtils.moveChild(nextList, list);
  14214. if (nextList.childNodes.length == 0) {
  14215. domUtils.remove(nextList);
  14216. }
  14217. }
  14218. if(nextList && domUtils.isFillChar(nextList)){
  14219. domUtils.remove(nextList);
  14220. }
  14221. var preList = list.previousSibling;
  14222. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14223. domUtils.moveChild(list, preList);
  14224. }
  14225. if(preList && domUtils.isFillChar(preList)){
  14226. domUtils.remove(preList);
  14227. }
  14228. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14229. if(getStyle(list)){
  14230. adjustListStyle(list.ownerDocument,true)
  14231. }
  14232. }
  14233. function setListStyle(list,style){
  14234. if(customStyle[style]){
  14235. list.className = 'custom_' + style;
  14236. }
  14237. try{
  14238. domUtils.setStyle(list, 'list-style-type', style);
  14239. }catch(e){}
  14240. }
  14241. function clearEmptySibling(node) {
  14242. var tmpNode = node.previousSibling;
  14243. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14244. domUtils.remove(tmpNode);
  14245. }
  14246. tmpNode = node.nextSibling;
  14247. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14248. domUtils.remove(tmpNode);
  14249. }
  14250. }
  14251. me.addListener('keydown', function (type, evt) {
  14252. function preventAndSave() {
  14253. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14254. me.fireEvent('contentchange');
  14255. me.undoManger && me.undoManger.save();
  14256. }
  14257. function findList(node,filterFn){
  14258. while(node && !domUtils.isBody(node)){
  14259. if(filterFn(node)){
  14260. return null
  14261. }
  14262. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  14263. return node;
  14264. }
  14265. node = node.parentNode;
  14266. }
  14267. return null;
  14268. }
  14269. var keyCode = evt.keyCode || evt.which;
  14270. if (keyCode == 13 && !evt.shiftKey) {//回车
  14271. var rng = me.selection.getRange(),
  14272. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  14273. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  14274. if(parent && parent.tagName != 'PRE' && !li){
  14275. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  14276. if(/^\s*1\s*\.[^\d]/.test(html)){
  14277. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  14278. rng.setStartAtLast(parent).collapse(true).select();
  14279. me.__hasEnterExecCommand = true;
  14280. me.execCommand('insertorderedlist');
  14281. me.__hasEnterExecCommand = false;
  14282. }
  14283. }
  14284. var range = me.selection.getRange(),
  14285. start = findList(range.startContainer,function (node) {
  14286. return node.tagName == 'TABLE';
  14287. }),
  14288. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  14289. return node.tagName == 'TABLE';
  14290. });
  14291. if (start && end && start === end) {
  14292. if (!range.collapsed) {
  14293. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14294. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14295. if (start && end && start === end) {
  14296. range.deleteContents();
  14297. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14298. if (li && domUtils.isEmptyBlock(li)) {
  14299. pre = li.previousSibling;
  14300. next = li.nextSibling;
  14301. p = me.document.createElement('p');
  14302. domUtils.fillNode(me.document, p);
  14303. parentList = li.parentNode;
  14304. if (pre && next) {
  14305. range.setStart(next, 0).collapse(true).select(true);
  14306. domUtils.remove(li);
  14307. } else {
  14308. if (!pre && !next || !pre) {
  14309. parentList.parentNode.insertBefore(p, parentList);
  14310. } else {
  14311. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14312. }
  14313. domUtils.remove(li);
  14314. if (!parentList.firstChild) {
  14315. domUtils.remove(parentList);
  14316. }
  14317. range.setStart(p, 0).setCursor();
  14318. }
  14319. preventAndSave();
  14320. return;
  14321. }
  14322. } else {
  14323. var tmpRange = range.cloneRange(),
  14324. bk = tmpRange.collapse(false).createBookmark();
  14325. range.deleteContents();
  14326. tmpRange.moveToBookmark(bk);
  14327. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14328. clearEmptySibling(li);
  14329. tmpRange.select();
  14330. preventAndSave();
  14331. return;
  14332. }
  14333. }
  14334. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14335. if (li) {
  14336. if (domUtils.isEmptyBlock(li)) {
  14337. bk = range.createBookmark();
  14338. var parentList = li.parentNode;
  14339. if (li !== parentList.lastChild) {
  14340. domUtils.breakParent(li, parentList);
  14341. clearEmptySibling(li);
  14342. } else {
  14343. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14344. if (domUtils.isEmptyNode(parentList)) {
  14345. domUtils.remove(parentList);
  14346. }
  14347. }
  14348. //嵌套不处理
  14349. if (!dtd.$list[li.parentNode.tagName]) {
  14350. if (!domUtils.isBlockElm(li.firstChild)) {
  14351. p = me.document.createElement('p');
  14352. li.parentNode.insertBefore(p, li);
  14353. while (li.firstChild) {
  14354. p.appendChild(li.firstChild);
  14355. }
  14356. domUtils.remove(li);
  14357. } else {
  14358. domUtils.remove(li, true);
  14359. }
  14360. }
  14361. range.moveToBookmark(bk).select();
  14362. } else {
  14363. var first = li.firstChild;
  14364. if (!first || !domUtils.isBlockElm(first)) {
  14365. var p = me.document.createElement('p');
  14366. !li.firstChild && domUtils.fillNode(me.document, p);
  14367. while (li.firstChild) {
  14368. p.appendChild(li.firstChild);
  14369. }
  14370. li.appendChild(p);
  14371. first = p;
  14372. }
  14373. var span = me.document.createElement('span');
  14374. range.insertNode(span);
  14375. domUtils.breakParent(span, li);
  14376. var nextLi = span.nextSibling;
  14377. first = nextLi.firstChild;
  14378. if (!first) {
  14379. p = me.document.createElement('p');
  14380. domUtils.fillNode(me.document, p);
  14381. nextLi.appendChild(p);
  14382. first = p;
  14383. }
  14384. if (domUtils.isEmptyNode(first)) {
  14385. first.innerHTML = '';
  14386. domUtils.fillNode(me.document, first);
  14387. }
  14388. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14389. domUtils.remove(span);
  14390. var pre = nextLi.previousSibling;
  14391. if (pre && domUtils.isEmptyBlock(pre)) {
  14392. pre.innerHTML = '<p></p>';
  14393. domUtils.fillNode(me.document, pre.firstChild);
  14394. }
  14395. }
  14396. // }
  14397. preventAndSave();
  14398. }
  14399. }
  14400. }
  14401. if (keyCode == 8) {
  14402. //修中ie中li下的问题
  14403. range = me.selection.getRange();
  14404. if (range.collapsed && domUtils.isStartInblock(range)) {
  14405. tmpRange = range.cloneRange().trimBoundary();
  14406. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14407. //要在li的最左边,才能处理
  14408. if (li && domUtils.isStartInblock(tmpRange)) {
  14409. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14410. if (start && start !== li.firstChild) {
  14411. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  14412. domUtils.breakParent(start,parentList);
  14413. clearEmptySibling(start);
  14414. me.fireEvent('contentchange');
  14415. range.setStart(start,0).setCursor(false,true);
  14416. me.fireEvent('saveScene');
  14417. domUtils.preventDefault(evt);
  14418. return;
  14419. }
  14420. if (li && (pre = li.previousSibling)) {
  14421. if (keyCode == 46 && li.childNodes.length) {
  14422. return;
  14423. }
  14424. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14425. if (dtd.$list[pre.tagName]) {
  14426. pre = pre.lastChild;
  14427. }
  14428. me.undoManger && me.undoManger.save();
  14429. first = li.firstChild;
  14430. if (domUtils.isBlockElm(first)) {
  14431. if (domUtils.isEmptyNode(first)) {
  14432. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14433. pre.appendChild(first);
  14434. range.setStart(first, 0).setCursor(false, true);
  14435. //first不是唯一的节点
  14436. while (li.firstChild) {
  14437. pre.appendChild(li.firstChild);
  14438. }
  14439. } else {
  14440. span = me.document.createElement('span');
  14441. range.insertNode(span);
  14442. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14443. if (domUtils.isEmptyBlock(pre)) {
  14444. pre.innerHTML = '';
  14445. }
  14446. domUtils.moveChild(li, pre);
  14447. range.setStartBefore(span).collapse(true).select(true);
  14448. domUtils.remove(span);
  14449. }
  14450. } else {
  14451. if (domUtils.isEmptyNode(li)) {
  14452. var p = me.document.createElement('p');
  14453. pre.appendChild(p);
  14454. range.setStart(p, 0).setCursor();
  14455. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14456. } else {
  14457. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14458. while (li.firstChild) {
  14459. pre.appendChild(li.firstChild);
  14460. }
  14461. }
  14462. }
  14463. domUtils.remove(li);
  14464. me.fireEvent('contentchange');
  14465. me.fireEvent('saveScene');
  14466. domUtils.preventDefault(evt);
  14467. return;
  14468. }
  14469. //trace:980
  14470. if (li && !li.previousSibling) {
  14471. var parentList = li.parentNode;
  14472. var bk = range.createBookmark();
  14473. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  14474. parentList.parentNode.insertBefore(li,parentList);
  14475. if(domUtils.isEmptyNode(parentList)){
  14476. domUtils.remove(parentList)
  14477. }
  14478. }else{
  14479. while(li.firstChild){
  14480. parentList.parentNode.insertBefore(li.firstChild,parentList);
  14481. }
  14482. domUtils.remove(li);
  14483. if(domUtils.isEmptyNode(parentList)){
  14484. domUtils.remove(parentList)
  14485. }
  14486. }
  14487. range.moveToBookmark(bk).setCursor(false,true);
  14488. me.fireEvent('contentchange');
  14489. me.fireEvent('saveScene');
  14490. domUtils.preventDefault(evt);
  14491. return;
  14492. }
  14493. }
  14494. }
  14495. }
  14496. });
  14497. me.addListener('keyup',function(type, evt){
  14498. var keyCode = evt.keyCode || evt.which;
  14499. if (keyCode == 8) {
  14500. var rng = me.selection.getRange(),list;
  14501. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  14502. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  14503. }
  14504. }
  14505. });
  14506. //处理tab键
  14507. me.addListener('tabkeydown',function(){
  14508. var range = me.selection.getRange();
  14509. //控制级数
  14510. function checkLevel(li){
  14511. if(me.options.maxListLevel != -1){
  14512. var level = li.parentNode,levelNum = 0;
  14513. while(/[ou]l/i.test(level.tagName)){
  14514. levelNum++;
  14515. level = level.parentNode;
  14516. }
  14517. if(levelNum >= me.options.maxListLevel){
  14518. return true;
  14519. }
  14520. }
  14521. }
  14522. //只以开始为准
  14523. //todo 后续改进
  14524. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14525. if(li){
  14526. var bk;
  14527. if(range.collapsed){
  14528. if(checkLevel(li))
  14529. return true;
  14530. var parentLi = li.parentNode,
  14531. list = me.document.createElement(parentLi.tagName),
  14532. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14533. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14534. var currentStyle = listStyle[list.tagName][index];
  14535. setListStyle(list,currentStyle);
  14536. if(domUtils.isStartInblock(range)){
  14537. me.fireEvent('saveScene');
  14538. bk = range.createBookmark();
  14539. parentLi.insertBefore(list, li);
  14540. list.appendChild(li);
  14541. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14542. me.fireEvent('contentchange');
  14543. range.moveToBookmark(bk).select(true);
  14544. return true;
  14545. }
  14546. }else{
  14547. me.fireEvent('saveScene');
  14548. bk = range.createBookmark();
  14549. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  14550. if(domUtils.isTagNode(ci,'ol ul')){
  14551. closeList = ci;
  14552. break;
  14553. }
  14554. }
  14555. var current = li;
  14556. if(bk.end){
  14557. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14558. if(checkLevel(current)){
  14559. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14560. continue;
  14561. }
  14562. var parentLi = current.parentNode,
  14563. list = me.document.createElement(parentLi.tagName),
  14564. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14565. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14566. var currentStyle = listStyle[list.tagName][currentIndex];
  14567. setListStyle(list,currentStyle);
  14568. parentLi.insertBefore(list, current);
  14569. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14570. li = current.nextSibling;
  14571. list.appendChild(current);
  14572. if(!li || domUtils.isTagNode(li,'ol ul')){
  14573. if(li){
  14574. while(li = li.firstChild){
  14575. if(li.tagName == 'LI'){
  14576. break;
  14577. }
  14578. }
  14579. }else{
  14580. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14581. }
  14582. break;
  14583. }
  14584. current = li;
  14585. }
  14586. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14587. current = li;
  14588. }
  14589. }
  14590. me.fireEvent('contentchange');
  14591. range.moveToBookmark(bk).select();
  14592. return true;
  14593. }
  14594. }
  14595. });
  14596. function getLi(start){
  14597. while(start && !domUtils.isBody(start)){
  14598. if(start.nodeName == 'TABLE'){
  14599. return null;
  14600. }
  14601. if(start.nodeName == 'LI'){
  14602. return start
  14603. }
  14604. start = start.parentNode;
  14605. }
  14606. }
  14607. /**
  14608. * 有序列表,与“insertunorderedlist”命令互斥
  14609. * @command insertorderedlist
  14610. * @method execCommand
  14611. * @param { String } command 命令字符串
  14612. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14613. * @example
  14614. * ```javascript
  14615. * editor.execCommand( 'insertorderedlist','decimal');
  14616. * ```
  14617. */
  14618. /**
  14619. * 查询当前选区内容是否有序列表
  14620. * @command insertorderedlist
  14621. * @method queryCommandState
  14622. * @param { String } cmd 命令字符串
  14623. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  14624. * @example
  14625. * ```javascript
  14626. * editor.queryCommandState( 'insertorderedlist' );
  14627. * ```
  14628. */
  14629. /**
  14630. * 查询当前选区内容是否有序列表
  14631. * @command insertorderedlist
  14632. * @method queryCommandValue
  14633. * @param { String } cmd 命令字符串
  14634. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14635. * @example
  14636. * ```javascript
  14637. * editor.queryCommandValue( 'insertorderedlist' );
  14638. * ```
  14639. */
  14640. /**
  14641. * 无序列表,与“insertorderedlist”命令互斥
  14642. * @command insertunorderedlist
  14643. * @method execCommand
  14644. * @param { String } command 命令字符串
  14645. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  14646. * @example
  14647. * ```javascript
  14648. * editor.execCommand( 'insertunorderedlist','circle');
  14649. * ```
  14650. */
  14651. /**
  14652. * 查询当前是否有word文档粘贴进来的图片
  14653. * @command insertunorderedlist
  14654. * @method insertunorderedlist
  14655. * @param { String } command 命令字符串
  14656. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  14657. * @example
  14658. * ```javascript
  14659. * editor.queryCommandState( 'insertunorderedlist' );
  14660. * ```
  14661. */
  14662. /**
  14663. * 查询当前选区内容是否有序列表
  14664. * @command insertunorderedlist
  14665. * @method queryCommandValue
  14666. * @param { String } command 命令字符串
  14667. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  14668. * @example
  14669. * ```javascript
  14670. * editor.queryCommandValue( 'insertunorderedlist' );
  14671. * ```
  14672. */
  14673. me.commands['insertorderedlist'] =
  14674. me.commands['insertunorderedlist'] = {
  14675. execCommand:function (command, style) {
  14676. if (!style) {
  14677. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  14678. }
  14679. var me = this,
  14680. range = this.selection.getRange(),
  14681. filterFn = function (node) {
  14682. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  14683. },
  14684. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  14685. frag = me.document.createDocumentFragment();
  14686. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  14687. //range.shrinkBoundary();//.adjustmentBoundary();
  14688. range.adjustmentBoundary().shrinkBoundary();
  14689. var bko = range.createBookmark(true),
  14690. start = getLi(me.document.getElementById(bko.start)),
  14691. modifyStart = 0,
  14692. end = getLi(me.document.getElementById(bko.end)),
  14693. modifyEnd = 0,
  14694. startParent, endParent,
  14695. list, tmp;
  14696. if (start || end) {
  14697. start && (startParent = start.parentNode);
  14698. if (!bko.end) {
  14699. end = start;
  14700. }
  14701. end && (endParent = end.parentNode);
  14702. if (startParent === endParent) {
  14703. while (start !== end) {
  14704. tmp = start;
  14705. start = start.nextSibling;
  14706. if (!domUtils.isBlockElm(tmp.firstChild)) {
  14707. var p = me.document.createElement('p');
  14708. while (tmp.firstChild) {
  14709. p.appendChild(tmp.firstChild);
  14710. }
  14711. tmp.appendChild(p);
  14712. }
  14713. frag.appendChild(tmp);
  14714. }
  14715. tmp = me.document.createElement('span');
  14716. startParent.insertBefore(tmp, end);
  14717. if (!domUtils.isBlockElm(end.firstChild)) {
  14718. p = me.document.createElement('p');
  14719. while (end.firstChild) {
  14720. p.appendChild(end.firstChild);
  14721. }
  14722. end.appendChild(p);
  14723. }
  14724. frag.appendChild(end);
  14725. domUtils.breakParent(tmp, startParent);
  14726. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  14727. domUtils.remove(tmp.previousSibling);
  14728. }
  14729. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  14730. domUtils.remove(tmp.nextSibling)
  14731. }
  14732. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  14733. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  14734. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  14735. if(domUtils.isTagNode(ci,'ol ul')){
  14736. // 删除时,子列表不处理
  14737. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  14738. // while(li.firstChild){
  14739. // tmpFrag.appendChild(li.firstChild);
  14740. // }
  14741. //
  14742. // });
  14743. tmpFrag.appendChild(ci);
  14744. }else{
  14745. while (ci.firstChild) {
  14746. tmpFrag.appendChild(ci.firstChild);
  14747. domUtils.remove(ci);
  14748. }
  14749. }
  14750. }
  14751. tmp.parentNode.insertBefore(tmpFrag, tmp);
  14752. } else {
  14753. list = me.document.createElement(tag);
  14754. setListStyle(list,style);
  14755. list.appendChild(frag);
  14756. tmp.parentNode.insertBefore(list, tmp);
  14757. }
  14758. domUtils.remove(tmp);
  14759. list && adjustList(list, tag, style);
  14760. range.moveToBookmark(bko).select();
  14761. return;
  14762. }
  14763. //开始
  14764. if (start) {
  14765. while (start) {
  14766. tmp = start.nextSibling;
  14767. if (domUtils.isTagNode(start, 'ol ul')) {
  14768. frag.appendChild(start);
  14769. } else {
  14770. var tmpfrag = me.document.createDocumentFragment(),
  14771. hasBlock = 0;
  14772. while (start.firstChild) {
  14773. if (domUtils.isBlockElm(start.firstChild)) {
  14774. hasBlock = 1;
  14775. }
  14776. tmpfrag.appendChild(start.firstChild);
  14777. }
  14778. if (!hasBlock) {
  14779. var tmpP = me.document.createElement('p');
  14780. tmpP.appendChild(tmpfrag);
  14781. frag.appendChild(tmpP);
  14782. } else {
  14783. frag.appendChild(tmpfrag);
  14784. }
  14785. domUtils.remove(start);
  14786. }
  14787. start = tmp;
  14788. }
  14789. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  14790. if (domUtils.isEmptyNode(startParent)) {
  14791. range.setStartBefore(startParent);
  14792. domUtils.remove(startParent);
  14793. } else {
  14794. range.setStartAfter(startParent);
  14795. }
  14796. modifyStart = 1;
  14797. }
  14798. if (end && domUtils.inDoc(endParent, me.document)) {
  14799. //结束
  14800. start = endParent.firstChild;
  14801. while (start && start !== end) {
  14802. tmp = start.nextSibling;
  14803. if (domUtils.isTagNode(start, 'ol ul')) {
  14804. frag.appendChild(start);
  14805. } else {
  14806. tmpfrag = me.document.createDocumentFragment();
  14807. hasBlock = 0;
  14808. while (start.firstChild) {
  14809. if (domUtils.isBlockElm(start.firstChild)) {
  14810. hasBlock = 1;
  14811. }
  14812. tmpfrag.appendChild(start.firstChild);
  14813. }
  14814. if (!hasBlock) {
  14815. tmpP = me.document.createElement('p');
  14816. tmpP.appendChild(tmpfrag);
  14817. frag.appendChild(tmpP);
  14818. } else {
  14819. frag.appendChild(tmpfrag);
  14820. }
  14821. domUtils.remove(start);
  14822. }
  14823. start = tmp;
  14824. }
  14825. var tmpDiv = domUtils.createElement(me.document, 'div', {
  14826. 'tmpDiv':1
  14827. });
  14828. domUtils.moveChild(end, tmpDiv);
  14829. frag.appendChild(tmpDiv);
  14830. domUtils.remove(end);
  14831. endParent.parentNode.insertBefore(frag, endParent);
  14832. range.setEndBefore(endParent);
  14833. if (domUtils.isEmptyNode(endParent)) {
  14834. domUtils.remove(endParent);
  14835. }
  14836. modifyEnd = 1;
  14837. }
  14838. }
  14839. if (!modifyStart) {
  14840. range.setStartBefore(me.document.getElementById(bko.start));
  14841. }
  14842. if (bko.end && !modifyEnd) {
  14843. range.setEndAfter(me.document.getElementById(bko.end));
  14844. }
  14845. range.enlarge(true, function (node) {
  14846. return notExchange[node.tagName];
  14847. });
  14848. frag = me.document.createDocumentFragment();
  14849. var bk = range.createBookmark(),
  14850. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  14851. tmpRange = range.cloneRange(),
  14852. tmpNode,
  14853. block = domUtils.isBlockElm;
  14854. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  14855. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  14856. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  14857. while (current.firstChild) {
  14858. frag.appendChild(current.firstChild);
  14859. }
  14860. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  14861. domUtils.remove(current);
  14862. current = tmpNode;
  14863. continue;
  14864. }
  14865. tmpNode = current;
  14866. tmpRange.setStartBefore(current);
  14867. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  14868. tmpNode = current;
  14869. current = domUtils.getNextDomNode(current, false, null, function (node) {
  14870. return !notExchange[node.tagName];
  14871. });
  14872. }
  14873. if (current && block(current)) {
  14874. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14875. if (tmp && domUtils.isBookmarkNode(tmp)) {
  14876. current = domUtils.getNextDomNode(tmp, false, filterFn);
  14877. tmpNode = tmp;
  14878. }
  14879. }
  14880. tmpRange.setEndAfter(tmpNode);
  14881. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14882. var li = range.document.createElement('li');
  14883. li.appendChild(tmpRange.extractContents());
  14884. if(domUtils.isEmptyNode(li)){
  14885. var tmpNode = range.document.createElement('p');
  14886. while(li.firstChild){
  14887. tmpNode.appendChild(li.firstChild)
  14888. }
  14889. li.appendChild(tmpNode);
  14890. }
  14891. frag.appendChild(li);
  14892. } else {
  14893. current = domUtils.getNextDomNode(current, true, filterFn);
  14894. }
  14895. }
  14896. range.moveToBookmark(bk).collapse(true);
  14897. list = me.document.createElement(tag);
  14898. setListStyle(list,style);
  14899. list.appendChild(frag);
  14900. range.insertNode(list);
  14901. //当前list上下看能否合并
  14902. adjustList(list, tag, style);
  14903. //去掉冗余的tmpDiv
  14904. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  14905. if (ci.getAttribute('tmpDiv')) {
  14906. domUtils.remove(ci, true)
  14907. }
  14908. }
  14909. range.moveToBookmark(bko).select();
  14910. },
  14911. queryCommandState:function (command) {
  14912. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14913. var path = this.selection.getStartElementPath();
  14914. for(var i= 0,ci;ci = path[i++];){
  14915. if(ci.nodeName == 'TABLE'){
  14916. return 0
  14917. }
  14918. if(tag == ci.nodeName.toLowerCase()){
  14919. return 1
  14920. };
  14921. }
  14922. return 0;
  14923. },
  14924. queryCommandValue:function (command) {
  14925. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14926. var path = this.selection.getStartElementPath(),
  14927. node;
  14928. for(var i= 0,ci;ci = path[i++];){
  14929. if(ci.nodeName == 'TABLE'){
  14930. node = null;
  14931. break;
  14932. }
  14933. if(tag == ci.nodeName.toLowerCase()){
  14934. node = ci;
  14935. break;
  14936. };
  14937. }
  14938. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14939. }
  14940. };
  14941. };
  14942. // plugins/source.js
  14943. /**
  14944. * 源码编辑插件
  14945. * @file
  14946. * @since 1.2.6.1
  14947. */
  14948. (function (){
  14949. var sourceEditors = {
  14950. textarea: function (editor, holder){
  14951. var textarea = holder.ownerDocument.createElement('textarea');
  14952. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14953. // todo: IE下只有onresize属性可用... 很纠结
  14954. if (browser.ie && browser.version < 8) {
  14955. textarea.style.width = holder.offsetWidth + 'px';
  14956. textarea.style.height = holder.offsetHeight + 'px';
  14957. holder.onresize = function (){
  14958. textarea.style.width = holder.offsetWidth + 'px';
  14959. textarea.style.height = holder.offsetHeight + 'px';
  14960. };
  14961. }
  14962. holder.appendChild(textarea);
  14963. return {
  14964. setContent: function (content){
  14965. textarea.value = content;
  14966. },
  14967. getContent: function (){
  14968. return textarea.value;
  14969. },
  14970. select: function (){
  14971. var range;
  14972. if (browser.ie) {
  14973. range = textarea.createTextRange();
  14974. range.collapse(true);
  14975. range.select();
  14976. } else {
  14977. //todo: chrome下无法设置焦点
  14978. textarea.setSelectionRange(0, 0);
  14979. textarea.focus();
  14980. }
  14981. },
  14982. dispose: function (){
  14983. holder.removeChild(textarea);
  14984. // todo
  14985. holder.onresize = null;
  14986. textarea = null;
  14987. holder = null;
  14988. }
  14989. };
  14990. },
  14991. codemirror: function (editor, holder){
  14992. var codeEditor = window.CodeMirror(holder, {
  14993. mode: "text/html",
  14994. tabMode: "indent",
  14995. lineNumbers: true,
  14996. lineWrapping:true
  14997. });
  14998. var dom = codeEditor.getWrapperElement();
  14999. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  15000. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  15001. codeEditor.refresh();
  15002. return {
  15003. getCodeMirror:function(){
  15004. return codeEditor;
  15005. },
  15006. setContent: function (content){
  15007. codeEditor.setValue(content);
  15008. },
  15009. getContent: function (){
  15010. return codeEditor.getValue();
  15011. },
  15012. select: function (){
  15013. codeEditor.focus();
  15014. },
  15015. dispose: function (){
  15016. holder.removeChild(dom);
  15017. dom = null;
  15018. codeEditor = null;
  15019. }
  15020. };
  15021. }
  15022. };
  15023. UE.plugins['source'] = function (){
  15024. var me = this;
  15025. var opt = this.options;
  15026. var sourceMode = false;
  15027. var sourceEditor;
  15028. var orgSetContent;
  15029. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  15030. me.setOpt({
  15031. sourceEditorFirst:false
  15032. });
  15033. function createSourceEditor(holder){
  15034. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  15035. }
  15036. var bakCssText;
  15037. //解决在源码模式下getContent不能得到最新的内容问题
  15038. var oldGetContent,
  15039. bakAddress;
  15040. /**
  15041. * 切换源码模式和编辑模式
  15042. * @command source
  15043. * @method execCommand
  15044. * @param { String } cmd 命令字符串
  15045. * @example
  15046. * ```javascript
  15047. * editor.execCommand( 'source');
  15048. * ```
  15049. */
  15050. /**
  15051. * 查询当前编辑区域的状态是源码模式还是可视化模式
  15052. * @command source
  15053. * @method queryCommandState
  15054. * @param { String } cmd 命令字符串
  15055. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  15056. * @example
  15057. * ```javascript
  15058. * editor.queryCommandState( 'source' );
  15059. * ```
  15060. */
  15061. me.commands['source'] = {
  15062. execCommand: function (){
  15063. sourceMode = !sourceMode;
  15064. if (sourceMode) {
  15065. bakAddress = me.selection.getRange().createAddress(false,true);
  15066. me.undoManger && me.undoManger.save(true);
  15067. if(browser.gecko){
  15068. me.body.contentEditable = false;
  15069. }
  15070. bakCssText = me.iframe.style.cssText;
  15071. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15072. me.fireEvent('beforegetcontent');
  15073. var root = UE.htmlparser(me.body.innerHTML);
  15074. me.filterOutputRule(root);
  15075. root.traversal(function (node) {
  15076. if (node.type == 'element') {
  15077. switch (node.tagName) {
  15078. case 'td':
  15079. case 'th':
  15080. case 'caption':
  15081. if(node.children && node.children.length == 1){
  15082. if(node.firstChild().tagName == 'br' ){
  15083. node.removeChild(node.firstChild())
  15084. }
  15085. };
  15086. break;
  15087. case 'pre':
  15088. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  15089. }
  15090. }
  15091. });
  15092. me.fireEvent('aftergetcontent');
  15093. var content = root.toHtml(true);
  15094. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15095. sourceEditor.setContent(content);
  15096. orgSetContent = me.setContent;
  15097. me.setContent = function(html){
  15098. //这里暂时不触发事件,防止报错
  15099. var root = UE.htmlparser(html);
  15100. me.filterInputRule(root);
  15101. html = root.toHtml();
  15102. sourceEditor.setContent(html);
  15103. };
  15104. setTimeout(function (){
  15105. sourceEditor.select();
  15106. me.addListener('fullscreenchanged', function(){
  15107. try{
  15108. sourceEditor.getCodeMirror().refresh()
  15109. }catch(e){}
  15110. });
  15111. });
  15112. //重置getContent,源码模式下取值也能是最新的数据
  15113. oldGetContent = me.getContent;
  15114. me.getContent = function (){
  15115. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15116. };
  15117. } else {
  15118. me.iframe.style.cssText = bakCssText;
  15119. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15120. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15121. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  15122. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  15123. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  15124. }
  15125. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  15126. });
  15127. me.setContent = orgSetContent;
  15128. me.setContent(cont);
  15129. sourceEditor.dispose();
  15130. sourceEditor = null;
  15131. //还原getContent方法
  15132. me.getContent = oldGetContent;
  15133. var first = me.body.firstChild;
  15134. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15135. if(!first){
  15136. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  15137. first = me.body.firstChild;
  15138. }
  15139. //要在ifm为显示时ff才能取到selection,否则报错
  15140. //这里不能比较位置了
  15141. me.undoManger && me.undoManger.save(true);
  15142. if(browser.gecko){
  15143. var input = document.createElement('input');
  15144. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15145. document.body.appendChild(input);
  15146. me.body.contentEditable = false;
  15147. setTimeout(function(){
  15148. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  15149. input.focus();
  15150. setTimeout(function(){
  15151. me.body.contentEditable = true;
  15152. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15153. domUtils.remove(input);
  15154. });
  15155. });
  15156. }else{
  15157. //ie下有可能报错,比如在代码顶头的情况
  15158. try{
  15159. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15160. }catch(e){}
  15161. }
  15162. }
  15163. this.fireEvent('sourcemodechanged', sourceMode);
  15164. },
  15165. queryCommandState: function (){
  15166. return sourceMode|0;
  15167. },
  15168. notNeedUndo : 1
  15169. };
  15170. var oldQueryCommandState = me.queryCommandState;
  15171. me.queryCommandState = function (cmdName){
  15172. cmdName = cmdName.toLowerCase();
  15173. if (sourceMode) {
  15174. //源码模式下可以开启的命令
  15175. return cmdName in {
  15176. 'source' : 1,
  15177. 'fullscreen' : 1
  15178. } ? 1 : -1
  15179. }
  15180. return oldQueryCommandState.apply(this, arguments);
  15181. };
  15182. if(opt.sourceEditor == "codemirror"){
  15183. me.addListener("ready",function(){
  15184. utils.loadFile(document,{
  15185. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15186. tag : "script",
  15187. type : "text/javascript",
  15188. defer : "defer"
  15189. },function(){
  15190. if(opt.sourceEditorFirst){
  15191. setTimeout(function(){
  15192. me.execCommand("source");
  15193. },0);
  15194. }
  15195. });
  15196. utils.loadFile(document,{
  15197. tag : "link",
  15198. rel : "stylesheet",
  15199. type : "text/css",
  15200. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15201. });
  15202. });
  15203. }
  15204. };
  15205. })();
  15206. // plugins/enterkey.js
  15207. ///import core
  15208. ///import plugins/undo.js
  15209. ///commands 设置回车标签p或br
  15210. ///commandsName EnterKey
  15211. ///commandsTitle 设置回车标签p或br
  15212. /**
  15213. * @description 处理回车
  15214. * @author zhanyi
  15215. */
  15216. UE.plugins['enterkey'] = function() {
  15217. var hTag,
  15218. me = this,
  15219. tag = me.options.enterTag;
  15220. me.addListener('keyup', function(type, evt) {
  15221. var keyCode = evt.keyCode || evt.which;
  15222. if (keyCode == 13) {
  15223. var range = me.selection.getRange(),
  15224. start = range.startContainer,
  15225. doSave;
  15226. //修正在h1-h6里边回车后不能嵌套p的问题
  15227. if (!browser.ie) {
  15228. if (/h\d/i.test(hTag)) {
  15229. if (browser.gecko) {
  15230. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  15231. if (!h) {
  15232. me.document.execCommand('formatBlock', false, '<p>');
  15233. doSave = 1;
  15234. }
  15235. } else {
  15236. //chrome remove div
  15237. if (start.nodeType == 1) {
  15238. var tmp = me.document.createTextNode(''),div;
  15239. range.insertNode(tmp);
  15240. div = domUtils.findParentByTagName(tmp, 'div', true);
  15241. if (div) {
  15242. var p = me.document.createElement('p');
  15243. while (div.firstChild) {
  15244. p.appendChild(div.firstChild);
  15245. }
  15246. div.parentNode.insertBefore(p, div);
  15247. domUtils.remove(div);
  15248. range.setStartBefore(tmp).setCursor();
  15249. doSave = 1;
  15250. }
  15251. domUtils.remove(tmp);
  15252. }
  15253. }
  15254. if (me.undoManger && doSave) {
  15255. me.undoManger.save();
  15256. }
  15257. }
  15258. //没有站位符,会出现多行的问题
  15259. browser.opera && range.select();
  15260. }else{
  15261. me.fireEvent('saveScene',true,true)
  15262. }
  15263. }
  15264. });
  15265. me.addListener('keydown', function(type, evt) {
  15266. var keyCode = evt.keyCode || evt.which;
  15267. if (keyCode == 13) {//回车
  15268. if(me.fireEvent('beforeenterkeydown')){
  15269. domUtils.preventDefault(evt);
  15270. return;
  15271. }
  15272. me.fireEvent('saveScene',true,true);
  15273. hTag = '';
  15274. var range = me.selection.getRange();
  15275. if (!range.collapsed) {
  15276. //跨td不能删
  15277. var start = range.startContainer,
  15278. end = range.endContainer,
  15279. startTd = domUtils.findParentByTagName(start, 'td', true),
  15280. endTd = domUtils.findParentByTagName(end, 'td', true);
  15281. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15282. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15283. return;
  15284. }
  15285. }
  15286. if (tag == 'p') {
  15287. if (!browser.ie) {
  15288. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  15289. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15290. //trace:2431
  15291. if (!start && !browser.opera) {
  15292. me.document.execCommand('formatBlock', false, '<p>');
  15293. if (browser.gecko) {
  15294. range = me.selection.getRange();
  15295. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15296. start && domUtils.removeDirtyAttr(start);
  15297. }
  15298. } else {
  15299. hTag = start.tagName;
  15300. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15301. }
  15302. }
  15303. } else {
  15304. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15305. if (!range.collapsed) {
  15306. range.deleteContents();
  15307. start = range.startContainer;
  15308. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15309. while (start.nodeType == 1) {
  15310. if (dtd.$empty[start.tagName]) {
  15311. range.setStartBefore(start).setCursor();
  15312. if (me.undoManger) {
  15313. me.undoManger.save();
  15314. }
  15315. return false;
  15316. }
  15317. if (!start.firstChild) {
  15318. var br = range.document.createElement('br');
  15319. start.appendChild(br);
  15320. range.setStart(start, 0).setCursor();
  15321. if (me.undoManger) {
  15322. me.undoManger.save();
  15323. }
  15324. return false;
  15325. }
  15326. start = start.firstChild;
  15327. }
  15328. if (start === range.startContainer.childNodes[range.startOffset]) {
  15329. br = range.document.createElement('br');
  15330. range.insertNode(br).setCursor();
  15331. } else {
  15332. range.setStart(start, 0).setCursor();
  15333. }
  15334. } else {
  15335. br = range.document.createElement('br');
  15336. range.insertNode(br).setStartAfter(br).setCursor();
  15337. }
  15338. } else {
  15339. br = range.document.createElement('br');
  15340. range.insertNode(br);
  15341. var parent = br.parentNode;
  15342. if (parent.lastChild === br) {
  15343. br.parentNode.insertBefore(br.cloneNode(true), br);
  15344. range.setStartBefore(br);
  15345. } else {
  15346. range.setStartAfter(br);
  15347. }
  15348. range.setCursor();
  15349. }
  15350. }
  15351. }
  15352. });
  15353. };
  15354. // plugins/keystrokes.js
  15355. /* 处理特殊键的兼容性问题 */
  15356. UE.plugins['keystrokes'] = function() {
  15357. var me = this;
  15358. var collapsed = true;
  15359. me.addListener('keydown', function(type, evt) {
  15360. var keyCode = evt.keyCode || evt.which,
  15361. rng = me.selection.getRange();
  15362. //处理全选的情况
  15363. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  15364. || keyCode >= 48 && keyCode <= 57 ||
  15365. keyCode >= 96 && keyCode <= 111 || {
  15366. 13:1,
  15367. 8:1,
  15368. 46:1
  15369. }[keyCode])
  15370. ){
  15371. var tmpNode = rng.startContainer;
  15372. if(domUtils.isFillChar(tmpNode)){
  15373. rng.setStartBefore(tmpNode)
  15374. }
  15375. tmpNode = rng.endContainer;
  15376. if(domUtils.isFillChar(tmpNode)){
  15377. rng.setEndAfter(tmpNode)
  15378. }
  15379. rng.txtToElmBoundary();
  15380. //结束边界可能放到了br的前边,要把br包含进来
  15381. // x[xxx]<br/>
  15382. if(rng.endContainer && rng.endContainer.nodeType == 1){
  15383. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15384. if(tmpNode && domUtils.isBr(tmpNode)){
  15385. rng.setEndAfter(tmpNode);
  15386. }
  15387. }
  15388. if(rng.startOffset == 0){
  15389. tmpNode = rng.startContainer;
  15390. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  15391. tmpNode = rng.endContainer;
  15392. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  15393. me.fireEvent('saveScene');
  15394. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  15395. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  15396. me._selectionChange();
  15397. return;
  15398. }
  15399. }
  15400. }
  15401. }
  15402. //处理backspace
  15403. if (keyCode == keymap.Backspace) {
  15404. rng = me.selection.getRange();
  15405. collapsed = rng.collapsed;
  15406. if(me.fireEvent('delkeydown',evt)){
  15407. return;
  15408. }
  15409. var start,end;
  15410. //避免按两次删除才能生效的问题
  15411. if(rng.collapsed && rng.inFillChar()){
  15412. start = rng.startContainer;
  15413. if(domUtils.isFillChar(start)){
  15414. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15415. domUtils.remove(start)
  15416. }else{
  15417. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  15418. rng.startOffset--;
  15419. rng.collapse(true).select(true)
  15420. }
  15421. }
  15422. //解决选中control元素不能删除的问题
  15423. if (start = rng.getClosedNode()) {
  15424. me.fireEvent('saveScene');
  15425. rng.setStartBefore(start);
  15426. domUtils.remove(start);
  15427. rng.setCursor();
  15428. me.fireEvent('saveScene');
  15429. domUtils.preventDefault(evt);
  15430. return;
  15431. }
  15432. //阻止在table上的删除
  15433. if (!browser.ie) {
  15434. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15435. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15436. if (start && !end || !start && end || start !== end) {
  15437. evt.preventDefault();
  15438. return;
  15439. }
  15440. }
  15441. }
  15442. //处理tab键的逻辑
  15443. if (keyCode == keymap.Tab) {
  15444. //不处理以下标签
  15445. var excludeTagNameForTabKey = {
  15446. 'ol' : 1,
  15447. 'ul' : 1,
  15448. 'table':1
  15449. };
  15450. //处理组件里的tab按下事件
  15451. if(me.fireEvent('tabkeydown',evt)){
  15452. domUtils.preventDefault(evt);
  15453. return;
  15454. }
  15455. var range = me.selection.getRange();
  15456. me.fireEvent('saveScene');
  15457. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15458. txt += tabNode;
  15459. }
  15460. var span = me.document.createElement('span');
  15461. span.innerHTML = txt + domUtils.fillChar;
  15462. if (range.collapsed) {
  15463. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15464. } else {
  15465. var filterFn = function(node) {
  15466. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15467. };
  15468. //普通的情况
  15469. start = domUtils.findParent(range.startContainer, filterFn,true);
  15470. end = domUtils.findParent(range.endContainer, filterFn,true);
  15471. if (start && end && start === end) {
  15472. range.deleteContents();
  15473. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15474. } else {
  15475. var bookmark = range.createBookmark();
  15476. range.enlarge(true);
  15477. var bookmark2 = range.createBookmark(),
  15478. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15479. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15480. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15481. current = domUtils.getNextDomNode(current, false, filterFn);
  15482. }
  15483. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15484. }
  15485. }
  15486. domUtils.preventDefault(evt)
  15487. }
  15488. //trace:1634
  15489. //ff的del键在容器空的时候,也会删除
  15490. if(browser.gecko && keyCode == 46){
  15491. range = me.selection.getRange();
  15492. if(range.collapsed){
  15493. start = range.startContainer;
  15494. if(domUtils.isEmptyBlock(start)){
  15495. var parent = start.parentNode;
  15496. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  15497. start = parent;
  15498. parent = parent.parentNode;
  15499. }
  15500. if(start === parent.lastChild)
  15501. evt.preventDefault();
  15502. return;
  15503. }
  15504. }
  15505. }
  15506. });
  15507. me.addListener('keyup', function(type, evt) {
  15508. var keyCode = evt.keyCode || evt.which,
  15509. rng,me = this;
  15510. if(keyCode == keymap.Backspace){
  15511. if(me.fireEvent('delkeyup')){
  15512. return;
  15513. }
  15514. rng = me.selection.getRange();
  15515. if(rng.collapsed){
  15516. var tmpNode,
  15517. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  15518. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  15519. if(domUtils.isEmptyBlock(tmpNode)){
  15520. var pre = tmpNode.previousSibling;
  15521. if(pre && pre.nodeName != 'TABLE'){
  15522. domUtils.remove(tmpNode);
  15523. rng.setStartAtLast(pre).setCursor(false,true);
  15524. return;
  15525. }else{
  15526. var next = tmpNode.nextSibling;
  15527. if(next && next.nodeName != 'TABLE'){
  15528. domUtils.remove(tmpNode);
  15529. rng.setStartAtFirst(next).setCursor(false,true);
  15530. return;
  15531. }
  15532. }
  15533. }
  15534. }
  15535. //处理当删除到body时,要重新给p标签展位
  15536. if(domUtils.isBody(rng.startContainer)){
  15537. var tmpNode = domUtils.createElement(me.document,'p',{
  15538. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  15539. });
  15540. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  15541. }
  15542. }
  15543. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  15544. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  15545. if(browser.ie){
  15546. var span = rng.document.createElement('span');
  15547. rng.insertNode(span).setStartBefore(span).collapse(true);
  15548. rng.select();
  15549. domUtils.remove(span)
  15550. }else{
  15551. rng.select()
  15552. }
  15553. }
  15554. }
  15555. })
  15556. };
  15557. // plugins/fiximgclick.js
  15558. ///import core
  15559. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15560. ///commandsName FixImgClick
  15561. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15562. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  15563. UE.plugins['fiximgclick'] = (function () {
  15564. var elementUpdated = false;
  15565. function Scale() {
  15566. this.editor = null;
  15567. this.resizer = null;
  15568. this.cover = null;
  15569. this.doc = document;
  15570. this.prePos = {x: 0, y: 0};
  15571. this.startPos = {x: 0, y: 0};
  15572. }
  15573. (function () {
  15574. var rect = [
  15575. //[left, top, width, height]
  15576. [0, 0, -1, -1],
  15577. [0, 0, 0, -1],
  15578. [0, 0, 1, -1],
  15579. [0, 0, -1, 0],
  15580. [0, 0, 1, 0],
  15581. [0, 0, -1, 1],
  15582. [0, 0, 0, 1],
  15583. [0, 0, 1, 1]
  15584. ];
  15585. Scale.prototype = {
  15586. init: function (editor) {
  15587. var me = this;
  15588. me.editor = editor;
  15589. me.startPos = this.prePos = {x: 0, y: 0};
  15590. me.dragId = -1;
  15591. var hands = [],
  15592. cover = me.cover = document.createElement('div'),
  15593. resizer = me.resizer = document.createElement('div');
  15594. cover.id = me.editor.ui.id + '_imagescale_cover';
  15595. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  15596. domUtils.on(cover, 'mousedown click', function () {
  15597. me.hide();
  15598. });
  15599. for (var i = 0; i < 8; i++) {
  15600. hands.push('<span class="edui-editor-imagescale-hand' + i + '"></span>');
  15601. }
  15602. resizer.id = me.editor.ui.id + '_imagescale';
  15603. resizer.className = 'edui-editor-imagescale';
  15604. resizer.innerHTML = hands.join('');
  15605. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  15606. me.editor.ui.getDom().appendChild(cover);
  15607. me.editor.ui.getDom().appendChild(resizer);
  15608. me.initStyle();
  15609. me.initEvents();
  15610. },
  15611. initStyle: function () {
  15612. utils.cssRule('imagescale', '.edui-editor-imagescale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;-webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;}' +
  15613. '.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  15614. + '.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  15615. + '.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  15616. + '.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  15617. + '.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  15618. + '.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  15619. + '.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  15620. + '.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  15621. + '.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  15622. },
  15623. initEvents: function () {
  15624. var me = this;
  15625. me.startPos.x = me.startPos.y = 0;
  15626. me.isDraging = false;
  15627. },
  15628. _eventHandler: function (e) {
  15629. var me = this;
  15630. switch (e.type) {
  15631. case 'mousedown':
  15632. var hand = e.target || e.srcElement, hand;
  15633. if (hand.className.indexOf('edui-editor-imagescale-hand') != -1 && me.dragId == -1) {
  15634. me.dragId = hand.className.slice(-1);
  15635. me.startPos.x = me.prePos.x = e.clientX;
  15636. me.startPos.y = me.prePos.y = e.clientY;
  15637. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15638. }
  15639. break;
  15640. case 'mousemove':
  15641. if (me.dragId != -1) {
  15642. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15643. me.prePos.x = e.clientX;
  15644. me.prePos.y = e.clientY;
  15645. elementUpdated = true;
  15646. me.updateTargetElement();
  15647. }
  15648. break;
  15649. case 'mouseup':
  15650. if (me.dragId != -1) {
  15651. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15652. me.updateTargetElement();
  15653. if (me.target.parentNode) me.attachTo(me.target);
  15654. me.dragId = -1;
  15655. }
  15656. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15657. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  15658. if(elementUpdated){
  15659. elementUpdated = false;
  15660. me.editor.fireEvent('contentchange');
  15661. }
  15662. break;
  15663. default:
  15664. break;
  15665. }
  15666. },
  15667. updateTargetElement: function () {
  15668. var me = this;
  15669. domUtils.setStyles(me.target, {
  15670. 'width': me.resizer.style.width,
  15671. 'height': me.resizer.style.height
  15672. });
  15673. me.target.width = parseInt(me.resizer.style.width);
  15674. me.target.height = parseInt(me.resizer.style.height);
  15675. me.attachTo(me.target);
  15676. },
  15677. updateContainerStyle: function (dir, offset) {
  15678. var me = this,
  15679. dom = me.resizer, tmp;
  15680. if (rect[dir][0] != 0) {
  15681. tmp = parseInt(dom.style.left) + offset.x;
  15682. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  15683. }
  15684. if (rect[dir][1] != 0) {
  15685. tmp = parseInt(dom.style.top) + offset.y;
  15686. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  15687. }
  15688. if (rect[dir][2] != 0) {
  15689. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  15690. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  15691. }
  15692. if (rect[dir][3] != 0) {
  15693. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  15694. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  15695. }
  15696. },
  15697. _validScaledProp: function (prop, value) {
  15698. var ele = this.resizer,
  15699. wrap = document;
  15700. value = isNaN(value) ? 0 : value;
  15701. switch (prop) {
  15702. case 'left':
  15703. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  15704. case 'top':
  15705. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  15706. case 'width':
  15707. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  15708. case 'height':
  15709. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  15710. }
  15711. },
  15712. hideCover: function () {
  15713. this.cover.style.display = 'none';
  15714. },
  15715. showCover: function () {
  15716. var me = this,
  15717. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  15718. iframePos = domUtils.getXY(me.editor.iframe);
  15719. domUtils.setStyles(me.cover, {
  15720. 'width': me.editor.iframe.offsetWidth + 'px',
  15721. 'height': me.editor.iframe.offsetHeight + 'px',
  15722. 'top': iframePos.y - editorPos.y + 'px',
  15723. 'left': iframePos.x - editorPos.x + 'px',
  15724. 'position': 'absolute',
  15725. 'display': ''
  15726. })
  15727. },
  15728. show: function (targetObj) {
  15729. var me = this;
  15730. me.resizer.style.display = 'block';
  15731. if(targetObj) me.attachTo(targetObj);
  15732. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15733. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15734. me.showCover();
  15735. me.editor.fireEvent('afterscaleshow', me);
  15736. me.editor.fireEvent('saveScene');
  15737. },
  15738. hide: function () {
  15739. var me = this;
  15740. me.hideCover();
  15741. me.resizer.style.display = 'none';
  15742. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15743. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15744. me.editor.fireEvent('afterscalehide', me);
  15745. },
  15746. proxy: function( fn, context ) {
  15747. return function(e) {
  15748. return fn.apply( context || this, arguments);
  15749. };
  15750. },
  15751. attachTo: function (targetObj) {
  15752. var me = this,
  15753. target = me.target = targetObj,
  15754. resizer = this.resizer,
  15755. imgPos = domUtils.getXY(target),
  15756. iframePos = domUtils.getXY(me.editor.iframe),
  15757. editorPos = domUtils.getXY(resizer.parentNode);
  15758. domUtils.setStyles(resizer, {
  15759. 'width': target.width + 'px',
  15760. 'height': target.height + 'px',
  15761. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  15762. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  15763. });
  15764. }
  15765. }
  15766. })();
  15767. return function () {
  15768. var me = this,
  15769. imageScale;
  15770. me.setOpt('imageScaleEnabled', true);
  15771. if ( !browser.ie && me.options.imageScaleEnabled) {
  15772. me.addListener('click', function (type, e) {
  15773. var range = me.selection.getRange(),
  15774. img = range.getClosedNode();
  15775. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  15776. if (img.className.indexOf("edui-faked-music") != -1 ||
  15777. img.getAttribute("anchorname") ||
  15778. domUtils.hasClass(img, 'loadingclass') ||
  15779. domUtils.hasClass(img, 'loaderrorclass')) { return }
  15780. if (!imageScale) {
  15781. imageScale = new Scale();
  15782. imageScale.init(me);
  15783. me.ui.getDom().appendChild(imageScale.resizer);
  15784. var _keyDownHandler = function (e) {
  15785. imageScale.hide();
  15786. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  15787. }, _mouseDownHandler = function (e) {
  15788. var ele = e.target || e.srcElement;
  15789. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-imagescale') == -1)) {
  15790. _keyDownHandler(e);
  15791. }
  15792. }, timer;
  15793. me.addListener('afterscaleshow', function (e) {
  15794. me.addListener('beforekeydown', _keyDownHandler);
  15795. me.addListener('beforemousedown', _mouseDownHandler);
  15796. domUtils.on(document, 'keydown', _keyDownHandler);
  15797. domUtils.on(document,'mousedown', _mouseDownHandler);
  15798. me.selection.getNative().removeAllRanges();
  15799. });
  15800. me.addListener('afterscalehide', function (e) {
  15801. me.removeListener('beforekeydown', _keyDownHandler);
  15802. me.removeListener('beforemousedown', _mouseDownHandler);
  15803. domUtils.un(document, 'keydown', _keyDownHandler);
  15804. domUtils.un(document,'mousedown', _mouseDownHandler);
  15805. var target = imageScale.target;
  15806. if (target.parentNode) {
  15807. me.selection.getRange().selectNode(target).select();
  15808. }
  15809. });
  15810. //TODO 有iframe的情况,mousedown不能往下传。。
  15811. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  15812. me.selection.getNative().removeAllRanges();
  15813. var ele = e.target || e.srcElement;
  15814. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15815. timer = setTimeout(function () {
  15816. imageScale.hide();
  15817. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  15818. }, 200);
  15819. }
  15820. });
  15821. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  15822. var ele = e.target || e.srcElement;
  15823. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15824. clearTimeout(timer);
  15825. }
  15826. });
  15827. }
  15828. imageScale.show(img);
  15829. } else {
  15830. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  15831. }
  15832. });
  15833. }
  15834. if (browser.webkit) {
  15835. me.addListener('click', function (type, e) {
  15836. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  15837. var range = new dom.Range(me.document);
  15838. range.selectNode(e.target).select();
  15839. }
  15840. });
  15841. }
  15842. }
  15843. })();
  15844. // plugins/autolink.js
  15845. ///import core
  15846. ///commands 为非ie浏览器自动添加a标签
  15847. ///commandsName AutoLink
  15848. ///commandsTitle 自动增加链接
  15849. /**
  15850. * @description 为非ie浏览器自动添加a标签
  15851. * @author zhanyi
  15852. */
  15853. UE.plugin.register('autolink',function(){
  15854. var cont = 0;
  15855. return !browser.ie ? {
  15856. bindEvents:{
  15857. 'reset' : function(){
  15858. cont = 0;
  15859. },
  15860. 'keydown':function(type, evt) {
  15861. var me = this;
  15862. var keyCode = evt.keyCode || evt.which;
  15863. if (keyCode == 32 || keyCode == 13) {
  15864. var sel = me.selection.getNative(),
  15865. range = sel.getRangeAt(0).cloneRange(),
  15866. offset,
  15867. charCode;
  15868. var start = range.startContainer;
  15869. while (start.nodeType == 1 && range.startOffset > 0) {
  15870. start = range.startContainer.childNodes[range.startOffset - 1];
  15871. if (!start){
  15872. break;
  15873. }
  15874. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  15875. range.collapse(true);
  15876. start = range.startContainer;
  15877. }
  15878. do{
  15879. if (range.startOffset == 0) {
  15880. start = range.startContainer.previousSibling;
  15881. while (start && start.nodeType == 1) {
  15882. start = start.lastChild;
  15883. }
  15884. if (!start || domUtils.isFillChar(start)){
  15885. break;
  15886. }
  15887. offset = start.nodeValue.length;
  15888. } else {
  15889. start = range.startContainer;
  15890. offset = range.startOffset;
  15891. }
  15892. range.setStart(start, offset - 1);
  15893. charCode = range.toString().charCodeAt(0);
  15894. } while (charCode != 160 && charCode != 32);
  15895. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  15896. while(range.toString().length){
  15897. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  15898. break;
  15899. }
  15900. try{
  15901. range.setStart(range.startContainer,range.startOffset+1);
  15902. }catch(e){
  15903. //trace:2121
  15904. var start = range.startContainer;
  15905. while(!(next = start.nextSibling)){
  15906. if(domUtils.isBody(start)){
  15907. return;
  15908. }
  15909. start = start.parentNode;
  15910. }
  15911. range.setStart(next,0);
  15912. }
  15913. }
  15914. //range的开始边界已经在a标签里的不再处理
  15915. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  15916. return;
  15917. }
  15918. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  15919. me.undoManger && me.undoManger.save();
  15920. a.appendChild(range.extractContents());
  15921. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  15922. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  15923. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  15924. a.setAttribute('_src',utils.html(href));
  15925. a.href = utils.html(href);
  15926. range.insertNode(a);
  15927. a.parentNode.insertBefore(text, a.nextSibling);
  15928. range.setStart(text, 0);
  15929. range.collapse(true);
  15930. sel.removeAllRanges();
  15931. sel.addRange(range);
  15932. me.undoManger && me.undoManger.save();
  15933. }
  15934. }
  15935. }
  15936. }
  15937. }:{}
  15938. },function(){
  15939. var keyCodes = {
  15940. 37:1, 38:1, 39:1, 40:1,
  15941. 13:1,32:1
  15942. };
  15943. function checkIsCludeLink(node){
  15944. if(node.nodeType == 3){
  15945. return null
  15946. }
  15947. if(node.nodeName == 'A'){
  15948. return node;
  15949. }
  15950. var lastChild = node.lastChild;
  15951. while(lastChild){
  15952. if(lastChild.nodeName == 'A'){
  15953. return lastChild;
  15954. }
  15955. if(lastChild.nodeType == 3){
  15956. if(domUtils.isWhitespace(lastChild)){
  15957. lastChild = lastChild.previousSibling;
  15958. continue;
  15959. }
  15960. return null
  15961. }
  15962. lastChild = lastChild.lastChild;
  15963. }
  15964. }
  15965. browser.ie && this.addListener('keyup',function(cmd,evt){
  15966. var me = this,keyCode = evt.keyCode;
  15967. if(keyCodes[keyCode]){
  15968. var rng = me.selection.getRange();
  15969. var start = rng.startContainer;
  15970. if(keyCode == 13){
  15971. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15972. start = start.parentNode;
  15973. }
  15974. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15975. var pre = start.previousSibling;
  15976. if(pre && pre.nodeType == 1){
  15977. var pre = checkIsCludeLink(pre);
  15978. if(pre && !pre.getAttribute('_href')){
  15979. domUtils.remove(pre,true);
  15980. }
  15981. }
  15982. }
  15983. }else if(keyCode == 32 ){
  15984. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15985. start = start.previousSibling;
  15986. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15987. domUtils.remove(start,true);
  15988. }
  15989. }
  15990. }else {
  15991. start = domUtils.findParentByTagName(start,'a',true);
  15992. if(start && !start.getAttribute('_href')){
  15993. var bk = rng.createBookmark();
  15994. domUtils.remove(start,true);
  15995. rng.moveToBookmark(bk).select(true)
  15996. }
  15997. }
  15998. }
  15999. });
  16000. }
  16001. );
  16002. // plugins/autoheight.js
  16003. ///import core
  16004. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  16005. ///commandsName AutoHeight,autoHeightEnabled
  16006. ///commandsTitle 自动增高
  16007. /**
  16008. * @description 自动伸展
  16009. * @author zhanyi
  16010. */
  16011. UE.plugins['autoheight'] = function () {
  16012. var me = this;
  16013. //提供开关,就算加载也可以关闭
  16014. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  16015. if (!me.autoHeightEnabled) {
  16016. return;
  16017. }
  16018. var bakOverflow,
  16019. lastHeight = 0,
  16020. options = me.options,
  16021. currentHeight,
  16022. timer;
  16023. function adjustHeight() {
  16024. var me = this;
  16025. clearTimeout(timer);
  16026. if(isFullscreen)return;
  16027. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  16028. timer = setTimeout(function(){
  16029. var node = me.body.lastChild;
  16030. while(node && node.nodeType != 1){
  16031. node = node.previousSibling;
  16032. }
  16033. if(node && node.nodeType == 1){
  16034. node.style.clear = 'both';
  16035. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  16036. if (currentHeight != lastHeight) {
  16037. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  16038. me.iframe.parentNode.style.height = currentHeight + 'px';
  16039. }
  16040. me.body.style.height = currentHeight + 'px';
  16041. lastHeight = currentHeight;
  16042. }
  16043. domUtils.removeStyle(node,'clear');
  16044. }
  16045. },50)
  16046. }
  16047. }
  16048. var isFullscreen;
  16049. me.addListener('fullscreenchanged',function(cmd,f){
  16050. isFullscreen = f
  16051. });
  16052. me.addListener('destroy', function () {
  16053. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  16054. });
  16055. me.enableAutoHeight = function () {
  16056. var me = this;
  16057. if (!me.autoHeightEnabled) {
  16058. return;
  16059. }
  16060. var doc = me.document;
  16061. me.autoHeightEnabled = true;
  16062. bakOverflow = doc.body.style.overflowY;
  16063. doc.body.style.overflowY = 'hidden';
  16064. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  16065. //ff不给事件算得不对
  16066. setTimeout(function () {
  16067. adjustHeight.call(me);
  16068. }, browser.gecko ? 100 : 0);
  16069. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16070. };
  16071. me.disableAutoHeight = function () {
  16072. me.body.style.overflowY = bakOverflow || '';
  16073. me.removeListener('contentchange', adjustHeight);
  16074. me.removeListener('keyup', adjustHeight);
  16075. me.removeListener('mouseup', adjustHeight);
  16076. me.autoHeightEnabled = false;
  16077. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16078. };
  16079. me.on('setHeight',function(){
  16080. me.disableAutoHeight()
  16081. });
  16082. me.addListener('ready', function () {
  16083. me.enableAutoHeight();
  16084. //trace:1764
  16085. var timer;
  16086. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16087. clearTimeout(timer);
  16088. timer = setTimeout(function () {
  16089. //trace:3681
  16090. adjustHeight.call(me);
  16091. }, 100);
  16092. });
  16093. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16094. var lastScrollY;
  16095. window.onscroll = function(){
  16096. if(lastScrollY === null){
  16097. lastScrollY = this.scrollY
  16098. }else if(this.scrollY == 0 && lastScrollY != 0){
  16099. me.window.scrollTo(0,0);
  16100. lastScrollY = null;
  16101. }
  16102. }
  16103. });
  16104. };
  16105. // plugins/autofloat.js
  16106. ///import core
  16107. ///commands 悬浮工具栏
  16108. ///commandsName AutoFloat,autoFloatEnabled
  16109. ///commandsTitle 悬浮工具栏
  16110. /**
  16111. * modified by chengchao01
  16112. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16113. */
  16114. UE.plugins['autofloat'] = function() {
  16115. var me = this,
  16116. lang = me.getLang();
  16117. me.setOpt({
  16118. topOffset:0
  16119. });
  16120. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16121. topOffset = me.options.topOffset;
  16122. //如果不固定toolbar的位置,则直接退出
  16123. if(!optsAutoFloatEnabled){
  16124. return;
  16125. }
  16126. var uiUtils = UE.ui.uiUtils,
  16127. LteIE6 = browser.ie && browser.version <= 6,
  16128. quirks = browser.quirks;
  16129. function checkHasUI(){
  16130. if(!UE.ui){
  16131. alert(lang.autofloatMsg);
  16132. return 0;
  16133. }
  16134. return 1;
  16135. }
  16136. function fixIE6FixedPos(){
  16137. var docStyle = document.body.style;
  16138. docStyle.backgroundImage = 'url("about:blank")';
  16139. docStyle.backgroundAttachment = 'fixed';
  16140. }
  16141. var bakCssText,
  16142. placeHolder = document.createElement('div'),
  16143. toolbarBox,orgTop,
  16144. getPosition,
  16145. flag =true; //ie7模式下需要偏移
  16146. function setFloating(){
  16147. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16148. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  16149. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  16150. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16151. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16152. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16153. if (LteIE6 || (quirks && browser.ie)) {
  16154. if(toolbarBox.style.position != 'absolute'){
  16155. toolbarBox.style.position = 'absolute';
  16156. }
  16157. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16158. } else {
  16159. if (browser.ie7Compat && flag) {
  16160. flag = false;
  16161. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  16162. }
  16163. if(toolbarBox.style.position != 'fixed'){
  16164. toolbarBox.style.position = 'fixed';
  16165. toolbarBox.style.top = topOffset +"px";
  16166. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16167. }
  16168. }
  16169. }
  16170. function unsetFloating(){
  16171. flag = true;
  16172. if(placeHolder.parentNode){
  16173. placeHolder.parentNode.removeChild(placeHolder);
  16174. }
  16175. toolbarBox.style.cssText = bakCssText;
  16176. }
  16177. function updateFloating(){
  16178. var rect3 = getPosition(me.container);
  16179. var offset=me.options.toolbarTopOffset||0;
  16180. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16181. setFloating();
  16182. }else{
  16183. unsetFloating();
  16184. }
  16185. }
  16186. var defer_updateFloating = utils.defer(function(){
  16187. updateFloating();
  16188. },browser.ie ? 200 : 100,true);
  16189. me.addListener('destroy',function(){
  16190. domUtils.un(window, ['scroll','resize'], updateFloating);
  16191. me.removeListener('keydown', defer_updateFloating);
  16192. });
  16193. me.addListener('ready', function(){
  16194. if(checkHasUI(me)){
  16195. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16196. if(!me.ui){
  16197. return;
  16198. }
  16199. getPosition = uiUtils.getClientRect;
  16200. toolbarBox = me.ui.getDom('toolbarbox');
  16201. orgTop = getPosition(toolbarBox).top;
  16202. bakCssText = toolbarBox.style.cssText;
  16203. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16204. if(LteIE6){
  16205. fixIE6FixedPos();
  16206. }
  16207. domUtils.on(window, ['scroll','resize'], updateFloating);
  16208. me.addListener('keydown', defer_updateFloating);
  16209. me.addListener('beforefullscreenchange', function (t, enabled){
  16210. if (enabled) {
  16211. unsetFloating();
  16212. }
  16213. });
  16214. me.addListener('fullscreenchanged', function (t, enabled){
  16215. if (!enabled) {
  16216. updateFloating();
  16217. }
  16218. });
  16219. me.addListener('sourcemodechanged', function (t, enabled){
  16220. setTimeout(function (){
  16221. updateFloating();
  16222. },0);
  16223. });
  16224. me.addListener("clearDoc",function(){
  16225. setTimeout(function(){
  16226. updateFloating();
  16227. },0);
  16228. })
  16229. }
  16230. });
  16231. };
  16232. // plugins/video.js
  16233. /**
  16234. * video插件, 为UEditor提供视频插入支持
  16235. * @file
  16236. * @since 1.2.6.1
  16237. */
  16238. UE.plugins['video'] = function (){
  16239. var me =this;
  16240. /**
  16241. * 创建插入视频字符窜
  16242. * @param url 视频地址
  16243. * @param width 视频宽度
  16244. * @param height 视频高度
  16245. * @param align 视频对齐
  16246. * @param toEmbed 是否以flash代替显示
  16247. * @param addParagraph 是否需要添加P 标签
  16248. */
  16249. function creatInsertStr(url,width,height,id,align,classname,type){
  16250. url = utils.unhtmlForUrl(url);
  16251. align = utils.unhtml(align);
  16252. classname = utils.unhtml(classname).trim();
  16253. width = parseInt(width, 10) || 0;
  16254. height = parseInt(height, 10) || 0;
  16255. var str;
  16256. switch (type){
  16257. case 'image':
  16258. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16259. ' 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 + ';': '')+'" />'
  16260. break;
  16261. case 'embed':
  16262. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16263. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  16264. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16265. break;
  16266. case 'video':
  16267. var ext = url.substr(url.lastIndexOf('.') + 1);
  16268. if(ext == 'ogv') ext = 'ogg';
  16269. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"': '') +
  16270. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16271. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  16272. break;
  16273. }
  16274. return str;
  16275. }
  16276. function switchImgAndVideo(root,img2video){
  16277. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  16278. var className = node.getAttr('class');
  16279. if(className && className.indexOf('edui-faked-video') != -1){
  16280. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  16281. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16282. }
  16283. if(className && className.indexOf('edui-upload-video') != -1){
  16284. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  16285. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16286. }
  16287. })
  16288. }
  16289. me.addOutputRule(function(root){
  16290. switchImgAndVideo(root,true)
  16291. });
  16292. me.addInputRule(function(root){
  16293. switchImgAndVideo(root)
  16294. });
  16295. /**
  16296. * 插入视频
  16297. * @command insertvideo
  16298. * @method execCommand
  16299. * @param { String } cmd 命令字符串
  16300. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16301. * @example
  16302. * ```javascript
  16303. *
  16304. * var videoAttr = {
  16305. * //视频地址
  16306. * url: 'http://www.youku.com/xxx',
  16307. * //视频宽高值, 单位px
  16308. * width: 200,
  16309. * height: 100
  16310. * };
  16311. *
  16312. * //editor 是编辑器实例
  16313. * //向编辑器插入单个视频
  16314. * editor.execCommand( 'insertvideo', videoAttr );
  16315. * ```
  16316. */
  16317. /**
  16318. * 插入视频
  16319. * @command insertvideo
  16320. * @method execCommand
  16321. * @param { String } cmd 命令字符串
  16322. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16323. * @example
  16324. * ```javascript
  16325. *
  16326. * var videoAttr1 = {
  16327. * //视频地址
  16328. * url: 'http://www.youku.com/xxx',
  16329. * //视频宽高值, 单位px
  16330. * width: 200,
  16331. * height: 100
  16332. * },
  16333. * videoAttr2 = {
  16334. * //视频地址
  16335. * url: 'http://www.youku.com/xxx',
  16336. * //视频宽高值, 单位px
  16337. * width: 200,
  16338. * height: 100
  16339. * }
  16340. *
  16341. * //editor 是编辑器实例
  16342. * //该方法将会向编辑器内插入两个视频
  16343. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16344. * ```
  16345. */
  16346. /**
  16347. * 查询当前光标所在处是否是一个视频
  16348. * @command insertvideo
  16349. * @method queryCommandState
  16350. * @param { String } cmd 需要查询的命令字符串
  16351. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16352. * @example
  16353. * ```javascript
  16354. *
  16355. * //editor 是编辑器实例
  16356. * editor.queryCommandState( 'insertvideo' );
  16357. * ```
  16358. */
  16359. me.commands["insertvideo"] = {
  16360. execCommand: function (cmd, videoObjs, type){
  16361. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  16362. var html = [],id = 'tmpVedio', cl;
  16363. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  16364. vi = videoObjs[i];
  16365. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  16366. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  16367. }
  16368. me.execCommand("inserthtml",html.join(""),true);
  16369. var rng = this.selection.getRange();
  16370. for(var i= 0,len=videoObjs.length;i<len;i++){
  16371. var img = this.document.getElementById('tmpVedio'+i);
  16372. domUtils.removeAttributes(img,'id');
  16373. rng.selectNode(img).select();
  16374. me.execCommand('imagefloat',videoObjs[i].align)
  16375. }
  16376. },
  16377. queryCommandState : function(){
  16378. var img = me.selection.getRange().getClosedNode(),
  16379. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  16380. return flag ? 1 : 0;
  16381. }
  16382. };
  16383. };
  16384. // plugins/table.core.js
  16385. /**
  16386. * Created with JetBrains WebStorm.
  16387. * User: taoqili
  16388. * Date: 13-1-18
  16389. * Time: 上午11:09
  16390. * To change this template use File | Settings | File Templates.
  16391. */
  16392. /**
  16393. * UE表格操作类
  16394. * @param table
  16395. * @constructor
  16396. */
  16397. (function () {
  16398. var UETable = UE.UETable = function (table) {
  16399. this.table = table;
  16400. this.indexTable = [];
  16401. this.selectedTds = [];
  16402. this.cellsRange = {};
  16403. this.update(table);
  16404. };
  16405. //===以下为静态工具方法===
  16406. UETable.removeSelectedClass = function (cells) {
  16407. utils.each(cells, function (cell) {
  16408. domUtils.removeClasses(cell, "selectTdClass");
  16409. })
  16410. };
  16411. UETable.addSelectedClass = function (cells) {
  16412. utils.each(cells, function (cell) {
  16413. domUtils.addClass(cell, "selectTdClass");
  16414. })
  16415. };
  16416. UETable.isEmptyBlock = function (node) {
  16417. var reg = new RegExp(domUtils.fillChar, 'g');
  16418. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16419. return 0;
  16420. }
  16421. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16422. if (node.getElementsByTagName(i).length) {
  16423. return 0;
  16424. }
  16425. }
  16426. return 1;
  16427. };
  16428. UETable.getWidth = function (cell) {
  16429. if (!cell)return 0;
  16430. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16431. };
  16432. /**
  16433. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16434. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16435. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16436. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16437. */
  16438. UETable.getTableCellAlignState = function ( cells ) {
  16439. !utils.isArray( cells ) && ( cells = [cells] );
  16440. var result = {},
  16441. status = ['align', 'valign'],
  16442. tempStatus = null,
  16443. isSame = true;//状态是否相同
  16444. utils.each( cells, function( cellNode ){
  16445. utils.each( status, function( currentState ){
  16446. tempStatus = cellNode.getAttribute( currentState );
  16447. if( !result[ currentState ] && tempStatus ) {
  16448. result[ currentState ] = tempStatus;
  16449. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  16450. isSame = false;
  16451. return false;
  16452. }
  16453. } );
  16454. return isSame;
  16455. });
  16456. return isSame ? result : null;
  16457. };
  16458. /**
  16459. * 根据当前选区获取相关的table信息
  16460. * @return {Object}
  16461. */
  16462. UETable.getTableItemsByRange = function (editor) {
  16463. var start = editor.selection.getStart();
  16464. //ff下会选中bookmark
  16465. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16466. start = start.nextSibling;
  16467. }
  16468. //在table或者td边缘有可能存在选中tr的情况
  16469. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16470. tr = cell && cell.parentNode,
  16471. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16472. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16473. return {
  16474. cell:cell,
  16475. tr:tr,
  16476. table:table,
  16477. caption:caption
  16478. }
  16479. };
  16480. UETable.getUETableBySelected = function (editor) {
  16481. var table = UETable.getTableItemsByRange(editor).table;
  16482. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16483. return table.ueTable;
  16484. }
  16485. return null;
  16486. };
  16487. UETable.getDefaultValue = function (editor, table) {
  16488. var borderMap = {
  16489. thin:'0px',
  16490. medium:'1px',
  16491. thick:'2px'
  16492. },
  16493. tableBorder, tdPadding, tdBorder, tmpValue;
  16494. if (!table) {
  16495. table = editor.document.createElement('table');
  16496. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16497. editor.body.appendChild(table);
  16498. var td = table.getElementsByTagName('td')[0];
  16499. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16500. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16501. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16502. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16503. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16504. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16505. domUtils.remove(table);
  16506. return {
  16507. tableBorder:tableBorder,
  16508. tdPadding:tdPadding,
  16509. tdBorder:tdBorder
  16510. };
  16511. } else {
  16512. td = table.getElementsByTagName('td')[0];
  16513. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16514. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16515. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16516. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16517. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16518. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16519. return {
  16520. tableBorder:tableBorder,
  16521. tdPadding:tdPadding,
  16522. tdBorder:tdBorder
  16523. };
  16524. }
  16525. };
  16526. /**
  16527. * 根据当前点击的td或者table获取索引对象
  16528. * @param tdOrTable
  16529. */
  16530. UETable.getUETable = function (tdOrTable) {
  16531. var tag = tdOrTable.tagName.toLowerCase();
  16532. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  16533. if (!tdOrTable.ueTable) {
  16534. tdOrTable.ueTable = new UETable(tdOrTable);
  16535. }
  16536. return tdOrTable.ueTable;
  16537. };
  16538. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  16539. if (!cell || utils.isString(cell)) {
  16540. return this.table.ownerDocument.createElement(cell || 'td');
  16541. }
  16542. var flag = domUtils.hasClass(cell, "selectTdClass");
  16543. flag && domUtils.removeClasses(cell, "selectTdClass");
  16544. var tmpCell = cell.cloneNode(true);
  16545. if (ignoreMerge) {
  16546. tmpCell.rowSpan = tmpCell.colSpan = 1;
  16547. }
  16548. //去掉宽高
  16549. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  16550. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  16551. tmpCell.style.borderLeftStyle = "";
  16552. tmpCell.style.borderTopStyle = "";
  16553. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  16554. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  16555. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  16556. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  16557. flag && domUtils.addClass(cell, "selectTdClass");
  16558. return tmpCell;
  16559. }
  16560. UETable.prototype = {
  16561. getMaxRows:function () {
  16562. var rows = this.table.rows, maxLen = 1;
  16563. for (var i = 0, row; row = rows[i]; i++) {
  16564. var currentMax = 1;
  16565. for (var j = 0, cj; cj = row.cells[j++];) {
  16566. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  16567. }
  16568. maxLen = Math.max(currentMax + i, maxLen);
  16569. }
  16570. return maxLen;
  16571. },
  16572. /**
  16573. * 获取当前表格的最大列数
  16574. */
  16575. getMaxCols:function () {
  16576. var rows = this.table.rows, maxLen = 0, cellRows = {};
  16577. for (var i = 0, row; row = rows[i]; i++) {
  16578. var cellsNum = 0;
  16579. for (var j = 0, cj; cj = row.cells[j++];) {
  16580. cellsNum += (cj.colSpan || 1);
  16581. if (cj.rowSpan && cj.rowSpan > 1) {
  16582. for (var k = 1; k < cj.rowSpan; k++) {
  16583. if (!cellRows['row_' + (i + k)]) {
  16584. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  16585. } else {
  16586. cellRows['row_' + (i + k)]++
  16587. }
  16588. }
  16589. }
  16590. }
  16591. cellsNum += cellRows['row_' + i] || 0;
  16592. maxLen = Math.max(cellsNum, maxLen);
  16593. }
  16594. return maxLen;
  16595. },
  16596. getCellColIndex:function (cell) {
  16597. },
  16598. /**
  16599. * 获取当前cell旁边的单元格,
  16600. * @param cell
  16601. * @param right
  16602. */
  16603. getHSideCell:function (cell, right) {
  16604. try {
  16605. var cellInfo = this.getCellInfo(cell),
  16606. previewRowIndex, previewColIndex;
  16607. var len = this.selectedTds.length,
  16608. range = this.cellsRange;
  16609. //首行或者首列没有前置单元格
  16610. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16611. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  16612. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16613. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  16614. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16615. } catch (e) {
  16616. showError(e);
  16617. }
  16618. },
  16619. getTabNextCell:function (cell, preRowIndex) {
  16620. var cellInfo = this.getCellInfo(cell),
  16621. rowIndex = preRowIndex || cellInfo.rowIndex,
  16622. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  16623. nextCell;
  16624. try {
  16625. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16626. } catch (e) {
  16627. try {
  16628. rowIndex = rowIndex * 1 + 1;
  16629. colIndex = 0;
  16630. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16631. } catch (e) {
  16632. }
  16633. }
  16634. return nextCell;
  16635. },
  16636. /**
  16637. * 获取视觉上的后置单元格
  16638. * @param cell
  16639. * @param bottom
  16640. */
  16641. getVSideCell:function (cell, bottom, ignoreRange) {
  16642. try {
  16643. var cellInfo = this.getCellInfo(cell),
  16644. nextRowIndex, nextColIndex;
  16645. var len = this.selectedTds.length && !ignoreRange,
  16646. range = this.cellsRange;
  16647. //末行或者末列没有后置单元格
  16648. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16649. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16650. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16651. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16652. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16653. } catch (e) {
  16654. showError(e);
  16655. }
  16656. },
  16657. /**
  16658. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  16659. */
  16660. getSameEndPosCells:function (cell, xOrY) {
  16661. try {
  16662. var flag = (xOrY.toLowerCase() === "x"),
  16663. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  16664. rows = this.table.rows,
  16665. cells = null, returns = [];
  16666. for (var i = 0; i < this.rowsNum; i++) {
  16667. cells = rows[i].cells;
  16668. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16669. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  16670. //对应行的td已经被上面行rowSpan了
  16671. if (tmpEnd > end && flag) break;
  16672. if (cell == tmpCell || end == tmpEnd) {
  16673. //只获取单一的单元格
  16674. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  16675. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  16676. returns.push(tmpCell);
  16677. }
  16678. if (flag) break;
  16679. }
  16680. }
  16681. }
  16682. return returns;
  16683. } catch (e) {
  16684. showError(e);
  16685. }
  16686. },
  16687. setCellContent:function (cell, content) {
  16688. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  16689. },
  16690. cloneCell:UETable.cloneCell,
  16691. /**
  16692. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  16693. */
  16694. getSameStartPosXCells:function (cell) {
  16695. try {
  16696. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  16697. rows = this.table.rows, cells , returns = [];
  16698. for (var i = 0; i < this.rowsNum; i++) {
  16699. cells = rows[i].cells;
  16700. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16701. var tmpStart = domUtils.getXY(tmpCell).x;
  16702. if (tmpStart > start) break;
  16703. if (tmpStart == start && tmpCell.colSpan == 1) {
  16704. returns.push(tmpCell);
  16705. break;
  16706. }
  16707. }
  16708. }
  16709. return returns;
  16710. } catch (e) {
  16711. showError(e);
  16712. }
  16713. },
  16714. /**
  16715. * 更新table对应的索引表
  16716. */
  16717. update:function (table) {
  16718. this.table = table || this.table;
  16719. this.selectedTds = [];
  16720. this.cellsRange = {};
  16721. this.indexTable = [];
  16722. var rows = this.table.rows,
  16723. rowsNum = this.getMaxRows(),
  16724. dNum = rowsNum - rows.length,
  16725. colsNum = this.getMaxCols();
  16726. while (dNum--) {
  16727. this.table.insertRow(rows.length);
  16728. }
  16729. this.rowsNum = rowsNum;
  16730. this.colsNum = colsNum;
  16731. for (var i = 0, len = rows.length; i < len; i++) {
  16732. this.indexTable[i] = new Array(colsNum);
  16733. }
  16734. //填充索引表
  16735. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  16736. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  16737. //修正整行被rowSpan时导致的行数计算错误
  16738. if (cell.rowSpan > rowsNum) {
  16739. cell.rowSpan = rowsNum;
  16740. }
  16741. var colIndex = cellIndex,
  16742. rowSpan = cell.rowSpan || 1,
  16743. colSpan = cell.colSpan || 1;
  16744. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  16745. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  16746. for (var j = 0; j < rowSpan; j++) {
  16747. for (var k = 0; k < colSpan; k++) {
  16748. this.indexTable[rowIndex + j][colIndex + k] = {
  16749. rowIndex:rowIndex,
  16750. cellIndex:cellIndex,
  16751. colIndex:colIndex,
  16752. rowSpan:rowSpan,
  16753. colSpan:colSpan
  16754. }
  16755. }
  16756. }
  16757. }
  16758. }
  16759. //修复残缺td
  16760. for (j = 0; j < rowsNum; j++) {
  16761. for (k = 0; k < colsNum; k++) {
  16762. if (this.indexTable[j][k] === undefined) {
  16763. row = rows[j];
  16764. cell = row.cells[row.cells.length - 1];
  16765. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  16766. this.setCellContent(cell);
  16767. if (cell.colSpan !== 1)cell.colSpan = 1;
  16768. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  16769. row.appendChild(cell);
  16770. this.indexTable[j][k] = {
  16771. rowIndex:j,
  16772. cellIndex:cell.cellIndex,
  16773. colIndex:k,
  16774. rowSpan:1,
  16775. colSpan:1
  16776. }
  16777. }
  16778. }
  16779. }
  16780. //当框选后删除行或者列后撤销,需要重建选区。
  16781. var tds = domUtils.getElementsByTagName(this.table, "td"),
  16782. selectTds = [];
  16783. utils.each(tds, function (td) {
  16784. if (domUtils.hasClass(td, "selectTdClass")) {
  16785. selectTds.push(td);
  16786. }
  16787. });
  16788. if (selectTds.length) {
  16789. var start = selectTds[0],
  16790. end = selectTds[selectTds.length - 1],
  16791. startInfo = this.getCellInfo(start),
  16792. endInfo = this.getCellInfo(end);
  16793. this.selectedTds = selectTds;
  16794. this.cellsRange = {
  16795. beginRowIndex:startInfo.rowIndex,
  16796. beginColIndex:startInfo.colIndex,
  16797. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  16798. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  16799. };
  16800. }
  16801. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  16802. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  16803. domUtils.addClass(this.table.rows[0], "firstRow");
  16804. for(var i = 1; i< this.table.rows.length; i++) {
  16805. domUtils.removeClasses(this.table.rows[i], "firstRow");
  16806. }
  16807. }
  16808. },
  16809. /**
  16810. * 获取单元格的索引信息
  16811. */
  16812. getCellInfo:function (cell) {
  16813. if (!cell) return;
  16814. var cellIndex = cell.cellIndex,
  16815. rowIndex = cell.parentNode.rowIndex,
  16816. rowInfo = this.indexTable[rowIndex],
  16817. numCols = this.colsNum;
  16818. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  16819. var cellInfo = rowInfo[colIndex];
  16820. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  16821. return cellInfo;
  16822. }
  16823. }
  16824. },
  16825. /**
  16826. * 根据行列号获取单元格
  16827. */
  16828. getCell:function (rowIndex, cellIndex) {
  16829. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  16830. },
  16831. /**
  16832. * 删除单元格
  16833. */
  16834. deleteCell:function (cell, rowIndex) {
  16835. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  16836. var row = this.table.rows[rowIndex];
  16837. row.deleteCell(cell.cellIndex);
  16838. },
  16839. /**
  16840. * 根据始末两个单元格获取被框选的所有单元格范围
  16841. */
  16842. getCellsRange:function (cellA, cellB) {
  16843. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  16844. var tmpBeginRowIndex = beginRowIndex,
  16845. tmpBeginColIndex = beginColIndex,
  16846. tmpEndRowIndex = endRowIndex,
  16847. tmpEndColIndex = endColIndex,
  16848. cellInfo, colIndex, rowIndex;
  16849. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16850. if (beginRowIndex > 0) {
  16851. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16852. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16853. rowIndex = cellInfo.rowIndex;
  16854. if (rowIndex < beginRowIndex) {
  16855. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16856. }
  16857. }
  16858. }
  16859. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16860. if (endColIndex < me.colsNum) {
  16861. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16862. cellInfo = me.indexTable[rowIndex][endColIndex];
  16863. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16864. if (colIndex > endColIndex) {
  16865. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16866. }
  16867. }
  16868. }
  16869. // 检查是否有超出TableRange下边界的情况
  16870. if (endRowIndex < me.rowsNum) {
  16871. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16872. cellInfo = me.indexTable[endRowIndex][colIndex];
  16873. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16874. if (rowIndex > endRowIndex) {
  16875. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16876. }
  16877. }
  16878. }
  16879. // 检查是否有超出TableRange左边界的情况
  16880. if (beginColIndex > 0) {
  16881. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16882. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16883. colIndex = cellInfo.colIndex;
  16884. if (colIndex < beginColIndex) {
  16885. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16886. }
  16887. }
  16888. }
  16889. //递归调用直至所有完成所有框选单元格的扩展
  16890. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16891. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16892. } else {
  16893. // 不需要扩展TableRange的情况
  16894. return {
  16895. beginRowIndex:beginRowIndex,
  16896. beginColIndex:beginColIndex,
  16897. endRowIndex:endRowIndex,
  16898. endColIndex:endColIndex
  16899. };
  16900. }
  16901. }
  16902. try {
  16903. var me = this,
  16904. cellAInfo = me.getCellInfo(cellA);
  16905. if (cellA === cellB) {
  16906. return {
  16907. beginRowIndex:cellAInfo.rowIndex,
  16908. beginColIndex:cellAInfo.colIndex,
  16909. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16910. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16911. };
  16912. }
  16913. var cellBInfo = me.getCellInfo(cellB);
  16914. // 计算TableRange的四个边
  16915. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16916. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16917. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16918. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16919. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16920. } catch (e) {
  16921. //throw e;
  16922. }
  16923. },
  16924. /**
  16925. * 依据cellsRange获取对应的单元格集合
  16926. */
  16927. getCells:function (range) {
  16928. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16929. this.clearSelected();
  16930. var beginRowIndex = range.beginRowIndex,
  16931. beginColIndex = range.beginColIndex,
  16932. endRowIndex = range.endRowIndex,
  16933. endColIndex = range.endColIndex,
  16934. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16935. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16936. for (var j = beginColIndex; j <= endColIndex; j++) {
  16937. cellInfo = this.indexTable[i][j];
  16938. rowIndex = cellInfo.rowIndex;
  16939. colIndex = cellInfo.colIndex;
  16940. // 如果Cells里已经包含了此Cell则跳过
  16941. var key = rowIndex + '|' + colIndex;
  16942. if (tdHash[key]) continue;
  16943. tdHash[key] = 1;
  16944. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16945. return null;
  16946. }
  16947. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16948. }
  16949. }
  16950. return returnTds;
  16951. },
  16952. /**
  16953. * 清理已经选中的单元格
  16954. */
  16955. clearSelected:function () {
  16956. UETable.removeSelectedClass(this.selectedTds);
  16957. this.selectedTds = [];
  16958. this.cellsRange = {};
  16959. },
  16960. /**
  16961. * 根据range设置已经选中的单元格
  16962. */
  16963. setSelected:function (range) {
  16964. var cells = this.getCells(range);
  16965. UETable.addSelectedClass(cells);
  16966. this.selectedTds = cells;
  16967. this.cellsRange = range;
  16968. },
  16969. isFullRow:function () {
  16970. var range = this.cellsRange;
  16971. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16972. },
  16973. isFullCol:function () {
  16974. var range = this.cellsRange,
  16975. table = this.table,
  16976. ths = table.getElementsByTagName("th"),
  16977. rows = range.endRowIndex - range.beginRowIndex + 1;
  16978. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16979. },
  16980. /**
  16981. * 获取视觉上的前置单元格,默认是左边,top传入时
  16982. * @param cell
  16983. * @param top
  16984. */
  16985. getNextCell:function (cell, bottom, ignoreRange) {
  16986. try {
  16987. var cellInfo = this.getCellInfo(cell),
  16988. nextRowIndex, nextColIndex;
  16989. var len = this.selectedTds.length && !ignoreRange,
  16990. range = this.cellsRange;
  16991. //末行或者末列没有后置单元格
  16992. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16993. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16994. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16995. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16996. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16997. } catch (e) {
  16998. showError(e);
  16999. }
  17000. },
  17001. getPreviewCell:function (cell, top) {
  17002. try {
  17003. var cellInfo = this.getCellInfo(cell),
  17004. previewRowIndex, previewColIndex;
  17005. var len = this.selectedTds.length,
  17006. range = this.cellsRange;
  17007. //首行或者首列没有前置单元格
  17008. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  17009. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  17010. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  17011. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  17012. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  17013. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  17014. } catch (e) {
  17015. showError(e);
  17016. }
  17017. },
  17018. /**
  17019. * 移动单元格中的内容
  17020. */
  17021. moveContent:function (cellTo, cellFrom) {
  17022. if (UETable.isEmptyBlock(cellFrom)) return;
  17023. if (UETable.isEmptyBlock(cellTo)) {
  17024. cellTo.innerHTML = cellFrom.innerHTML;
  17025. return;
  17026. }
  17027. var child = cellTo.lastChild;
  17028. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  17029. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  17030. }
  17031. while (child = cellFrom.firstChild) {
  17032. cellTo.appendChild(child);
  17033. }
  17034. },
  17035. /**
  17036. * 向右合并单元格
  17037. */
  17038. mergeRight:function (cell) {
  17039. var cellInfo = this.getCellInfo(cell),
  17040. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  17041. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  17042. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  17043. //合并
  17044. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  17045. //被合并的单元格不应存在宽度属性
  17046. cell.removeAttribute("width");
  17047. //移动内容
  17048. this.moveContent(cell, rightCell);
  17049. //删掉被合并的Cell
  17050. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  17051. this.update();
  17052. },
  17053. /**
  17054. * 向下合并单元格
  17055. */
  17056. mergeDown:function (cell) {
  17057. var cellInfo = this.getCellInfo(cell),
  17058. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  17059. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  17060. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  17061. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  17062. cell.removeAttribute("height");
  17063. this.moveContent(cell, downCell);
  17064. this.deleteCell(downCell, downCellInfo.rowIndex);
  17065. this.update();
  17066. },
  17067. /**
  17068. * 合并整个range中的内容
  17069. */
  17070. mergeRange:function () {
  17071. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17072. var range = this.cellsRange,
  17073. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17074. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17075. var index = this.indexTable,
  17076. info = this.getCellInfo(leftTopCell);
  17077. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17078. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17079. }
  17080. // 删除剩余的Cells
  17081. var cells = this.getCells(range);
  17082. for(var i= 0,ci;ci=cells[i++];){
  17083. if (ci !== leftTopCell) {
  17084. this.moveContent(leftTopCell, ci);
  17085. this.deleteCell(ci);
  17086. }
  17087. }
  17088. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17089. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17090. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17091. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17092. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17093. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17094. leftTopCell.colSpan = 1;
  17095. }
  17096. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17097. var rowIndex = leftTopCell.parentNode.rowIndex;
  17098. //解决IE下的表格操作问题
  17099. if( this.table.deleteRow ) {
  17100. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  17101. this.table.deleteRow(curIndex);
  17102. }
  17103. } else {
  17104. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  17105. var row = this.table.rows[rowIndex + 1];
  17106. row.parentNode.removeChild(row);
  17107. }
  17108. }
  17109. leftTopCell.rowSpan = 1;
  17110. }
  17111. this.update();
  17112. },
  17113. /**
  17114. * 插入一行单元格
  17115. */
  17116. insertRow:function (rowIndex, sourceCell) {
  17117. var numCols = this.colsNum,
  17118. table = this.table,
  17119. row = table.insertRow(rowIndex), cell,
  17120. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17121. function replaceTdToTh(colIndex, cell, tableRow) {
  17122. if (colIndex == 0) {
  17123. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17124. th = tr.cells[colIndex];
  17125. if (th.tagName == 'TH') {
  17126. th = cell.ownerDocument.createElement("th");
  17127. th.appendChild(cell.firstChild);
  17128. tableRow.insertBefore(th, cell);
  17129. domUtils.remove(cell)
  17130. }
  17131. }else{
  17132. if (cell.tagName == 'TH') {
  17133. var td = cell.ownerDocument.createElement("td");
  17134. td.appendChild(cell.firstChild);
  17135. tableRow.insertBefore(td, cell);
  17136. domUtils.remove(cell)
  17137. }
  17138. }
  17139. }
  17140. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17141. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17142. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17143. cell = this.cloneCell(sourceCell, true);
  17144. this.setCellContent(cell);
  17145. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17146. row.appendChild(cell);
  17147. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17148. }
  17149. } else {
  17150. var infoRow = this.indexTable[rowIndex],
  17151. cellIndex = 0;
  17152. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17153. var cellInfo = infoRow[colIndex];
  17154. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17155. if (cellInfo.rowIndex < rowIndex) {
  17156. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17157. cell.rowSpan = cellInfo.rowSpan + 1;
  17158. } else {
  17159. cell = this.cloneCell(sourceCell, true);
  17160. this.setCellContent(cell);
  17161. row.appendChild(cell);
  17162. }
  17163. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17164. }
  17165. }
  17166. //框选时插入不触发contentchange,需要手动更新索引。
  17167. this.update();
  17168. return row;
  17169. },
  17170. /**
  17171. * 删除一行单元格
  17172. * @param rowIndex
  17173. */
  17174. deleteRow:function (rowIndex) {
  17175. var row = this.table.rows[rowIndex],
  17176. infoRow = this.indexTable[rowIndex],
  17177. colsNum = this.colsNum,
  17178. count = 0; //处理计数
  17179. for (var colIndex = 0; colIndex < colsNum;) {
  17180. var cellInfo = infoRow[colIndex],
  17181. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17182. if (cell.rowSpan > 1) {
  17183. if (cellInfo.rowIndex == rowIndex) {
  17184. var clone = cell.cloneNode(true);
  17185. clone.rowSpan = cell.rowSpan - 1;
  17186. clone.innerHTML = "";
  17187. cell.rowSpan = 1;
  17188. var nextRowIndex = rowIndex + 1,
  17189. nextRow = this.table.rows[nextRowIndex],
  17190. insertCellIndex,
  17191. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17192. if (preMerged < colIndex) {
  17193. insertCellIndex = colIndex - preMerged - 1;
  17194. //nextRow.insertCell(insertCellIndex);
  17195. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17196. } else {
  17197. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17198. }
  17199. count += 1;
  17200. //cell.parentNode.removeChild(cell);
  17201. }
  17202. }
  17203. colIndex += cell.colSpan || 1;
  17204. }
  17205. var deleteTds = [], cacheMap = {};
  17206. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17207. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17208. tmpCellIndex = infoRow[colIndex].cellIndex,
  17209. key = tmpRowIndex + "_" + tmpCellIndex;
  17210. if (cacheMap[key])continue;
  17211. cacheMap[key] = 1;
  17212. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17213. deleteTds.push(cell);
  17214. }
  17215. var mergeTds = [];
  17216. utils.each(deleteTds, function (td) {
  17217. if (td.rowSpan == 1) {
  17218. td.parentNode.removeChild(td);
  17219. } else {
  17220. mergeTds.push(td);
  17221. }
  17222. });
  17223. utils.each(mergeTds, function (td) {
  17224. td.rowSpan--;
  17225. });
  17226. row.parentNode.removeChild(row);
  17227. //浏览器方法本身存在bug,采用自定义方法删除
  17228. //this.table.deleteRow(rowIndex);
  17229. this.update();
  17230. },
  17231. insertCol:function (colIndex, sourceCell, defaultValue) {
  17232. var rowsNum = this.rowsNum,
  17233. rowIndex = 0,
  17234. tableRow, cell,
  17235. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17236. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17237. function replaceTdToTh(rowIndex, cell, tableRow) {
  17238. if (rowIndex == 0) {
  17239. var th = cell.nextSibling || cell.previousSibling;
  17240. if (th.tagName == 'TH') {
  17241. th = cell.ownerDocument.createElement("th");
  17242. th.appendChild(cell.firstChild);
  17243. tableRow.insertBefore(th, cell);
  17244. domUtils.remove(cell)
  17245. }
  17246. }else{
  17247. if (cell.tagName == 'TH') {
  17248. var td = cell.ownerDocument.createElement("td");
  17249. td.appendChild(cell.firstChild);
  17250. tableRow.insertBefore(td, cell);
  17251. domUtils.remove(cell)
  17252. }
  17253. }
  17254. }
  17255. var preCell;
  17256. if (colIndex == 0 || colIndex == this.colsNum) {
  17257. for (; rowIndex < rowsNum; rowIndex++) {
  17258. tableRow = this.table.rows[rowIndex];
  17259. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17260. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17261. this.setCellContent(cell);
  17262. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17263. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17264. if (!colIndex) {
  17265. tableRow.insertBefore(cell, tableRow.cells[0]);
  17266. } else {
  17267. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17268. }
  17269. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17270. }
  17271. } else {
  17272. for (; rowIndex < rowsNum; rowIndex++) {
  17273. var cellInfo = this.indexTable[rowIndex][colIndex];
  17274. if (cellInfo.colIndex < colIndex) {
  17275. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17276. cell.colSpan = cellInfo.colSpan + 1;
  17277. } else {
  17278. tableRow = this.table.rows[rowIndex];
  17279. preCell = tableRow.cells[cellInfo.cellIndex];
  17280. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17281. this.setCellContent(cell);
  17282. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17283. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17284. //防止IE下报错
  17285. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17286. }
  17287. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17288. }
  17289. }
  17290. //框选时插入不触发contentchange,需要手动更新索引
  17291. this.update();
  17292. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  17293. },
  17294. updateWidth:function (width, defaultValue) {
  17295. var table = this.table,
  17296. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17297. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17298. table.setAttribute("width", tmpWidth);
  17299. return;
  17300. }
  17301. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17302. utils.each(tds, function (td) {
  17303. td.setAttribute("width", width);
  17304. })
  17305. },
  17306. deleteCol:function (colIndex) {
  17307. var indexTable = this.indexTable,
  17308. tableRows = this.table.rows,
  17309. backTableWidth = this.table.getAttribute("width"),
  17310. backTdWidth = 0,
  17311. rowsNum = this.rowsNum,
  17312. cacheMap = {};
  17313. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17314. var infoRow = indexTable[rowIndex],
  17315. cellInfo = infoRow[colIndex],
  17316. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17317. // 跳过已经处理过的Cell
  17318. if (cacheMap[key])continue;
  17319. cacheMap[key] = 1;
  17320. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17321. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17322. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17323. if (cell.colSpan > 1) {
  17324. cell.colSpan--;
  17325. } else {
  17326. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17327. }
  17328. rowIndex += cellInfo.rowSpan || 1;
  17329. }
  17330. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17331. this.update();
  17332. },
  17333. splitToCells:function (cell) {
  17334. var me = this,
  17335. cells = this.splitToRows(cell);
  17336. utils.each(cells, function (cell) {
  17337. me.splitToCols(cell);
  17338. })
  17339. },
  17340. splitToRows:function (cell) {
  17341. var cellInfo = this.getCellInfo(cell),
  17342. rowIndex = cellInfo.rowIndex,
  17343. colIndex = cellInfo.colIndex,
  17344. results = [];
  17345. // 修改Cell的rowSpan
  17346. cell.rowSpan = 1;
  17347. results.push(cell);
  17348. // 补齐单元格
  17349. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17350. if (i == rowIndex)continue;
  17351. var tableRow = this.table.rows[i],
  17352. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17353. tmpCell.colSpan = cellInfo.colSpan;
  17354. this.setCellContent(tmpCell);
  17355. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17356. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17357. if (cell.style.cssText) {
  17358. tmpCell.style.cssText = cell.style.cssText;
  17359. }
  17360. results.push(tmpCell);
  17361. }
  17362. this.update();
  17363. return results;
  17364. },
  17365. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  17366. var indexRow = this.indexTable[rowIndex],
  17367. num = 0;
  17368. for (var i = 0; i < colIndex;) {
  17369. var colSpan = indexRow[i].colSpan,
  17370. tmpRowIndex = indexRow[i].rowIndex;
  17371. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17372. i += colSpan;
  17373. }
  17374. return num;
  17375. },
  17376. splitToCols:function (cell) {
  17377. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17378. cellInfo = this.getCellInfo(cell),
  17379. rowIndex = cellInfo.rowIndex,
  17380. colIndex = cellInfo.colIndex,
  17381. results = [];
  17382. // 修改Cell的rowSpan
  17383. cell.colSpan = 1;
  17384. cell.setAttribute("width", backWidth);
  17385. results.push(cell);
  17386. // 补齐单元格
  17387. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17388. if (j == colIndex)continue;
  17389. var tableRow = this.table.rows[rowIndex],
  17390. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17391. tmpCell.rowSpan = cellInfo.rowSpan;
  17392. this.setCellContent(tmpCell);
  17393. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17394. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17395. tmpCell.setAttribute('width', backWidth);
  17396. if (cell.style.cssText) {
  17397. tmpCell.style.cssText = cell.style.cssText;
  17398. }
  17399. //处理th的情况
  17400. if (cell.tagName == 'TH') {
  17401. var th = cell.ownerDocument.createElement('th');
  17402. th.appendChild(tmpCell.firstChild);
  17403. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17404. th.rowSpan = tmpCell.rowSpan;
  17405. tableRow.insertBefore(th, tmpCell);
  17406. domUtils.remove(tmpCell);
  17407. }
  17408. results.push(tmpCell);
  17409. }
  17410. this.update();
  17411. return results;
  17412. },
  17413. isLastCell:function (cell, rowsNum, colsNum) {
  17414. rowsNum = rowsNum || this.rowsNum;
  17415. colsNum = colsNum || this.colsNum;
  17416. var cellInfo = this.getCellInfo(cell);
  17417. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17418. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17419. },
  17420. getLastCell:function (cells) {
  17421. cells = cells || this.table.getElementsByTagName("td");
  17422. var firstInfo = this.getCellInfo(cells[0]);
  17423. var me = this, last = cells[0],
  17424. tr = last.parentNode,
  17425. cellsNum = 0, cols = 0, rows;
  17426. utils.each(cells, function (cell) {
  17427. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  17428. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17429. });
  17430. rows = cellsNum / cols;
  17431. utils.each(cells, function (cell) {
  17432. if (me.isLastCell(cell, rows, cols)) {
  17433. last = cell;
  17434. return false;
  17435. }
  17436. });
  17437. return last;
  17438. },
  17439. selectRow:function (rowIndex) {
  17440. var indexRow = this.indexTable[rowIndex],
  17441. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17442. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17443. range = this.getCellsRange(start, end);
  17444. this.setSelected(range);
  17445. },
  17446. selectTable:function () {
  17447. var tds = this.table.getElementsByTagName("td"),
  17448. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17449. this.setSelected(range);
  17450. },
  17451. setBackground:function (cells, value) {
  17452. if (typeof value === "string") {
  17453. utils.each(cells, function (cell) {
  17454. cell.style.backgroundColor = value;
  17455. })
  17456. } else if (typeof value === "object") {
  17457. value = utils.extend({
  17458. repeat:true,
  17459. colorList:["#ddd", "#fff"]
  17460. }, value);
  17461. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17462. count = 0,
  17463. colors = value.colorList,
  17464. getColor = function (list, index, repeat) {
  17465. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17466. };
  17467. for (var i = 0, cell; cell = cells[i++];) {
  17468. var cellInfo = this.getCellInfo(cell);
  17469. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17470. }
  17471. }
  17472. },
  17473. removeBackground:function (cells) {
  17474. utils.each(cells, function (cell) {
  17475. cell.style.backgroundColor = "";
  17476. })
  17477. }
  17478. };
  17479. function showError(e) {
  17480. }
  17481. })();
  17482. // plugins/table.cmds.js
  17483. /**
  17484. * Created with JetBrains PhpStorm.
  17485. * User: taoqili
  17486. * Date: 13-2-20
  17487. * Time: 下午6:25
  17488. * To change this template use File | Settings | File Templates.
  17489. */
  17490. ;
  17491. (function () {
  17492. var UT = UE.UETable,
  17493. getTableItemsByRange = function (editor) {
  17494. return UT.getTableItemsByRange(editor);
  17495. },
  17496. getUETableBySelected = function (editor) {
  17497. return UT.getUETableBySelected(editor)
  17498. },
  17499. getDefaultValue = function (editor, table) {
  17500. return UT.getDefaultValue(editor, table);
  17501. },
  17502. getUETable = function (tdOrTable) {
  17503. return UT.getUETable(tdOrTable);
  17504. };
  17505. UE.commands['inserttable'] = {
  17506. queryCommandState: function () {
  17507. return getTableItemsByRange(this).table ? -1 : 0;
  17508. },
  17509. execCommand: function (cmd, opt) {
  17510. function createTable(opt, tdWidth) {
  17511. var html = [],
  17512. rowsNum = opt.numRows,
  17513. colsNum = opt.numCols;
  17514. for (var r = 0; r < rowsNum; r++) {
  17515. html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
  17516. for (var c = 0; c < colsNum; c++) {
  17517. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  17518. }
  17519. html.push('</tr>')
  17520. }
  17521. //禁止指定table-width
  17522. return '<table><tbody>' + html.join('') + '</tbody></table>'
  17523. }
  17524. if (!opt) {
  17525. opt = utils.extend({}, {
  17526. numCols: this.options.defaultCols,
  17527. numRows: this.options.defaultRows,
  17528. tdvalign: this.options.tdvalign
  17529. })
  17530. }
  17531. var me = this;
  17532. var range = this.selection.getRange(),
  17533. start = range.startContainer,
  17534. firstParentBlock = domUtils.findParent(start, function (node) {
  17535. return domUtils.isBlockElm(node);
  17536. }, true) || me.body;
  17537. var defaultValue = getDefaultValue(me),
  17538. tableWidth = firstParentBlock.offsetWidth,
  17539. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  17540. //todo其他属性
  17541. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  17542. me.execCommand("inserthtml", createTable(opt, tdWidth));
  17543. }
  17544. };
  17545. UE.commands['insertparagraphbeforetable'] = {
  17546. queryCommandState: function () {
  17547. return getTableItemsByRange(this).cell ? 0 : -1;
  17548. },
  17549. execCommand: function () {
  17550. var table = getTableItemsByRange(this).table;
  17551. if (table) {
  17552. var p = this.document.createElement("p");
  17553. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  17554. table.parentNode.insertBefore(p, table);
  17555. this.selection.getRange().setStart(p, 0).setCursor();
  17556. }
  17557. }
  17558. };
  17559. UE.commands['deletetable'] = {
  17560. queryCommandState: function () {
  17561. var rng = this.selection.getRange();
  17562. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  17563. },
  17564. execCommand: function (cmd, table) {
  17565. var rng = this.selection.getRange();
  17566. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  17567. if (table) {
  17568. var next = table.nextSibling;
  17569. if (!next) {
  17570. next = domUtils.createElement(this.document, 'p', {
  17571. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  17572. });
  17573. table.parentNode.insertBefore(next, table);
  17574. }
  17575. domUtils.remove(table);
  17576. rng = this.selection.getRange();
  17577. if (next.nodeType == 3) {
  17578. rng.setStartBefore(next)
  17579. } else {
  17580. rng.setStart(next, 0)
  17581. }
  17582. rng.setCursor(false, true)
  17583. this.fireEvent("tablehasdeleted")
  17584. }
  17585. }
  17586. };
  17587. UE.commands['cellalign'] = {
  17588. queryCommandState: function () {
  17589. return getSelectedArr(this).length ? 0 : -1
  17590. },
  17591. execCommand: function (cmd, align) {
  17592. var selectedTds = getSelectedArr(this);
  17593. if (selectedTds.length) {
  17594. for (var i = 0, ci; ci = selectedTds[i++];) {
  17595. ci.setAttribute('align', align);
  17596. }
  17597. }
  17598. }
  17599. };
  17600. UE.commands['cellvalign'] = {
  17601. queryCommandState: function () {
  17602. return getSelectedArr(this).length ? 0 : -1;
  17603. },
  17604. execCommand: function (cmd, valign) {
  17605. var selectedTds = getSelectedArr(this);
  17606. if (selectedTds.length) {
  17607. for (var i = 0, ci; ci = selectedTds[i++];) {
  17608. ci.setAttribute('vAlign', valign);
  17609. }
  17610. }
  17611. }
  17612. };
  17613. UE.commands['insertcaption'] = {
  17614. queryCommandState: function () {
  17615. var table = getTableItemsByRange(this).table;
  17616. if (table) {
  17617. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  17618. }
  17619. return -1;
  17620. },
  17621. execCommand: function () {
  17622. var table = getTableItemsByRange(this).table;
  17623. if (table) {
  17624. var caption = this.document.createElement('caption');
  17625. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  17626. table.insertBefore(caption, table.firstChild);
  17627. var range = this.selection.getRange();
  17628. range.setStart(caption, 0).setCursor();
  17629. }
  17630. }
  17631. };
  17632. UE.commands['deletecaption'] = {
  17633. queryCommandState: function () {
  17634. var rng = this.selection.getRange(),
  17635. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17636. if (table) {
  17637. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  17638. }
  17639. return -1;
  17640. },
  17641. execCommand: function () {
  17642. var rng = this.selection.getRange(),
  17643. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17644. if (table) {
  17645. domUtils.remove(table.getElementsByTagName('caption')[0]);
  17646. var range = this.selection.getRange();
  17647. range.setStart(table.rows[0].cells[0], 0).setCursor();
  17648. }
  17649. }
  17650. };
  17651. UE.commands['inserttitle'] = {
  17652. queryCommandState: function () {
  17653. var table = getTableItemsByRange(this).table;
  17654. if (table) {
  17655. var firstRow = table.rows[0];
  17656. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  17657. }
  17658. return -1;
  17659. },
  17660. execCommand: function () {
  17661. var table = getTableItemsByRange(this).table;
  17662. if (table) {
  17663. getUETable(table).insertRow(0, 'th');
  17664. }
  17665. var th = table.getElementsByTagName('th')[0];
  17666. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17667. }
  17668. };
  17669. UE.commands['deletetitle'] = {
  17670. queryCommandState: function () {
  17671. var table = getTableItemsByRange(this).table;
  17672. if (table) {
  17673. var firstRow = table.rows[0];
  17674. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  17675. }
  17676. return -1;
  17677. },
  17678. execCommand: function () {
  17679. var table = getTableItemsByRange(this).table;
  17680. if (table) {
  17681. domUtils.remove(table.rows[0])
  17682. }
  17683. var td = table.getElementsByTagName('td')[0];
  17684. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17685. }
  17686. };
  17687. UE.commands['inserttitlecol'] = {
  17688. queryCommandState: function () {
  17689. var table = getTableItemsByRange(this).table;
  17690. if (table) {
  17691. var lastRow = table.rows[table.rows.length-1];
  17692. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  17693. }
  17694. return -1;
  17695. },
  17696. execCommand: function (cmd) {
  17697. var table = getTableItemsByRange(this).table;
  17698. if (table) {
  17699. getUETable(table).insertCol(0, 'th');
  17700. }
  17701. resetTdWidth(table, this);
  17702. var th = table.getElementsByTagName('th')[0];
  17703. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17704. }
  17705. };
  17706. UE.commands['deletetitlecol'] = {
  17707. queryCommandState: function () {
  17708. var table = getTableItemsByRange(this).table;
  17709. if (table) {
  17710. var lastRow = table.rows[table.rows.length-1];
  17711. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  17712. }
  17713. return -1;
  17714. },
  17715. execCommand: function () {
  17716. var table = getTableItemsByRange(this).table;
  17717. if (table) {
  17718. for(var i = 0; i< table.rows.length; i++ ){
  17719. domUtils.remove(table.rows[i].children[0])
  17720. }
  17721. }
  17722. resetTdWidth(table, this);
  17723. var td = table.getElementsByTagName('td')[0];
  17724. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17725. }
  17726. };
  17727. UE.commands["mergeright"] = {
  17728. queryCommandState: function (cmd) {
  17729. var tableItems = getTableItemsByRange(this),
  17730. table = tableItems.table,
  17731. cell = tableItems.cell;
  17732. if (!table || !cell) return -1;
  17733. var ut = getUETable(table);
  17734. if (ut.selectedTds.length) return -1;
  17735. var cellInfo = ut.getCellInfo(cell),
  17736. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  17737. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  17738. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  17739. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  17740. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  17741. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17742. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  17743. },
  17744. execCommand: function (cmd) {
  17745. var rng = this.selection.getRange(),
  17746. bk = rng.createBookmark(true);
  17747. var cell = getTableItemsByRange(this).cell,
  17748. ut = getUETable(cell);
  17749. ut.mergeRight(cell);
  17750. rng.moveToBookmark(bk).select();
  17751. }
  17752. };
  17753. UE.commands["mergedown"] = {
  17754. queryCommandState: function (cmd) {
  17755. var tableItems = getTableItemsByRange(this),
  17756. table = tableItems.table,
  17757. cell = tableItems.cell;
  17758. if (!table || !cell) return -1;
  17759. var ut = getUETable(table);
  17760. if (ut.selectedTds.length)return -1;
  17761. var cellInfo = ut.getCellInfo(cell),
  17762. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  17763. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  17764. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  17765. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  17766. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  17767. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17768. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  17769. },
  17770. execCommand: function () {
  17771. var rng = this.selection.getRange(),
  17772. bk = rng.createBookmark(true);
  17773. var cell = getTableItemsByRange(this).cell,
  17774. ut = getUETable(cell);
  17775. ut.mergeDown(cell);
  17776. rng.moveToBookmark(bk).select();
  17777. }
  17778. };
  17779. UE.commands["mergecells"] = {
  17780. queryCommandState: function () {
  17781. return getUETableBySelected(this) ? 0 : -1;
  17782. },
  17783. execCommand: function () {
  17784. var ut = getUETableBySelected(this);
  17785. if (ut && ut.selectedTds.length) {
  17786. var cell = ut.selectedTds[0];
  17787. ut.mergeRange();
  17788. var rng = this.selection.getRange();
  17789. if (domUtils.isEmptyBlock(cell)) {
  17790. rng.setStart(cell, 0).collapse(true)
  17791. } else {
  17792. rng.selectNodeContents(cell)
  17793. }
  17794. rng.select();
  17795. }
  17796. }
  17797. };
  17798. UE.commands["insertrow"] = {
  17799. queryCommandState: function () {
  17800. var tableItems = getTableItemsByRange(this),
  17801. cell = tableItems.cell;
  17802. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  17803. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17804. },
  17805. execCommand: function () {
  17806. var rng = this.selection.getRange(),
  17807. bk = rng.createBookmark(true);
  17808. var tableItems = getTableItemsByRange(this),
  17809. cell = tableItems.cell,
  17810. table = tableItems.table,
  17811. ut = getUETable(table),
  17812. cellInfo = ut.getCellInfo(cell);
  17813. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  17814. if (!ut.selectedTds.length) {
  17815. ut.insertRow(cellInfo.rowIndex, cell);
  17816. } else {
  17817. var range = ut.cellsRange;
  17818. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17819. ut.insertRow(range.beginRowIndex, cell);
  17820. }
  17821. }
  17822. rng.moveToBookmark(bk).select();
  17823. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17824. }
  17825. };
  17826. //后插入行
  17827. UE.commands["insertrownext"] = {
  17828. queryCommandState: function () {
  17829. var tableItems = getTableItemsByRange(this),
  17830. cell = tableItems.cell;
  17831. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17832. },
  17833. execCommand: function () {
  17834. var rng = this.selection.getRange(),
  17835. bk = rng.createBookmark(true);
  17836. var tableItems = getTableItemsByRange(this),
  17837. cell = tableItems.cell,
  17838. table = tableItems.table,
  17839. ut = getUETable(table),
  17840. cellInfo = ut.getCellInfo(cell);
  17841. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  17842. if (!ut.selectedTds.length) {
  17843. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  17844. } else {
  17845. var range = ut.cellsRange;
  17846. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17847. ut.insertRow(range.endRowIndex + 1, cell);
  17848. }
  17849. }
  17850. rng.moveToBookmark(bk).select();
  17851. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17852. }
  17853. };
  17854. UE.commands["deleterow"] = {
  17855. queryCommandState: function () {
  17856. var tableItems = getTableItemsByRange(this);
  17857. return tableItems.cell ? 0 : -1;
  17858. },
  17859. execCommand: function () {
  17860. var cell = getTableItemsByRange(this).cell,
  17861. ut = getUETable(cell),
  17862. cellsRange = ut.cellsRange,
  17863. cellInfo = ut.getCellInfo(cell),
  17864. preCell = ut.getVSideCell(cell),
  17865. nextCell = ut.getVSideCell(cell, true),
  17866. rng = this.selection.getRange();
  17867. if (utils.isEmptyObject(cellsRange)) {
  17868. ut.deleteRow(cellInfo.rowIndex);
  17869. } else {
  17870. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17871. ut.deleteRow(cellsRange.beginRowIndex);
  17872. }
  17873. }
  17874. var table = ut.table;
  17875. if (!table.getElementsByTagName('td').length) {
  17876. var nextSibling = table.nextSibling;
  17877. domUtils.remove(table);
  17878. if (nextSibling) {
  17879. rng.setStart(nextSibling, 0).setCursor(false, true);
  17880. }
  17881. } else {
  17882. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17883. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17884. } else {
  17885. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17886. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17887. }
  17888. }
  17889. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17890. }
  17891. };
  17892. UE.commands["insertcol"] = {
  17893. queryCommandState: function (cmd) {
  17894. var tableItems = getTableItemsByRange(this),
  17895. cell = tableItems.cell;
  17896. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17897. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17898. },
  17899. execCommand: function (cmd) {
  17900. var rng = this.selection.getRange(),
  17901. bk = rng.createBookmark(true);
  17902. if (this.queryCommandState(cmd) == -1)return;
  17903. var cell = getTableItemsByRange(this).cell,
  17904. ut = getUETable(cell),
  17905. cellInfo = ut.getCellInfo(cell);
  17906. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17907. if (!ut.selectedTds.length) {
  17908. ut.insertCol(cellInfo.colIndex, cell);
  17909. } else {
  17910. var range = ut.cellsRange;
  17911. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17912. ut.insertCol(range.beginColIndex, cell);
  17913. }
  17914. }
  17915. rng.moveToBookmark(bk).select(true);
  17916. }
  17917. };
  17918. UE.commands["insertcolnext"] = {
  17919. queryCommandState: function () {
  17920. var tableItems = getTableItemsByRange(this),
  17921. cell = tableItems.cell;
  17922. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17923. },
  17924. execCommand: function () {
  17925. var rng = this.selection.getRange(),
  17926. bk = rng.createBookmark(true);
  17927. var cell = getTableItemsByRange(this).cell,
  17928. ut = getUETable(cell),
  17929. cellInfo = ut.getCellInfo(cell);
  17930. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17931. if (!ut.selectedTds.length) {
  17932. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17933. } else {
  17934. var range = ut.cellsRange;
  17935. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17936. ut.insertCol(range.endColIndex + 1, cell);
  17937. }
  17938. }
  17939. rng.moveToBookmark(bk).select();
  17940. }
  17941. };
  17942. UE.commands["deletecol"] = {
  17943. queryCommandState: function () {
  17944. var tableItems = getTableItemsByRange(this);
  17945. return tableItems.cell ? 0 : -1;
  17946. },
  17947. execCommand: function () {
  17948. var cell = getTableItemsByRange(this).cell,
  17949. ut = getUETable(cell),
  17950. range = ut.cellsRange,
  17951. cellInfo = ut.getCellInfo(cell),
  17952. preCell = ut.getHSideCell(cell),
  17953. nextCell = ut.getHSideCell(cell, true);
  17954. if (utils.isEmptyObject(range)) {
  17955. ut.deleteCol(cellInfo.colIndex);
  17956. } else {
  17957. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17958. ut.deleteCol(range.beginColIndex);
  17959. }
  17960. }
  17961. var table = ut.table,
  17962. rng = this.selection.getRange();
  17963. if (!table.getElementsByTagName('td').length) {
  17964. var nextSibling = table.nextSibling;
  17965. domUtils.remove(table);
  17966. if (nextSibling) {
  17967. rng.setStart(nextSibling, 0).setCursor(false, true);
  17968. }
  17969. } else {
  17970. if (domUtils.inDoc(cell, this.document)) {
  17971. rng.setStart(cell, 0).setCursor(false, true);
  17972. } else {
  17973. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17974. rng.selectNodeContents(nextCell).setCursor(false, true);
  17975. } else {
  17976. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17977. rng.selectNodeContents(preCell).setCursor(true, true);
  17978. }
  17979. }
  17980. }
  17981. }
  17982. }
  17983. };
  17984. UE.commands["splittocells"] = {
  17985. queryCommandState: function () {
  17986. var tableItems = getTableItemsByRange(this),
  17987. cell = tableItems.cell;
  17988. if (!cell) return -1;
  17989. var ut = getUETable(tableItems.table);
  17990. if (ut.selectedTds.length > 0) return -1;
  17991. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17992. },
  17993. execCommand: function () {
  17994. var rng = this.selection.getRange(),
  17995. bk = rng.createBookmark(true);
  17996. var cell = getTableItemsByRange(this).cell,
  17997. ut = getUETable(cell);
  17998. ut.splitToCells(cell);
  17999. rng.moveToBookmark(bk).select();
  18000. }
  18001. };
  18002. UE.commands["splittorows"] = {
  18003. queryCommandState: function () {
  18004. var tableItems = getTableItemsByRange(this),
  18005. cell = tableItems.cell;
  18006. if (!cell) return -1;
  18007. var ut = getUETable(tableItems.table);
  18008. if (ut.selectedTds.length > 0) return -1;
  18009. return cell && cell.rowSpan > 1 ? 0 : -1;
  18010. },
  18011. execCommand: function () {
  18012. var rng = this.selection.getRange(),
  18013. bk = rng.createBookmark(true);
  18014. var cell = getTableItemsByRange(this).cell,
  18015. ut = getUETable(cell);
  18016. ut.splitToRows(cell);
  18017. rng.moveToBookmark(bk).select();
  18018. }
  18019. };
  18020. UE.commands["splittocols"] = {
  18021. queryCommandState: function () {
  18022. var tableItems = getTableItemsByRange(this),
  18023. cell = tableItems.cell;
  18024. if (!cell) return -1;
  18025. var ut = getUETable(tableItems.table);
  18026. if (ut.selectedTds.length > 0) return -1;
  18027. return cell && cell.colSpan > 1 ? 0 : -1;
  18028. },
  18029. execCommand: function () {
  18030. var rng = this.selection.getRange(),
  18031. bk = rng.createBookmark(true);
  18032. var cell = getTableItemsByRange(this).cell,
  18033. ut = getUETable(cell);
  18034. ut.splitToCols(cell);
  18035. rng.moveToBookmark(bk).select();
  18036. }
  18037. };
  18038. UE.commands["adaptbytext"] =
  18039. UE.commands["adaptbywindow"] = {
  18040. queryCommandState: function () {
  18041. return getTableItemsByRange(this).table ? 0 : -1
  18042. },
  18043. execCommand: function (cmd) {
  18044. var tableItems = getTableItemsByRange(this),
  18045. table = tableItems.table;
  18046. if (table) {
  18047. if (cmd == 'adaptbywindow') {
  18048. resetTdWidth(table, this);
  18049. } else {
  18050. var cells = domUtils.getElementsByTagName(table, "td th");
  18051. utils.each(cells, function (cell) {
  18052. cell.removeAttribute("width");
  18053. });
  18054. table.removeAttribute("width");
  18055. }
  18056. }
  18057. }
  18058. };
  18059. //平均分配各列
  18060. UE.commands['averagedistributecol'] = {
  18061. queryCommandState: function () {
  18062. var ut = getUETableBySelected(this);
  18063. if (!ut) return -1;
  18064. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18065. },
  18066. execCommand: function (cmd) {
  18067. var me = this,
  18068. ut = getUETableBySelected(me);
  18069. function getAverageWidth() {
  18070. var tb = ut.table,
  18071. averageWidth, sumWidth = 0, colsNum = 0,
  18072. tbAttr = getDefaultValue(me, tb);
  18073. if (ut.isFullRow()) {
  18074. sumWidth = tb.offsetWidth;
  18075. colsNum = ut.colsNum;
  18076. } else {
  18077. var begin = ut.cellsRange.beginColIndex,
  18078. end = ut.cellsRange.endColIndex,
  18079. node;
  18080. for (var i = begin; i <= end;) {
  18081. node = ut.selectedTds[i];
  18082. sumWidth += node.offsetWidth;
  18083. i += node.colSpan;
  18084. colsNum += 1;
  18085. }
  18086. }
  18087. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18088. return averageWidth;
  18089. }
  18090. function setAverageWidth(averageWidth) {
  18091. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18092. node.setAttribute("width", "");
  18093. });
  18094. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18095. utils.each(cells, function (node) {
  18096. if (node.colSpan == 1) {
  18097. node.setAttribute("width", averageWidth);
  18098. }
  18099. });
  18100. }
  18101. if (ut && ut.selectedTds.length) {
  18102. setAverageWidth(getAverageWidth());
  18103. }
  18104. }
  18105. };
  18106. //平均分配各行
  18107. UE.commands['averagedistributerow'] = {
  18108. queryCommandState: function () {
  18109. var ut = getUETableBySelected(this);
  18110. if (!ut) return -1;
  18111. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18112. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18113. },
  18114. execCommand: function (cmd) {
  18115. var me = this,
  18116. ut = getUETableBySelected(me);
  18117. function getAverageHeight() {
  18118. var averageHeight, rowNum, sumHeight = 0,
  18119. tb = ut.table,
  18120. tbAttr = getDefaultValue(me, tb),
  18121. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18122. if (ut.isFullCol()) {
  18123. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18124. thArr = domUtils.getElementsByTagName(tb, "th"),
  18125. captionHeight, thHeight;
  18126. if (captionArr.length > 0) {
  18127. captionHeight = captionArr[0].offsetHeight;
  18128. }
  18129. if (thArr.length > 0) {
  18130. thHeight = thArr[0].offsetHeight;
  18131. }
  18132. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18133. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18134. } else {
  18135. var begin = ut.cellsRange.beginRowIndex,
  18136. end = ut.cellsRange.endRowIndex,
  18137. count = 0,
  18138. trs = domUtils.getElementsByTagName(tb, "tr");
  18139. for (var i = begin; i <= end; i++) {
  18140. sumHeight += trs[i].offsetHeight;
  18141. count += 1;
  18142. }
  18143. rowNum = count;
  18144. }
  18145. //ie8下是混杂模式
  18146. if (browser.ie && browser.version < 9) {
  18147. averageHeight = Math.ceil(sumHeight / rowNum);
  18148. } else {
  18149. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18150. }
  18151. return averageHeight;
  18152. }
  18153. function setAverageHeight(averageHeight) {
  18154. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18155. utils.each(cells, function (node) {
  18156. if (node.rowSpan == 1) {
  18157. node.setAttribute("height", averageHeight);
  18158. }
  18159. });
  18160. }
  18161. if (ut && ut.selectedTds.length) {
  18162. setAverageHeight(getAverageHeight());
  18163. }
  18164. }
  18165. };
  18166. //单元格对齐方式
  18167. UE.commands['cellalignment'] = {
  18168. queryCommandState: function () {
  18169. return getTableItemsByRange(this).table ? 0 : -1
  18170. },
  18171. execCommand: function (cmd, data) {
  18172. var me = this,
  18173. ut = getUETableBySelected(me);
  18174. if (!ut) {
  18175. var start = me.selection.getStart(),
  18176. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18177. if (!/caption/ig.test(cell.tagName)) {
  18178. domUtils.setAttributes(cell, data);
  18179. } else {
  18180. cell.style.textAlign = data.align;
  18181. cell.style.verticalAlign = data.vAlign;
  18182. }
  18183. me.selection.getRange().setCursor(true);
  18184. } else {
  18185. utils.each(ut.selectedTds, function (cell) {
  18186. domUtils.setAttributes(cell, data);
  18187. });
  18188. }
  18189. },
  18190. /**
  18191. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18192. * @see UE.UETable.getTableCellAlignState
  18193. */
  18194. queryCommandValue: function (cmd) {
  18195. var activeMenuCell = getTableItemsByRange( this).cell;
  18196. if( !activeMenuCell ) {
  18197. activeMenuCell = getSelectedArr(this)[0];
  18198. }
  18199. if (!activeMenuCell) {
  18200. return null;
  18201. } else {
  18202. //获取同时选中的其他单元格
  18203. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18204. !cells.length && ( cells = activeMenuCell );
  18205. return UE.UETable.getTableCellAlignState(cells);
  18206. }
  18207. }
  18208. };
  18209. //表格对齐方式
  18210. UE.commands['tablealignment'] = {
  18211. queryCommandState: function () {
  18212. if (browser.ie && browser.version < 8) {
  18213. return -1;
  18214. }
  18215. return getTableItemsByRange(this).table ? 0 : -1
  18216. },
  18217. execCommand: function (cmd, value) {
  18218. var me = this,
  18219. start = me.selection.getStart(),
  18220. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18221. if (table) {
  18222. table.setAttribute("align",value);
  18223. }
  18224. }
  18225. };
  18226. //表格属性
  18227. UE.commands['edittable'] = {
  18228. queryCommandState: function () {
  18229. return getTableItemsByRange(this).table ? 0 : -1
  18230. },
  18231. execCommand: function (cmd, color) {
  18232. var rng = this.selection.getRange(),
  18233. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18234. if (table) {
  18235. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18236. domUtils.getElementsByTagName(table, "th"),
  18237. domUtils.getElementsByTagName(table, "caption")
  18238. );
  18239. utils.each(arr, function (node) {
  18240. node.style.borderColor = color;
  18241. });
  18242. }
  18243. }
  18244. };
  18245. //单元格属性
  18246. UE.commands['edittd'] = {
  18247. queryCommandState: function () {
  18248. return getTableItemsByRange(this).table ? 0 : -1
  18249. },
  18250. execCommand: function (cmd, bkColor) {
  18251. var me = this,
  18252. ut = getUETableBySelected(me);
  18253. if (!ut) {
  18254. var start = me.selection.getStart(),
  18255. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18256. if (cell) {
  18257. cell.style.backgroundColor = bkColor;
  18258. }
  18259. } else {
  18260. utils.each(ut.selectedTds, function (cell) {
  18261. cell.style.backgroundColor = bkColor;
  18262. });
  18263. }
  18264. }
  18265. };
  18266. UE.commands["settablebackground"] = {
  18267. queryCommandState: function () {
  18268. return getSelectedArr(this).length > 1 ? 0 : -1;
  18269. },
  18270. execCommand: function (cmd, value) {
  18271. var cells, ut;
  18272. cells = getSelectedArr(this);
  18273. ut = getUETable(cells[0]);
  18274. ut.setBackground(cells, value);
  18275. }
  18276. };
  18277. UE.commands["cleartablebackground"] = {
  18278. queryCommandState: function () {
  18279. var cells = getSelectedArr(this);
  18280. if (!cells.length)return -1;
  18281. for (var i = 0, cell; cell = cells[i++];) {
  18282. if (cell.style.backgroundColor !== "") return 0;
  18283. }
  18284. return -1;
  18285. },
  18286. execCommand: function () {
  18287. var cells = getSelectedArr(this),
  18288. ut = getUETable(cells[0]);
  18289. ut.removeBackground(cells);
  18290. }
  18291. };
  18292. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18293. queryCommandState: function (cmd) {
  18294. var table = getTableItemsByRange(this).table;
  18295. if (!table) return -1;
  18296. var interlaced = table.getAttribute("interlaced");
  18297. if (cmd == "interlacetable") {
  18298. //TODO 待定
  18299. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18300. return (interlaced === "enabled") ? -1 : 0;
  18301. } else {
  18302. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18303. }
  18304. },
  18305. execCommand: function (cmd, classList) {
  18306. var table = getTableItemsByRange(this).table;
  18307. if (cmd == "interlacetable") {
  18308. table.setAttribute("interlaced", "enabled");
  18309. this.fireEvent("interlacetable", table, classList);
  18310. } else {
  18311. table.setAttribute("interlaced", "disabled");
  18312. this.fireEvent("uninterlacetable", table);
  18313. }
  18314. }
  18315. };
  18316. UE.commands["setbordervisible"] = {
  18317. queryCommandState: function (cmd) {
  18318. var table = getTableItemsByRange(this).table;
  18319. if (!table) return -1;
  18320. return 0;
  18321. },
  18322. execCommand: function () {
  18323. var table = getTableItemsByRange(this).table;
  18324. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  18325. td.style.borderWidth = '1px';
  18326. td.style.borderStyle = 'solid';
  18327. })
  18328. }
  18329. };
  18330. function resetTdWidth(table, editor) {
  18331. var tds = domUtils.getElementsByTagName(table,'td th');
  18332. utils.each(tds, function (td) {
  18333. td.removeAttribute("width");
  18334. });
  18335. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18336. var tdsWidths = [];
  18337. setTimeout(function () {
  18338. utils.each(tds, function (td) {
  18339. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18340. })
  18341. utils.each(tds, function (td,i) {
  18342. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18343. })
  18344. }, 0);
  18345. }
  18346. function getTableWidth(editor, needIEHack, defaultValue) {
  18347. var body = editor.body;
  18348. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18349. }
  18350. function getSelectedArr(editor) {
  18351. var cell = getTableItemsByRange(editor).cell;
  18352. if (cell) {
  18353. var ut = getUETable(cell);
  18354. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18355. } else {
  18356. return [];
  18357. }
  18358. }
  18359. })();
  18360. // plugins/table.action.js
  18361. /**
  18362. * Created with JetBrains PhpStorm.
  18363. * User: taoqili
  18364. * Date: 12-10-12
  18365. * Time: 上午10:05
  18366. * To change this template use File | Settings | File Templates.
  18367. */
  18368. UE.plugins['table'] = function () {
  18369. var me = this,
  18370. tabTimer = null,
  18371. //拖动计时器
  18372. tableDragTimer = null,
  18373. //双击计时器
  18374. tableResizeTimer = null,
  18375. //单元格最小宽度
  18376. cellMinWidth = 5,
  18377. isInResizeBuffer = false,
  18378. //单元格边框大小
  18379. cellBorderWidth = 5,
  18380. //鼠标偏移距离
  18381. offsetOfTableCell = 10,
  18382. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18383. singleClickState = 0,
  18384. userActionStatus = null,
  18385. //双击允许的时间范围
  18386. dblclickTime = 360,
  18387. UT = UE.UETable,
  18388. getUETable = function (tdOrTable) {
  18389. return UT.getUETable(tdOrTable);
  18390. },
  18391. getUETableBySelected = function (editor) {
  18392. return UT.getUETableBySelected(editor);
  18393. },
  18394. getDefaultValue = function (editor, table) {
  18395. return UT.getDefaultValue(editor, table);
  18396. },
  18397. removeSelectedClass = function (cells) {
  18398. return UT.removeSelectedClass(cells);
  18399. };
  18400. function showError(e) {
  18401. // throw e;
  18402. }
  18403. me.ready(function(){
  18404. var me = this;
  18405. var orgGetText = me.selection.getText;
  18406. me.selection.getText = function(){
  18407. var table = getUETableBySelected(me);
  18408. if(table){
  18409. var str = '';
  18410. utils.each(table.selectedTds,function(td){
  18411. str += td[browser.ie?'innerText':'textContent'];
  18412. })
  18413. return str;
  18414. }else{
  18415. return orgGetText.call(me.selection)
  18416. }
  18417. }
  18418. })
  18419. //处理拖动及框选相关方法
  18420. var startTd = null, //鼠标按下时的锚点td
  18421. currentTd = null, //当前鼠标经过时的td
  18422. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18423. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18424. dragButton = null,
  18425. dragOver = false,
  18426. dragLine = null, //模拟的拖动线
  18427. dragTd = null; //发生拖动的目标td
  18428. var mousedown = false,
  18429. //todo 判断混乱模式
  18430. needIEHack = true;
  18431. me.setOpt({
  18432. 'maxColNum':20,
  18433. 'maxRowNum':100,
  18434. 'defaultCols':5,
  18435. 'defaultRows':5,
  18436. 'tdvalign':'top',
  18437. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18438. 'tableDragable':false,
  18439. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  18440. });
  18441. me.getUETable = getUETable;
  18442. var commands = {
  18443. 'deletetable':1,
  18444. 'inserttable':1,
  18445. 'cellvalign':1,
  18446. 'insertcaption':1,
  18447. 'deletecaption':1,
  18448. 'inserttitle':1,
  18449. 'deletetitle':1,
  18450. "mergeright":1,
  18451. "mergedown":1,
  18452. "mergecells":1,
  18453. "insertrow":1,
  18454. "insertrownext":1,
  18455. "deleterow":1,
  18456. "insertcol":1,
  18457. "insertcolnext":1,
  18458. "deletecol":1,
  18459. "splittocells":1,
  18460. "splittorows":1,
  18461. "splittocols":1,
  18462. "adaptbytext":1,
  18463. "adaptbywindow":1,
  18464. "adaptbycustomer":1,
  18465. "insertparagraph":1,
  18466. "insertparagraphbeforetable":1,
  18467. "averagedistributecol":1,
  18468. "averagedistributerow":1
  18469. };
  18470. me.ready(function () {
  18471. utils.cssRule('table',
  18472. //选中的td上的样式
  18473. '.selectTdClass{background-color:#edf5fa !important}' +
  18474. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18475. //插入的表格的默认样式
  18476. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18477. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18478. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18479. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18480. 'table tr.firstRow th{border-top-width:2px;}' +
  18481. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18482. 'td p{margin:0;padding:0;}', me.document);
  18483. var tableCopyList, isFullCol, isFullRow;
  18484. //注册del/backspace事件
  18485. me.addListener('keydown', function (cmd, evt) {
  18486. var me = this;
  18487. var keyCode = evt.keyCode || evt.which;
  18488. if (keyCode == 8) {
  18489. var ut = getUETableBySelected(me);
  18490. if (ut && ut.selectedTds.length) {
  18491. if (ut.isFullCol()) {
  18492. me.execCommand('deletecol')
  18493. } else if (ut.isFullRow()) {
  18494. me.execCommand('deleterow')
  18495. } else {
  18496. me.fireEvent('delcells');
  18497. }
  18498. domUtils.preventDefault(evt);
  18499. }
  18500. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18501. range = me.selection.getRange();
  18502. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18503. me.fireEvent('saveScene');
  18504. var table = caption.parentNode;
  18505. domUtils.remove(caption);
  18506. if (table) {
  18507. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18508. }
  18509. me.fireEvent('saveScene');
  18510. }
  18511. }
  18512. if (keyCode == 46) {
  18513. ut = getUETableBySelected(me);
  18514. if (ut) {
  18515. me.fireEvent('saveScene');
  18516. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  18517. domUtils.fillNode(me.document, ci)
  18518. }
  18519. me.fireEvent('saveScene');
  18520. domUtils.preventDefault(evt);
  18521. }
  18522. }
  18523. if (keyCode == 13) {
  18524. var rng = me.selection.getRange(),
  18525. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  18526. if (caption) {
  18527. var table = domUtils.findParentByTagName(caption, 'table');
  18528. if (!rng.collapsed) {
  18529. rng.deleteContents();
  18530. me.fireEvent('saveScene');
  18531. } else {
  18532. if (caption) {
  18533. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18534. }
  18535. }
  18536. domUtils.preventDefault(evt);
  18537. return;
  18538. }
  18539. if (rng.collapsed) {
  18540. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18541. if (table) {
  18542. var cell = table.rows[0].cells[0],
  18543. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  18544. preNode = table.previousSibling;
  18545. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  18546. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  18547. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  18548. me.execCommand('insertparagraphbeforetable');
  18549. domUtils.preventDefault(evt);
  18550. }
  18551. }
  18552. }
  18553. }
  18554. }
  18555. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  18556. tableCopyList = null;
  18557. var ut = getUETableBySelected(me);
  18558. if (ut) {
  18559. var tds = ut.selectedTds;
  18560. isFullCol = ut.isFullCol();
  18561. isFullRow = ut.isFullRow();
  18562. tableCopyList = [
  18563. [ut.cloneCell(tds[0],null,true)]
  18564. ];
  18565. for (var i = 1, ci; ci = tds[i]; i++) {
  18566. if (ci.parentNode !== tds[i - 1].parentNode) {
  18567. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  18568. } else {
  18569. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  18570. }
  18571. }
  18572. }
  18573. }
  18574. });
  18575. me.addListener("tablehasdeleted",function(){
  18576. toggleDraggableState(this, false, "", null);
  18577. if (dragButton)domUtils.remove(dragButton);
  18578. });
  18579. me.addListener('beforepaste', function (cmd, html) {
  18580. var me = this;
  18581. var rng = me.selection.getRange();
  18582. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  18583. var div = me.document.createElement("div");
  18584. div.innerHTML = html.html;
  18585. //trace:3729
  18586. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  18587. return;
  18588. }
  18589. var table = getUETableBySelected(me);
  18590. if (tableCopyList) {
  18591. me.fireEvent('saveScene');
  18592. var rng = me.selection.getRange();
  18593. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  18594. if (td) {
  18595. var ut = getUETable(td);
  18596. if (isFullRow) {
  18597. var rowIndex = ut.getCellInfo(td).rowIndex;
  18598. if (td.tagName == 'TH') {
  18599. rowIndex++;
  18600. }
  18601. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18602. var tr = ut.insertRow(rowIndex++, "td");
  18603. for (var j = 0, cj; cj = ci[j]; j++) {
  18604. var cell = tr.cells[j];
  18605. if (!cell) {
  18606. cell = tr.insertCell(j)
  18607. }
  18608. cell.innerHTML = cj.innerHTML;
  18609. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  18610. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18611. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  18612. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  18613. }
  18614. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  18615. if (!ci[j])
  18616. break;
  18617. cj.innerHTML = ci[j].innerHTML;
  18618. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  18619. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  18620. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  18621. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  18622. }
  18623. }
  18624. } else {
  18625. if (isFullCol) {
  18626. cellInfo = ut.getCellInfo(td);
  18627. var maxColNum = 0;
  18628. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  18629. maxColNum += cj.colSpan || 1;
  18630. }
  18631. me.__hasEnterExecCommand = true;
  18632. for (i = 0; i < maxColNum; i++) {
  18633. me.execCommand('insertcol');
  18634. }
  18635. me.__hasEnterExecCommand = false;
  18636. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  18637. if (td.tagName == 'TH') {
  18638. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  18639. }
  18640. }
  18641. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18642. tmpNode = td;
  18643. for (var j = 0, cj; cj = ci[j++];) {
  18644. if (td) {
  18645. td.innerHTML = cj.innerHTML;
  18646. //todo 定制处理
  18647. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  18648. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18649. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  18650. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  18651. preNode = td;
  18652. td = td.nextSibling;
  18653. } else {
  18654. var cloneTd = cj.cloneNode(true);
  18655. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  18656. preNode.parentNode.appendChild(cloneTd)
  18657. }
  18658. }
  18659. td = ut.getNextCell(tmpNode, true, true);
  18660. if (!tableCopyList[i])
  18661. break;
  18662. if (!td) {
  18663. var cellInfo = ut.getCellInfo(tmpNode);
  18664. ut.table.insertRow(ut.table.rows.length);
  18665. ut.update();
  18666. td = ut.getVSideCell(tmpNode, true);
  18667. }
  18668. }
  18669. }
  18670. ut.update();
  18671. } else {
  18672. table = me.document.createElement('table');
  18673. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18674. var tr = table.insertRow(table.rows.length);
  18675. for (var j = 0, cj; cj = ci[j++];) {
  18676. cloneTd = UT.cloneCell(cj,null,true);
  18677. domUtils.removeAttributes(cloneTd, ['class']);
  18678. tr.appendChild(cloneTd)
  18679. }
  18680. if (j == 2 && cloneTd.rowSpan > 1) {
  18681. cloneTd.rowSpan = 1;
  18682. }
  18683. }
  18684. var defaultValue = getDefaultValue(me),
  18685. width = me.body.offsetWidth -
  18686. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  18687. me.execCommand('insertHTML', '<table ' +
  18688. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  18689. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  18690. }
  18691. me.fireEvent('contentchange');
  18692. me.fireEvent('saveScene');
  18693. html.html = '';
  18694. return true;
  18695. } else {
  18696. var div = me.document.createElement("div"), tables;
  18697. div.innerHTML = html.html;
  18698. tables = div.getElementsByTagName("table");
  18699. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  18700. utils.each(tables, function (t) {
  18701. domUtils.remove(t)
  18702. });
  18703. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  18704. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  18705. }
  18706. } else {
  18707. utils.each(tables, function (table) {
  18708. removeStyleSize(table, true);
  18709. domUtils.removeAttributes(table, ['style', 'border']);
  18710. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  18711. if (isEmptyBlock(td)) {
  18712. domUtils.fillNode(me.document, td);
  18713. }
  18714. removeStyleSize(td, true);
  18715. // domUtils.removeAttributes(td, ['style'])
  18716. });
  18717. });
  18718. }
  18719. html.html = div.innerHTML;
  18720. }
  18721. });
  18722. me.addListener('afterpaste', function () {
  18723. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  18724. if (table.offsetWidth > me.body.offsetWidth) {
  18725. var defaultValue = getDefaultValue(me, table);
  18726. 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'
  18727. }
  18728. })
  18729. });
  18730. me.addListener('blur', function () {
  18731. tableCopyList = null;
  18732. });
  18733. var timer;
  18734. me.addListener('keydown', function () {
  18735. clearTimeout(timer);
  18736. timer = setTimeout(function () {
  18737. var rng = me.selection.getRange(),
  18738. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  18739. if (cell) {
  18740. var table = cell.parentNode.parentNode.parentNode;
  18741. if (table.offsetWidth > table.getAttribute("width")) {
  18742. cell.style.wordBreak = "break-all";
  18743. }
  18744. }
  18745. }, 100);
  18746. });
  18747. me.addListener("selectionchange", function () {
  18748. toggleDraggableState(me, false, "", null);
  18749. });
  18750. //内容变化时触发索引更新
  18751. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  18752. me.addListener("contentchange", function () {
  18753. var me = this;
  18754. //尽可能排除一些不需要更新的状况
  18755. hideDragLine(me);
  18756. if (getUETableBySelected(me))return;
  18757. var rng = me.selection.getRange();
  18758. var start = rng.startContainer;
  18759. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  18760. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  18761. if (me.fireEvent("excludetable", table) === true) return;
  18762. table.ueTable = new UT(table);
  18763. //trace:3742
  18764. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  18765. //
  18766. // if (domUtils.isEmptyBlock(td) && td !== start) {
  18767. // domUtils.fillNode(me.document, td);
  18768. // if (browser.ie && browser.version == 6) {
  18769. // td.innerHTML = '&nbsp;'
  18770. // }
  18771. // }
  18772. // });
  18773. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  18774. // if (domUtils.isEmptyBlock(th) && th !== start) {
  18775. // domUtils.fillNode(me.document, th);
  18776. // if (browser.ie && browser.version == 6) {
  18777. // th.innerHTML = '&nbsp;'
  18778. // }
  18779. // }
  18780. // });
  18781. table.onmouseover = function () {
  18782. me.fireEvent('tablemouseover', table);
  18783. };
  18784. table.onmousemove = function () {
  18785. me.fireEvent('tablemousemove', table);
  18786. me.options.tableDragable && toggleDragButton(true, this, me);
  18787. utils.defer(function(){
  18788. me.fireEvent('contentchange',50)
  18789. },true)
  18790. };
  18791. table.onmouseout = function () {
  18792. me.fireEvent('tablemouseout', table);
  18793. toggleDraggableState(me, false, "", null);
  18794. hideDragLine(me);
  18795. };
  18796. table.onclick = function (evt) {
  18797. evt = me.window.event || evt;
  18798. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18799. if (!target)return;
  18800. var ut = getUETable(target),
  18801. table = ut.table,
  18802. cellInfo = ut.getCellInfo(target),
  18803. cellsRange,
  18804. rng = me.selection.getRange();
  18805. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  18806. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  18807. // ut.setSelected(cellsRange);
  18808. // return;
  18809. // }
  18810. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  18811. //
  18812. // return;
  18813. // }
  18814. if (inTableSide(table, target, evt, true)) {
  18815. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  18816. if (evt.shiftKey && ut.selectedTds.length) {
  18817. if (ut.selectedTds[0] !== endTdCol) {
  18818. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  18819. ut.setSelected(cellsRange);
  18820. } else {
  18821. rng && rng.selectNodeContents(endTdCol).select();
  18822. }
  18823. } else {
  18824. if (target !== endTdCol) {
  18825. cellsRange = ut.getCellsRange(target, endTdCol);
  18826. ut.setSelected(cellsRange);
  18827. } else {
  18828. rng && rng.selectNodeContents(endTdCol).select();
  18829. }
  18830. }
  18831. return;
  18832. }
  18833. if (inTableSide(table, target, evt)) {
  18834. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  18835. if (evt.shiftKey && ut.selectedTds.length) {
  18836. if (ut.selectedTds[0] !== endTdRow) {
  18837. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  18838. ut.setSelected(cellsRange);
  18839. } else {
  18840. rng && rng.selectNodeContents(endTdRow).select();
  18841. }
  18842. } else {
  18843. if (target !== endTdRow) {
  18844. cellsRange = ut.getCellsRange(target, endTdRow);
  18845. ut.setSelected(cellsRange);
  18846. } else {
  18847. rng && rng.selectNodeContents(endTdRow).select();
  18848. }
  18849. }
  18850. }
  18851. };
  18852. });
  18853. switchBorderColor(me, true);
  18854. });
  18855. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18856. domUtils.on(me.document, "mouseout", function (evt) {
  18857. var target = evt.target || evt.srcElement;
  18858. if (target.tagName == "TABLE") {
  18859. toggleDraggableState(me, false, "", null);
  18860. }
  18861. });
  18862. /**
  18863. * 表格隔行变色
  18864. */
  18865. me.addListener("interlacetable",function(type,table,classList){
  18866. if(!table) return;
  18867. var me = this,
  18868. rows = table.rows,
  18869. len = rows.length,
  18870. getClass = function(list,index,repeat){
  18871. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18872. };
  18873. for(var i = 0;i<len;i++){
  18874. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18875. }
  18876. });
  18877. me.addListener("uninterlacetable",function(type,table){
  18878. if(!table) return;
  18879. var me = this,
  18880. rows = table.rows,
  18881. classList = me.options.classList,
  18882. len = rows.length;
  18883. for(var i = 0;i<len;i++){
  18884. domUtils.removeClasses( rows[i], classList );
  18885. }
  18886. });
  18887. me.addListener("mousedown", mouseDownEvent);
  18888. me.addListener("mouseup", mouseUpEvent);
  18889. //拖动的时候触发mouseup
  18890. domUtils.on( me.body, 'dragstart', function( evt ){
  18891. mouseUpEvent.call( me, 'dragstart', evt );
  18892. });
  18893. me.addOutputRule(function(root){
  18894. utils.each(root.getNodesByTagName('div'),function(n){
  18895. if (n.getAttr('id') == 'ue_tableDragLine') {
  18896. n.parentNode.removeChild(n);
  18897. }
  18898. });
  18899. });
  18900. var currentRowIndex = 0;
  18901. me.addListener("mousedown", function () {
  18902. currentRowIndex = 0;
  18903. });
  18904. me.addListener('tabkeydown', function () {
  18905. var range = this.selection.getRange(),
  18906. common = range.getCommonAncestor(true, true),
  18907. table = domUtils.findParentByTagName(common, 'table');
  18908. if (table) {
  18909. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18910. var cell = domUtils.getElementsByTagName(table, 'th td');
  18911. if (cell && cell.length) {
  18912. range.setStart(cell[0], 0).setCursor(false, true)
  18913. }
  18914. } else {
  18915. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18916. ua = getUETable(cell);
  18917. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18918. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18919. if (nextCell) {
  18920. if (isEmptyBlock(nextCell)) {
  18921. range.setStart(nextCell, 0).setCursor(false, true)
  18922. } else {
  18923. range.selectNodeContents(nextCell).select()
  18924. }
  18925. } else {
  18926. me.fireEvent('saveScene');
  18927. me.__hasEnterExecCommand = true;
  18928. this.execCommand('insertrownext');
  18929. me.__hasEnterExecCommand = false;
  18930. range = this.selection.getRange();
  18931. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18932. me.fireEvent('saveScene');
  18933. }
  18934. }
  18935. return true;
  18936. }
  18937. });
  18938. browser.ie && me.addListener('selectionchange', function () {
  18939. toggleDraggableState(this, false, "", null);
  18940. });
  18941. me.addListener("keydown", function (type, evt) {
  18942. var me = this;
  18943. //处理在表格的最后一个输入tab产生新的表格
  18944. var keyCode = evt.keyCode || evt.which;
  18945. if (keyCode == 8 || keyCode == 46) {
  18946. return;
  18947. }
  18948. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18949. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18950. var ut = getUETableBySelected(me);
  18951. if (!ut) return;
  18952. notCtrlKey && ut.clearSelected();
  18953. });
  18954. me.addListener("beforegetcontent", function () {
  18955. switchBorderColor(this, false);
  18956. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18957. if (domUtils.isEmptyNode(ci)) {
  18958. ci.innerHTML = '&nbsp;'
  18959. }
  18960. });
  18961. });
  18962. me.addListener("aftergetcontent", function () {
  18963. switchBorderColor(this, true);
  18964. });
  18965. me.addListener("getAllHtml", function () {
  18966. removeSelectedClass(me.document.getElementsByTagName("td"));
  18967. });
  18968. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18969. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18970. if (!fullscreen) {
  18971. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18972. tables = domUtils.getElementsByTagName(this.body, "table");
  18973. utils.each(tables, function (table) {
  18974. if (table.offsetWidth < me.body.offsetWidth) return false;
  18975. var tds = domUtils.getElementsByTagName(table, "td"),
  18976. backWidths = [];
  18977. utils.each(tds, function (td) {
  18978. backWidths.push(td.offsetWidth);
  18979. });
  18980. for (var i = 0, td; td = tds[i]; i++) {
  18981. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18982. }
  18983. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18984. });
  18985. }
  18986. });
  18987. //重写execCommand命令,用于处理框选时的处理
  18988. var oldExecCommand = me.execCommand;
  18989. me.execCommand = function (cmd, datatat) {
  18990. var me = this,
  18991. args = arguments;
  18992. cmd = cmd.toLowerCase();
  18993. var ut = getUETableBySelected(me), tds,
  18994. range = new dom.Range(me.document),
  18995. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18996. result;
  18997. if (!cmdFun) return;
  18998. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18999. me.__hasEnterExecCommand = true;
  19000. me.fireEvent("beforeexeccommand", cmd);
  19001. tds = ut.selectedTds;
  19002. var lastState = -2, lastValue = -2, value, state;
  19003. for (var i = 0, td; td = tds[i]; i++) {
  19004. if (isEmptyBlock(td)) {
  19005. range.setStart(td, 0).setCursor(false, true)
  19006. } else {
  19007. range.selectNode(td).select(true);
  19008. }
  19009. state = me.queryCommandState(cmd);
  19010. value = me.queryCommandValue(cmd);
  19011. if (state != -1) {
  19012. if (lastState !== state || lastValue !== value) {
  19013. me._ignoreContentChange = true;
  19014. result = oldExecCommand.apply(me, arguments);
  19015. me._ignoreContentChange = false;
  19016. }
  19017. lastState = me.queryCommandState(cmd);
  19018. lastValue = me.queryCommandValue(cmd);
  19019. if (domUtils.isEmptyBlock(td)) {
  19020. domUtils.fillNode(me.document, td)
  19021. }
  19022. }
  19023. }
  19024. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  19025. me.fireEvent('contentchange');
  19026. me.fireEvent("afterexeccommand", cmd);
  19027. me.__hasEnterExecCommand = false;
  19028. me._selectionChange();
  19029. } else {
  19030. result = oldExecCommand.apply(me, arguments);
  19031. }
  19032. return result;
  19033. };
  19034. });
  19035. /**
  19036. * 删除obj的宽高style,改成属性宽高
  19037. * @param obj
  19038. * @param replaceToProperty
  19039. */
  19040. function removeStyleSize(obj, replaceToProperty) {
  19041. removeStyle(obj, "width", true);
  19042. removeStyle(obj, "height", true);
  19043. }
  19044. function removeStyle(obj, styleName, replaceToProperty) {
  19045. if (obj.style[styleName]) {
  19046. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  19047. obj.style[styleName] = "";
  19048. }
  19049. }
  19050. function getParentTdOrTh(ele) {
  19051. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  19052. var td;
  19053. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  19054. return null;
  19055. }
  19056. function isEmptyBlock(node) {
  19057. var reg = new RegExp(domUtils.fillChar, 'g');
  19058. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  19059. return 0;
  19060. }
  19061. for (var n in dtd.$isNotEmpty) {
  19062. if (node.getElementsByTagName(n).length) {
  19063. return 0;
  19064. }
  19065. }
  19066. return 1;
  19067. }
  19068. function mouseCoords(evt) {
  19069. if (evt.pageX || evt.pageY) {
  19070. return { x:evt.pageX, y:evt.pageY };
  19071. }
  19072. return {
  19073. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19074. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19075. };
  19076. }
  19077. function mouseMoveEvent(evt) {
  19078. if( isEditorDisabled() ) {
  19079. return;
  19080. }
  19081. try {
  19082. //普通状态下鼠标移动
  19083. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19084. pos;
  19085. //区分用户的行为是拖动还是双击
  19086. if( isInResizeBuffer ) {
  19087. me.body.style.webkitUserSelect = 'none';
  19088. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  19089. clearTableDragTimer();
  19090. isInResizeBuffer = false;
  19091. singleClickState = 0;
  19092. //drag action
  19093. tableBorderDrag(evt);
  19094. }
  19095. }
  19096. //修改单元格大小时的鼠标移动
  19097. if (onDrag && dragTd) {
  19098. singleClickState = 0;
  19099. me.body.style.webkitUserSelect = 'none';
  19100. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19101. pos = mouseCoords(evt);
  19102. toggleDraggableState(me, true, onDrag, pos, target);
  19103. if (onDrag == "h") {
  19104. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19105. } else if (onDrag == "v") {
  19106. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19107. }
  19108. return;
  19109. }
  19110. //当鼠标处于table上时,修改移动过程中的光标状态
  19111. if (target) {
  19112. //针对使用table作为容器的组件不触发拖拽效果
  19113. if (me.fireEvent('excludetable', target) === true)
  19114. return;
  19115. pos = mouseCoords(evt);
  19116. var state = getRelation(target, pos),
  19117. table = domUtils.findParentByTagName(target, "table", true);
  19118. if (inTableSide(table, target, evt, true)) {
  19119. if (me.fireEvent("excludetable", table) === true) return;
  19120. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19121. } else if (inTableSide(table, target, evt)) {
  19122. if (me.fireEvent("excludetable", table) === true) return;
  19123. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19124. } else {
  19125. me.body.style.cursor = "text";
  19126. var curCell = target;
  19127. if (/\d/.test(state)) {
  19128. state = state.replace(/\d/, '');
  19129. target = getUETable(target).getPreviewCell(target, state == "v");
  19130. }
  19131. //位于第一行的顶部或者第一列的左边时不可拖动
  19132. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19133. }
  19134. } else {
  19135. toggleDragButton(false, table, me);
  19136. }
  19137. } catch (e) {
  19138. showError(e);
  19139. }
  19140. }
  19141. var dragButtonTimer;
  19142. function toggleDragButton(show, table, editor) {
  19143. if (!show) {
  19144. if (dragOver)return;
  19145. dragButtonTimer = setTimeout(function () {
  19146. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19147. }, 2000);
  19148. } else {
  19149. createDragButton(table, editor);
  19150. }
  19151. }
  19152. function createDragButton(table, editor) {
  19153. var pos = domUtils.getXY(table),
  19154. doc = table.ownerDocument;
  19155. if (dragButton && dragButton.parentNode)return dragButton;
  19156. dragButton = doc.createElement("div");
  19157. dragButton.contentEditable = false;
  19158. dragButton.innerHTML = "";
  19159. 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;";
  19160. domUtils.unSelectable(dragButton);
  19161. dragButton.onmouseover = function (evt) {
  19162. dragOver = true;
  19163. };
  19164. dragButton.onmouseout = function (evt) {
  19165. dragOver = false;
  19166. };
  19167. domUtils.on(dragButton, 'click', function (type, evt) {
  19168. doClick(evt, this);
  19169. });
  19170. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19171. doDblClick(evt);
  19172. });
  19173. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19174. domUtils.preventDefault(evt);
  19175. });
  19176. var timer;
  19177. function doClick(evt, button) {
  19178. // 部分浏览器下需要清理
  19179. clearTimeout(timer);
  19180. timer = setTimeout(function () {
  19181. editor.fireEvent("tableClicked", table, button);
  19182. }, 300);
  19183. }
  19184. function doDblClick(evt) {
  19185. clearTimeout(timer);
  19186. var ut = getUETable(table),
  19187. start = table.rows[0].cells[0],
  19188. end = ut.getLastCell(),
  19189. range = ut.getCellsRange(start, end);
  19190. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19191. ut.setSelected(range);
  19192. }
  19193. doc.body.appendChild(dragButton);
  19194. }
  19195. // function inPosition(table, pos) {
  19196. // var tablePos = domUtils.getXY(table),
  19197. // width = table.offsetWidth,
  19198. // height = table.offsetHeight;
  19199. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19200. // return "topLeft";
  19201. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19202. // return "bottomRight";
  19203. // }
  19204. // }
  19205. function inTableSide(table, cell, evt, top) {
  19206. var pos = mouseCoords(evt),
  19207. state = getRelation(cell, pos);
  19208. if (top) {
  19209. var caption = table.getElementsByTagName("caption")[0],
  19210. capHeight = caption ? caption.offsetHeight : 0;
  19211. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19212. } else {
  19213. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19214. }
  19215. }
  19216. /**
  19217. * 获取拖动时允许的X轴坐标
  19218. * @param dragTd
  19219. * @param evt
  19220. */
  19221. function getPermissionX(dragTd, evt) {
  19222. var ut = getUETable(dragTd);
  19223. if (ut) {
  19224. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19225. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19226. mouseX = mouseCoords(evt).x,
  19227. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  19228. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19229. left += cellMinWidth;
  19230. right -= cellMinWidth;
  19231. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19232. }
  19233. }
  19234. /**
  19235. * 获取拖动时允许的Y轴坐标
  19236. */
  19237. function getPermissionY(dragTd, evt) {
  19238. try {
  19239. var top = domUtils.getXY(dragTd).y,
  19240. mousePosY = mouseCoords(evt).y;
  19241. return mousePosY < top ? top : mousePosY;
  19242. } catch (e) {
  19243. showError(e);
  19244. }
  19245. }
  19246. /**
  19247. * 移动状态切换
  19248. */
  19249. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19250. try {
  19251. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19252. if (browser.ie) {
  19253. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19254. getDragLine(editor, editor.document);
  19255. showDragLineAt(dir, cell);
  19256. } else {
  19257. hideDragLine(editor)
  19258. }
  19259. }
  19260. onBorder = draggable;
  19261. } catch (e) {
  19262. showError(e);
  19263. }
  19264. }
  19265. /**
  19266. * 获取与UETable相关的resize line
  19267. * @param uetable UETable对象
  19268. */
  19269. function getResizeLineByUETable() {
  19270. var lineId = '_UETableResizeLine',
  19271. line = this.document.getElementById( lineId );
  19272. if( !line ) {
  19273. line = this.document.createElement("div");
  19274. line.id = lineId;
  19275. line.contnetEditable = false;
  19276. line.setAttribute("unselectable", "on");
  19277. var styles = {
  19278. width: 2*cellBorderWidth + 1 + 'px',
  19279. position: 'absolute',
  19280. 'z-index': 100000,
  19281. cursor: 'col-resize',
  19282. background: 'red',
  19283. display: 'none'
  19284. };
  19285. //切换状态
  19286. line.onmouseout = function(){
  19287. this.style.display = 'none';
  19288. };
  19289. utils.extend( line.style, styles );
  19290. this.document.body.appendChild( line );
  19291. }
  19292. return line;
  19293. }
  19294. /**
  19295. * 更新resize-line
  19296. */
  19297. function updateResizeLine( cell, uetable ) {
  19298. var line = getResizeLineByUETable.call( this ),
  19299. table = uetable.table,
  19300. styles = {
  19301. top: domUtils.getXY( table ).y + 'px',
  19302. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19303. display: 'block',
  19304. height: table.offsetHeight + 'px'
  19305. };
  19306. utils.extend( line.style, styles );
  19307. }
  19308. /**
  19309. * 显示resize-line
  19310. */
  19311. function showResizeLine( cell ) {
  19312. var uetable = getUETable( cell );
  19313. updateResizeLine.call( this, cell, uetable );
  19314. }
  19315. /**
  19316. * 获取鼠标与当前单元格的相对位置
  19317. * @param ele
  19318. * @param mousePos
  19319. */
  19320. function getRelation(ele, mousePos) {
  19321. var elePos = domUtils.getXY(ele);
  19322. if( !elePos ) {
  19323. return '';
  19324. }
  19325. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  19326. return "h";
  19327. }
  19328. if (mousePos.x - elePos.x < cellBorderWidth) {
  19329. return 'h1'
  19330. }
  19331. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19332. return "v";
  19333. }
  19334. if (mousePos.y - elePos.y < cellBorderWidth) {
  19335. return 'v1'
  19336. }
  19337. return '';
  19338. }
  19339. function mouseDownEvent(type, evt) {
  19340. if( isEditorDisabled() ) {
  19341. return ;
  19342. }
  19343. userActionStatus = {
  19344. x: evt.clientX,
  19345. y: evt.clientY
  19346. };
  19347. //右键菜单单独处理
  19348. if (evt.button == 2) {
  19349. var ut = getUETableBySelected(me),
  19350. flag = false;
  19351. if (ut) {
  19352. var td = getTargetTd(me, evt);
  19353. utils.each(ut.selectedTds, function (ti) {
  19354. if (ti === td) {
  19355. flag = true;
  19356. }
  19357. });
  19358. if (!flag) {
  19359. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19360. ut.clearSelected()
  19361. } else {
  19362. td = ut.selectedTds[0];
  19363. setTimeout(function () {
  19364. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19365. }, 0);
  19366. }
  19367. }
  19368. } else {
  19369. tableClickHander( evt );
  19370. }
  19371. }
  19372. //清除表格的计时器
  19373. function clearTableTimer() {
  19374. tabTimer && clearTimeout( tabTimer );
  19375. tabTimer = null;
  19376. }
  19377. //双击收缩
  19378. function tableDbclickHandler(evt) {
  19379. singleClickState = 0;
  19380. evt = evt || me.window.event;
  19381. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19382. if (target) {
  19383. var h;
  19384. if (h = getRelation(target, mouseCoords(evt))) {
  19385. hideDragLine( me );
  19386. if (h == 'h1') {
  19387. h = 'h';
  19388. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19389. me.execCommand('adaptbywindow');
  19390. } else {
  19391. target = getUETable(target).getPreviewCell(target);
  19392. if (target) {
  19393. var rng = me.selection.getRange();
  19394. rng.selectNodeContents(target).setCursor(true, true)
  19395. }
  19396. }
  19397. }
  19398. if (h == 'h') {
  19399. var ut = getUETable(target),
  19400. table = ut.table,
  19401. cells = getCellsByMoveBorder( target, table, true );
  19402. cells = extractArray( cells, 'left' );
  19403. ut.width = ut.offsetWidth;
  19404. var oldWidth = [],
  19405. newWidth = [];
  19406. utils.each( cells, function( cell ){
  19407. oldWidth.push( cell.offsetWidth );
  19408. } );
  19409. utils.each( cells, function( cell ){
  19410. cell.removeAttribute("width");
  19411. } );
  19412. window.setTimeout( function(){
  19413. //是否允许改变
  19414. var changeable = true;
  19415. utils.each( cells, function( cell, index ){
  19416. var width = cell.offsetWidth;
  19417. if( width > oldWidth[index] ) {
  19418. changeable = false;
  19419. return false;
  19420. }
  19421. newWidth.push( width );
  19422. } );
  19423. var change = changeable ? newWidth : oldWidth;
  19424. utils.each( cells, function( cell, index ){
  19425. cell.width = change[index] - getTabcellSpace();
  19426. } );
  19427. }, 0 );
  19428. // minWidth -= cellMinWidth;
  19429. //
  19430. // table.removeAttribute("width");
  19431. // utils.each(cells, function (cell) {
  19432. // cell.style.width = "";
  19433. // cell.width -= minWidth;
  19434. // });
  19435. }
  19436. }
  19437. }
  19438. }
  19439. function tableClickHander( evt ) {
  19440. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19441. //trace:3113
  19442. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19443. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19444. t.ueTable = null;
  19445. });
  19446. startTd = getTargetTd(me, evt);
  19447. if( !startTd ) return;
  19448. var table = domUtils.findParentByTagName(startTd, "table", true);
  19449. ut = getUETable(table);
  19450. ut && ut.clearSelected();
  19451. //判断当前鼠标状态
  19452. if (!onBorder) {
  19453. me.document.body.style.webkitUserSelect = '';
  19454. mousedown = true;
  19455. me.addListener('mouseover', mouseOverEvent);
  19456. } else {
  19457. //边框上的动作处理
  19458. borderActionHandler( evt );
  19459. }
  19460. }
  19461. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  19462. function borderActionHandler( evt ) {
  19463. if ( browser.ie ) {
  19464. evt = reconstruct(evt );
  19465. }
  19466. clearTableDragTimer();
  19467. //是否正在等待resize的缓冲中
  19468. isInResizeBuffer = true;
  19469. tableDragTimer = setTimeout(function(){
  19470. tableBorderDrag( evt );
  19471. }, dblclickTime);
  19472. }
  19473. function extractArray( originArr, key ) {
  19474. var result = [],
  19475. tmp = null;
  19476. for( var i = 0, len = originArr.length; i<len; i++ ) {
  19477. tmp = originArr[ i ][ key ];
  19478. if( tmp ) {
  19479. result.push( tmp );
  19480. }
  19481. }
  19482. return result;
  19483. }
  19484. function clearTableDragTimer() {
  19485. tableDragTimer && clearTimeout(tableDragTimer);
  19486. tableDragTimer = null;
  19487. }
  19488. function reconstruct( obj ) {
  19489. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  19490. newObj = {};
  19491. if( obj ) {
  19492. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  19493. val=obj[ key ];
  19494. val && (newObj[ key ] = val);
  19495. }
  19496. }
  19497. return newObj;
  19498. }
  19499. //边框拖动
  19500. function tableBorderDrag( evt ) {
  19501. isInResizeBuffer = false;
  19502. startTd = evt.target || evt.srcElement;
  19503. if( !startTd ) return;
  19504. var state = getRelation(startTd, mouseCoords(evt));
  19505. if (/\d/.test(state)) {
  19506. state = state.replace(/\d/, '');
  19507. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  19508. }
  19509. hideDragLine(me);
  19510. getDragLine(me, me.document);
  19511. me.fireEvent('saveScene');
  19512. showDragLineAt(state, startTd);
  19513. mousedown = true;
  19514. //拖动开始
  19515. onDrag = state;
  19516. dragTd = startTd;
  19517. }
  19518. function mouseUpEvent(type, evt) {
  19519. if( isEditorDisabled() ) {
  19520. return ;
  19521. }
  19522. clearTableDragTimer();
  19523. isInResizeBuffer = false;
  19524. if( onBorder ) {
  19525. singleClickState = ++singleClickState % 3;
  19526. userActionStatus = {
  19527. x: evt.clientX,
  19528. y: evt.clientY
  19529. };
  19530. tableResizeTimer = setTimeout(function(){
  19531. singleClickState > 0 && singleClickState--;
  19532. }, dblclickTime );
  19533. if( singleClickState === 2 ) {
  19534. singleClickState = 0;
  19535. tableDbclickHandler(evt);
  19536. return;
  19537. }
  19538. }
  19539. if (evt.button == 2)return;
  19540. var me = this;
  19541. //清除表格上原生跨选问题
  19542. var range = me.selection.getRange(),
  19543. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  19544. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  19545. if (start || end) {
  19546. if (start === end) {
  19547. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  19548. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  19549. if (start !== end) {
  19550. me.selection.clearRange()
  19551. }
  19552. } else {
  19553. me.selection.clearRange()
  19554. }
  19555. }
  19556. mousedown = false;
  19557. me.document.body.style.webkitUserSelect = '';
  19558. //拖拽状态下的mouseUP
  19559. if ( onDrag && dragTd ) {
  19560. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19561. singleClickState = 0;
  19562. dragLine = me.document.getElementById('ue_tableDragLine');
  19563. // trace 3973
  19564. if (dragLine) {
  19565. var dragTdPos = domUtils.getXY(dragTd),
  19566. dragLinePos = domUtils.getXY(dragLine);
  19567. switch (onDrag) {
  19568. case "h":
  19569. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  19570. break;
  19571. case "v":
  19572. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  19573. break;
  19574. default:
  19575. }
  19576. onDrag = "";
  19577. dragTd = null;
  19578. hideDragLine(me);
  19579. me.fireEvent('saveScene');
  19580. return;
  19581. }
  19582. }
  19583. //正常状态下的mouseup
  19584. if (!startTd) {
  19585. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  19586. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  19587. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  19588. if (me.fireEvent("excludetable", target) === true) return;
  19589. range = new dom.Range(me.document);
  19590. range.setStart(target, 0).setCursor(false, true);
  19591. }
  19592. } else {
  19593. var ut = getUETable(startTd),
  19594. cell = ut ? ut.selectedTds[0] : null;
  19595. if (cell) {
  19596. range = new dom.Range(me.document);
  19597. if (domUtils.isEmptyBlock(cell)) {
  19598. range.setStart(cell, 0).setCursor(false, true);
  19599. } else {
  19600. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  19601. }
  19602. } else {
  19603. range = me.selection.getRange().shrinkBoundary();
  19604. if (!range.collapsed) {
  19605. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  19606. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  19607. //在table里边的不能清除
  19608. if (start && !end || !start && end || start && end && start !== end) {
  19609. range.setCursor(false, true);
  19610. }
  19611. }
  19612. }
  19613. startTd = null;
  19614. me.removeListener('mouseover', mouseOverEvent);
  19615. }
  19616. me._selectionChange(250, evt);
  19617. }
  19618. function mouseOverEvent(type, evt) {
  19619. if( isEditorDisabled() ) {
  19620. return;
  19621. }
  19622. var me = this,
  19623. tar = evt.target || evt.srcElement;
  19624. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  19625. //需要判断两个TD是否位于同一个表格内
  19626. if (startTd && currentTd &&
  19627. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  19628. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  19629. var ut = getUETable(currentTd);
  19630. if (startTd != currentTd) {
  19631. me.document.body.style.webkitUserSelect = 'none';
  19632. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19633. var range = ut.getCellsRange(startTd, currentTd);
  19634. ut.setSelected(range);
  19635. } else {
  19636. me.document.body.style.webkitUserSelect = '';
  19637. ut.clearSelected();
  19638. }
  19639. }
  19640. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  19641. }
  19642. function setCellHeight(cell, height, backHeight) {
  19643. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  19644. tmpHeight = backHeight + height;
  19645. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  19646. if (cell.style.height) cell.style.height = "";
  19647. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  19648. }
  19649. function getWidth(cell) {
  19650. if (!cell)return 0;
  19651. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  19652. }
  19653. function changeColWidth(cell, changeValue) {
  19654. var ut = getUETable(cell);
  19655. if (ut) {
  19656. //根据当前移动的边框获取相关的单元格
  19657. var table = ut.table,
  19658. cells = getCellsByMoveBorder( cell, table );
  19659. table.style.width = "";
  19660. table.removeAttribute("width");
  19661. //修正改变量
  19662. changeValue = correctChangeValue( changeValue, cell, cells );
  19663. if (cell.nextSibling) {
  19664. var i=0;
  19665. utils.each( cells, function( cellGroup ){
  19666. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  19667. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  19668. } );
  19669. } else {
  19670. utils.each( cells, function( cellGroup ){
  19671. cellGroup.left.width -= -changeValue;
  19672. } );
  19673. }
  19674. }
  19675. }
  19676. function isEditorDisabled() {
  19677. return me.body.contentEditable === "false";
  19678. }
  19679. function changeRowHeight(td, changeValue) {
  19680. if (Math.abs(changeValue) < 10) return;
  19681. var ut = getUETable(td);
  19682. if (ut) {
  19683. var cells = ut.getSameEndPosCells(td, "y"),
  19684. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  19685. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  19686. for (var i = 0, cell; cell = cells[i++];) {
  19687. setCellHeight(cell, changeValue, backHeight);
  19688. }
  19689. }
  19690. }
  19691. /**
  19692. * 获取调整单元格大小的相关单元格
  19693. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  19694. */
  19695. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  19696. if( !table ) {
  19697. table = domUtils.findParentByTagName( cell, 'table' );
  19698. }
  19699. if( !table ) {
  19700. return null;
  19701. }
  19702. //获取到该单元格所在行的序列号
  19703. var index = domUtils.getNodeIndex( cell ),
  19704. temp = cell,
  19705. rows = table.rows,
  19706. colIndex = 0;
  19707. while( temp ) {
  19708. //获取到当前单元格在未发生单元格合并时的序列
  19709. if( temp.nodeType === 1 ) {
  19710. colIndex += (temp.colSpan || 1);
  19711. }
  19712. temp = temp.previousSibling;
  19713. }
  19714. temp = null;
  19715. //记录想关的单元格
  19716. var borderCells = [];
  19717. utils.each(rows, function( tabRow ){
  19718. var cells = tabRow.cells,
  19719. currIndex = 0;
  19720. utils.each( cells, function( tabCell ){
  19721. currIndex += (tabCell.colSpan || 1);
  19722. if( currIndex === colIndex ) {
  19723. borderCells.push({
  19724. left: tabCell,
  19725. right: tabCell.nextSibling || null
  19726. });
  19727. return false;
  19728. } else if( currIndex > colIndex ) {
  19729. if( isContainMergeCell ) {
  19730. borderCells.push({
  19731. left: tabCell
  19732. });
  19733. }
  19734. return false;
  19735. }
  19736. } );
  19737. });
  19738. return borderCells;
  19739. }
  19740. /**
  19741. * 通过给定的单元格集合获取最小的单元格width
  19742. */
  19743. function getMinWidthByTableCells( cells ) {
  19744. var minWidth = Number.MAX_VALUE;
  19745. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  19746. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  19747. }
  19748. return minWidth;
  19749. }
  19750. function correctChangeValue( changeValue, relatedCell, cells ) {
  19751. //为单元格的paading预留空间
  19752. changeValue -= getTabcellSpace();
  19753. if( changeValue < 0 ) {
  19754. return 0;
  19755. }
  19756. changeValue -= getTableCellWidth( relatedCell );
  19757. //确定方向
  19758. var direction = changeValue < 0 ? 'left':'right';
  19759. changeValue = Math.abs(changeValue);
  19760. //只关心非最后一个单元格就可以
  19761. utils.each( cells, function( cellGroup ){
  19762. var curCell = cellGroup[direction];
  19763. //为单元格保留最小空间
  19764. if( curCell ) {
  19765. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  19766. }
  19767. } );
  19768. //修正越界
  19769. changeValue = changeValue < 0 ? 0 : changeValue;
  19770. return direction === 'left' ? -changeValue : changeValue;
  19771. }
  19772. function getTableCellWidth( cell ) {
  19773. var width = 0,
  19774. //偏移纠正量
  19775. offset = 0,
  19776. width = cell.offsetWidth - getTabcellSpace();
  19777. //最后一个节点纠正一下
  19778. if( !cell.nextSibling ) {
  19779. width -= getTableCellOffset( cell );
  19780. }
  19781. width = width < 0 ? 0 : width;
  19782. try {
  19783. cell.width = width;
  19784. } catch(e) {
  19785. }
  19786. return width;
  19787. }
  19788. /**
  19789. * 获取单元格所在表格的最末单元格的偏移量
  19790. */
  19791. function getTableCellOffset( cell ) {
  19792. tab = domUtils.findParentByTagName( cell, "table", false);
  19793. if( tab.offsetVal === undefined ) {
  19794. var prev = cell.previousSibling;
  19795. if( prev ) {
  19796. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  19797. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  19798. } else {
  19799. tab.offsetVal = 0;
  19800. }
  19801. }
  19802. return tab.offsetVal;
  19803. }
  19804. function getTabcellSpace() {
  19805. if( UT.tabcellSpace === undefined ) {
  19806. var cell = null,
  19807. tab = me.document.createElement("table"),
  19808. tbody = me.document.createElement("tbody"),
  19809. trow = me.document.createElement("tr"),
  19810. tabcell = me.document.createElement("td"),
  19811. mirror = null;
  19812. tabcell.style.cssText = 'border: 0;';
  19813. tabcell.width = 1;
  19814. trow.appendChild( tabcell );
  19815. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  19816. tbody.appendChild( trow );
  19817. tab.appendChild( tbody );
  19818. tab.style.cssText = "visibility: hidden;";
  19819. me.body.appendChild( tab );
  19820. UT.paddingSpace = tabcell.offsetWidth - 1;
  19821. var tmpTabWidth = tab.offsetWidth;
  19822. tabcell.style.cssText = '';
  19823. mirror.style.cssText = '';
  19824. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  19825. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  19826. me.body.removeChild( tab );
  19827. }
  19828. getTabcellSpace = function(){ return UT.tabcellSpace; };
  19829. return UT.tabcellSpace;
  19830. }
  19831. function getDragLine(editor, doc) {
  19832. if (mousedown)return;
  19833. dragLine = editor.document.createElement("div");
  19834. domUtils.setAttributes(dragLine, {
  19835. id:"ue_tableDragLine",
  19836. unselectable:'on',
  19837. contenteditable:false,
  19838. 'onresizestart':'return false',
  19839. 'ondragstart':'return false',
  19840. 'onselectstart':'return false',
  19841. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  19842. });
  19843. editor.body.appendChild(dragLine);
  19844. }
  19845. function hideDragLine(editor) {
  19846. if (mousedown)return;
  19847. var line;
  19848. while (line = editor.document.getElementById('ue_tableDragLine')) {
  19849. domUtils.remove(line)
  19850. }
  19851. }
  19852. /**
  19853. * 依据state(v|h)在cell位置显示横线
  19854. * @param state
  19855. * @param cell
  19856. */
  19857. function showDragLineAt(state, cell) {
  19858. if (!cell) return;
  19859. var table = domUtils.findParentByTagName(cell, "table"),
  19860. caption = table.getElementsByTagName('caption'),
  19861. width = table.offsetWidth,
  19862. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  19863. tablePos = domUtils.getXY(table),
  19864. cellPos = domUtils.getXY(cell), css;
  19865. switch (state) {
  19866. case "h":
  19867. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19868. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19869. break;
  19870. case "v":
  19871. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19872. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19873. 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)';
  19874. break;
  19875. default:
  19876. }
  19877. }
  19878. /**
  19879. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19880. * @param editor
  19881. * @param flag
  19882. */
  19883. function switchBorderColor(editor, flag) {
  19884. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19885. for (var i = 0, node; node = tableArr[i++];) {
  19886. var td = domUtils.getElementsByTagName(node, "td");
  19887. if (td[0]) {
  19888. if (flag) {
  19889. color = (td[0].style.borderColor).replace(/\s/g, "");
  19890. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19891. domUtils.addClass(node, "noBorderTable")
  19892. } else {
  19893. domUtils.removeClasses(node, "noBorderTable")
  19894. }
  19895. }
  19896. }
  19897. }
  19898. function getTableWidth(editor, needIEHack, defaultValue) {
  19899. var body = editor.body;
  19900. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19901. }
  19902. /**
  19903. * 获取当前拖动的单元格
  19904. */
  19905. function getTargetTd(editor, evt) {
  19906. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19907. dir = null;
  19908. if( !target ) {
  19909. return null;
  19910. }
  19911. dir = getRelation( target, mouseCoords( evt ) );
  19912. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19913. if( !target ) {
  19914. return null;
  19915. }
  19916. if( dir === 'h1' && target.previousSibling ) {
  19917. var position = domUtils.getXY( target),
  19918. cellWidth = target.offsetWidth;
  19919. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19920. target = target.previousSibling;
  19921. }
  19922. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19923. var position = domUtils.getXY( target),
  19924. cellHeight = target.offsetHeight;
  19925. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19926. target = target.parentNode.previousSibling.firstChild;
  19927. }
  19928. }
  19929. //排除了非td内部以及用于代码高亮部分的td
  19930. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19931. }
  19932. };
  19933. // plugins/table.sort.js
  19934. /**
  19935. * Created with JetBrains PhpStorm.
  19936. * User: Jinqn
  19937. * Date: 13-10-12
  19938. * Time: 上午10:20
  19939. * To change this template use File | Settings | File Templates.
  19940. */
  19941. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19942. var table = this.table,
  19943. rows = table.rows,
  19944. trArray = [],
  19945. flag = rows[0].cells[0].tagName === "TH",
  19946. lastRowIndex = 0;
  19947. if(this.selectedTds.length){
  19948. var range = this.cellsRange,
  19949. len = range.endRowIndex + 1;
  19950. for (var i = range.beginRowIndex; i < len; i++) {
  19951. trArray[i] = rows[i];
  19952. }
  19953. trArray.splice(0,range.beginRowIndex);
  19954. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19955. }else{
  19956. for (var i = 0,len = rows.length; i < len; i++) {
  19957. trArray[i] = rows[i];
  19958. }
  19959. }
  19960. var Fn = {
  19961. 'reversecurrent': function(td1,td2){
  19962. return 1;
  19963. },
  19964. 'orderbyasc': function(td1,td2){
  19965. var value1 = td1.innerText||td1.textContent,
  19966. value2 = td2.innerText||td2.textContent;
  19967. return value1.localeCompare(value2);
  19968. },
  19969. 'reversebyasc': function(td1,td2){
  19970. var value1 = td1.innerHTML,
  19971. value2 = td2.innerHTML;
  19972. return value2.localeCompare(value1);
  19973. },
  19974. 'orderbynum': function(td1,td2){
  19975. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19976. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19977. if(value1) value1 = +value1[0];
  19978. if(value2) value2 = +value2[0];
  19979. return (value1||0) - (value2||0);
  19980. },
  19981. 'reversebynum': function(td1,td2){
  19982. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19983. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19984. if(value1) value1 = +value1[0];
  19985. if(value2) value2 = +value2[0];
  19986. return (value2||0) - (value1||0);
  19987. }
  19988. };
  19989. //对表格设置排序的标记data-sort-type
  19990. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19991. //th不参与排序
  19992. flag && trArray.splice(0, 1);
  19993. trArray = utils.sort(trArray,function (tr1, tr2) {
  19994. var result;
  19995. if (compareFn && typeof compareFn === "function") {
  19996. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19997. } else if (compareFn && typeof compareFn === "number") {
  19998. result = 1;
  19999. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  20000. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20001. } else {
  20002. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20003. }
  20004. return result;
  20005. });
  20006. var fragment = table.ownerDocument.createDocumentFragment();
  20007. for (var j = 0, len = trArray.length; j < len; j++) {
  20008. fragment.appendChild(trArray[j]);
  20009. }
  20010. var tbody = table.getElementsByTagName("tbody")[0];
  20011. if(!lastRowIndex){
  20012. tbody.appendChild(fragment);
  20013. }else{
  20014. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  20015. }
  20016. };
  20017. UE.plugins['tablesort'] = function () {
  20018. var me = this,
  20019. UT = UE.UETable,
  20020. getUETable = function (tdOrTable) {
  20021. return UT.getUETable(tdOrTable);
  20022. },
  20023. getTableItemsByRange = function (editor) {
  20024. return UT.getTableItemsByRange(editor);
  20025. };
  20026. me.ready(function () {
  20027. //添加表格可排序的样式
  20028. utils.cssRule('tablesort',
  20029. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  20030. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  20031. me.document);
  20032. //做单元格合并操作时,清除可排序标识
  20033. me.addListener("afterexeccommand", function (type, cmd) {
  20034. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  20035. this.execCommand('disablesort');
  20036. }
  20037. });
  20038. });
  20039. //表格排序
  20040. UE.commands['sorttable'] = {
  20041. queryCommandState: function () {
  20042. var me = this,
  20043. tableItems = getTableItemsByRange(me);
  20044. if (!tableItems.cell) return -1;
  20045. var table = tableItems.table,
  20046. cells = table.getElementsByTagName("td");
  20047. for (var i = 0, cell; cell = cells[i++];) {
  20048. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  20049. }
  20050. return 0;
  20051. },
  20052. execCommand: function (cmd, fn) {
  20053. var me = this,
  20054. range = me.selection.getRange(),
  20055. bk = range.createBookmark(true),
  20056. tableItems = getTableItemsByRange(me),
  20057. cell = tableItems.cell,
  20058. ut = getUETable(tableItems.table),
  20059. cellInfo = ut.getCellInfo(cell);
  20060. ut.sortTable(cellInfo.cellIndex, fn);
  20061. range.moveToBookmark(bk);
  20062. try{
  20063. range.select();
  20064. }catch(e){}
  20065. }
  20066. };
  20067. //设置表格可排序,清除表格可排序
  20068. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20069. queryCommandState: function (cmd) {
  20070. var table = getTableItemsByRange(this).table;
  20071. if(table && cmd=='enablesort') {
  20072. var cells = domUtils.getElementsByTagName(table, 'th td');
  20073. for(var i = 0; i<cells.length; i++) {
  20074. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  20075. }
  20076. }
  20077. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  20078. },
  20079. execCommand: function (cmd) {
  20080. var table = getTableItemsByRange(this).table;
  20081. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20082. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  20083. }
  20084. };
  20085. };
  20086. // plugins/contextmenu.js
  20087. ///import core
  20088. ///commands 右键菜单
  20089. ///commandsName ContextMenu
  20090. ///commandsTitle 右键菜单
  20091. /**
  20092. * 右键菜单
  20093. * @function
  20094. * @name baidu.editor.plugins.contextmenu
  20095. * @author zhanyi
  20096. */
  20097. UE.plugins['contextmenu'] = function () {
  20098. var me = this;
  20099. me.setOpt('enableContextMenu',true);
  20100. if(me.getOpt('enableContextMenu') === false){
  20101. return;
  20102. }
  20103. var lang = me.getLang( "contextMenu" ),
  20104. menu,
  20105. items = me.options.contextMenu || [
  20106. {label:lang['selectall'], cmdName:'selectall'},
  20107. {
  20108. label:lang.cleardoc,
  20109. cmdName:'cleardoc',
  20110. exec:function () {
  20111. if ( confirm( lang.confirmclear ) ) {
  20112. this.execCommand( 'cleardoc' );
  20113. }
  20114. }
  20115. },
  20116. '-',
  20117. {
  20118. label:lang.unlink,
  20119. cmdName:'unlink'
  20120. },
  20121. '-',
  20122. {
  20123. group:lang.paragraph,
  20124. icon:'justifyjustify',
  20125. subMenu:[
  20126. {
  20127. label:lang.justifyleft,
  20128. cmdName:'justify',
  20129. value:'left'
  20130. },
  20131. {
  20132. label:lang.justifyright,
  20133. cmdName:'justify',
  20134. value:'right'
  20135. },
  20136. {
  20137. label:lang.justifycenter,
  20138. cmdName:'justify',
  20139. value:'center'
  20140. },
  20141. {
  20142. label:lang.justifyjustify,
  20143. cmdName:'justify',
  20144. value:'justify'
  20145. }
  20146. ]
  20147. },
  20148. '-',
  20149. {
  20150. group:lang.table,
  20151. icon:'table',
  20152. subMenu:[
  20153. {
  20154. label:lang.inserttable,
  20155. cmdName:'inserttable'
  20156. },
  20157. {
  20158. label:lang.deletetable,
  20159. cmdName:'deletetable'
  20160. },
  20161. '-',
  20162. {
  20163. label:lang.deleterow,
  20164. cmdName:'deleterow'
  20165. },
  20166. {
  20167. label:lang.deletecol,
  20168. cmdName:'deletecol'
  20169. },
  20170. {
  20171. label:lang.insertcol,
  20172. cmdName:'insertcol'
  20173. },
  20174. {
  20175. label:lang.insertcolnext,
  20176. cmdName:'insertcolnext'
  20177. },
  20178. {
  20179. label:lang.insertrow,
  20180. cmdName:'insertrow'
  20181. },
  20182. {
  20183. label:lang.insertrownext,
  20184. cmdName:'insertrownext'
  20185. },
  20186. '-',
  20187. {
  20188. label:lang.insertcaption,
  20189. cmdName:'insertcaption'
  20190. },
  20191. {
  20192. label:lang.deletecaption,
  20193. cmdName:'deletecaption'
  20194. },
  20195. {
  20196. label:lang.inserttitle,
  20197. cmdName:'inserttitle'
  20198. },
  20199. {
  20200. label:lang.deletetitle,
  20201. cmdName:'deletetitle'
  20202. },
  20203. {
  20204. label:lang.inserttitlecol,
  20205. cmdName:'inserttitlecol'
  20206. },
  20207. {
  20208. label:lang.deletetitlecol,
  20209. cmdName:'deletetitlecol'
  20210. },
  20211. '-',
  20212. {
  20213. label:lang.mergecells,
  20214. cmdName:'mergecells'
  20215. },
  20216. {
  20217. label:lang.mergeright,
  20218. cmdName:'mergeright'
  20219. },
  20220. {
  20221. label:lang.mergedown,
  20222. cmdName:'mergedown'
  20223. },
  20224. '-',
  20225. {
  20226. label:lang.splittorows,
  20227. cmdName:'splittorows'
  20228. },
  20229. {
  20230. label:lang.splittocols,
  20231. cmdName:'splittocols'
  20232. },
  20233. {
  20234. label:lang.splittocells,
  20235. cmdName:'splittocells'
  20236. },
  20237. '-',
  20238. {
  20239. label:lang.averageDiseRow,
  20240. cmdName:'averagedistributerow'
  20241. },
  20242. {
  20243. label:lang.averageDisCol,
  20244. cmdName:'averagedistributecol'
  20245. },
  20246. '-',
  20247. {
  20248. label:lang.edittd,
  20249. cmdName:'edittd',
  20250. exec:function () {
  20251. if ( UE.ui['edittd'] ) {
  20252. new UE.ui['edittd']( this );
  20253. }
  20254. this.getDialog('edittd').open();
  20255. }
  20256. },
  20257. {
  20258. label:lang.edittable,
  20259. cmdName:'edittable',
  20260. exec:function () {
  20261. if ( UE.ui['edittable'] ) {
  20262. new UE.ui['edittable']( this );
  20263. }
  20264. this.getDialog('edittable').open();
  20265. }
  20266. },
  20267. {
  20268. label:lang.setbordervisible,
  20269. cmdName:'setbordervisible'
  20270. }
  20271. ]
  20272. },
  20273. {
  20274. group:lang.tablesort,
  20275. icon:'tablesort',
  20276. subMenu:[
  20277. {
  20278. label:lang.enablesort,
  20279. cmdName:'enablesort'
  20280. },
  20281. {
  20282. label:lang.disablesort,
  20283. cmdName:'disablesort'
  20284. },
  20285. '-',
  20286. {
  20287. label:lang.reversecurrent,
  20288. cmdName:'sorttable',
  20289. value:'reversecurrent'
  20290. },
  20291. {
  20292. label:lang.orderbyasc,
  20293. cmdName:'sorttable',
  20294. value:'orderbyasc'
  20295. },
  20296. {
  20297. label:lang.reversebyasc,
  20298. cmdName:'sorttable',
  20299. value:'reversebyasc'
  20300. },
  20301. {
  20302. label:lang.orderbynum,
  20303. cmdName:'sorttable',
  20304. value:'orderbynum'
  20305. },
  20306. {
  20307. label:lang.reversebynum,
  20308. cmdName:'sorttable',
  20309. value:'reversebynum'
  20310. }
  20311. ]
  20312. },
  20313. {
  20314. group:lang.borderbk,
  20315. icon:'borderBack',
  20316. subMenu:[
  20317. {
  20318. label:lang.setcolor,
  20319. cmdName:"interlacetable",
  20320. exec:function(){
  20321. this.execCommand("interlacetable");
  20322. }
  20323. },
  20324. {
  20325. label:lang.unsetcolor,
  20326. cmdName:"uninterlacetable",
  20327. exec:function(){
  20328. this.execCommand("uninterlacetable");
  20329. }
  20330. },
  20331. {
  20332. label:lang.setbackground,
  20333. cmdName:"settablebackground",
  20334. exec:function(){
  20335. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  20336. }
  20337. },
  20338. {
  20339. label:lang.unsetbackground,
  20340. cmdName:"cleartablebackground",
  20341. exec:function(){
  20342. this.execCommand("cleartablebackground");
  20343. }
  20344. },
  20345. {
  20346. label:lang.redandblue,
  20347. cmdName:"settablebackground",
  20348. exec:function(){
  20349. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  20350. }
  20351. },
  20352. {
  20353. label:lang.threecolorgradient,
  20354. cmdName:"settablebackground",
  20355. exec:function(){
  20356. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  20357. }
  20358. }
  20359. ]
  20360. },
  20361. {
  20362. group:lang.aligntd,
  20363. icon:'aligntd',
  20364. subMenu:[
  20365. {
  20366. cmdName:'cellalignment',
  20367. value:{align:'left',vAlign:'top'}
  20368. },
  20369. {
  20370. cmdName:'cellalignment',
  20371. value:{align:'center',vAlign:'top'}
  20372. },
  20373. {
  20374. cmdName:'cellalignment',
  20375. value:{align:'right',vAlign:'top'}
  20376. },
  20377. {
  20378. cmdName:'cellalignment',
  20379. value:{align:'left',vAlign:'middle'}
  20380. },
  20381. {
  20382. cmdName:'cellalignment',
  20383. value:{align:'center',vAlign:'middle'}
  20384. },
  20385. {
  20386. cmdName:'cellalignment',
  20387. value:{align:'right',vAlign:'middle'}
  20388. },
  20389. {
  20390. cmdName:'cellalignment',
  20391. value:{align:'left',vAlign:'bottom'}
  20392. },
  20393. {
  20394. cmdName:'cellalignment',
  20395. value:{align:'center',vAlign:'bottom'}
  20396. },
  20397. {
  20398. cmdName:'cellalignment',
  20399. value:{align:'right',vAlign:'bottom'}
  20400. }
  20401. ]
  20402. },
  20403. {
  20404. group:lang.aligntable,
  20405. icon:'aligntable',
  20406. subMenu:[
  20407. {
  20408. cmdName:'tablealignment',
  20409. className: 'left',
  20410. label:lang.tableleft,
  20411. value:"left"
  20412. },
  20413. {
  20414. cmdName:'tablealignment',
  20415. className: 'center',
  20416. label:lang.tablecenter,
  20417. value:"center"
  20418. },
  20419. {
  20420. cmdName:'tablealignment',
  20421. className: 'right',
  20422. label:lang.tableright,
  20423. value:"right"
  20424. }
  20425. ]
  20426. },
  20427. '-',
  20428. {
  20429. label:lang.insertparagraphbefore,
  20430. cmdName:'insertparagraph',
  20431. value:true
  20432. },
  20433. {
  20434. label:lang.insertparagraphafter,
  20435. cmdName:'insertparagraph'
  20436. },
  20437. {
  20438. label:lang['copy'],
  20439. cmdName:'copy'
  20440. },
  20441. {
  20442. label:lang['paste'],
  20443. cmdName:'paste'
  20444. }
  20445. ];
  20446. if ( !items.length ) {
  20447. return;
  20448. }
  20449. var uiUtils = UE.ui.uiUtils;
  20450. me.addListener( 'contextmenu', function ( type, evt ) {
  20451. var offset = uiUtils.getViewportOffsetByEvent( evt );
  20452. me.fireEvent( 'beforeselectionchange' );
  20453. if ( menu ) {
  20454. menu.destroy();
  20455. }
  20456. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  20457. var last;
  20458. (function ( item ) {
  20459. if ( item == '-' ) {
  20460. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  20461. contextItems.push( '-' );
  20462. }
  20463. } else if ( item.hasOwnProperty( "group" ) ) {
  20464. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  20465. (function ( subItem ) {
  20466. if ( subItem == '-' ) {
  20467. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  20468. subMenu.push( '-' );
  20469. }else{
  20470. subMenu.splice(subMenu.length-1);
  20471. }
  20472. } else {
  20473. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  20474. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  20475. subMenu.push( {
  20476. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  20477. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  20478. onclick:subItem.exec ? function () {
  20479. subItem.exec.call( me );
  20480. } : function () {
  20481. me.execCommand( subItem.cmdName, subItem.value );
  20482. }
  20483. } );
  20484. }
  20485. }
  20486. })( cj );
  20487. }
  20488. if ( subMenu.length ) {
  20489. function getLabel(){
  20490. switch (item.icon){
  20491. case "table":
  20492. return me.getLang( "contextMenu.table" );
  20493. case "justifyjustify":
  20494. return me.getLang( "contextMenu.paragraph" );
  20495. case "aligntd":
  20496. return me.getLang("contextMenu.aligntd");
  20497. case "aligntable":
  20498. return me.getLang("contextMenu.aligntable");
  20499. case "tablesort":
  20500. return lang.tablesort;
  20501. case "borderBack":
  20502. return lang.borderbk;
  20503. default :
  20504. return '';
  20505. }
  20506. }
  20507. contextItems.push( {
  20508. //todo 修正成自动获取方式
  20509. 'label':getLabel(),
  20510. className:'edui-for-' + item.icon,
  20511. 'subMenu':{
  20512. items:subMenu,
  20513. editor:me
  20514. }
  20515. } );
  20516. }
  20517. } else {
  20518. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  20519. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  20520. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  20521. contextItems.push( {
  20522. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  20523. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  20524. onclick:item.exec ? function () {
  20525. item.exec.call( me );
  20526. } : function () {
  20527. me.execCommand( item.cmdName, item.value );
  20528. }
  20529. } );
  20530. }
  20531. }
  20532. })( ti );
  20533. }
  20534. if ( contextItems[contextItems.length - 1] == '-' ) {
  20535. contextItems.pop();
  20536. }
  20537. menu = new UE.ui.Menu( {
  20538. items:contextItems,
  20539. className:"edui-contextmenu",
  20540. editor:me
  20541. } );
  20542. menu.render();
  20543. menu.showAt( offset );
  20544. me.fireEvent("aftershowcontextmenu",menu);
  20545. domUtils.preventDefault( evt );
  20546. if ( browser.ie ) {
  20547. var ieRange;
  20548. try {
  20549. ieRange = me.selection.getNative().createRange();
  20550. } catch ( e ) {
  20551. return;
  20552. }
  20553. if ( ieRange.item ) {
  20554. var range = new dom.Range( me.document );
  20555. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  20556. }
  20557. }
  20558. });
  20559. // 添加复制的flash按钮
  20560. me.addListener('aftershowcontextmenu', function(type, menu) {
  20561. if (me.zeroclipboard) {
  20562. var items = menu.items;
  20563. for (var key in items) {
  20564. if (items[key].className == 'edui-for-copy') {
  20565. me.zeroclipboard.clip(items[key].getDom());
  20566. }
  20567. }
  20568. }
  20569. });
  20570. };
  20571. // plugins/shortcutmenu.js
  20572. ///import core
  20573. ///commands 弹出菜单
  20574. // commandsName popupmenu
  20575. ///commandsTitle 弹出菜单
  20576. /**
  20577. * 弹出菜单
  20578. * @function
  20579. * @name baidu.editor.plugins.popupmenu
  20580. * @author xuheng
  20581. */
  20582. UE.plugins['shortcutmenu'] = function () {
  20583. var me = this,
  20584. menu,
  20585. items = me.options.shortcutMenu || [];
  20586. if (!items.length) {
  20587. return;
  20588. }
  20589. me.addListener ('contextmenu mouseup' , function (type , e) {
  20590. var me = this,
  20591. customEvt = {
  20592. type : type ,
  20593. target : e.target || e.srcElement ,
  20594. screenX : e.screenX ,
  20595. screenY : e.screenY ,
  20596. clientX : e.clientX ,
  20597. clientY : e.clientY
  20598. };
  20599. setTimeout (function () {
  20600. var rng = me.selection.getRange ();
  20601. if (rng.collapsed === false || type == "contextmenu") {
  20602. if (!menu) {
  20603. menu = new baidu.editor.ui.ShortCutMenu ({
  20604. editor : me ,
  20605. items : items ,
  20606. theme : me.options.theme ,
  20607. className : 'edui-shortcutmenu'
  20608. });
  20609. menu.render ();
  20610. me.fireEvent ("afterrendershortcutmenu" , menu);
  20611. }
  20612. menu.show (customEvt , !!UE.plugins['contextmenu']);
  20613. }
  20614. });
  20615. if (type == 'contextmenu') {
  20616. domUtils.preventDefault (e);
  20617. if (browser.ie9below) {
  20618. var ieRange;
  20619. try {
  20620. ieRange = me.selection.getNative().createRange();
  20621. } catch (e) {
  20622. return;
  20623. }
  20624. if (ieRange.item) {
  20625. var range = new dom.Range (me.document);
  20626. range.selectNode (ieRange.item (0)).select (true , true);
  20627. }
  20628. }
  20629. }
  20630. });
  20631. me.addListener ('keydown' , function (type) {
  20632. if (type == "keydown") {
  20633. menu && !menu.isHidden && menu.hide ();
  20634. }
  20635. });
  20636. };
  20637. // plugins/basestyle.js
  20638. /**
  20639. * B、I、sub、super命令支持
  20640. * @file
  20641. * @since 1.2.6.1
  20642. */
  20643. UE.plugins['basestyle'] = function(){
  20644. /**
  20645. * 字体加粗
  20646. * @command bold
  20647. * @param { String } cmd 命令字符串
  20648. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  20649. * @method execCommand
  20650. * @example
  20651. * ```javascript
  20652. * //editor是编辑器实例
  20653. * //对当前选中的文本内容执行加粗操作
  20654. * //第一次执行, 文本内容加粗
  20655. * editor.execCommand( 'bold' );
  20656. *
  20657. * //第二次执行, 文本内容取消加粗
  20658. * editor.execCommand( 'bold' );
  20659. * ```
  20660. */
  20661. /**
  20662. * 字体倾斜
  20663. * @command italic
  20664. * @method execCommand
  20665. * @param { String } cmd 命令字符串
  20666. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  20667. * @example
  20668. * ```javascript
  20669. * //editor是编辑器实例
  20670. * //对当前选中的文本内容执行斜体操作
  20671. * //第一次操作, 文本内容将变成斜体
  20672. * editor.execCommand( 'italic' );
  20673. *
  20674. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20675. * editor.execCommand( 'italic' );
  20676. * ```
  20677. */
  20678. /**
  20679. * 下标文本,与“superscript”命令互斥
  20680. * @command subscript
  20681. * @method execCommand
  20682. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  20683. * @param { String } cmd 命令字符串
  20684. * @example
  20685. * ```javascript
  20686. * //editor是编辑器实例
  20687. * //对当前选中的文本内容执行下标操作
  20688. * //第一次操作, 文本内容将变成下标文本
  20689. * editor.execCommand( 'subscript' );
  20690. *
  20691. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20692. * editor.execCommand( 'subscript' );
  20693. * ```
  20694. */
  20695. /**
  20696. * 上标文本,与“subscript”命令互斥
  20697. * @command superscript
  20698. * @method execCommand
  20699. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  20700. * @param { String } cmd 命令字符串
  20701. * @example
  20702. * ```javascript
  20703. * //editor是编辑器实例
  20704. * //对当前选中的文本内容执行上标操作
  20705. * //第一次操作, 文本内容将变成上标文本
  20706. * editor.execCommand( 'superscript' );
  20707. *
  20708. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20709. * editor.execCommand( 'superscript' );
  20710. * ```
  20711. */
  20712. var basestyles = {
  20713. 'bold':['strong','b'],
  20714. 'italic':['em','i'],
  20715. 'subscript':['sub'],
  20716. 'superscript':['sup']
  20717. },
  20718. getObj = function(editor,tagNames){
  20719. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  20720. },
  20721. me = this;
  20722. //添加快捷键
  20723. me.addshortcutkey({
  20724. "Bold" : "ctrl+66",//^B
  20725. "Italic" : "ctrl+73", //^I
  20726. "Underline" : "ctrl+85"//^U
  20727. });
  20728. me.addInputRule(function(root){
  20729. utils.each(root.getNodesByTagName('b i'),function(node){
  20730. switch (node.tagName){
  20731. case 'b':
  20732. node.tagName = 'strong';
  20733. break;
  20734. case 'i':
  20735. node.tagName = 'em';
  20736. }
  20737. });
  20738. });
  20739. for ( var style in basestyles ) {
  20740. (function( cmd, tagNames ) {
  20741. me.commands[cmd] = {
  20742. execCommand : function( cmdName ) {
  20743. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  20744. if ( range.collapsed ) {
  20745. if ( obj ) {
  20746. var tmpText = me.document.createTextNode('');
  20747. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  20748. range.setStartBefore(tmpText);
  20749. domUtils.remove(tmpText);
  20750. } else {
  20751. var tmpNode = range.document.createElement( tagNames[0] );
  20752. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20753. tmpText = me.document.createTextNode('');
  20754. range.insertNode(tmpText)
  20755. .removeInlineStyle(['sub','sup'])
  20756. .setStartBefore(tmpText)
  20757. .collapse(true);
  20758. }
  20759. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  20760. }
  20761. range.collapse( true );
  20762. } else {
  20763. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20764. if(!obj || obj.tagName.toLowerCase() != cmdName){
  20765. range.removeInlineStyle(['sub','sup']);
  20766. }
  20767. }
  20768. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  20769. }
  20770. range.select();
  20771. },
  20772. queryCommandState : function() {
  20773. return getObj(this,tagNames) ? 1 : 0;
  20774. }
  20775. };
  20776. })( style, basestyles[style] );
  20777. }
  20778. };
  20779. // plugins/elementpath.js
  20780. /**
  20781. * 选取路径命令
  20782. * @file
  20783. */
  20784. UE.plugins['elementpath'] = function(){
  20785. var currentLevel,
  20786. tagNames,
  20787. me = this;
  20788. me.setOpt('elementPathEnabled',true);
  20789. if(!me.options.elementPathEnabled){
  20790. return;
  20791. }
  20792. me.commands['elementpath'] = {
  20793. execCommand : function( cmdName, level ) {
  20794. var start = tagNames[level],
  20795. range = me.selection.getRange();
  20796. currentLevel = level*1;
  20797. range.selectNode(start).select();
  20798. },
  20799. queryCommandValue : function() {
  20800. //产生一个副本,不能修改原来的startElementPath;
  20801. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  20802. names = [];
  20803. tagNames = parents;
  20804. for(var i=0,ci;ci=parents[i];i++){
  20805. if(ci.nodeType == 3) {
  20806. continue;
  20807. }
  20808. var name = ci.tagName.toLowerCase();
  20809. if(name == 'img' && ci.getAttribute('anchorname')){
  20810. name = 'anchor';
  20811. }
  20812. names[i] = name;
  20813. if(currentLevel == i){
  20814. currentLevel = -1;
  20815. break;
  20816. }
  20817. }
  20818. return names;
  20819. }
  20820. };
  20821. };
  20822. // plugins/formatmatch.js
  20823. /**
  20824. * 格式刷,只格式inline的
  20825. * @file
  20826. * @since 1.2.6.1
  20827. */
  20828. /**
  20829. * 格式刷
  20830. * @command formatmatch
  20831. * @method execCommand
  20832. * @remind 该操作不能复制段落格式
  20833. * @param { String } cmd 命令字符串
  20834. * @example
  20835. * ```javascript
  20836. * //editor是编辑器实例
  20837. * //获取格式刷
  20838. * editor.execCommand( 'formatmatch' );
  20839. * ```
  20840. */
  20841. UE.plugins['formatmatch'] = function(){
  20842. var me = this,
  20843. list = [],img,
  20844. flag = 0;
  20845. me.addListener('reset',function(){
  20846. list = [];
  20847. flag = 0;
  20848. });
  20849. function addList(type,evt){
  20850. if(browser.webkit){
  20851. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  20852. }
  20853. function addFormat(range){
  20854. if(text){
  20855. range.selectNode(text);
  20856. }
  20857. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  20858. }
  20859. me.undoManger && me.undoManger.save();
  20860. var range = me.selection.getRange(),
  20861. imgT = target || range.getClosedNode();
  20862. if(img && imgT && imgT.tagName == 'IMG'){
  20863. //trace:964
  20864. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  20865. img = null;
  20866. }else{
  20867. if(!img){
  20868. var collapsed = range.collapsed;
  20869. if(collapsed){
  20870. var text = me.document.createTextNode('match');
  20871. range.insertNode(text).select();
  20872. }
  20873. me.__hasEnterExecCommand = true;
  20874. //不能把block上的属性干掉
  20875. //trace:1553
  20876. var removeFormatAttributes = me.options.removeFormatAttributes;
  20877. me.options.removeFormatAttributes = '';
  20878. me.execCommand('removeformat');
  20879. me.options.removeFormatAttributes = removeFormatAttributes;
  20880. me.__hasEnterExecCommand = false;
  20881. //trace:969
  20882. range = me.selection.getRange();
  20883. if(list.length){
  20884. addFormat(range);
  20885. }
  20886. if(text){
  20887. range.setStartBefore(text).collapse(true);
  20888. }
  20889. range.select();
  20890. text && domUtils.remove(text);
  20891. }
  20892. }
  20893. me.undoManger && me.undoManger.save();
  20894. me.removeListener('mouseup',addList);
  20895. flag = 0;
  20896. }
  20897. me.commands['formatmatch'] = {
  20898. execCommand : function( cmdName ) {
  20899. if(flag){
  20900. flag = 0;
  20901. list = [];
  20902. me.removeListener('mouseup',addList);
  20903. return;
  20904. }
  20905. var range = me.selection.getRange();
  20906. img = range.getClosedNode();
  20907. if(!img || img.tagName != 'IMG'){
  20908. range.collapse(true).shrinkBoundary();
  20909. var start = range.startContainer;
  20910. list = domUtils.findParents(start,true,function(node){
  20911. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20912. });
  20913. //a不能加入格式刷, 并且克隆节点
  20914. for(var i=0,ci;ci=list[i];i++){
  20915. if(ci.tagName == 'A'){
  20916. list.splice(i,1);
  20917. break;
  20918. }
  20919. }
  20920. }
  20921. me.addListener('mouseup',addList);
  20922. flag = 1;
  20923. },
  20924. queryCommandState : function() {
  20925. return flag;
  20926. },
  20927. notNeedUndo : 1
  20928. };
  20929. };
  20930. // plugins/searchreplace.js
  20931. ///import core
  20932. ///commands 查找替换
  20933. ///commandsName SearchReplace
  20934. ///commandsTitle 查询替换
  20935. ///commandsDialog dialogs\searchreplace
  20936. /**
  20937. * @description 查找替换
  20938. * @author zhanyi
  20939. */
  20940. UE.plugin.register('searchreplace',function(){
  20941. var me = this;
  20942. var _blockElm = {'table':1,'tbody':1,'tr':1,'ol':1,'ul':1};
  20943. function findTextInString(textContent,opt,currentIndex){
  20944. var str = opt.searchStr;
  20945. if(opt.dir == -1){
  20946. textContent = textContent.split('').reverse().join('');
  20947. str = str.split('').reverse().join('');
  20948. currentIndex = textContent.length - currentIndex;
  20949. }
  20950. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20951. while(match = reg.exec(textContent)){
  20952. if(match.index >= currentIndex){
  20953. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20954. }
  20955. }
  20956. return -1
  20957. }
  20958. function findTextBlockElm(node,currentIndex,opt){
  20959. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20960. if(domUtils.isBody(node)){
  20961. node = node.firstChild;
  20962. }
  20963. var first = 1;
  20964. while(node){
  20965. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20966. index = findTextInString(textContent,opt,currentIndex );
  20967. first = 0;
  20968. if(index!=-1){
  20969. return {
  20970. 'node':node,
  20971. 'index':index
  20972. }
  20973. }
  20974. node = domUtils[methodName](node);
  20975. while(node && _blockElm[node.nodeName.toLowerCase()]){
  20976. node = domUtils[methodName](node,true);
  20977. }
  20978. if(node){
  20979. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20980. }
  20981. }
  20982. }
  20983. function findNTextInBlockElm(node,index,str){
  20984. var currentIndex = 0,
  20985. currentNode = node.firstChild,
  20986. currentNodeLength = 0,
  20987. result;
  20988. while(currentNode){
  20989. if(currentNode.nodeType == 3){
  20990. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20991. currentIndex += currentNodeLength;
  20992. if(currentIndex >= index){
  20993. return {
  20994. 'node':currentNode,
  20995. 'index': currentNodeLength - (currentIndex - index)
  20996. }
  20997. }
  20998. }else if(!dtd.$empty[currentNode.tagName]){
  20999. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  21000. currentIndex += currentNodeLength;
  21001. if(currentIndex >= index){
  21002. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  21003. if(result){
  21004. return result;
  21005. }
  21006. }
  21007. }
  21008. currentNode = domUtils.getNextDomNode(currentNode);
  21009. }
  21010. }
  21011. function searchReplace(me,opt){
  21012. var rng = me.selection.getRange(),
  21013. startBlockNode,
  21014. searchStr = opt.searchStr,
  21015. span = me.document.createElement('span');
  21016. span.innerHTML = '$$ueditor_searchreplace_key$$';
  21017. rng.shrinkBoundary(true);
  21018. //判断是不是第一次选中
  21019. if(!rng.collapsed){
  21020. rng.select();
  21021. var rngText = me.selection.getText();
  21022. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  21023. if(opt.replaceStr != undefined){
  21024. replaceText(rng,opt.replaceStr);
  21025. rng.select();
  21026. return true;
  21027. }else{
  21028. rng.collapse(opt.dir == -1)
  21029. }
  21030. }
  21031. }
  21032. rng.insertNode(span);
  21033. rng.enlargeToBlockElm(true);
  21034. startBlockNode = rng.startContainer;
  21035. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  21036. rng.setStartBefore(span);
  21037. domUtils.remove(span);
  21038. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  21039. if(result){
  21040. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  21041. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  21042. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  21043. if(opt.replaceStr !== undefined){
  21044. replaceText(rng,opt.replaceStr)
  21045. }
  21046. rng.select();
  21047. return true;
  21048. }else{
  21049. rng.setCursor()
  21050. }
  21051. }
  21052. function replaceText(rng,str){
  21053. str = me.document.createTextNode(str);
  21054. rng.deleteContents().insertNode(str);
  21055. }
  21056. return {
  21057. commands:{
  21058. 'searchreplace':{
  21059. execCommand:function(cmdName,opt){
  21060. utils.extend(opt,{
  21061. all : false,
  21062. casesensitive : false,
  21063. dir : 1
  21064. },true);
  21065. var num = 0;
  21066. if(opt.all){
  21067. var rng = me.selection.getRange(),
  21068. first = me.body.firstChild;
  21069. if(first && first.nodeType == 1){
  21070. rng.setStart(first,0);
  21071. rng.shrinkBoundary(true);
  21072. }else if(first.nodeType == 3){
  21073. rng.setStartBefore(first)
  21074. }
  21075. rng.collapse(true).select(true);
  21076. if(opt.replaceStr !== undefined){
  21077. me.fireEvent('saveScene');
  21078. }
  21079. while(searchReplace(this,opt)){
  21080. num++;
  21081. }
  21082. if(num){
  21083. me.fireEvent('saveScene');
  21084. }
  21085. }else{
  21086. if(opt.replaceStr !== undefined){
  21087. me.fireEvent('saveScene');
  21088. }
  21089. if(searchReplace(this,opt)){
  21090. num++
  21091. }
  21092. if(num){
  21093. me.fireEvent('saveScene');
  21094. }
  21095. }
  21096. return num;
  21097. },
  21098. notNeedUndo:1
  21099. }
  21100. }
  21101. }
  21102. });
  21103. // plugins/customstyle.js
  21104. /**
  21105. * 自定义样式
  21106. * @file
  21107. * @since 1.2.6.1
  21108. */
  21109. /**
  21110. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  21111. * @command customstyle
  21112. * @method execCommand
  21113. * @param { String } cmd 命令字符串
  21114. * @example
  21115. * ```javascript
  21116. * editor.execCommand( 'customstyle' );
  21117. * ```
  21118. */
  21119. UE.plugins['customstyle'] = function() {
  21120. var me = this;
  21121. me.setOpt({ 'customstyle':[
  21122. {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;'},
  21123. {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;'},
  21124. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  21125. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  21126. ]});
  21127. me.commands['customstyle'] = {
  21128. execCommand : function(cmdName, obj) {
  21129. var me = this,
  21130. tagName = obj.tag,
  21131. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21132. return node.getAttribute('label');
  21133. }, true),
  21134. range,bk,tmpObj = {};
  21135. for (var p in obj) {
  21136. if(obj[p]!==undefined)
  21137. tmpObj[p] = obj[p];
  21138. }
  21139. delete tmpObj.tag;
  21140. if (node && node.getAttribute('label') == obj.label) {
  21141. range = this.selection.getRange();
  21142. bk = range.createBookmark();
  21143. if (range.collapsed) {
  21144. //trace:1732 删掉自定义标签,要有p来回填站位
  21145. if(dtd.$block[node.tagName]){
  21146. var fillNode = me.document.createElement('p');
  21147. domUtils.moveChild(node, fillNode);
  21148. node.parentNode.insertBefore(fillNode, node);
  21149. domUtils.remove(node);
  21150. }else{
  21151. domUtils.remove(node,true);
  21152. }
  21153. } else {
  21154. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  21155. nodes = domUtils.getElementsByTagName(common, tagName);
  21156. if(new RegExp(tagName,'i').test(common.tagName)){
  21157. nodes.push(common);
  21158. }
  21159. for (var i = 0,ni; ni = nodes[i++];) {
  21160. if (ni.getAttribute('label') == obj.label) {
  21161. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  21162. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  21163. &&
  21164. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  21165. )
  21166. if (dtd.$block[tagName]) {
  21167. var fillNode = me.document.createElement('p');
  21168. domUtils.moveChild(ni, fillNode);
  21169. ni.parentNode.insertBefore(fillNode, ni);
  21170. }
  21171. domUtils.remove(ni, true);
  21172. }
  21173. }
  21174. node = domUtils.findParent(common, function(node) {
  21175. return node.getAttribute('label') == obj.label;
  21176. }, true);
  21177. if (node) {
  21178. domUtils.remove(node, true);
  21179. }
  21180. }
  21181. range.moveToBookmark(bk).select();
  21182. } else {
  21183. if (dtd.$block[tagName]) {
  21184. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  21185. range = me.selection.getRange();
  21186. if (!range.collapsed) {
  21187. range.collapse();
  21188. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21189. return node.getAttribute('label') == obj.label;
  21190. }, true);
  21191. var pNode = me.document.createElement('p');
  21192. domUtils.insertAfter(node, pNode);
  21193. domUtils.fillNode(me.document, pNode);
  21194. range.setStart(pNode, 0).setCursor();
  21195. }
  21196. } else {
  21197. range = me.selection.getRange();
  21198. if (range.collapsed) {
  21199. node = me.document.createElement(tagName);
  21200. domUtils.setAttributes(node, tmpObj);
  21201. range.insertNode(node).setStart(node, 0).setCursor();
  21202. return;
  21203. }
  21204. bk = range.createBookmark();
  21205. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  21206. }
  21207. }
  21208. },
  21209. queryCommandValue : function() {
  21210. var parent = domUtils.filterNodeList(
  21211. this.selection.getStartElementPath(),
  21212. function(node){return node.getAttribute('label')}
  21213. );
  21214. return parent ? parent.getAttribute('label') : '';
  21215. }
  21216. };
  21217. //当去掉customstyle是,如果是块元素,用p代替
  21218. me.addListener('keyup', function(type, evt) {
  21219. var keyCode = evt.keyCode || evt.which;
  21220. if (keyCode == 32 || keyCode == 13) {
  21221. var range = me.selection.getRange();
  21222. if (range.collapsed) {
  21223. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  21224. return node.getAttribute('label');
  21225. }, true);
  21226. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  21227. var p = me.document.createElement('p');
  21228. domUtils.insertAfter(node, p);
  21229. domUtils.fillNode(me.document, p);
  21230. domUtils.remove(node);
  21231. range.setStart(p, 0).setCursor();
  21232. }
  21233. }
  21234. }
  21235. });
  21236. };
  21237. // plugins/catchremoteimage.js
  21238. ///import core
  21239. ///commands 远程图片抓取
  21240. ///commandsName catchRemoteImage,catchremoteimageenable
  21241. ///commandsTitle 远程图片抓取
  21242. /**
  21243. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  21244. */
  21245. UE.plugins['catchremoteimage'] = function () {
  21246. var me = this,
  21247. ajax = UE.ajax;
  21248. /* 设置默认值 */
  21249. if (me.options.catchRemoteImageEnable === false) return;
  21250. me.setOpt({
  21251. catchRemoteImageEnable: false
  21252. });
  21253. me.addListener("afterpaste", function () {
  21254. me.fireEvent("catchRemoteImage");
  21255. });
  21256. me.addListener("catchRemoteImage", function () {
  21257. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  21258. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  21259. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  21260. catcherFieldName = me.getOpt('catcherFieldName');
  21261. var remoteImages = [],
  21262. imgs = domUtils.getElementsByTagName(me.document, "img"),
  21263. test = function (src, urls) {
  21264. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  21265. return true;
  21266. }
  21267. if (urls) {
  21268. for (var j = 0, url; url = urls[j++];) {
  21269. if (src.indexOf(url) !== -1) {
  21270. return true;
  21271. }
  21272. }
  21273. }
  21274. return false;
  21275. };
  21276. for (var i = 0, ci; ci = imgs[i++];) {
  21277. if (ci.getAttribute("word_img")) {
  21278. continue;
  21279. }
  21280. var src = ci.getAttribute("_src") || ci.src || "";
  21281. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  21282. remoteImages.push(src);
  21283. }
  21284. }
  21285. if (remoteImages.length) {
  21286. catchremoteimage(remoteImages, {
  21287. //成功抓取
  21288. success: function (r) {
  21289. try {
  21290. var info = r.state !== undefined ? r:eval("(" + r.responseText + ")");
  21291. } catch (e) {
  21292. return;
  21293. }
  21294. /* 获取源路径和新路径 */
  21295. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  21296. for (i = 0; ci = imgs[i++];) {
  21297. oldSrc = ci.getAttribute("_src") || ci.src || "";
  21298. for (j = 0; cj = list[j++];) {
  21299. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  21300. newSrc = catcherUrlPrefix + cj.url;
  21301. domUtils.setAttributes(ci, {
  21302. "src": newSrc,
  21303. "_src": newSrc
  21304. });
  21305. break;
  21306. }
  21307. }
  21308. }
  21309. me.fireEvent('catchremotesuccess')
  21310. },
  21311. //回调失败,本次请求超时
  21312. error: function () {
  21313. me.fireEvent("catchremoteerror");
  21314. }
  21315. });
  21316. }
  21317. function catchremoteimage(imgs, callbacks) {
  21318. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21319. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?':'&') + params),
  21320. isJsonp = utils.isCrossDomainUrl(url),
  21321. opt = {
  21322. 'method': 'POST',
  21323. 'dataType': isJsonp ? 'jsonp':'',
  21324. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  21325. 'onsuccess': callbacks["success"],
  21326. 'onerror': callbacks["error"]
  21327. };
  21328. opt[catcherFieldName] = imgs;
  21329. ajax.request(url, opt);
  21330. }
  21331. });
  21332. };
  21333. // plugins/snapscreen.js
  21334. /**
  21335. * 截屏插件,为UEditor提供插入支持
  21336. * @file
  21337. * @since 1.4.2
  21338. */
  21339. UE.plugin.register('snapscreen', function (){
  21340. var me = this;
  21341. var snapplugin;
  21342. function getLocation(url){
  21343. var search,
  21344. a = document.createElement('a'),
  21345. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  21346. a.href = url;
  21347. if (browser.ie) {
  21348. a.href = a.href;
  21349. }
  21350. search = a.search;
  21351. if (params) {
  21352. search = search + (search.indexOf('?') == -1 ? '?':'&')+ params;
  21353. search = search.replace(/[&]+/ig, '&');
  21354. }
  21355. return {
  21356. 'port': a.port,
  21357. 'hostname': a.hostname,
  21358. 'path': a.pathname + search || + a.hash
  21359. }
  21360. }
  21361. return {
  21362. commands:{
  21363. /**
  21364. * 字体背景颜色
  21365. * @command snapscreen
  21366. * @method execCommand
  21367. * @param { String } cmd 命令字符串
  21368. * @example
  21369. * ```javascript
  21370. * editor.execCommand('snapscreen');
  21371. * ```
  21372. */
  21373. 'snapscreen':{
  21374. execCommand:function (cmd) {
  21375. var url, local, res;
  21376. var lang = me.getLang("snapScreen_plugin");
  21377. if(!snapplugin){
  21378. var container = me.container;
  21379. var doc = me.container.ownerDocument || me.container.document;
  21380. snapplugin = doc.createElement("object");
  21381. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  21382. return;
  21383. }
  21384. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  21385. snapplugin.setAttribute("width","0");
  21386. snapplugin.setAttribute("height","0");
  21387. container.appendChild(snapplugin);
  21388. }
  21389. function onSuccess(rs){
  21390. try{
  21391. rs = eval("("+ rs +")");
  21392. if(rs.state == 'SUCCESS'){
  21393. var opt = me.options;
  21394. me.execCommand('insertimage', {
  21395. src: opt.snapscreenUrlPrefix + rs.url,
  21396. _src: opt.snapscreenUrlPrefix + rs.url,
  21397. alt: rs.title || '',
  21398. floatStyle: opt.snapscreenImgAlign
  21399. });
  21400. } else {
  21401. alert(rs.state);
  21402. }
  21403. }catch(e){
  21404. alert(lang.callBackErrorMsg);
  21405. }
  21406. }
  21407. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  21408. local = getLocation(url);
  21409. setTimeout(function () {
  21410. try{
  21411. res =snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  21412. }catch(e){
  21413. me.ui._dialogs['snapscreenDialog'].open();
  21414. return;
  21415. }
  21416. onSuccess(res);
  21417. }, 50);
  21418. },
  21419. queryCommandState: function(){
  21420. return (navigator.userAgent.indexOf("Windows",0) != -1) ? 0:-1;
  21421. }
  21422. }
  21423. }
  21424. }
  21425. });
  21426. // plugins/insertparagraph.js
  21427. /**
  21428. * 插入段落
  21429. * @file
  21430. * @since 1.2.6.1
  21431. */
  21432. /**
  21433. * 插入段落
  21434. * @command insertparagraph
  21435. * @method execCommand
  21436. * @param { String } cmd 命令字符串
  21437. * @example
  21438. * ```javascript
  21439. * //editor是编辑器实例
  21440. * editor.execCommand( 'insertparagraph' );
  21441. * ```
  21442. */
  21443. UE.commands['insertparagraph'] = {
  21444. execCommand : function( cmdName,front) {
  21445. var me = this,
  21446. range = me.selection.getRange(),
  21447. start = range.startContainer,tmpNode;
  21448. while(start ){
  21449. if(domUtils.isBody(start)){
  21450. break;
  21451. }
  21452. tmpNode = start;
  21453. start = start.parentNode;
  21454. }
  21455. if(tmpNode){
  21456. var p = me.document.createElement('p');
  21457. if(front){
  21458. tmpNode.parentNode.insertBefore(p,tmpNode)
  21459. }else{
  21460. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  21461. }
  21462. domUtils.fillNode(me.document,p);
  21463. range.setStart(p,0).setCursor(false,true);
  21464. }
  21465. }
  21466. };
  21467. // plugins/webapp.js
  21468. /**
  21469. * 百度应用
  21470. * @file
  21471. * @since 1.2.6.1
  21472. */
  21473. /**
  21474. * 插入百度应用
  21475. * @command webapp
  21476. * @method execCommand
  21477. * @remind 需要百度APPKey
  21478. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21479. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21480. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21481. * @example
  21482. * ```javascript
  21483. * //editor是编辑器实例
  21484. * //在编辑器里插入一个“植物大战僵尸”的APP
  21485. * editor.execCommand( 'webapp' , {
  21486. * title: '植物大战僵尸',
  21487. * width: 560,
  21488. * height: 465,
  21489. * logo: '应用展示的图片',
  21490. * url: '百度应用的地址'
  21491. * } );
  21492. * ```
  21493. */
  21494. //UE.plugins['webapp'] = function () {
  21495. // var me = this;
  21496. // function createInsertStr( obj, toIframe, addParagraph ) {
  21497. // return !toIframe ?
  21498. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21499. // ' 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 + '" />' +
  21500. // (addParagraph ? '</p>' : '')
  21501. // :
  21502. // '<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>';
  21503. // }
  21504. //
  21505. // function switchImgAndIframe( img2frame ) {
  21506. // var tmpdiv,
  21507. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  21508. // for ( var i = 0, node; node = nodes[i++]; ) {
  21509. // if ( node.className != "edui-faked-webapp" ){
  21510. // continue;
  21511. // }
  21512. // tmpdiv = me.document.createElement( "div" );
  21513. // 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 );
  21514. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  21515. // }
  21516. // }
  21517. //
  21518. // me.addListener( "beforegetcontent", function () {
  21519. // switchImgAndIframe( true );
  21520. // } );
  21521. // me.addListener( 'aftersetcontent', function () {
  21522. // switchImgAndIframe( false );
  21523. // } );
  21524. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  21525. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  21526. // return;
  21527. // }
  21528. // switchImgAndIframe( false );
  21529. // } );
  21530. //
  21531. // me.commands['webapp'] = {
  21532. // execCommand:function ( cmd, obj ) {
  21533. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  21534. // }
  21535. // };
  21536. //};
  21537. UE.plugin.register('webapp', function (){
  21538. var me = this;
  21539. function createInsertStr(obj,toEmbed){
  21540. return !toEmbed ?
  21541. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21542. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  21543. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  21544. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21545. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21546. '/>'
  21547. :
  21548. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  21549. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21550. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21551. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  21552. }
  21553. return {
  21554. outputRule: function(root){
  21555. utils.each(root.getNodesByTagName('img'),function(node){
  21556. var html;
  21557. if(node.getAttr('class') == 'edui-faked-webapp'){
  21558. html = createInsertStr({
  21559. title:node.getAttr('title'),
  21560. 'width':node.getAttr('width'),
  21561. 'height':node.getAttr('height'),
  21562. 'align':node.getAttr('align'),
  21563. 'cssfloat':node.getStyle('float'),
  21564. 'url':node.getAttr("_url"),
  21565. 'logo':node.getAttr('_logo_url')
  21566. },true);
  21567. var embed = UE.uNode.createElement(html);
  21568. node.parentNode.replaceChild(embed,node);
  21569. }
  21570. })
  21571. },
  21572. inputRule:function(root){
  21573. utils.each(root.getNodesByTagName('iframe'),function(node){
  21574. if(node.getAttr('class') == 'edui-faked-webapp'){
  21575. var img = UE.uNode.createElement(createInsertStr({
  21576. title:node.getAttr('title'),
  21577. 'width':node.getAttr('width'),
  21578. 'height':node.getAttr('height'),
  21579. 'align':node.getAttr('align'),
  21580. 'cssfloat':node.getStyle('float'),
  21581. 'url':node.getAttr("src"),
  21582. 'logo':node.getAttr('logo_url')
  21583. }));
  21584. node.parentNode.replaceChild(img,node);
  21585. }
  21586. })
  21587. },
  21588. commands:{
  21589. /**
  21590. * 插入百度应用
  21591. * @command webapp
  21592. * @method execCommand
  21593. * @remind 需要百度APPKey
  21594. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21595. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21596. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21597. * @example
  21598. * ```javascript
  21599. * //editor是编辑器实例
  21600. * //在编辑器里插入一个“植物大战僵尸”的APP
  21601. * editor.execCommand( 'webapp' , {
  21602. * title: '植物大战僵尸',
  21603. * width: 560,
  21604. * height: 465,
  21605. * logo: '应用展示的图片',
  21606. * url: '百度应用的地址'
  21607. * } );
  21608. * ```
  21609. */
  21610. 'webapp':{
  21611. execCommand:function (cmd, obj) {
  21612. var me = this,
  21613. str = createInsertStr(utils.extend(obj,{
  21614. align:'none'
  21615. }), false);
  21616. me.execCommand("inserthtml",str);
  21617. },
  21618. queryCommandState:function () {
  21619. var me = this,
  21620. img = me.selection.getRange().getClosedNode(),
  21621. flag = img && (img.className == "edui-faked-webapp");
  21622. return flag ? 1 : 0;
  21623. }
  21624. }
  21625. }
  21626. }
  21627. });
  21628. // plugins/template.js
  21629. ///import core
  21630. ///import plugins\inserthtml.js
  21631. ///import plugins\cleardoc.js
  21632. ///commands 模板
  21633. ///commandsName template
  21634. ///commandsTitle 模板
  21635. ///commandsDialog dialogs\template
  21636. UE.plugins['template'] = function () {
  21637. UE.commands['template'] = {
  21638. execCommand:function (cmd, obj) {
  21639. obj.html && this.execCommand("inserthtml", obj.html);
  21640. }
  21641. };
  21642. this.addListener("click", function (type, evt) {
  21643. var el = evt.target || evt.srcElement,
  21644. range = this.selection.getRange();
  21645. var tnode = domUtils.findParent(el, function (node) {
  21646. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21647. return node;
  21648. }
  21649. }, true);
  21650. tnode && range.selectNode(tnode).shrinkBoundary().select();
  21651. });
  21652. this.addListener("keydown", function (type, evt) {
  21653. var range = this.selection.getRange();
  21654. if (!range.collapsed) {
  21655. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  21656. var tnode = domUtils.findParent(range.startContainer, function (node) {
  21657. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21658. return node;
  21659. }
  21660. }, true);
  21661. if (tnode) {
  21662. domUtils.removeClasses(tnode, ["ue_t"]);
  21663. }
  21664. }
  21665. }
  21666. });
  21667. };
  21668. // plugins/music.js
  21669. /**
  21670. * 插入音乐命令
  21671. * @file
  21672. */
  21673. UE.plugin.register('music', function (){
  21674. var me = this;
  21675. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  21676. return !toEmbed ?
  21677. '<img ' +
  21678. (align && !cssfloat? 'align="' + align + '"' : '') +
  21679. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21680. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  21681. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  21682. :
  21683. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  21684. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  21685. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21686. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  21687. }
  21688. return {
  21689. outputRule: function(root){
  21690. utils.each(root.getNodesByTagName('img'),function(node){
  21691. var html;
  21692. if(node.getAttr('class') == 'edui-faked-music'){
  21693. var cssfloat = node.getStyle('float');
  21694. var align = node.getAttr('align');
  21695. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  21696. var embed = UE.uNode.createElement(html);
  21697. node.parentNode.replaceChild(embed,node);
  21698. }
  21699. })
  21700. },
  21701. inputRule:function(root){
  21702. utils.each(root.getNodesByTagName('embed'),function(node){
  21703. if(node.getAttr('class') == 'edui-faked-music'){
  21704. var cssfloat = node.getStyle('float');
  21705. var align = node.getAttr('align');
  21706. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  21707. var img = UE.uNode.createElement(html);
  21708. node.parentNode.replaceChild(img,node);
  21709. }
  21710. })
  21711. },
  21712. commands:{
  21713. /**
  21714. * 插入音乐
  21715. * @command music
  21716. * @method execCommand
  21717. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  21718. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  21719. * @example
  21720. * ```javascript
  21721. * //editor是编辑器实例
  21722. * //在编辑器里插入一个“植物大战僵尸”的APP
  21723. * editor.execCommand( 'music' , {
  21724. * width: 400,
  21725. * height: 95,
  21726. * align: "center",
  21727. * url: "音乐地址"
  21728. * } );
  21729. * ```
  21730. */
  21731. 'music':{
  21732. execCommand:function (cmd, musicObj) {
  21733. var me = this,
  21734. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  21735. me.execCommand("inserthtml",str);
  21736. },
  21737. queryCommandState:function () {
  21738. var me = this,
  21739. img = me.selection.getRange().getClosedNode(),
  21740. flag = img && (img.className == "edui-faked-music");
  21741. return flag ? 1 : 0;
  21742. }
  21743. }
  21744. }
  21745. }
  21746. });
  21747. // plugins/autoupload.js
  21748. /**
  21749. * @description
  21750. * 1.拖放文件到编辑区域,自动上传并插入到选区
  21751. * 2.插入粘贴板的图片,自动上传并插入到选区
  21752. * @author Jinqn
  21753. * @date 2013-10-14
  21754. */
  21755. UE.plugin.register('autoupload', function (){
  21756. function sendAndInsertFile(file, editor) {
  21757. var me = editor;
  21758. //模拟数据
  21759. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  21760. loadingHtml, errorHandler, successHandler,
  21761. filetype = /image\/\w+/i.test(file.type) ? 'image':'file',
  21762. loadingId = 'loading_' + (+new Date()).toString(36);
  21763. fieldName = me.getOpt(filetype + 'FieldName');
  21764. urlPrefix = me.getOpt(filetype + 'UrlPrefix');
  21765. maxSize = me.getOpt(filetype + 'MaxSize');
  21766. allowFiles = me.getOpt(filetype + 'AllowFiles');
  21767. actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
  21768. errorHandler = function(title) {
  21769. var loader = me.document.getElementById(loadingId);
  21770. loader && domUtils.remove(loader);
  21771. me.fireEvent('showmessage', {
  21772. 'id': loadingId,
  21773. 'content': title,
  21774. 'type': 'error',
  21775. 'timeout': 4000
  21776. });
  21777. };
  21778. if (filetype == 'image') {
  21779. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  21780. me.options.themePath + me.options.theme +
  21781. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
  21782. successHandler = function(data) {
  21783. var link = urlPrefix + data.url,
  21784. loader = me.document.getElementById(loadingId);
  21785. if (loader) {
  21786. loader.setAttribute('src', link);
  21787. loader.setAttribute('_src', link);
  21788. loader.setAttribute('title', data.title || '');
  21789. loader.setAttribute('alt', data.original || '');
  21790. loader.removeAttribute('id');
  21791. domUtils.removeClasses(loader, 'loadingclass');
  21792. }
  21793. };
  21794. } else {
  21795. loadingHtml = '<p>' +
  21796. '<img class="loadingclass" id="' + loadingId + '" src="' +
  21797. me.options.themePath + me.options.theme +
  21798. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >' +
  21799. '</p>';
  21800. successHandler = function(data) {
  21801. var link = urlPrefix + data.url,
  21802. loader = me.document.getElementById(loadingId);
  21803. var rng = me.selection.getRange(),
  21804. bk = rng.createBookmark();
  21805. rng.selectNode(loader).select();
  21806. me.execCommand('insertfile', {'url': link});
  21807. rng.moveToBookmark(bk).select();
  21808. };
  21809. }
  21810. /* 插入loading的占位符 */
  21811. me.execCommand('inserthtml', loadingHtml);
  21812. /* 判断后端配置是否没有加载成功 */
  21813. if (!me.getOpt(filetype + 'ActionName')) {
  21814. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  21815. return;
  21816. }
  21817. /* 判断文件大小是否超出限制 */
  21818. if(file.size > maxSize) {
  21819. errorHandler(me.getLang('autoupload.exceedSizeError'));
  21820. return;
  21821. }
  21822. /* 判断文件格式是否超出允许 */
  21823. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')):'';
  21824. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  21825. errorHandler(me.getLang('autoupload.exceedTypeError'));
  21826. return;
  21827. }
  21828. /* 创建Ajax并提交 */
  21829. var xhr = new XMLHttpRequest(),
  21830. fd = new FormData(),
  21831. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21832. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + params);
  21833. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  21834. fd.append('type', 'ajax');
  21835. xhr.open("post", url, true);
  21836. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  21837. xhr.addEventListener('load', function (e) {
  21838. try{
  21839. var json = (new Function("return " + utils.trim(e.target.response)))();
  21840. if (json.state == 'SUCCESS' && json.url) {
  21841. successHandler(json);
  21842. } else {
  21843. errorHandler(json.state);
  21844. }
  21845. }catch(er){
  21846. errorHandler(me.getLang('autoupload.loadError'));
  21847. }
  21848. });
  21849. xhr.send(fd);
  21850. }
  21851. function getPasteImage(e){
  21852. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  21853. }
  21854. function getDropImage(e){
  21855. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  21856. }
  21857. return {
  21858. outputRule: function(root){
  21859. utils.each(root.getNodesByTagName('img'),function(n){
  21860. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  21861. n.parentNode.removeChild(n);
  21862. }
  21863. });
  21864. utils.each(root.getNodesByTagName('p'),function(n){
  21865. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  21866. n.parentNode.removeChild(n);
  21867. }
  21868. });
  21869. },
  21870. bindEvents:{
  21871. //插入粘贴板的图片,拖放插入图片
  21872. 'ready':function(e){
  21873. var me = this;
  21874. if(window.FormData && window.FileReader) {
  21875. domUtils.on(me.body, 'paste drop', function(e){
  21876. var hasImg = false,
  21877. items;
  21878. //获取粘贴板文件列表或者拖放文件列表
  21879. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  21880. if(items){
  21881. var len = items.length,
  21882. file;
  21883. while (len--){
  21884. file = items[len];
  21885. if(file.getAsFile) file = file.getAsFile();
  21886. if(file && file.size > 0) {
  21887. sendAndInsertFile(file, me);
  21888. hasImg = true;
  21889. }
  21890. }
  21891. hasImg && e.preventDefault();
  21892. }
  21893. });
  21894. //取消拖放图片时出现的文字光标位置提示
  21895. domUtils.on(me.body, 'dragover', function (e) {
  21896. if(e.dataTransfer.types[0] == 'Files') {
  21897. e.preventDefault();
  21898. }
  21899. });
  21900. //设置loading的样式
  21901. utils.cssRule('loading',
  21902. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  21903. + this.options.themePath
  21904. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  21905. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  21906. + this.options.themePath
  21907. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  21908. '}',
  21909. this.document);
  21910. }
  21911. }
  21912. }
  21913. }
  21914. });
  21915. // plugins/autosave.js
  21916. UE.plugin.register('autosave', function (){
  21917. var me = this,
  21918. //无限循环保护
  21919. lastSaveTime = new Date(),
  21920. //最小保存间隔时间
  21921. MIN_TIME = 20,
  21922. //auto save key
  21923. saveKey = null;
  21924. function save ( editor ) {
  21925. var saveData;
  21926. if ( new Date() - lastSaveTime < MIN_TIME ) {
  21927. return;
  21928. }
  21929. if ( !editor.hasContents() ) {
  21930. //这里不能调用命令来删除, 会造成事件死循环
  21931. saveKey && me.removePreferences( saveKey );
  21932. return;
  21933. }
  21934. lastSaveTime = new Date();
  21935. editor._saveFlag = null;
  21936. saveData = me.body.innerHTML;
  21937. if ( editor.fireEvent( "beforeautosave", {
  21938. content: saveData
  21939. } ) === false ) {
  21940. return;
  21941. }
  21942. me.setPreferences( saveKey, saveData );
  21943. editor.fireEvent( "afterautosave", {
  21944. content: saveData
  21945. } );
  21946. }
  21947. return {
  21948. defaultOptions: {
  21949. //默认间隔时间
  21950. saveInterval: 500,
  21951. enableAutoSave: true // HaoChuan9421
  21952. },
  21953. bindEvents:{
  21954. 'ready':function(){
  21955. var _suffix = "-drafts-data",
  21956. key = null;
  21957. if ( me.key ) {
  21958. key = me.key + _suffix;
  21959. } else {
  21960. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21961. }
  21962. //页面地址+编辑器ID 保持唯一
  21963. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21964. },
  21965. 'contentchange': function () {
  21966. // HaoChuan9421
  21967. if (!me.getOpt('enableAutoSave')) {
  21968. return;
  21969. }
  21970. if ( !saveKey ) {
  21971. return;
  21972. }
  21973. if ( me._saveFlag ) {
  21974. window.clearTimeout( me._saveFlag );
  21975. }
  21976. if ( me.options.saveInterval > 0 ) {
  21977. me._saveFlag = window.setTimeout( function () {
  21978. save( me );
  21979. }, me.options.saveInterval );
  21980. } else {
  21981. save(me);
  21982. }
  21983. }
  21984. },
  21985. commands:{
  21986. 'clearlocaldata':{
  21987. execCommand:function (cmd, name) {
  21988. if ( saveKey && me.getPreferences( saveKey ) ) {
  21989. me.removePreferences( saveKey )
  21990. }
  21991. },
  21992. notNeedUndo: true,
  21993. ignoreContentChange:true
  21994. },
  21995. 'getlocaldata':{
  21996. execCommand:function (cmd, name) {
  21997. return saveKey ? me.getPreferences( saveKey ) || '' : '';
  21998. },
  21999. notNeedUndo: true,
  22000. ignoreContentChange:true
  22001. },
  22002. 'drafts':{
  22003. execCommand:function (cmd, name) {
  22004. if ( saveKey ) {
  22005. me.body.innerHTML = me.getPreferences( saveKey ) || '<p>'+domUtils.fillHtml+'</p>';
  22006. me.focus(true);
  22007. }
  22008. },
  22009. queryCommandState: function () {
  22010. return saveKey ? ( me.getPreferences( saveKey ) === null ? -1 : 0 ) : -1;
  22011. },
  22012. notNeedUndo: true,
  22013. ignoreContentChange:true
  22014. }
  22015. }
  22016. }
  22017. });
  22018. // plugins/charts.js
  22019. UE.plugin.register('charts', function (){
  22020. var me = this;
  22021. return {
  22022. bindEvents: {
  22023. 'chartserror': function () {
  22024. }
  22025. },
  22026. commands:{
  22027. 'charts': {
  22028. execCommand: function ( cmd, data ) {
  22029. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  22030. flagText = [],
  22031. config = {};
  22032. if ( !tableNode ) {
  22033. return false;
  22034. }
  22035. if ( !validData( tableNode ) ) {
  22036. me.fireEvent( "chartserror" );
  22037. return false;
  22038. }
  22039. config.title = data.title || '';
  22040. config.subTitle = data.subTitle || '';
  22041. config.xTitle = data.xTitle || '';
  22042. config.yTitle = data.yTitle || '';
  22043. config.suffix = data.suffix || '';
  22044. config.tip = data.tip || '';
  22045. //数据对齐方式
  22046. config.dataFormat = data.tableDataFormat || '';
  22047. //图表类型
  22048. config.chartType = data.chartType || 0;
  22049. for ( var key in config ) {
  22050. if ( !config.hasOwnProperty( key ) ) {
  22051. continue;
  22052. }
  22053. flagText.push( key+":"+config[ key ] );
  22054. }
  22055. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  22056. domUtils.addClass( tableNode, "edui-charts-table" );
  22057. },
  22058. queryCommandState: function ( cmd, name ) {
  22059. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  22060. return tableNode && validData( tableNode ) ? 0 : -1;
  22061. }
  22062. }
  22063. },
  22064. inputRule:function(root){
  22065. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22066. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22067. tableNode.setAttr("style");
  22068. }
  22069. })
  22070. },
  22071. outputRule:function(root){
  22072. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22073. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22074. tableNode.setAttr("style", "display: none;");
  22075. }
  22076. })
  22077. }
  22078. }
  22079. function validData ( table ) {
  22080. var firstRows = null,
  22081. cellCount = 0;
  22082. //行数不够
  22083. if ( table.rows.length < 2 ) {
  22084. return false;
  22085. }
  22086. //列数不够
  22087. if ( table.rows[0].cells.length < 2 ) {
  22088. return false;
  22089. }
  22090. //第一行所有cell必须是th
  22091. firstRows = table.rows[ 0 ].cells;
  22092. cellCount = firstRows.length;
  22093. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  22094. if ( cell.tagName.toLowerCase() !== 'th' ) {
  22095. return false;
  22096. }
  22097. }
  22098. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  22099. //每行单元格数不匹配, 返回false
  22100. if ( row.cells.length != cellCount ) {
  22101. return false;
  22102. }
  22103. //第一列不是th也返回false
  22104. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  22105. return false;
  22106. }
  22107. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  22108. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  22109. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  22110. //必须是数字
  22111. if ( !/^\d*\.?\d+$/.test( value ) ) {
  22112. return false;
  22113. }
  22114. }
  22115. }
  22116. return true;
  22117. }
  22118. });
  22119. // plugins/section.js
  22120. /**
  22121. * 目录大纲支持插件
  22122. * @file
  22123. * @since 1.3.0
  22124. */
  22125. UE.plugin.register('section', function (){
  22126. /* 目录节点对象 */
  22127. function Section(option){
  22128. this.tag = '';
  22129. this.level = -1,
  22130. this.dom = null;
  22131. this.nextSection = null;
  22132. this.previousSection = null;
  22133. this.parentSection = null;
  22134. this.startAddress = [];
  22135. this.endAddress = [];
  22136. this.children = [];
  22137. }
  22138. function getSection(option) {
  22139. var section = new Section();
  22140. return utils.extend(section, option);
  22141. }
  22142. function getNodeFromAddress(startAddress, root) {
  22143. var current = root;
  22144. for(var i = 0;i < startAddress.length; i++) {
  22145. if(!current.childNodes) return null;
  22146. current = current.childNodes[startAddress[i]];
  22147. }
  22148. return current;
  22149. }
  22150. var me = this;
  22151. return {
  22152. bindMultiEvents:{
  22153. type: 'aftersetcontent afterscencerestore',
  22154. handler: function(){
  22155. me.fireEvent('updateSections');
  22156. }
  22157. },
  22158. bindEvents:{
  22159. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  22160. 'ready': function (){
  22161. me.fireEvent('updateSections');
  22162. domUtils.on(me.body, 'drop paste', function(){
  22163. me.fireEvent('updateSections');
  22164. });
  22165. },
  22166. /* 执行paragraph命令之后 */
  22167. 'afterexeccommand': function (type, cmd) {
  22168. if(cmd == 'paragraph') {
  22169. me.fireEvent('updateSections');
  22170. }
  22171. },
  22172. /* 部分键盘操作,触发updateSections事件 */
  22173. 'keyup': function (type, e) {
  22174. var me = this,
  22175. range = me.selection.getRange();
  22176. if(range.collapsed != true) {
  22177. me.fireEvent('updateSections');
  22178. } else {
  22179. var keyCode = e.keyCode || e.which;
  22180. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  22181. me.fireEvent('updateSections');
  22182. }
  22183. }
  22184. }
  22185. },
  22186. commands:{
  22187. 'getsections': {
  22188. execCommand: function (cmd, levels) {
  22189. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  22190. for (var i = 0; i < levelFn.length; i++) {
  22191. if (typeof levelFn[i] == 'string') {
  22192. levelFn[i] = function(fn){
  22193. return function(node){
  22194. return node.tagName == fn.toUpperCase()
  22195. };
  22196. }(levelFn[i]);
  22197. } else if (typeof levelFn[i] != 'function') {
  22198. levelFn[i] = function (node) {
  22199. return null;
  22200. }
  22201. }
  22202. }
  22203. function getSectionLevel(node) {
  22204. for (var i = 0; i < levelFn.length; i++) {
  22205. if (levelFn[i](node)) return i;
  22206. }
  22207. return -1;
  22208. }
  22209. var me = this,
  22210. Directory = getSection({'level':-1, 'title':'root'}),
  22211. previous = Directory;
  22212. function traversal(node, Directory) {
  22213. var level,
  22214. tmpSection = null,
  22215. parent,
  22216. child,
  22217. children = node.childNodes;
  22218. for (var i = 0, len = children.length; i < len; i++) {
  22219. child = children[i];
  22220. level = getSectionLevel(child);
  22221. if (level >= 0) {
  22222. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  22223. current = getSection({
  22224. 'tag': child.tagName,
  22225. 'title': child.innerText || child.textContent || '',
  22226. 'level': level,
  22227. 'dom': child,
  22228. 'startAddress': utils.clone(address, []),
  22229. 'endAddress': utils.clone(address, []),
  22230. 'children': []
  22231. });
  22232. previous.nextSection = current;
  22233. current.previousSection = previous;
  22234. parent = previous;
  22235. while(level <= parent.level){
  22236. parent = parent.parentSection;
  22237. }
  22238. current.parentSection = parent;
  22239. parent.children.push(current);
  22240. tmpSection = previous = current;
  22241. } else {
  22242. child.nodeType === 1 && traversal(child, Directory);
  22243. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  22244. }
  22245. }
  22246. }
  22247. traversal(me.body, Directory);
  22248. return Directory;
  22249. },
  22250. notNeedUndo: true
  22251. },
  22252. 'movesection': {
  22253. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  22254. var me = this,
  22255. targetAddress,
  22256. target;
  22257. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  22258. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  22259. target = getNodeFromAddress(targetAddress, me.body);
  22260. /* 判断目标地址是否被源章节包含 */
  22261. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  22262. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  22263. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  22264. current,
  22265. nextNode;
  22266. if(isAfter) {
  22267. current = endNode;
  22268. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  22269. nextNode = current.previousSibling;
  22270. domUtils.insertAfter(target, current);
  22271. if(current == startNode) break;
  22272. current = nextNode;
  22273. }
  22274. } else {
  22275. current = startNode;
  22276. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22277. nextNode = current.nextSibling;
  22278. target.parentNode.insertBefore(current, target);
  22279. if(current == endNode) break;
  22280. current = nextNode;
  22281. }
  22282. }
  22283. me.fireEvent('updateSections');
  22284. /* 获取地址的包含关系 */
  22285. function isContainsAddress(startAddress, endAddress, addressTarget){
  22286. var isAfterStartAddress = false,
  22287. isBeforeEndAddress = false;
  22288. for(var i = 0; i< startAddress.length; i++){
  22289. if(i >= addressTarget.length) break;
  22290. if(addressTarget[i] > startAddress[i]) {
  22291. isAfterStartAddress = true;
  22292. break;
  22293. } else if(addressTarget[i] < startAddress[i]) {
  22294. break;
  22295. }
  22296. }
  22297. for(var i = 0; i< endAddress.length; i++){
  22298. if(i >= addressTarget.length) break;
  22299. if(addressTarget[i] < startAddress[i]) {
  22300. isBeforeEndAddress = true;
  22301. break;
  22302. } else if(addressTarget[i] > startAddress[i]) {
  22303. break;
  22304. }
  22305. }
  22306. return isAfterStartAddress && isBeforeEndAddress;
  22307. }
  22308. }
  22309. },
  22310. 'deletesection': {
  22311. execCommand: function (cmd, section, keepChildren) {
  22312. var me = this;
  22313. if(!section) return;
  22314. function getNodeFromAddress(startAddress) {
  22315. var current = me.body;
  22316. for(var i = 0;i < startAddress.length; i++) {
  22317. if(!current.childNodes) return null;
  22318. current = current.childNodes[startAddress[i]];
  22319. }
  22320. return current;
  22321. }
  22322. var startNode = getNodeFromAddress(section.startAddress),
  22323. endNode = getNodeFromAddress(section.endAddress),
  22324. current = startNode,
  22325. nextNode;
  22326. if(!keepChildren) {
  22327. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22328. nextNode = current.nextSibling;
  22329. domUtils.remove(current);
  22330. current = nextNode;
  22331. }
  22332. } else {
  22333. domUtils.remove(current);
  22334. }
  22335. me.fireEvent('updateSections');
  22336. }
  22337. },
  22338. 'selectsection': {
  22339. execCommand: function (cmd, section) {
  22340. if(!section && !section.dom) return false;
  22341. var me = this,
  22342. range = me.selection.getRange(),
  22343. address = {
  22344. 'startAddress':utils.clone(section.startAddress, []),
  22345. 'endAddress':utils.clone(section.endAddress, [])
  22346. };
  22347. address.endAddress[address.endAddress.length - 1]++;
  22348. range.moveToAddress(address).select().scrollToView();
  22349. return true;
  22350. },
  22351. notNeedUndo: true
  22352. },
  22353. 'scrolltosection': {
  22354. execCommand: function (cmd, section) {
  22355. if(!section && !section.dom) return false;
  22356. var me = this,
  22357. range = me.selection.getRange(),
  22358. address = {
  22359. 'startAddress':section.startAddress,
  22360. 'endAddress':section.endAddress
  22361. };
  22362. address.endAddress[address.endAddress.length - 1]++;
  22363. range.moveToAddress(address).scrollToView();
  22364. return true;
  22365. },
  22366. notNeedUndo: true
  22367. }
  22368. }
  22369. }
  22370. });
  22371. // plugins/simpleupload.js
  22372. /**
  22373. * @description
  22374. * 简单上传:点击按钮,直接选择文件上传。
  22375. * 原 UEditor 作者使用了 form 表单 + iframe 的方式上传
  22376. * 但由于同源策略的限制,父页面无法访问跨域的 iframe 内容
  22377. * 导致无法获取接口返回的数据,使得单图上传无法在跨域的情况下使用
  22378. * 这里改为普通的XHR上传,兼容到IE10+
  22379. * @author HaoChuan9421 <hc199421@gmail.com>
  22380. * @date 2018-12-20
  22381. */
  22382. UE.plugin.register('simpleupload', function() {
  22383. var me = this,
  22384. containerBtn,
  22385. timestrap = (+new Date()).toString(36);
  22386. function initUploadBtn() {
  22387. var w = containerBtn.offsetWidth || 20,
  22388. h = containerBtn.offsetHeight || 20,
  22389. btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';
  22390. var form = document.createElement('form');
  22391. var input = document.createElement('input');
  22392. form.id = 'edui_form_' + timestrap;
  22393. form.enctype = 'multipart/form-data';
  22394. form.style = btnStyle;
  22395. input.id = 'edui_input_' + timestrap;
  22396. input.type = 'file'
  22397. input.accept = 'image/*';
  22398. input.name = me.options.imageFieldName;
  22399. input.style = btnStyle;
  22400. form.appendChild(input);
  22401. containerBtn.appendChild(form);
  22402. input.addEventListener('change', function(event) {
  22403. if (!input.value) return;
  22404. var loadingId = 'loading_' + (+new Date()).toString(36);
  22405. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22406. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22407. var action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?' : '&') + params);
  22408. var allowFiles = me.getOpt('imageAllowFiles');
  22409. me.focus();
  22410. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme + '/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22411. function showErrorLoader(title) {
  22412. if (loadingId) {
  22413. var loader = me.document.getElementById(loadingId);
  22414. loader && domUtils.remove(loader);
  22415. me.fireEvent('showmessage', {
  22416. 'id': loadingId,
  22417. 'content': title,
  22418. 'type': 'error',
  22419. 'timeout': 4000
  22420. });
  22421. }
  22422. }
  22423. /* 判断后端配置是否没有加载成功 */
  22424. if (!me.getOpt('imageActionName')) {
  22425. showErrorLoader(me.getLang('autoupload.errorLoadConfig'));
  22426. return;
  22427. }
  22428. // 判断文件格式是否错误
  22429. var filename = input.value,
  22430. fileext = filename ? filename.substr(filename.lastIndexOf('.')) : '';
  22431. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22432. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22433. return;
  22434. }
  22435. var xhr = new XMLHttpRequest()
  22436. xhr.open('post', action, true)
  22437. if (me.options.headers && Object.prototype.toString.apply(me.options.headers) === "[object Object]") {
  22438. for (var key in me.options.headers) {
  22439. xhr.setRequestHeader(key, me.options.headers[key])
  22440. }
  22441. }
  22442. xhr.onload = function() {
  22443. if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
  22444. var res = JSON.parse(xhr.responseText)
  22445. var link = me.options.imageUrlPrefix + res.url;
  22446. if (res.state == 'SUCCESS' && res.url) {
  22447. loader = me.document.getElementById(loadingId);
  22448. loader.setAttribute('src', link);
  22449. loader.setAttribute('_src', link);
  22450. loader.setAttribute('title', res.title || '');
  22451. loader.setAttribute('alt', res.original || '');
  22452. loader.removeAttribute('id');
  22453. domUtils.removeClasses(loader, 'loadingclass');
  22454. me.fireEvent("contentchange");
  22455. } else {
  22456. showErrorLoader(res.state);
  22457. }
  22458. } else {
  22459. showErrorLoader(me.getLang('simpleupload.loadError'));
  22460. }
  22461. };
  22462. xhr.onerror = function() {
  22463. showErrorLoader(me.getLang('simpleupload.loadError'));
  22464. };
  22465. xhr.send(new FormData(form));
  22466. form.reset();
  22467. })
  22468. }
  22469. return {
  22470. bindEvents: {
  22471. 'ready': function() {
  22472. //设置loading的样式
  22473. utils.cssRule('loading',
  22474. '.loadingclass{display:inline-block;cursor:default;background: url(\'' +
  22475. this.options.themePath +
  22476. this.options.theme + '/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22477. '.loaderrorclass{display:inline-block;cursor:default;background: url(\'' +
  22478. this.options.themePath +
  22479. this.options.theme + '/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22480. '}',
  22481. this.document);
  22482. },
  22483. /* 初始化简单上传按钮 */
  22484. 'simpleuploadbtnready': function(type, container) {
  22485. containerBtn = container;
  22486. me.afterConfigReady(initUploadBtn);
  22487. }
  22488. },
  22489. outputRule: function(root) {
  22490. utils.each(root.getNodesByTagName('img'), function(n) {
  22491. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22492. n.parentNode.removeChild(n);
  22493. }
  22494. });
  22495. }
  22496. }
  22497. });
  22498. // plugins/serverparam.js
  22499. /**
  22500. * 服务器提交的额外参数列表设置插件
  22501. * @file
  22502. * @since 1.2.6.1
  22503. */
  22504. UE.plugin.register('serverparam', function (){
  22505. var me = this,
  22506. serverParam = {};
  22507. return {
  22508. commands:{
  22509. /**
  22510. * 修改服务器提交的额外参数列表,清除所有项
  22511. * @command serverparam
  22512. * @method execCommand
  22513. * @param { String } cmd 命令字符串
  22514. * @example
  22515. * ```javascript
  22516. * editor.execCommand('serverparam');
  22517. * editor.queryCommandValue('serverparam'); //返回空
  22518. * ```
  22519. */
  22520. /**
  22521. * 修改服务器提交的额外参数列表,删除指定项
  22522. * @command serverparam
  22523. * @method execCommand
  22524. * @param { String } cmd 命令字符串
  22525. * @param { String } key 要清除的属性
  22526. * @example
  22527. * ```javascript
  22528. * editor.execCommand('serverparam', 'name'); //删除属性name
  22529. * ```
  22530. */
  22531. /**
  22532. * 修改服务器提交的额外参数列表,使用键值添加项
  22533. * @command serverparam
  22534. * @method execCommand
  22535. * @param { String } cmd 命令字符串
  22536. * @param { String } key 要添加的属性
  22537. * @param { String } value 要添加属性的值
  22538. * @example
  22539. * ```javascript
  22540. * editor.execCommand('serverparam', 'name', 'hello');
  22541. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22542. * ```
  22543. */
  22544. /**
  22545. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  22546. * @command serverparam
  22547. * @method execCommand
  22548. * @param { String } cmd 命令字符串
  22549. * @param { Object } key 传入的键值对对象
  22550. * @example
  22551. * ```javascript
  22552. * editor.execCommand('serverparam', {'name': 'hello'});
  22553. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22554. * ```
  22555. */
  22556. /**
  22557. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  22558. * @command serverparam
  22559. * @method execCommand
  22560. * @param { String } cmd 命令字符串
  22561. * @param { Function } key 自定义获取参数的函数
  22562. * @example
  22563. * ```javascript
  22564. * editor.execCommand('serverparam', function(editor){
  22565. * return {'key': 'value'};
  22566. * });
  22567. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  22568. * ```
  22569. */
  22570. /**
  22571. * 获取服务器提交的额外参数列表
  22572. * @command serverparam
  22573. * @method queryCommandValue
  22574. * @param { String } cmd 命令字符串
  22575. * @example
  22576. * ```javascript
  22577. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  22578. * ```
  22579. */
  22580. 'serverparam':{
  22581. execCommand:function (cmd, key, value) {
  22582. if (key === undefined || key === null) { //不传参数,清空列表
  22583. serverParam = {};
  22584. } else if (utils.isString(key)) { //传入键值
  22585. if(value === undefined || value === null) {
  22586. delete serverParam[key];
  22587. } else {
  22588. serverParam[key] = value;
  22589. }
  22590. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  22591. utils.extend(serverParam, key, true);
  22592. } else if (utils.isFunction(key)){ //传入函数,添加列表项
  22593. utils.extend(serverParam, key(), true);
  22594. }
  22595. },
  22596. queryCommandValue: function(){
  22597. return serverParam || {};
  22598. }
  22599. }
  22600. }
  22601. }
  22602. });
  22603. // plugins/insertfile.js
  22604. /**
  22605. * 插入附件
  22606. */
  22607. UE.plugin.register('insertfile', function (){
  22608. var me = this;
  22609. function getFileIcon(url){
  22610. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  22611. maps = {
  22612. "rar":"icon_rar.gif",
  22613. "zip":"icon_rar.gif",
  22614. "tar":"icon_rar.gif",
  22615. "gz":"icon_rar.gif",
  22616. "bz2":"icon_rar.gif",
  22617. "doc":"icon_doc.gif",
  22618. "docx":"icon_doc.gif",
  22619. "pdf":"icon_pdf.gif",
  22620. "mp3":"icon_mp3.gif",
  22621. "xls":"icon_xls.gif",
  22622. "chm":"icon_chm.gif",
  22623. "ppt":"icon_ppt.gif",
  22624. "pptx":"icon_ppt.gif",
  22625. "avi":"icon_mv.gif",
  22626. "rmvb":"icon_mv.gif",
  22627. "wmv":"icon_mv.gif",
  22628. "flv":"icon_mv.gif",
  22629. "swf":"icon_mv.gif",
  22630. "rm":"icon_mv.gif",
  22631. "exe":"icon_exe.gif",
  22632. "psd":"icon_psd.gif",
  22633. "txt":"icon_txt.gif",
  22634. "jpg":"icon_jpg.gif",
  22635. "png":"icon_jpg.gif",
  22636. "jpeg":"icon_jpg.gif",
  22637. "gif":"icon_jpg.gif",
  22638. "ico":"icon_jpg.gif",
  22639. "bmp":"icon_jpg.gif"
  22640. };
  22641. return maps[ext] ? maps[ext]:maps['txt'];
  22642. }
  22643. return {
  22644. commands:{
  22645. 'insertfile': {
  22646. execCommand: function (command, filelist){
  22647. filelist = utils.isArray(filelist) ? filelist : [filelist];
  22648. var i, item, icon, title,
  22649. html = '',
  22650. URL = me.getOpt('UEDITOR_HOME_URL'),
  22651. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '':'/') + 'dialogs/attachment/fileTypeImages/';
  22652. for (i = 0; i < filelist.length; i++) {
  22653. item = filelist[i];
  22654. icon = iconDir + getFileIcon(item.url);
  22655. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  22656. html += '<p style="line-height: 16px;">' +
  22657. '<img style="vertical-align: middle; margin-right: 2px;" src="'+ icon + '" _src="' + icon + '" />' +
  22658. '<a style="font-size:12px; color:#0066cc;" href="' + item.url +'" title="' + title + '">' + title + '</a>' +
  22659. '</p>';
  22660. }
  22661. me.execCommand('insertHtml', html);
  22662. }
  22663. }
  22664. }
  22665. }
  22666. });
  22667. // plugins/xssFilter.js
  22668. /**
  22669. * @file xssFilter.js
  22670. * @desc xss过滤器
  22671. * @author robbenmu
  22672. */
  22673. UE.plugins.xssFilter = function() {
  22674. var config = UEDITOR_CONFIG;
  22675. var whitList = config.whitList;
  22676. function filter(node) {
  22677. var tagName = node.tagName;
  22678. var attrs = node.attrs;
  22679. if (!whitList.hasOwnProperty(tagName)) {
  22680. node.parentNode.removeChild(node);
  22681. return false;
  22682. }
  22683. UE.utils.each(attrs, function (val, key) {
  22684. if (whitList[tagName].indexOf(key) === -1) {
  22685. node.setAttr(key);
  22686. }
  22687. });
  22688. }
  22689. // 添加inserthtml\paste等操作用的过滤规则
  22690. if (whitList && config.xssFilterRules) {
  22691. this.options.filterRules = function () {
  22692. var result = {};
  22693. UE.utils.each(whitList, function(val, key) {
  22694. result[key] = function (node) {
  22695. return filter(node);
  22696. };
  22697. });
  22698. return result;
  22699. }();
  22700. }
  22701. var tagList = [];
  22702. UE.utils.each(whitList, function (val, key) {
  22703. tagList.push(key);
  22704. });
  22705. // 添加input过滤规则
  22706. //
  22707. if (whitList && config.inputXssFilter) {
  22708. this.addInputRule(function (root) {
  22709. root.traversal(function(node) {
  22710. if (node.type !== 'element') {
  22711. return false;
  22712. }
  22713. filter(node);
  22714. });
  22715. });
  22716. }
  22717. // 添加output过滤规则
  22718. //
  22719. if (whitList && config.outputXssFilter) {
  22720. this.addOutputRule(function (root) {
  22721. root.traversal(function(node) {
  22722. if (node.type !== 'element') {
  22723. return false;
  22724. }
  22725. filter(node);
  22726. });
  22727. });
  22728. }
  22729. };
  22730. // ui/ui.js
  22731. var baidu = baidu || {};
  22732. baidu.editor = baidu.editor || {};
  22733. UE.ui = baidu.editor.ui = {};
  22734. // ui/uiutils.js
  22735. (function (){
  22736. var browser = baidu.editor.browser,
  22737. domUtils = baidu.editor.dom.domUtils;
  22738. var magic = '$EDITORUI';
  22739. var root = window[magic] = {};
  22740. var uidMagic = 'ID' + magic;
  22741. var uidCount = 0;
  22742. var uiUtils = baidu.editor.ui.uiUtils = {
  22743. uid: function (obj){
  22744. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  22745. },
  22746. hook: function ( fn, callback ) {
  22747. var dg;
  22748. if (fn && fn._callbacks) {
  22749. dg = fn;
  22750. } else {
  22751. dg = function (){
  22752. var q;
  22753. if (fn) {
  22754. q = fn.apply(this, arguments);
  22755. }
  22756. var callbacks = dg._callbacks;
  22757. var k = callbacks.length;
  22758. while (k --) {
  22759. var r = callbacks[k].apply(this, arguments);
  22760. if (q === undefined) {
  22761. q = r;
  22762. }
  22763. }
  22764. return q;
  22765. };
  22766. dg._callbacks = [];
  22767. }
  22768. dg._callbacks.push(callback);
  22769. return dg;
  22770. },
  22771. createElementByHtml: function (html){
  22772. var el = document.createElement('div');
  22773. el.innerHTML = html;
  22774. el = el.firstChild;
  22775. el.parentNode.removeChild(el);
  22776. return el;
  22777. },
  22778. getViewportElement: function (){
  22779. return (browser.ie && browser.quirks) ?
  22780. document.body : document.documentElement;
  22781. },
  22782. getClientRect: function (element){
  22783. var bcr;
  22784. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  22785. try{
  22786. bcr = element.getBoundingClientRect();
  22787. }catch(e){
  22788. bcr={left:0,top:0,height:0,width:0}
  22789. }
  22790. var rect = {
  22791. left: Math.round(bcr.left),
  22792. top: Math.round(bcr.top),
  22793. height: Math.round(bcr.bottom - bcr.top),
  22794. width: Math.round(bcr.right - bcr.left)
  22795. };
  22796. var doc;
  22797. while ((doc = element.ownerDocument) !== document &&
  22798. (element = domUtils.getWindow(doc).frameElement)) {
  22799. bcr = element.getBoundingClientRect();
  22800. rect.left += bcr.left;
  22801. rect.top += bcr.top;
  22802. }
  22803. rect.bottom = rect.top + rect.height;
  22804. rect.right = rect.left + rect.width;
  22805. return rect;
  22806. },
  22807. getViewportRect: function (){
  22808. var viewportEl = uiUtils.getViewportElement();
  22809. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  22810. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  22811. return {
  22812. left: 0,
  22813. top: 0,
  22814. height: height,
  22815. width: width,
  22816. bottom: height,
  22817. right: width
  22818. };
  22819. },
  22820. setViewportOffset: function (element, offset){
  22821. var rect;
  22822. var fixedLayer = uiUtils.getFixedLayer();
  22823. if (element.parentNode === fixedLayer) {
  22824. element.style.left = offset.left + 'px';
  22825. element.style.top = offset.top + 'px';
  22826. } else {
  22827. domUtils.setViewportOffset(element, offset);
  22828. }
  22829. },
  22830. getEventOffset: function (evt){
  22831. var el = evt.target || evt.srcElement;
  22832. var rect = uiUtils.getClientRect(el);
  22833. var offset = uiUtils.getViewportOffsetByEvent(evt);
  22834. return {
  22835. left: offset.left - rect.left,
  22836. top: offset.top - rect.top
  22837. };
  22838. },
  22839. getViewportOffsetByEvent: function (evt){
  22840. var el = evt.target || evt.srcElement;
  22841. var frameEl = domUtils.getWindow(el).frameElement;
  22842. var offset = {
  22843. left: evt.clientX,
  22844. top: evt.clientY
  22845. };
  22846. if (frameEl && el.ownerDocument !== document) {
  22847. var rect = uiUtils.getClientRect(frameEl);
  22848. offset.left += rect.left;
  22849. offset.top += rect.top;
  22850. }
  22851. return offset;
  22852. },
  22853. setGlobal: function (id, obj){
  22854. root[id] = obj;
  22855. return magic + '["' + id + '"]';
  22856. },
  22857. unsetGlobal: function (id){
  22858. delete root[id];
  22859. },
  22860. copyAttributes: function (tgt, src){
  22861. var attributes = src.attributes;
  22862. var k = attributes.length;
  22863. while (k --) {
  22864. var attrNode = attributes[k];
  22865. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  22866. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  22867. }
  22868. }
  22869. if (src.className) {
  22870. domUtils.addClass(tgt,src.className);
  22871. }
  22872. if (src.style.cssText) {
  22873. tgt.style.cssText += ';' + src.style.cssText;
  22874. }
  22875. },
  22876. removeStyle: function (el, styleName){
  22877. if (el.style.removeProperty) {
  22878. el.style.removeProperty(styleName);
  22879. } else if (el.style.removeAttribute) {
  22880. el.style.removeAttribute(styleName);
  22881. } else throw '';
  22882. },
  22883. contains: function (elA, elB){
  22884. return elA && elB && (elA === elB ? false : (
  22885. elA.contains ? elA.contains(elB) :
  22886. elA.compareDocumentPosition(elB) & 16
  22887. ));
  22888. },
  22889. startDrag: function (evt, callbacks,doc){
  22890. var doc = doc || document;
  22891. var startX = evt.clientX;
  22892. var startY = evt.clientY;
  22893. function handleMouseMove(evt){
  22894. var x = evt.clientX - startX;
  22895. var y = evt.clientY - startY;
  22896. callbacks.ondragmove(x, y,evt);
  22897. if (evt.stopPropagation) {
  22898. evt.stopPropagation();
  22899. } else {
  22900. evt.cancelBubble = true;
  22901. }
  22902. }
  22903. if (doc.addEventListener) {
  22904. function handleMouseUp(evt){
  22905. doc.removeEventListener('mousemove', handleMouseMove, true);
  22906. doc.removeEventListener('mouseup', handleMouseUp, true);
  22907. window.removeEventListener('mouseup', handleMouseUp, true);
  22908. callbacks.ondragstop();
  22909. }
  22910. doc.addEventListener('mousemove', handleMouseMove, true);
  22911. doc.addEventListener('mouseup', handleMouseUp, true);
  22912. window.addEventListener('mouseup', handleMouseUp, true);
  22913. evt.preventDefault();
  22914. } else {
  22915. var elm = evt.srcElement;
  22916. elm.setCapture();
  22917. function releaseCaptrue(){
  22918. elm.releaseCapture();
  22919. elm.detachEvent('onmousemove', handleMouseMove);
  22920. elm.detachEvent('onmouseup', releaseCaptrue);
  22921. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  22922. callbacks.ondragstop();
  22923. }
  22924. elm.attachEvent('onmousemove', handleMouseMove);
  22925. elm.attachEvent('onmouseup', releaseCaptrue);
  22926. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  22927. evt.returnValue = false;
  22928. }
  22929. callbacks.ondragstart();
  22930. },
  22931. getFixedLayer: function (){
  22932. var layer = document.getElementById('edui_fixedlayer');
  22933. if (layer == null) {
  22934. layer = document.createElement('div');
  22935. layer.id = 'edui_fixedlayer';
  22936. document.body.appendChild(layer);
  22937. if (browser.ie && browser.version <= 8) {
  22938. layer.style.position = 'absolute';
  22939. bindFixedLayer();
  22940. setTimeout(updateFixedOffset);
  22941. } else {
  22942. layer.style.position = 'fixed';
  22943. }
  22944. layer.style.left = '0';
  22945. layer.style.top = '0';
  22946. layer.style.width = '0';
  22947. layer.style.height = '0';
  22948. }
  22949. return layer;
  22950. },
  22951. makeUnselectable: function (element){
  22952. if (browser.opera || (browser.ie && browser.version < 9)) {
  22953. element.unselectable = 'on';
  22954. if (element.hasChildNodes()) {
  22955. for (var i=0; i<element.childNodes.length; i++) {
  22956. if (element.childNodes[i].nodeType == 1) {
  22957. uiUtils.makeUnselectable(element.childNodes[i]);
  22958. }
  22959. }
  22960. }
  22961. } else {
  22962. if (element.style.MozUserSelect !== undefined) {
  22963. element.style.MozUserSelect = 'none';
  22964. } else if (element.style.WebkitUserSelect !== undefined) {
  22965. element.style.WebkitUserSelect = 'none';
  22966. } else if (element.style.KhtmlUserSelect !== undefined) {
  22967. element.style.KhtmlUserSelect = 'none';
  22968. }
  22969. }
  22970. }
  22971. };
  22972. function updateFixedOffset(){
  22973. var layer = document.getElementById('edui_fixedlayer');
  22974. uiUtils.setViewportOffset(layer, {
  22975. left: 0,
  22976. top: 0
  22977. });
  22978. // layer.style.display = 'none';
  22979. // layer.style.display = 'block';
  22980. //#trace: 1354
  22981. // setTimeout(updateFixedOffset);
  22982. }
  22983. function bindFixedLayer(adjOffset){
  22984. domUtils.on(window, 'scroll', updateFixedOffset);
  22985. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  22986. }
  22987. })();
  22988. // ui/uibase.js
  22989. (function () {
  22990. var utils = baidu.editor.utils,
  22991. uiUtils = baidu.editor.ui.uiUtils,
  22992. EventBase = baidu.editor.EventBase,
  22993. UIBase = baidu.editor.ui.UIBase = function () {
  22994. };
  22995. UIBase.prototype = {
  22996. className:'',
  22997. uiName:'',
  22998. initOptions:function (options) {
  22999. var me = this;
  23000. for (var k in options) {
  23001. me[k] = options[k];
  23002. }
  23003. this.id = this.id || 'edui' + uiUtils.uid();
  23004. },
  23005. initUIBase:function () {
  23006. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  23007. },
  23008. render:function (holder) {
  23009. var html = this.renderHtml();
  23010. var el = uiUtils.createElementByHtml(html);
  23011. //by xuheng 给每个node添加class
  23012. var list = domUtils.getElementsByTagName(el, "*");
  23013. var theme = "edui-" + (this.theme || this.editor.options.theme);
  23014. var layer = document.getElementById('edui_fixedlayer');
  23015. for (var i = 0, node; node = list[i++];) {
  23016. domUtils.addClass(node, theme);
  23017. }
  23018. domUtils.addClass(el, theme);
  23019. if(layer){
  23020. layer.className="";
  23021. domUtils.addClass(layer,theme);
  23022. }
  23023. var seatEl = this.getDom();
  23024. if (seatEl != null) {
  23025. seatEl.parentNode.replaceChild(el, seatEl);
  23026. uiUtils.copyAttributes(el, seatEl);
  23027. } else {
  23028. if (typeof holder == 'string') {
  23029. holder = document.getElementById(holder);
  23030. }
  23031. holder = holder || uiUtils.getFixedLayer();
  23032. domUtils.addClass(holder, theme);
  23033. holder.appendChild(el);
  23034. }
  23035. this.postRender();
  23036. },
  23037. getDom:function (name) {
  23038. if (!name) {
  23039. return document.getElementById(this.id);
  23040. } else {
  23041. return document.getElementById(this.id + '_' + name);
  23042. }
  23043. },
  23044. postRender:function () {
  23045. this.fireEvent('postrender');
  23046. },
  23047. getHtmlTpl:function () {
  23048. return '';
  23049. },
  23050. formatHtml:function (tpl) {
  23051. var prefix = 'edui-' + this.uiName;
  23052. return (tpl
  23053. .replace(/##/g, this.id)
  23054. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  23055. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  23056. .replace(/\$\$/g, this._globalKey));
  23057. },
  23058. renderHtml:function () {
  23059. return this.formatHtml(this.getHtmlTpl());
  23060. },
  23061. dispose:function () {
  23062. var box = this.getDom();
  23063. if (box) baidu.editor.dom.domUtils.remove(box);
  23064. uiUtils.unsetGlobal(this.id);
  23065. }
  23066. };
  23067. utils.inherits(UIBase, EventBase);
  23068. })();
  23069. // ui/separator.js
  23070. (function (){
  23071. var utils = baidu.editor.utils,
  23072. UIBase = baidu.editor.ui.UIBase,
  23073. Separator = baidu.editor.ui.Separator = function (options){
  23074. this.initOptions(options);
  23075. this.initSeparator();
  23076. };
  23077. Separator.prototype = {
  23078. uiName: 'separator',
  23079. initSeparator: function (){
  23080. this.initUIBase();
  23081. },
  23082. getHtmlTpl: function (){
  23083. return '<div id="##" class="edui-box %%"></div>';
  23084. }
  23085. };
  23086. utils.inherits(Separator, UIBase);
  23087. })();
  23088. // ui/mask.js
  23089. ///import core
  23090. ///import uicore
  23091. (function (){
  23092. var utils = baidu.editor.utils,
  23093. domUtils = baidu.editor.dom.domUtils,
  23094. UIBase = baidu.editor.ui.UIBase,
  23095. uiUtils = baidu.editor.ui.uiUtils;
  23096. var Mask = baidu.editor.ui.Mask = function (options){
  23097. this.initOptions(options);
  23098. this.initUIBase();
  23099. };
  23100. Mask.prototype = {
  23101. getHtmlTpl: function (){
  23102. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  23103. },
  23104. postRender: function (){
  23105. var me = this;
  23106. domUtils.on(window, 'resize', function (){
  23107. setTimeout(function (){
  23108. if (!me.isHidden()) {
  23109. me._fill();
  23110. }
  23111. });
  23112. });
  23113. },
  23114. show: function (zIndex){
  23115. this._fill();
  23116. this.getDom().style.display = '';
  23117. this.getDom().style.zIndex = zIndex;
  23118. },
  23119. hide: function (){
  23120. this.getDom().style.display = 'none';
  23121. this.getDom().style.zIndex = '';
  23122. },
  23123. isHidden: function (){
  23124. return this.getDom().style.display == 'none';
  23125. },
  23126. _onMouseDown: function (){
  23127. return false;
  23128. },
  23129. _onClick: function (e, target){
  23130. this.fireEvent('click', e, target);
  23131. },
  23132. _fill: function (){
  23133. var el = this.getDom();
  23134. var vpRect = uiUtils.getViewportRect();
  23135. el.style.width = vpRect.width + 'px';
  23136. el.style.height = vpRect.height + 'px';
  23137. }
  23138. };
  23139. utils.inherits(Mask, UIBase);
  23140. })();
  23141. // ui/popup.js
  23142. ///import core
  23143. ///import uicore
  23144. (function () {
  23145. var utils = baidu.editor.utils,
  23146. uiUtils = baidu.editor.ui.uiUtils,
  23147. domUtils = baidu.editor.dom.domUtils,
  23148. UIBase = baidu.editor.ui.UIBase,
  23149. Popup = baidu.editor.ui.Popup = function (options){
  23150. this.initOptions(options);
  23151. this.initPopup();
  23152. };
  23153. var allPopups = [];
  23154. function closeAllPopup( evt,el ){
  23155. for ( var i = 0; i < allPopups.length; i++ ) {
  23156. var pop = allPopups[i];
  23157. if (!pop.isHidden()) {
  23158. if (pop.queryAutoHide(el) !== false) {
  23159. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  23160. pop.hide();
  23161. }
  23162. }
  23163. }
  23164. if(allPopups.length)
  23165. pop.editor.fireEvent("afterhidepop");
  23166. }
  23167. Popup.postHide = closeAllPopup;
  23168. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  23169. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  23170. Popup.prototype = {
  23171. SHADOW_RADIUS: 5,
  23172. content: null,
  23173. _hidden: false,
  23174. autoRender: true,
  23175. canSideLeft: true,
  23176. canSideUp: true,
  23177. initPopup: function (){
  23178. this.initUIBase();
  23179. allPopups.push( this );
  23180. },
  23181. getHtmlTpl: function (){
  23182. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  23183. ' <div id="##_body" class="edui-popup-body">' +
  23184. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  23185. ' <div class="edui-shadow"></div>' +
  23186. ' <div id="##_content" class="edui-popup-content">' +
  23187. this.getContentHtmlTpl() +
  23188. ' </div>' +
  23189. ' </div>' +
  23190. '</div>';
  23191. },
  23192. getContentHtmlTpl: function (){
  23193. if(this.content){
  23194. if (typeof this.content == 'string') {
  23195. return this.content;
  23196. }
  23197. return this.content.renderHtml();
  23198. }else{
  23199. return ''
  23200. }
  23201. },
  23202. _UIBase_postRender: UIBase.prototype.postRender,
  23203. postRender: function (){
  23204. if (this.content instanceof UIBase) {
  23205. this.content.postRender();
  23206. }
  23207. //捕获鼠标滚轮
  23208. if( this.captureWheel && !this.captured ) {
  23209. this.captured = true;
  23210. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  23211. _height = this.getDom().offsetHeight,
  23212. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  23213. content = this.getDom('content'),
  23214. ifr = this.getDom('body').getElementsByTagName('iframe'),
  23215. me = this;
  23216. ifr.length && ( ifr = ifr[0] );
  23217. while( _top + _height > winHeight ) {
  23218. _height -= 30;
  23219. }
  23220. content.style.height = _height + 'px';
  23221. //同步更改iframe高度
  23222. ifr && ( ifr.style.height = _height + 'px' );
  23223. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  23224. if( window.XMLHttpRequest ) {
  23225. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  23226. if(e.preventDefault) {
  23227. e.preventDefault();
  23228. } else {
  23229. e.returnValue = false;
  23230. }
  23231. if( e.wheelDelta ) {
  23232. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  23233. } else {
  23234. content.scrollTop -= ( e.detail / -3 )*60;
  23235. }
  23236. });
  23237. } else {
  23238. //ie6
  23239. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  23240. e.returnValue = false;
  23241. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  23242. });
  23243. }
  23244. }
  23245. this.fireEvent('postRenderAfter');
  23246. this.hide(true);
  23247. this._UIBase_postRender();
  23248. },
  23249. _doAutoRender: function (){
  23250. if (!this.getDom() && this.autoRender) {
  23251. this.render();
  23252. }
  23253. },
  23254. mesureSize: function (){
  23255. var box = this.getDom('content');
  23256. return uiUtils.getClientRect(box);
  23257. },
  23258. fitSize: function (){
  23259. if( this.captureWheel && this.sized ) {
  23260. return this.__size;
  23261. }
  23262. this.sized = true;
  23263. var popBodyEl = this.getDom('body');
  23264. popBodyEl.style.width = '';
  23265. popBodyEl.style.height = '';
  23266. var size = this.mesureSize();
  23267. if( this.captureWheel ) {
  23268. popBodyEl.style.width = -(-20 -size.width) + 'px';
  23269. var height = parseInt( this.getDom('content').style.height, 10 );
  23270. !window.isNaN( height ) && ( size.height = height );
  23271. } else {
  23272. popBodyEl.style.width = size.width + 'px';
  23273. }
  23274. popBodyEl.style.height = size.height + 'px';
  23275. this.__size = size;
  23276. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  23277. return size;
  23278. },
  23279. showAnchor: function ( element, hoz ){
  23280. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  23281. },
  23282. showAnchorRect: function ( rect, hoz, adj ){
  23283. this._doAutoRender();
  23284. var vpRect = uiUtils.getViewportRect();
  23285. this.getDom().style.visibility = 'hidden';
  23286. this._show();
  23287. var popSize = this.fitSize();
  23288. var sideLeft, sideUp, left, top;
  23289. if (hoz) {
  23290. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23291. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23292. left = (sideLeft ? rect.left - popSize.width : rect.right);
  23293. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  23294. } else {
  23295. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23296. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23297. left = (sideLeft ? rect.right - popSize.width : rect.left);
  23298. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  23299. }
  23300. var popEl = this.getDom();
  23301. uiUtils.setViewportOffset(popEl, {
  23302. left: left,
  23303. top: top
  23304. });
  23305. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  23306. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  23307. if(this.editor){
  23308. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  23309. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  23310. }
  23311. this.getDom().style.visibility = 'visible';
  23312. },
  23313. showAt: function (offset) {
  23314. var left = offset.left;
  23315. var top = offset.top;
  23316. var rect = {
  23317. left: left,
  23318. top: top,
  23319. right: left,
  23320. bottom: top,
  23321. height: 0,
  23322. width: 0
  23323. };
  23324. this.showAnchorRect(rect, false, true);
  23325. },
  23326. _show: function (){
  23327. if (this._hidden) {
  23328. var box = this.getDom();
  23329. box.style.display = '';
  23330. this._hidden = false;
  23331. // if (box.setActive) {
  23332. // box.setActive();
  23333. // }
  23334. this.fireEvent('show');
  23335. }
  23336. },
  23337. isHidden: function (){
  23338. return this._hidden;
  23339. },
  23340. show: function (){
  23341. this._doAutoRender();
  23342. this._show();
  23343. },
  23344. hide: function (notNofity){
  23345. if (!this._hidden && this.getDom()) {
  23346. this.getDom().style.display = 'none';
  23347. this._hidden = true;
  23348. if (!notNofity) {
  23349. this.fireEvent('hide');
  23350. }
  23351. }
  23352. },
  23353. queryAutoHide: function (el){
  23354. return !el || !uiUtils.contains(this.getDom(), el);
  23355. }
  23356. };
  23357. utils.inherits(Popup, UIBase);
  23358. domUtils.on( document, 'mousedown', function ( evt ) {
  23359. var el = evt.target || evt.srcElement;
  23360. closeAllPopup( evt,el );
  23361. } );
  23362. domUtils.on( window, 'scroll', function (evt,el) {
  23363. closeAllPopup( evt,el );
  23364. } );
  23365. })();
  23366. // ui/colorpicker.js
  23367. ///import core
  23368. ///import uicore
  23369. (function (){
  23370. var utils = baidu.editor.utils,
  23371. UIBase = baidu.editor.ui.UIBase,
  23372. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  23373. this.initOptions(options);
  23374. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  23375. this.initUIBase();
  23376. };
  23377. ColorPicker.prototype = {
  23378. getHtmlTpl: function (){
  23379. return genColorPicker(this.noColorText,this.editor);
  23380. },
  23381. _onTableClick: function (evt){
  23382. var tgt = evt.target || evt.srcElement;
  23383. var color = tgt.getAttribute('data-color');
  23384. if (color) {
  23385. this.fireEvent('pickcolor', color);
  23386. }
  23387. },
  23388. _onTableOver: function (evt){
  23389. var tgt = evt.target || evt.srcElement;
  23390. var color = tgt.getAttribute('data-color');
  23391. if (color) {
  23392. this.getDom('preview').style.backgroundColor = color;
  23393. }
  23394. },
  23395. _onTableOut: function (){
  23396. this.getDom('preview').style.backgroundColor = '';
  23397. },
  23398. _onPickNoColor: function (){
  23399. this.fireEvent('picknocolor');
  23400. }
  23401. };
  23402. utils.inherits(ColorPicker, UIBase);
  23403. var COLORS = (
  23404. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  23405. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  23406. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  23407. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  23408. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  23409. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  23410. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  23411. function genColorPicker(noColorText,editor){
  23412. var html = '<div id="##" class="edui-colorpicker %%">' +
  23413. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  23414. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  23415. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  23416. '</div>' +
  23417. '<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">' +
  23418. '<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>'+
  23419. '<tr class="edui-colorpicker-tablefirstrow" >';
  23420. for (var i=0; i<COLORS.length; i++) {
  23421. if (i && i%10 === 0) {
  23422. 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"':'')+'>';
  23423. }
  23424. 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"' +
  23425. ' data-color="#'+ COLORS[i] +'"'+
  23426. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  23427. (i<10 || i>=60?'border-width:1px;':
  23428. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  23429. 'border-width:0 1px 0 1px;')+
  23430. '"' +
  23431. '></a></td>':'';
  23432. }
  23433. html += '</tr></table></div>';
  23434. return html;
  23435. }
  23436. })();
  23437. // ui/tablepicker.js
  23438. ///import core
  23439. ///import uicore
  23440. (function (){
  23441. var utils = baidu.editor.utils,
  23442. uiUtils = baidu.editor.ui.uiUtils,
  23443. UIBase = baidu.editor.ui.UIBase;
  23444. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  23445. this.initOptions(options);
  23446. this.initTablePicker();
  23447. };
  23448. TablePicker.prototype = {
  23449. defaultNumRows: 10,
  23450. defaultNumCols: 10,
  23451. maxNumRows: 20,
  23452. maxNumCols: 20,
  23453. numRows: 10,
  23454. numCols: 10,
  23455. lengthOfCellSide: 22,
  23456. initTablePicker: function (){
  23457. this.initUIBase();
  23458. },
  23459. getHtmlTpl: function (){
  23460. var me = this;
  23461. return '<div id="##" class="edui-tablepicker %%">' +
  23462. '<div class="edui-tablepicker-body">' +
  23463. '<div class="edui-infoarea">' +
  23464. '<span id="##_label" class="edui-label"></span>' +
  23465. '</div>' +
  23466. '<div class="edui-pickarea"' +
  23467. ' onmousemove="$$._onMouseMove(event, this);"' +
  23468. ' onmouseover="$$._onMouseOver(event, this);"' +
  23469. ' onmouseout="$$._onMouseOut(event, this);"' +
  23470. ' onclick="$$._onClick(event, this);"' +
  23471. '>' +
  23472. '<div id="##_overlay" class="edui-overlay"></div>' +
  23473. '</div>' +
  23474. '</div>' +
  23475. '</div>';
  23476. },
  23477. _UIBase_render: UIBase.prototype.render,
  23478. render: function (holder){
  23479. this._UIBase_render(holder);
  23480. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  23481. },
  23482. _track: function (numCols, numRows){
  23483. var style = this.getDom('overlay').style;
  23484. var sideLen = this.lengthOfCellSide;
  23485. style.width = numCols * sideLen + 'px';
  23486. style.height = numRows * sideLen + 'px';
  23487. var label = this.getDom('label');
  23488. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  23489. this.numCols = numCols;
  23490. this.numRows = numRows;
  23491. },
  23492. _onMouseOver: function (evt, el){
  23493. var rel = evt.relatedTarget || evt.fromElement;
  23494. if (!uiUtils.contains(el, rel) && el !== rel) {
  23495. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23496. this.getDom('overlay').style.visibility = '';
  23497. }
  23498. },
  23499. _onMouseOut: function (evt, el){
  23500. var rel = evt.relatedTarget || evt.toElement;
  23501. if (!uiUtils.contains(el, rel) && el !== rel) {
  23502. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23503. this.getDom('overlay').style.visibility = 'hidden';
  23504. }
  23505. },
  23506. _onMouseMove: function (evt, el){
  23507. var style = this.getDom('overlay').style;
  23508. var offset = uiUtils.getEventOffset(evt);
  23509. var sideLen = this.lengthOfCellSide;
  23510. var numCols = Math.ceil(offset.left / sideLen);
  23511. var numRows = Math.ceil(offset.top / sideLen);
  23512. this._track(numCols, numRows);
  23513. },
  23514. _onClick: function (){
  23515. this.fireEvent('picktable', this.numCols, this.numRows);
  23516. }
  23517. };
  23518. utils.inherits(TablePicker, UIBase);
  23519. })();
  23520. // ui/stateful.js
  23521. (function (){
  23522. var browser = baidu.editor.browser,
  23523. domUtils = baidu.editor.dom.domUtils,
  23524. uiUtils = baidu.editor.ui.uiUtils;
  23525. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  23526. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  23527. ( browser.ie ? (
  23528. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  23529. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  23530. : (
  23531. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  23532. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  23533. baidu.editor.ui.Stateful = {
  23534. alwalysHoverable: false,
  23535. target:null,//目标元素和this指向dom不一样
  23536. Stateful_init: function (){
  23537. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  23538. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  23539. },
  23540. Stateful_getHtmlTpl: function (){
  23541. var tpl = this._Stateful_dGetHtmlTpl();
  23542. // 使用function避免$转义
  23543. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  23544. },
  23545. Stateful_onMouseEnter: function (evt, el){
  23546. this.target=el;
  23547. if (!this.isDisabled() || this.alwalysHoverable) {
  23548. this.addState('hover');
  23549. this.fireEvent('over');
  23550. }
  23551. },
  23552. Stateful_onMouseLeave: function (evt, el){
  23553. if (!this.isDisabled() || this.alwalysHoverable) {
  23554. this.removeState('hover');
  23555. this.removeState('active');
  23556. this.fireEvent('out');
  23557. }
  23558. },
  23559. Stateful_onMouseOver: function (evt, el){
  23560. var rel = evt.relatedTarget;
  23561. if (!uiUtils.contains(el, rel) && el !== rel) {
  23562. this.Stateful_onMouseEnter(evt, el);
  23563. }
  23564. },
  23565. Stateful_onMouseOut: function (evt, el){
  23566. var rel = evt.relatedTarget;
  23567. if (!uiUtils.contains(el, rel) && el !== rel) {
  23568. this.Stateful_onMouseLeave(evt, el);
  23569. }
  23570. },
  23571. Stateful_onMouseDown: function (evt, el){
  23572. if (!this.isDisabled()) {
  23573. this.addState('active');
  23574. }
  23575. },
  23576. Stateful_onMouseUp: function (evt, el){
  23577. if (!this.isDisabled()) {
  23578. this.removeState('active');
  23579. }
  23580. },
  23581. Stateful_postRender: function (){
  23582. if (this.disabled && !this.hasState('disabled')) {
  23583. this.addState('disabled');
  23584. }
  23585. },
  23586. hasState: function (state){
  23587. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  23588. },
  23589. addState: function (state){
  23590. if (!this.hasState(state)) {
  23591. this.getStateDom().className += ' edui-state-' + state;
  23592. }
  23593. },
  23594. removeState: function (state){
  23595. if (this.hasState(state)) {
  23596. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  23597. }
  23598. },
  23599. getStateDom: function (){
  23600. return this.getDom('state');
  23601. },
  23602. isChecked: function (){
  23603. return this.hasState('checked');
  23604. },
  23605. setChecked: function (checked){
  23606. if (!this.isDisabled() && checked) {
  23607. this.addState('checked');
  23608. } else {
  23609. this.removeState('checked');
  23610. }
  23611. },
  23612. isDisabled: function (){
  23613. return this.hasState('disabled');
  23614. },
  23615. setDisabled: function (disabled){
  23616. if (disabled) {
  23617. this.removeState('hover');
  23618. this.removeState('checked');
  23619. this.removeState('active');
  23620. this.addState('disabled');
  23621. } else {
  23622. this.removeState('disabled');
  23623. }
  23624. }
  23625. };
  23626. })();
  23627. // ui/button.js
  23628. ///import core
  23629. ///import uicore
  23630. ///import ui/stateful.js
  23631. (function (){
  23632. var utils = baidu.editor.utils,
  23633. UIBase = baidu.editor.ui.UIBase,
  23634. Stateful = baidu.editor.ui.Stateful,
  23635. Button = baidu.editor.ui.Button = function (options){
  23636. if(options.name){
  23637. var btnName = options.name;
  23638. var cssRules = options.cssRules;
  23639. if(!options.className){
  23640. options.className = 'edui-for-' + btnName;
  23641. }
  23642. options.cssRules = '.edui-default .edui-for-'+ btnName +' .edui-icon {'+ cssRules +'}'
  23643. }
  23644. this.initOptions(options);
  23645. this.initButton();
  23646. };
  23647. Button.prototype = {
  23648. uiName: 'button',
  23649. label: '',
  23650. title: '',
  23651. showIcon: true,
  23652. showText: true,
  23653. cssRules:'',
  23654. initButton: function (){
  23655. this.initUIBase();
  23656. this.Stateful_init();
  23657. if(this.cssRules){
  23658. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  23659. }
  23660. },
  23661. getHtmlTpl: function (){
  23662. return '<div id="##" class="edui-box %%">' +
  23663. '<div id="##_state" stateful>' +
  23664. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  23665. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  23666. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  23667. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  23668. '</div>' +
  23669. '</div>' +
  23670. '</div></div>';
  23671. },
  23672. postRender: function (){
  23673. this.Stateful_postRender();
  23674. this.setDisabled(this.disabled)
  23675. },
  23676. _onMouseDown: function (e){
  23677. var target = e.target || e.srcElement,
  23678. tagName = target && target.tagName && target.tagName.toLowerCase();
  23679. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  23680. return false;
  23681. }
  23682. },
  23683. _onClick: function (){
  23684. if (!this.isDisabled()) {
  23685. this.fireEvent('click');
  23686. }
  23687. },
  23688. setTitle: function(text){
  23689. var label = this.getDom('label');
  23690. label.innerHTML = text;
  23691. }
  23692. };
  23693. utils.inherits(Button, UIBase);
  23694. utils.extend(Button.prototype, Stateful);
  23695. })();
  23696. // ui/splitbutton.js
  23697. ///import core
  23698. ///import uicore
  23699. ///import ui/stateful.js
  23700. (function (){
  23701. var utils = baidu.editor.utils,
  23702. uiUtils = baidu.editor.ui.uiUtils,
  23703. domUtils = baidu.editor.dom.domUtils,
  23704. UIBase = baidu.editor.ui.UIBase,
  23705. Stateful = baidu.editor.ui.Stateful,
  23706. SplitButton = baidu.editor.ui.SplitButton = function (options){
  23707. this.initOptions(options);
  23708. this.initSplitButton();
  23709. };
  23710. SplitButton.prototype = {
  23711. popup: null,
  23712. uiName: 'splitbutton',
  23713. title: '',
  23714. initSplitButton: function (){
  23715. this.initUIBase();
  23716. this.Stateful_init();
  23717. var me = this;
  23718. if (this.popup != null) {
  23719. var popup = this.popup;
  23720. this.popup = null;
  23721. this.setPopup(popup);
  23722. }
  23723. },
  23724. _UIBase_postRender: UIBase.prototype.postRender,
  23725. postRender: function (){
  23726. this.Stateful_postRender();
  23727. this._UIBase_postRender();
  23728. },
  23729. setPopup: function (popup){
  23730. if (this.popup === popup) return;
  23731. if (this.popup != null) {
  23732. this.popup.dispose();
  23733. }
  23734. popup.addListener('show', utils.bind(this._onPopupShow, this));
  23735. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  23736. popup.addListener('postrender', utils.bind(function (){
  23737. popup.getDom('body').appendChild(
  23738. uiUtils.createElementByHtml('<div id="' +
  23739. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  23740. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  23741. );
  23742. popup.getDom().className += ' ' + this.className;
  23743. }, this));
  23744. this.popup = popup;
  23745. },
  23746. _onPopupShow: function (){
  23747. this.addState('opened');
  23748. },
  23749. _onPopupHide: function (){
  23750. this.removeState('opened');
  23751. },
  23752. getHtmlTpl: function (){
  23753. return '<div id="##" class="edui-box %%">' +
  23754. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  23755. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  23756. '<div class="edui-box edui-icon"></div>' +
  23757. '</div>' +
  23758. '<div class="edui-box edui-splitborder"></div>' +
  23759. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  23760. '</div></div></div>';
  23761. },
  23762. showPopup: function (){
  23763. // 当popup往上弹出的时候,做特殊处理
  23764. var rect = uiUtils.getClientRect(this.getDom());
  23765. rect.top -= this.popup.SHADOW_RADIUS;
  23766. rect.height += this.popup.SHADOW_RADIUS;
  23767. this.popup.showAnchorRect(rect);
  23768. },
  23769. _onArrowClick: function (event, el){
  23770. if (!this.isDisabled()) {
  23771. this.showPopup();
  23772. }
  23773. },
  23774. _onButtonClick: function (){
  23775. if (!this.isDisabled()) {
  23776. this.fireEvent('buttonclick');
  23777. }
  23778. }
  23779. };
  23780. utils.inherits(SplitButton, UIBase);
  23781. utils.extend(SplitButton.prototype, Stateful, true);
  23782. })();
  23783. // ui/colorbutton.js
  23784. ///import core
  23785. ///import uicore
  23786. ///import ui/colorpicker.js
  23787. ///import ui/popup.js
  23788. ///import ui/splitbutton.js
  23789. (function (){
  23790. var utils = baidu.editor.utils,
  23791. uiUtils = baidu.editor.ui.uiUtils,
  23792. ColorPicker = baidu.editor.ui.ColorPicker,
  23793. Popup = baidu.editor.ui.Popup,
  23794. SplitButton = baidu.editor.ui.SplitButton,
  23795. ColorButton = baidu.editor.ui.ColorButton = function (options){
  23796. this.initOptions(options);
  23797. this.initColorButton();
  23798. };
  23799. ColorButton.prototype = {
  23800. initColorButton: function (){
  23801. var me = this;
  23802. this.popup = new Popup({
  23803. content: new ColorPicker({
  23804. noColorText: me.editor.getLang("clearColor"),
  23805. editor:me.editor,
  23806. onpickcolor: function (t, color){
  23807. me._onPickColor(color);
  23808. },
  23809. onpicknocolor: function (t, color){
  23810. me._onPickNoColor(color);
  23811. }
  23812. }),
  23813. editor:me.editor
  23814. });
  23815. this.initSplitButton();
  23816. },
  23817. _SplitButton_postRender: SplitButton.prototype.postRender,
  23818. postRender: function (){
  23819. this._SplitButton_postRender();
  23820. this.getDom('button_body').appendChild(
  23821. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  23822. );
  23823. this.getDom().className += ' edui-colorbutton';
  23824. },
  23825. setColor: function (color){
  23826. this.getDom('colorlump').style.backgroundColor = color;
  23827. this.color = color;
  23828. },
  23829. _onPickColor: function (color){
  23830. if (this.fireEvent('pickcolor', color) !== false) {
  23831. this.setColor(color);
  23832. this.popup.hide();
  23833. }
  23834. },
  23835. _onPickNoColor: function (color){
  23836. if (this.fireEvent('picknocolor') !== false) {
  23837. this.popup.hide();
  23838. }
  23839. }
  23840. };
  23841. utils.inherits(ColorButton, SplitButton);
  23842. })();
  23843. // ui/tablebutton.js
  23844. ///import core
  23845. ///import uicore
  23846. ///import ui/popup.js
  23847. ///import ui/tablepicker.js
  23848. ///import ui/splitbutton.js
  23849. (function (){
  23850. var utils = baidu.editor.utils,
  23851. Popup = baidu.editor.ui.Popup,
  23852. TablePicker = baidu.editor.ui.TablePicker,
  23853. SplitButton = baidu.editor.ui.SplitButton,
  23854. TableButton = baidu.editor.ui.TableButton = function (options){
  23855. this.initOptions(options);
  23856. this.initTableButton();
  23857. };
  23858. TableButton.prototype = {
  23859. initTableButton: function (){
  23860. var me = this;
  23861. this.popup = new Popup({
  23862. content: new TablePicker({
  23863. editor:me.editor,
  23864. onpicktable: function (t, numCols, numRows){
  23865. me._onPickTable(numCols, numRows);
  23866. }
  23867. }),
  23868. 'editor':me.editor
  23869. });
  23870. this.initSplitButton();
  23871. },
  23872. _onPickTable: function (numCols, numRows){
  23873. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  23874. this.popup.hide();
  23875. }
  23876. }
  23877. };
  23878. utils.inherits(TableButton, SplitButton);
  23879. })();
  23880. // ui/autotypesetpicker.js
  23881. ///import core
  23882. ///import uicore
  23883. (function () {
  23884. var utils = baidu.editor.utils,
  23885. UIBase = baidu.editor.ui.UIBase;
  23886. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  23887. this.initOptions(options);
  23888. this.initAutoTypeSetPicker();
  23889. };
  23890. AutoTypeSetPicker.prototype = {
  23891. initAutoTypeSetPicker:function () {
  23892. this.initUIBase();
  23893. },
  23894. getHtmlTpl:function () {
  23895. var me = this.editor,
  23896. opt = me.options.autotypeset,
  23897. lang = me.getLang("autoTypeSet");
  23898. var textAlignInputName = 'textAlignValue' + me.uid,
  23899. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  23900. symbolConverInputName = 'symbolConverValue' + me.uid;
  23901. return '<div id="##" class="edui-autotypesetpicker %%">' +
  23902. '<div class="edui-autotypesetpicker-body">' +
  23903. '<table >' +
  23904. '<tr><td nowrap><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "" ) + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "" ) + '>' + lang.delLine + '</td></tr>' +
  23905. '<tr><td nowrap><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "" ) + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "" ) + '>' + lang.indent + '</td></tr>' +
  23906. '<tr>' +
  23907. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td>' +
  23908. '<td colspan="2" id="' + textAlignInputName + '">' +
  23909. '<input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23910. '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23911. '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23912. '</td>' +
  23913. '</tr>' +
  23914. '<tr>' +
  23915. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  23916. '<td nowrap id="'+ imageBlockInputName +'">' +
  23917. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  23918. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23919. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23920. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23921. '</td>' +
  23922. '</tr>' +
  23923. '<tr><td nowrap><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "" ) + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "" ) + '>' + lang.removeFontFamily + '</td></tr>' +
  23924. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  23925. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  23926. '<tr>' +
  23927. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "" ) + '>' + lang.symbol + '</td>' +
  23928. '<td id="' + symbolConverInputName + '">' +
  23929. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "" ) + '>' + lang.bdc2sb +
  23930. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "" ) + '>' + lang.tobdc + '' +
  23931. '</td>' +
  23932. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  23933. '</tr>' +
  23934. '</table>' +
  23935. '</div>' +
  23936. '</div>';
  23937. },
  23938. _UIBase_render:UIBase.prototype.render
  23939. };
  23940. utils.inherits(AutoTypeSetPicker, UIBase);
  23941. })();
  23942. // ui/autotypesetbutton.js
  23943. ///import core
  23944. ///import uicore
  23945. ///import ui/popup.js
  23946. ///import ui/autotypesetpicker.js
  23947. ///import ui/splitbutton.js
  23948. (function (){
  23949. var utils = baidu.editor.utils,
  23950. Popup = baidu.editor.ui.Popup,
  23951. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  23952. SplitButton = baidu.editor.ui.SplitButton,
  23953. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  23954. this.initOptions(options);
  23955. this.initAutoTypeSetButton();
  23956. };
  23957. function getPara(me){
  23958. var opt = {},
  23959. cont = me.getDom(),
  23960. editorId = me.editor.uid,
  23961. inputType = null,
  23962. attrName = null,
  23963. ipts = domUtils.getElementsByTagName(cont,"input");
  23964. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  23965. inputType = ipt.getAttribute("type");
  23966. if(inputType=="checkbox"){
  23967. attrName = ipt.getAttribute("name");
  23968. opt[attrName] && delete opt[attrName];
  23969. if(ipt.checked){
  23970. var attrValue = document.getElementById( attrName + "Value" + editorId );
  23971. if(attrValue){
  23972. if(/input/ig.test(attrValue.tagName)){
  23973. opt[attrName] = attrValue.value;
  23974. } else {
  23975. var iptChilds = attrValue.getElementsByTagName("input");
  23976. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  23977. if(iptchild.checked){
  23978. opt[attrName] = iptchild.value;
  23979. break;
  23980. }
  23981. }
  23982. }
  23983. } else {
  23984. opt[attrName] = true;
  23985. }
  23986. } else {
  23987. opt[attrName] = false;
  23988. }
  23989. } else {
  23990. opt[ipt.getAttribute("value")] = ipt.checked;
  23991. }
  23992. }
  23993. var selects = domUtils.getElementsByTagName(cont,"select");
  23994. for(var i=0,si;si=selects[i++];){
  23995. var attr = si.getAttribute('name');
  23996. opt[attr] = opt[attr] ? si.value : '';
  23997. }
  23998. utils.extend(me.editor.options.autotypeset,opt);
  23999. me.editor.setPreferences('autotypeset', opt);
  24000. }
  24001. AutoTypeSetButton.prototype = {
  24002. initAutoTypeSetButton: function (){
  24003. var me = this;
  24004. this.popup = new Popup({
  24005. //传入配置参数
  24006. content: new AutoTypeSetPicker({editor:me.editor}),
  24007. 'editor':me.editor,
  24008. hide : function(){
  24009. if (!this._hidden && this.getDom()) {
  24010. getPara(this);
  24011. this.getDom().style.display = 'none';
  24012. this._hidden = true;
  24013. this.fireEvent('hide');
  24014. }
  24015. }
  24016. });
  24017. var flag = 0;
  24018. this.popup.addListener('postRenderAfter',function(){
  24019. var popupUI = this;
  24020. if(flag)return;
  24021. var cont = this.getDom(),
  24022. btn = cont.getElementsByTagName('button')[0];
  24023. btn.onclick = function(){
  24024. getPara(popupUI);
  24025. me.editor.execCommand('autotypeset');
  24026. popupUI.hide()
  24027. };
  24028. domUtils.on(cont, 'click', function(e) {
  24029. var target = e.target || e.srcElement,
  24030. editorId = me.editor.uid;
  24031. if (target && target.tagName == 'INPUT') {
  24032. // 点击图片浮动的checkbox,去除对应的radio
  24033. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  24034. var checked = target.checked,
  24035. radioTd = document.getElementById( target.name + 'Value' + editorId),
  24036. radios = radioTd.getElementsByTagName('input'),
  24037. defalutSelect = {
  24038. 'imageBlockLine': 'none',
  24039. 'textAlign': 'left',
  24040. 'symbolConver': 'tobdc'
  24041. };
  24042. for (var i = 0; i < radios.length; i++) {
  24043. if (checked) {
  24044. if (radios[i].value == defalutSelect[target.name]) {
  24045. radios[i].checked = 'checked';
  24046. }
  24047. } else {
  24048. radios[i].checked = false;
  24049. }
  24050. }
  24051. }
  24052. // 点击radio,选中对应的checkbox
  24053. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  24054. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  24055. checkboxs && (checkboxs[0].checked = true);
  24056. }
  24057. getPara(popupUI);
  24058. }
  24059. });
  24060. flag = 1;
  24061. });
  24062. this.initSplitButton();
  24063. }
  24064. };
  24065. utils.inherits(AutoTypeSetButton, SplitButton);
  24066. })();
  24067. // ui/cellalignpicker.js
  24068. ///import core
  24069. ///import uicore
  24070. (function () {
  24071. var utils = baidu.editor.utils,
  24072. Popup = baidu.editor.ui.Popup,
  24073. Stateful = baidu.editor.ui.Stateful,
  24074. UIBase = baidu.editor.ui.UIBase;
  24075. /**
  24076. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  24077. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  24078. * @update 2013/4/2 hancong03@baidu.com
  24079. */
  24080. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  24081. this.initOptions(options);
  24082. this.initSelected();
  24083. this.initCellAlignPicker();
  24084. };
  24085. CellAlignPicker.prototype = {
  24086. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  24087. initSelected: function(){
  24088. var status = {
  24089. valign: {
  24090. top: 0,
  24091. middle: 1,
  24092. bottom: 2
  24093. },
  24094. align: {
  24095. left: 0,
  24096. center: 1,
  24097. right: 2
  24098. },
  24099. count: 3
  24100. },
  24101. result = -1;
  24102. if( this.selected ) {
  24103. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  24104. }
  24105. },
  24106. initCellAlignPicker:function () {
  24107. this.initUIBase();
  24108. this.Stateful_init();
  24109. },
  24110. getHtmlTpl:function () {
  24111. var alignType = [ 'left', 'center', 'right' ],
  24112. COUNT = 9,
  24113. tempClassName = null,
  24114. tempIndex = -1,
  24115. tmpl = [];
  24116. for( var i= 0; i<COUNT; i++ ) {
  24117. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  24118. tempIndex = i % 3;
  24119. tempIndex === 0 && tmpl.push('<tr>');
  24120. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  24121. tempIndex === 2 && tmpl.push('</tr>');
  24122. }
  24123. return '<div id="##" class="edui-cellalignpicker %%">' +
  24124. '<div class="edui-cellalignpicker-body">' +
  24125. '<table onclick="$$._onClick(event);">' +
  24126. tmpl.join('') +
  24127. '</table>' +
  24128. '</div>' +
  24129. '</div>';
  24130. },
  24131. getStateDom: function (){
  24132. return this.target;
  24133. },
  24134. _onClick: function (evt){
  24135. var target= evt.target || evt.srcElement;
  24136. if(/icon/.test(target.className)){
  24137. this.items[target.parentNode.getAttribute("index")].onclick();
  24138. Popup.postHide(evt);
  24139. }
  24140. },
  24141. _UIBase_render:UIBase.prototype.render
  24142. };
  24143. utils.inherits(CellAlignPicker, UIBase);
  24144. utils.extend(CellAlignPicker.prototype, Stateful,true);
  24145. })();
  24146. // ui/pastepicker.js
  24147. ///import core
  24148. ///import uicore
  24149. (function () {
  24150. var utils = baidu.editor.utils,
  24151. Stateful = baidu.editor.ui.Stateful,
  24152. uiUtils = baidu.editor.ui.uiUtils,
  24153. UIBase = baidu.editor.ui.UIBase;
  24154. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  24155. this.initOptions(options);
  24156. this.initPastePicker();
  24157. };
  24158. PastePicker.prototype = {
  24159. initPastePicker:function () {
  24160. this.initUIBase();
  24161. this.Stateful_init();
  24162. },
  24163. getHtmlTpl:function () {
  24164. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  24165. '<div class="edui-pastecontainer">' +
  24166. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  24167. '<div class="edui-button">' +
  24168. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  24169. '<div class="edui-richtxticon"></div></div>' +
  24170. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  24171. '<div class="edui-tagicon"></div></div>' +
  24172. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  24173. '<div class="edui-plaintxticon"></div></div>' +
  24174. '</div>' +
  24175. '</div>' +
  24176. '</div>'
  24177. },
  24178. getStateDom:function () {
  24179. return this.target;
  24180. },
  24181. format:function (param) {
  24182. this.editor.ui._isTransfer = true;
  24183. this.editor.fireEvent('pasteTransfer', param);
  24184. },
  24185. _onClick:function (cur) {
  24186. var node = domUtils.getNextDomNode(cur),
  24187. screenHt = uiUtils.getViewportRect().height,
  24188. subPop = uiUtils.getClientRect(node);
  24189. if ((subPop.top + subPop.height) > screenHt)
  24190. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  24191. else
  24192. node.style.top = "";
  24193. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  24194. node.style.visibility = "visible";
  24195. domUtils.addClass(cur, "edui-state-opened");
  24196. } else {
  24197. node.style.visibility = "hidden";
  24198. domUtils.removeClasses(cur, "edui-state-opened")
  24199. }
  24200. },
  24201. _UIBase_render:UIBase.prototype.render
  24202. };
  24203. utils.inherits(PastePicker, UIBase);
  24204. utils.extend(PastePicker.prototype, Stateful, true);
  24205. })();
  24206. // ui/toolbar.js
  24207. (function (){
  24208. var utils = baidu.editor.utils,
  24209. uiUtils = baidu.editor.ui.uiUtils,
  24210. UIBase = baidu.editor.ui.UIBase,
  24211. Toolbar = baidu.editor.ui.Toolbar = function (options){
  24212. this.initOptions(options);
  24213. this.initToolbar();
  24214. };
  24215. Toolbar.prototype = {
  24216. items: null,
  24217. initToolbar: function (){
  24218. this.items = this.items || [];
  24219. this.initUIBase();
  24220. },
  24221. add: function (item,index){
  24222. if(index === undefined){
  24223. this.items.push(item);
  24224. }else{
  24225. this.items.splice(index,0,item)
  24226. }
  24227. },
  24228. getHtmlTpl: function (){
  24229. var buff = [];
  24230. for (var i=0; i<this.items.length; i++) {
  24231. buff[i] = this.items[i].renderHtml();
  24232. }
  24233. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  24234. buff.join('') +
  24235. '</div>'
  24236. },
  24237. postRender: function (){
  24238. var box = this.getDom();
  24239. for (var i=0; i<this.items.length; i++) {
  24240. this.items[i].postRender();
  24241. }
  24242. uiUtils.makeUnselectable(box);
  24243. },
  24244. _onMouseDown: function (e){
  24245. var target = e.target || e.srcElement,
  24246. tagName = target && target.tagName && target.tagName.toLowerCase();
  24247. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  24248. return false;
  24249. }
  24250. }
  24251. };
  24252. utils.inherits(Toolbar, UIBase);
  24253. })();
  24254. // ui/menu.js
  24255. ///import core
  24256. ///import uicore
  24257. ///import ui\popup.js
  24258. ///import ui\stateful.js
  24259. (function () {
  24260. var utils = baidu.editor.utils,
  24261. domUtils = baidu.editor.dom.domUtils,
  24262. uiUtils = baidu.editor.ui.uiUtils,
  24263. UIBase = baidu.editor.ui.UIBase,
  24264. Popup = baidu.editor.ui.Popup,
  24265. Stateful = baidu.editor.ui.Stateful,
  24266. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  24267. Menu = baidu.editor.ui.Menu = function (options) {
  24268. this.initOptions(options);
  24269. this.initMenu();
  24270. };
  24271. var menuSeparator = {
  24272. renderHtml:function () {
  24273. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  24274. },
  24275. postRender:function () {
  24276. },
  24277. queryAutoHide:function () {
  24278. return true;
  24279. }
  24280. };
  24281. Menu.prototype = {
  24282. items:null,
  24283. uiName:'menu',
  24284. initMenu:function () {
  24285. this.items = this.items || [];
  24286. this.initPopup();
  24287. this.initItems();
  24288. },
  24289. initItems:function () {
  24290. for (var i = 0; i < this.items.length; i++) {
  24291. var item = this.items[i];
  24292. if (item == '-') {
  24293. this.items[i] = this.getSeparator();
  24294. } else if (!(item instanceof MenuItem)) {
  24295. item.editor = this.editor;
  24296. item.theme = this.editor.options.theme;
  24297. this.items[i] = this.createItem(item);
  24298. }
  24299. }
  24300. },
  24301. getSeparator:function () {
  24302. return menuSeparator;
  24303. },
  24304. createItem:function (item) {
  24305. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24306. item.menu = this;
  24307. return new MenuItem(item);
  24308. },
  24309. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  24310. getContentHtmlTpl:function () {
  24311. if (this.items.length == 0) {
  24312. return this._Popup_getContentHtmlTpl();
  24313. }
  24314. var buff = [];
  24315. for (var i = 0; i < this.items.length; i++) {
  24316. var item = this.items[i];
  24317. buff[i] = item.renderHtml();
  24318. }
  24319. return ('<div class="%%-body">' + buff.join('') + '</div>');
  24320. },
  24321. _Popup_postRender:Popup.prototype.postRender,
  24322. postRender:function () {
  24323. var me = this;
  24324. for (var i = 0; i < this.items.length; i++) {
  24325. var item = this.items[i];
  24326. item.ownerMenu = this;
  24327. item.postRender();
  24328. }
  24329. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  24330. evt = evt || event;
  24331. var rel = evt.relatedTarget || evt.fromElement;
  24332. var el = me.getDom();
  24333. if (!uiUtils.contains(el, rel) && el !== rel) {
  24334. me.fireEvent('over');
  24335. }
  24336. });
  24337. this._Popup_postRender();
  24338. },
  24339. queryAutoHide:function (el) {
  24340. if (el) {
  24341. if (uiUtils.contains(this.getDom(), el)) {
  24342. return false;
  24343. }
  24344. for (var i = 0; i < this.items.length; i++) {
  24345. var item = this.items[i];
  24346. if (item.queryAutoHide(el) === false) {
  24347. return false;
  24348. }
  24349. }
  24350. }
  24351. },
  24352. clearItems:function () {
  24353. for (var i = 0; i < this.items.length; i++) {
  24354. var item = this.items[i];
  24355. clearTimeout(item._showingTimer);
  24356. clearTimeout(item._closingTimer);
  24357. if (item.subMenu) {
  24358. item.subMenu.destroy();
  24359. }
  24360. }
  24361. this.items = [];
  24362. },
  24363. destroy:function () {
  24364. if (this.getDom()) {
  24365. domUtils.remove(this.getDom());
  24366. }
  24367. this.clearItems();
  24368. },
  24369. dispose:function () {
  24370. this.destroy();
  24371. }
  24372. };
  24373. utils.inherits(Menu, Popup);
  24374. /**
  24375. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24376. * @type {Function}
  24377. */
  24378. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  24379. this.initOptions(options);
  24380. this.initUIBase();
  24381. this.Stateful_init();
  24382. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  24383. if (options.className && options.className.indexOf("aligntd") != -1) {
  24384. var me = this;
  24385. //获取单元格对齐初始状态
  24386. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  24387. this.subMenu = new Popup({
  24388. content:new CellAlignPicker(this.subMenu),
  24389. parentMenu:me,
  24390. editor:me.editor,
  24391. destroy:function () {
  24392. if (this.getDom()) {
  24393. domUtils.remove(this.getDom());
  24394. }
  24395. }
  24396. });
  24397. this.subMenu.addListener("postRenderAfter", function () {
  24398. domUtils.on(this.getDom(), "mouseover", function () {
  24399. me.addState('opened');
  24400. });
  24401. });
  24402. } else {
  24403. this.subMenu = new Menu(this.subMenu);
  24404. }
  24405. }
  24406. };
  24407. MenuItem.prototype = {
  24408. label:'',
  24409. subMenu:null,
  24410. ownerMenu:null,
  24411. uiName:'menuitem',
  24412. alwalysHoverable:true,
  24413. getHtmlTpl:function () {
  24414. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  24415. '<div class="%%-body">' +
  24416. this.renderLabelHtml() +
  24417. '</div>' +
  24418. '</div>';
  24419. },
  24420. postRender:function () {
  24421. var me = this;
  24422. this.addListener('over', function () {
  24423. me.ownerMenu.fireEvent('submenuover', me);
  24424. if (me.subMenu) {
  24425. me.delayShowSubMenu();
  24426. }
  24427. });
  24428. if (this.subMenu) {
  24429. this.getDom().className += ' edui-hassubmenu';
  24430. this.subMenu.render();
  24431. this.addListener('out', function () {
  24432. me.delayHideSubMenu();
  24433. });
  24434. this.subMenu.addListener('over', function () {
  24435. clearTimeout(me._closingTimer);
  24436. me._closingTimer = null;
  24437. me.addState('opened');
  24438. });
  24439. this.ownerMenu.addListener('hide', function () {
  24440. me.hideSubMenu();
  24441. });
  24442. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  24443. if (subMenu !== me) {
  24444. me.delayHideSubMenu();
  24445. }
  24446. });
  24447. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  24448. this.subMenu.queryAutoHide = function (el) {
  24449. if (el && uiUtils.contains(me.getDom(), el)) {
  24450. return false;
  24451. }
  24452. return this._bakQueryAutoHide(el);
  24453. };
  24454. }
  24455. this.getDom().style.tabIndex = '-1';
  24456. uiUtils.makeUnselectable(this.getDom());
  24457. this.Stateful_postRender();
  24458. },
  24459. delayShowSubMenu:function () {
  24460. var me = this;
  24461. if (!me.isDisabled()) {
  24462. me.addState('opened');
  24463. clearTimeout(me._showingTimer);
  24464. clearTimeout(me._closingTimer);
  24465. me._closingTimer = null;
  24466. me._showingTimer = setTimeout(function () {
  24467. me.showSubMenu();
  24468. }, 250);
  24469. }
  24470. },
  24471. delayHideSubMenu:function () {
  24472. var me = this;
  24473. if (!me.isDisabled()) {
  24474. me.removeState('opened');
  24475. clearTimeout(me._showingTimer);
  24476. if (!me._closingTimer) {
  24477. me._closingTimer = setTimeout(function () {
  24478. if (!me.hasState('opened')) {
  24479. me.hideSubMenu();
  24480. }
  24481. me._closingTimer = null;
  24482. }, 400);
  24483. }
  24484. }
  24485. },
  24486. renderLabelHtml:function () {
  24487. return '<div class="edui-arrow"></div>' +
  24488. '<div class="edui-box edui-icon"></div>' +
  24489. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  24490. },
  24491. getStateDom:function () {
  24492. return this.getDom();
  24493. },
  24494. queryAutoHide:function (el) {
  24495. if (this.subMenu && this.hasState('opened')) {
  24496. return this.subMenu.queryAutoHide(el);
  24497. }
  24498. },
  24499. _onClick:function (event, this_) {
  24500. if (this.hasState('disabled')) return;
  24501. if (this.fireEvent('click', event, this_) !== false) {
  24502. if (this.subMenu) {
  24503. this.showSubMenu();
  24504. } else {
  24505. Popup.postHide(event);
  24506. }
  24507. }
  24508. },
  24509. showSubMenu:function () {
  24510. var rect = uiUtils.getClientRect(this.getDom());
  24511. rect.right -= 5;
  24512. rect.left += 2;
  24513. rect.width -= 7;
  24514. rect.top -= 4;
  24515. rect.bottom += 4;
  24516. rect.height += 8;
  24517. this.subMenu.showAnchorRect(rect, true, true);
  24518. },
  24519. hideSubMenu:function () {
  24520. this.subMenu.hide();
  24521. }
  24522. };
  24523. utils.inherits(MenuItem, UIBase);
  24524. utils.extend(MenuItem.prototype, Stateful, true);
  24525. })();
  24526. // ui/combox.js
  24527. ///import core
  24528. ///import uicore
  24529. ///import ui/menu.js
  24530. ///import ui/splitbutton.js
  24531. (function (){
  24532. // todo: menu和item提成通用list
  24533. var utils = baidu.editor.utils,
  24534. uiUtils = baidu.editor.ui.uiUtils,
  24535. Menu = baidu.editor.ui.Menu,
  24536. SplitButton = baidu.editor.ui.SplitButton,
  24537. Combox = baidu.editor.ui.Combox = function (options){
  24538. this.initOptions(options);
  24539. this.initCombox();
  24540. };
  24541. Combox.prototype = {
  24542. uiName: 'combox',
  24543. onbuttonclick:function () {
  24544. this.showPopup();
  24545. },
  24546. initCombox: function (){
  24547. var me = this;
  24548. this.items = this.items || [];
  24549. for (var i=0; i<this.items.length; i++) {
  24550. var item = this.items[i];
  24551. item.uiName = 'listitem';
  24552. item.index = i;
  24553. item.onclick = function (){
  24554. me.selectByIndex(this.index);
  24555. };
  24556. }
  24557. this.popup = new Menu({
  24558. items: this.items,
  24559. uiName: 'list',
  24560. editor:this.editor,
  24561. captureWheel: true,
  24562. combox: this
  24563. });
  24564. this.initSplitButton();
  24565. },
  24566. _SplitButton_postRender: SplitButton.prototype.postRender,
  24567. postRender: function (){
  24568. this._SplitButton_postRender();
  24569. this.setLabel(this.label || '');
  24570. this.setValue(this.initValue || '');
  24571. },
  24572. showPopup: function (){
  24573. var rect = uiUtils.getClientRect(this.getDom());
  24574. rect.top += 1;
  24575. rect.bottom -= 1;
  24576. rect.height -= 2;
  24577. this.popup.showAnchorRect(rect);
  24578. },
  24579. getValue: function (){
  24580. return this.value;
  24581. },
  24582. setValue: function (value){
  24583. var index = this.indexByValue(value);
  24584. if (index != -1) {
  24585. this.selectedIndex = index;
  24586. this.setLabel(this.items[index].label);
  24587. this.value = this.items[index].value;
  24588. } else {
  24589. this.selectedIndex = -1;
  24590. this.setLabel(this.getLabelForUnknowValue(value));
  24591. this.value = value;
  24592. }
  24593. },
  24594. setLabel: function (label){
  24595. this.getDom('button_body').innerHTML = label;
  24596. this.label = label;
  24597. },
  24598. getLabelForUnknowValue: function (value){
  24599. return value;
  24600. },
  24601. indexByValue: function (value){
  24602. for (var i=0; i<this.items.length; i++) {
  24603. if (value == this.items[i].value) {
  24604. return i;
  24605. }
  24606. }
  24607. return -1;
  24608. },
  24609. getItem: function (index){
  24610. return this.items[index];
  24611. },
  24612. selectByIndex: function (index){
  24613. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  24614. this.selectedIndex = index;
  24615. this.value = this.items[index].value;
  24616. this.setLabel(this.items[index].label);
  24617. }
  24618. }
  24619. };
  24620. utils.inherits(Combox, SplitButton);
  24621. })();
  24622. // ui/dialog.js
  24623. ///import core
  24624. ///import uicore
  24625. ///import ui/mask.js
  24626. ///import ui/button.js
  24627. (function (){
  24628. var utils = baidu.editor.utils,
  24629. domUtils = baidu.editor.dom.domUtils,
  24630. uiUtils = baidu.editor.ui.uiUtils,
  24631. Mask = baidu.editor.ui.Mask,
  24632. UIBase = baidu.editor.ui.UIBase,
  24633. Button = baidu.editor.ui.Button,
  24634. Dialog = baidu.editor.ui.Dialog = function (options){
  24635. if(options.name){
  24636. var name = options.name;
  24637. var cssRules = options.cssRules;
  24638. if(!options.className){
  24639. options.className = 'edui-for-' + name;
  24640. }
  24641. if(cssRules){
  24642. options.cssRules = '.edui-default .edui-for-'+ name +' .edui-dialog-content {'+ cssRules +'}'
  24643. }
  24644. }
  24645. this.initOptions(utils.extend({
  24646. autoReset: true,
  24647. draggable: true,
  24648. onok: function (){},
  24649. oncancel: function (){},
  24650. onclose: function (t, ok){
  24651. return ok ? this.onok() : this.oncancel();
  24652. },
  24653. //是否控制dialog中的scroll事件, 默认为不阻止
  24654. holdScroll: false
  24655. },options));
  24656. this.initDialog();
  24657. };
  24658. var modalMask;
  24659. var dragMask;
  24660. var activeDialog;
  24661. Dialog.prototype = {
  24662. draggable: false,
  24663. uiName: 'dialog',
  24664. initDialog: function (){
  24665. var me = this,
  24666. theme=this.editor.options.theme;
  24667. if(this.cssRules){
  24668. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  24669. }
  24670. this.initUIBase();
  24671. this.modalMask = (modalMask || (modalMask = new Mask({
  24672. className: 'edui-dialog-modalmask',
  24673. theme:theme,
  24674. onclick: function (){
  24675. activeDialog && activeDialog.close(false);
  24676. }
  24677. })));
  24678. this.dragMask = (dragMask || (dragMask = new Mask({
  24679. className: 'edui-dialog-dragmask',
  24680. theme:theme
  24681. })));
  24682. this.closeButton = new Button({
  24683. className: 'edui-dialog-closebutton',
  24684. title: me.closeDialog,
  24685. theme:theme,
  24686. onclick: function (){
  24687. me.close(false);
  24688. }
  24689. });
  24690. this.fullscreen && this.initResizeEvent();
  24691. if (this.buttons) {
  24692. for (var i=0; i<this.buttons.length; i++) {
  24693. if (!(this.buttons[i] instanceof Button)) {
  24694. this.buttons[i] = new Button(utils.extend(this.buttons[i],{
  24695. editor : this.editor
  24696. },true));
  24697. }
  24698. }
  24699. }
  24700. },
  24701. initResizeEvent: function () {
  24702. var me = this;
  24703. domUtils.on( window, "resize", function () {
  24704. if ( me._hidden || me._hidden === undefined ) {
  24705. return;
  24706. }
  24707. if ( me.__resizeTimer ) {
  24708. window.clearTimeout( me.__resizeTimer );
  24709. }
  24710. me.__resizeTimer = window.setTimeout( function () {
  24711. me.__resizeTimer = null;
  24712. var dialogWrapNode = me.getDom(),
  24713. contentNode = me.getDom('content'),
  24714. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24715. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  24716. vpRect = uiUtils.getViewportRect();
  24717. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24718. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24719. dialogWrapNode.style.width = vpRect.width + "px";
  24720. dialogWrapNode.style.height = vpRect.height + "px";
  24721. me.fireEvent( "resize" );
  24722. }, 100 );
  24723. } );
  24724. },
  24725. fitSize: function (){
  24726. var popBodyEl = this.getDom('body');
  24727. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  24728. // uiUtils.removeStyle(popBodyEl, 'width');
  24729. // uiUtils.removeStyle(popBodyEl, 'height');
  24730. // }
  24731. var size = this.mesureSize();
  24732. popBodyEl.style.width = size.width + 'px';
  24733. popBodyEl.style.height = size.height + 'px';
  24734. return size;
  24735. },
  24736. safeSetOffset: function (offset){
  24737. var me = this;
  24738. var el = me.getDom();
  24739. var vpRect = uiUtils.getViewportRect();
  24740. var rect = uiUtils.getClientRect(el);
  24741. var left = offset.left;
  24742. if (left + rect.width > vpRect.right) {
  24743. left = vpRect.right - rect.width;
  24744. }
  24745. var top = offset.top;
  24746. if (top + rect.height > vpRect.bottom) {
  24747. top = vpRect.bottom - rect.height;
  24748. }
  24749. el.style.left = Math.max(left, 0) + 'px';
  24750. el.style.top = Math.max(top, 0) + 'px';
  24751. },
  24752. showAtCenter: function (){
  24753. var vpRect = uiUtils.getViewportRect();
  24754. if ( !this.fullscreen ) {
  24755. this.getDom().style.display = '';
  24756. var popSize = this.fitSize();
  24757. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  24758. var left = vpRect.width / 2 - popSize.width / 2;
  24759. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  24760. var popEl = this.getDom();
  24761. this.safeSetOffset({
  24762. left: Math.max(left | 0, 0),
  24763. top: Math.max(top | 0, 0)
  24764. });
  24765. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  24766. popEl.className += ' edui-state-centered';
  24767. }
  24768. } else {
  24769. var dialogWrapNode = this.getDom(),
  24770. contentNode = this.getDom('content');
  24771. dialogWrapNode.style.display = "block";
  24772. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24773. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  24774. dialogWrapNode.style.left = "-100000px";
  24775. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24776. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24777. dialogWrapNode.style.width = vpRect.width + "px";
  24778. dialogWrapNode.style.height = vpRect.height + "px";
  24779. dialogWrapNode.style.left = 0;
  24780. //保存环境的overflow值
  24781. this._originalContext = {
  24782. html: {
  24783. overflowX: document.documentElement.style.overflowX,
  24784. overflowY: document.documentElement.style.overflowY
  24785. },
  24786. body: {
  24787. overflowX: document.body.style.overflowX,
  24788. overflowY: document.body.style.overflowY
  24789. }
  24790. };
  24791. document.documentElement.style.overflowX = 'hidden';
  24792. document.documentElement.style.overflowY = 'hidden';
  24793. document.body.style.overflowX = 'hidden';
  24794. document.body.style.overflowY = 'hidden';
  24795. }
  24796. this._show();
  24797. },
  24798. getContentHtml: function (){
  24799. var contentHtml = '';
  24800. if (typeof this.content == 'string') {
  24801. contentHtml = this.content;
  24802. } else if (this.iframeUrl) {
  24803. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  24804. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  24805. }
  24806. return contentHtml;
  24807. },
  24808. getHtmlTpl: function (){
  24809. var footHtml = '';
  24810. if (this.buttons) {
  24811. var buff = [];
  24812. for (var i=0; i<this.buttons.length; i++) {
  24813. buff[i] = this.buttons[i].renderHtml();
  24814. }
  24815. footHtml = '<div class="%%-foot">' +
  24816. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  24817. '</div>';
  24818. }
  24819. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  24820. '<div class="%%-shadow"></div>' +
  24821. '<div id="##_titlebar" class="%%-titlebar">' +
  24822. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  24823. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  24824. '</div>' +
  24825. this.closeButton.renderHtml() +
  24826. '</div>' +
  24827. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  24828. footHtml +
  24829. '</div></div></div>';
  24830. },
  24831. postRender: function (){
  24832. // todo: 保持居中/记住上次关闭位置选项
  24833. if (!this.modalMask.getDom()) {
  24834. this.modalMask.render();
  24835. this.modalMask.hide();
  24836. }
  24837. if (!this.dragMask.getDom()) {
  24838. this.dragMask.render();
  24839. this.dragMask.hide();
  24840. }
  24841. var me = this;
  24842. this.addListener('show', function (){
  24843. me.modalMask.show(this.getDom().style.zIndex - 2);
  24844. });
  24845. this.addListener('hide', function (){
  24846. me.modalMask.hide();
  24847. });
  24848. if (this.buttons) {
  24849. for (var i=0; i<this.buttons.length; i++) {
  24850. this.buttons[i].postRender();
  24851. }
  24852. }
  24853. domUtils.on(window, 'resize', function (){
  24854. setTimeout(function (){
  24855. if (!me.isHidden()) {
  24856. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  24857. }
  24858. });
  24859. });
  24860. //hold住scroll事件,防止dialog的滚动影响页面
  24861. // if( this.holdScroll ) {
  24862. //
  24863. // if( !me.iframeUrl ) {
  24864. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24865. // domUtils.preventDefault(e);
  24866. // } );
  24867. // } else {
  24868. // me.addListener('dialogafterreset', function(){
  24869. // window.setTimeout(function(){
  24870. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  24871. //
  24872. // if( browser.ie ) {
  24873. //
  24874. // var timer = window.setInterval(function(){
  24875. //
  24876. // if( iframeWindow.document && iframeWindow.document.body ) {
  24877. // window.clearInterval( timer );
  24878. // timer = null;
  24879. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24880. // domUtils.preventDefault(e);
  24881. // } );
  24882. // }
  24883. //
  24884. // }, 100);
  24885. //
  24886. // } else {
  24887. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24888. // domUtils.preventDefault(e);
  24889. // } );
  24890. // }
  24891. //
  24892. // }, 1);
  24893. // });
  24894. // }
  24895. //
  24896. // }
  24897. this._hide();
  24898. },
  24899. mesureSize: function (){
  24900. var body = this.getDom('body');
  24901. var width = uiUtils.getClientRect(this.getDom('content')).width;
  24902. var dialogBodyStyle = body.style;
  24903. dialogBodyStyle.width = width;
  24904. return uiUtils.getClientRect(body);
  24905. },
  24906. _onTitlebarMouseDown: function (evt, el){
  24907. if (this.draggable) {
  24908. var rect;
  24909. var vpRect = uiUtils.getViewportRect();
  24910. var me = this;
  24911. uiUtils.startDrag(evt, {
  24912. ondragstart: function (){
  24913. rect = uiUtils.getClientRect(me.getDom());
  24914. me.getDom('contmask').style.visibility = 'visible';
  24915. me.dragMask.show(me.getDom().style.zIndex - 1);
  24916. },
  24917. ondragmove: function (x, y){
  24918. var left = rect.left + x;
  24919. var top = rect.top + y;
  24920. me.safeSetOffset({
  24921. left: left,
  24922. top: top
  24923. });
  24924. },
  24925. ondragstop: function (){
  24926. me.getDom('contmask').style.visibility = 'hidden';
  24927. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  24928. me.dragMask.hide();
  24929. }
  24930. });
  24931. }
  24932. },
  24933. reset: function (){
  24934. this.getDom('content').innerHTML = this.getContentHtml();
  24935. this.fireEvent('dialogafterreset');
  24936. },
  24937. _show: function (){
  24938. if (this._hidden) {
  24939. this.getDom().style.display = '';
  24940. //要高过编辑器的zindxe
  24941. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  24942. this._hidden = false;
  24943. this.fireEvent('show');
  24944. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  24945. }
  24946. },
  24947. isHidden: function (){
  24948. return this._hidden;
  24949. },
  24950. _hide: function (){
  24951. if (!this._hidden) {
  24952. var wrapNode = this.getDom();
  24953. wrapNode.style.display = 'none';
  24954. wrapNode.style.zIndex = '';
  24955. wrapNode.style.width = '';
  24956. wrapNode.style.height = '';
  24957. this._hidden = true;
  24958. this.fireEvent('hide');
  24959. }
  24960. },
  24961. open: function (){
  24962. if (this.autoReset) {
  24963. //有可能还没有渲染
  24964. try{
  24965. this.reset();
  24966. }catch(e){
  24967. this.render();
  24968. this.open()
  24969. }
  24970. }
  24971. this.showAtCenter();
  24972. if (this.iframeUrl) {
  24973. try {
  24974. this.getDom('iframe').focus();
  24975. } catch(ex){}
  24976. }
  24977. activeDialog = this;
  24978. },
  24979. _onCloseButtonClick: function (evt, el){
  24980. this.close(false);
  24981. },
  24982. close: function (ok){
  24983. if (this.fireEvent('close', ok) !== false) {
  24984. //还原环境
  24985. if ( this.fullscreen ) {
  24986. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  24987. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  24988. document.body.style.overflowX = this._originalContext.body.overflowX;
  24989. document.body.style.overflowY = this._originalContext.body.overflowY;
  24990. delete this._originalContext;
  24991. }
  24992. this._hide();
  24993. //销毁content
  24994. var content = this.getDom('content');
  24995. var iframe = this.getDom('iframe');
  24996. if (content && iframe) {
  24997. var doc = iframe.contentDocument || iframe.contentWindow.document;
  24998. doc && (doc.body.innerHTML = '');
  24999. domUtils.remove(content);
  25000. }
  25001. }
  25002. }
  25003. };
  25004. utils.inherits(Dialog, UIBase);
  25005. })();
  25006. // ui/menubutton.js
  25007. ///import core
  25008. ///import uicore
  25009. ///import ui/menu.js
  25010. ///import ui/splitbutton.js
  25011. (function (){
  25012. var utils = baidu.editor.utils,
  25013. Menu = baidu.editor.ui.Menu,
  25014. SplitButton = baidu.editor.ui.SplitButton,
  25015. MenuButton = baidu.editor.ui.MenuButton = function (options){
  25016. this.initOptions(options);
  25017. this.initMenuButton();
  25018. };
  25019. MenuButton.prototype = {
  25020. initMenuButton: function (){
  25021. var me = this;
  25022. this.uiName = "menubutton";
  25023. this.popup = new Menu({
  25024. items: me.items,
  25025. className: me.className,
  25026. editor:me.editor
  25027. });
  25028. this.popup.addListener('show', function (){
  25029. var list = this;
  25030. for (var i=0; i<list.items.length; i++) {
  25031. list.items[i].removeState('checked');
  25032. if (list.items[i].value == me._value) {
  25033. list.items[i].addState('checked');
  25034. this.value = me._value;
  25035. }
  25036. }
  25037. });
  25038. this.initSplitButton();
  25039. },
  25040. setValue : function(value){
  25041. this._value = value;
  25042. }
  25043. };
  25044. utils.inherits(MenuButton, SplitButton);
  25045. })();
  25046. // ui/multiMenu.js
  25047. ///import core
  25048. ///import uicore
  25049. ///commands 表情
  25050. (function(){
  25051. var utils = baidu.editor.utils,
  25052. Popup = baidu.editor.ui.Popup,
  25053. SplitButton = baidu.editor.ui.SplitButton,
  25054. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  25055. this.initOptions(options);
  25056. this.initMultiMenu();
  25057. };
  25058. MultiMenuPop.prototype = {
  25059. initMultiMenu: function (){
  25060. var me = this;
  25061. this.popup = new Popup({
  25062. content: '',
  25063. editor : me.editor,
  25064. iframe_rendered: false,
  25065. onshow: function (){
  25066. if (!this.iframe_rendered) {
  25067. this.iframe_rendered = true;
  25068. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  25069. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25070. }
  25071. }
  25072. // canSideUp:false,
  25073. // canSideLeft:false
  25074. });
  25075. this.onbuttonclick = function(){
  25076. this.showPopup();
  25077. };
  25078. this.initSplitButton();
  25079. }
  25080. };
  25081. utils.inherits(MultiMenuPop, SplitButton);
  25082. })();
  25083. // ui/shortcutmenu.js
  25084. (function () {
  25085. var UI = baidu.editor.ui,
  25086. UIBase = UI.UIBase,
  25087. uiUtils = UI.uiUtils,
  25088. utils = baidu.editor.utils,
  25089. domUtils = baidu.editor.dom.domUtils;
  25090. var allMenus = [],//存储所有快捷菜单
  25091. timeID,
  25092. isSubMenuShow = false;//是否有子pop显示
  25093. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25094. this.initOptions (options);
  25095. this.initShortCutMenu ();
  25096. };
  25097. ShortCutMenu.postHide = hideAllMenu;
  25098. ShortCutMenu.prototype = {
  25099. isHidden : true ,
  25100. SPACE : 5 ,
  25101. initShortCutMenu : function () {
  25102. this.items = this.items || [];
  25103. this.initUIBase ();
  25104. this.initItems ();
  25105. this.initEvent ();
  25106. allMenus.push (this);
  25107. } ,
  25108. initEvent : function () {
  25109. var me = this,
  25110. doc = me.editor.document;
  25111. domUtils.on (doc , "mousemove" , function (e) {
  25112. if (me.isHidden === false) {
  25113. //有pop显示就不隐藏快捷菜单
  25114. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  25115. var flag = true,
  25116. el = me.getDom (),
  25117. wt = el.offsetWidth,
  25118. ht = el.offsetHeight,
  25119. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25120. distanceY = ht / 2,//距离中心Y标准
  25121. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  25122. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  25123. clearTimeout (timeID);
  25124. timeID = setTimeout (function () {
  25125. if (y > 0 && y < distanceY) {
  25126. me.setOpacity (el , "1");
  25127. } else if (y > distanceY && y < distanceY + 70) {
  25128. me.setOpacity (el , "0.5");
  25129. flag = false;
  25130. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25131. me.hide ();
  25132. }
  25133. if (flag && x > 0 && x < distanceX) {
  25134. me.setOpacity (el , "1")
  25135. } else if (x > distanceX && x < distanceX + 70) {
  25136. me.setOpacity (el , "0.5")
  25137. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25138. me.hide ();
  25139. }
  25140. });
  25141. }
  25142. });
  25143. //ie\ff下 mouseout不准
  25144. if (browser.chrome) {
  25145. domUtils.on (doc , "mouseout" , function (e) {
  25146. var relatedTgt = e.relatedTarget || e.toElement;
  25147. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25148. me.hide ();
  25149. }
  25150. });
  25151. }
  25152. me.editor.addListener ("afterhidepop" , function () {
  25153. if (!me.isHidden) {
  25154. isSubMenuShow = true;
  25155. }
  25156. });
  25157. } ,
  25158. initItems : function () {
  25159. if (utils.isArray (this.items)) {
  25160. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25161. var item = this.items[i].toLowerCase ();
  25162. if (UI[item]) {
  25163. this.items[i] = new UI[item] (this.editor);
  25164. this.items[i].className += " edui-shortcutsubmenu ";
  25165. }
  25166. }
  25167. }
  25168. } ,
  25169. setOpacity : function (el , value) {
  25170. if (browser.ie && browser.version < 9) {
  25171. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25172. } else {
  25173. el.style.opacity = value;
  25174. }
  25175. } ,
  25176. getSubMenuMark : function () {
  25177. isSubMenuShow = false;
  25178. var layerEle = uiUtils.getFixedLayer ();
  25179. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25180. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25181. });
  25182. for (var i = 0, node ; node = list[i++] ;) {
  25183. if (node.style.display != "none") {
  25184. isSubMenuShow = true;
  25185. }
  25186. }
  25187. return isSubMenuShow;
  25188. } ,
  25189. show : function (e , hasContextmenu) {
  25190. var me = this,
  25191. offset = {},
  25192. el = this.getDom (),
  25193. fixedlayer = uiUtils.getFixedLayer ();
  25194. function setPos (offset) {
  25195. if (offset.left < 0) {
  25196. offset.left = 0;
  25197. }
  25198. if (offset.top < 0) {
  25199. offset.top = 0;
  25200. }
  25201. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25202. }
  25203. function setPosByCxtMenu (menu) {
  25204. if (!menu.tagName) {
  25205. menu = menu.getDom ();
  25206. }
  25207. offset.left = parseInt (menu.style.left);
  25208. offset.top = parseInt (menu.style.top);
  25209. offset.top -= el.offsetHeight + 15;
  25210. setPos (offset);
  25211. }
  25212. me.eventType = e.type;
  25213. el.style.cssText = "display:block;left:-9999px";
  25214. if (e.type == "contextmenu" && hasContextmenu) {
  25215. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25216. if (menu) {
  25217. setPosByCxtMenu (menu)
  25218. } else {
  25219. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25220. setPosByCxtMenu (menu);
  25221. });
  25222. }
  25223. } else {
  25224. offset = uiUtils.getViewportOffsetByEvent (e);
  25225. offset.top -= el.offsetHeight + me.SPACE;
  25226. offset.left += me.SPACE + 20;
  25227. setPos (offset);
  25228. me.setOpacity (el , 0.2);
  25229. }
  25230. me.isHidden = false;
  25231. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25232. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25233. if (me.editor) {
  25234. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25235. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25236. }
  25237. } ,
  25238. hide : function () {
  25239. if (this.getDom ()) {
  25240. this.getDom ().style.display = "none";
  25241. }
  25242. this.isHidden = true;
  25243. } ,
  25244. postRender : function () {
  25245. if (utils.isArray (this.items)) {
  25246. for (var i = 0, item ; item = this.items[i++] ;) {
  25247. item.postRender ();
  25248. }
  25249. }
  25250. } ,
  25251. getHtmlTpl : function () {
  25252. var buff;
  25253. if (utils.isArray (this.items)) {
  25254. buff = [];
  25255. for (var i = 0 ; i < this.items.length ; i++) {
  25256. buff[i] = this.items[i].renderHtml ();
  25257. }
  25258. buff = buff.join ("");
  25259. } else {
  25260. buff = this.items;
  25261. }
  25262. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25263. buff +
  25264. '</div>';
  25265. }
  25266. };
  25267. utils.inherits (ShortCutMenu , UIBase);
  25268. function hideAllMenu (e) {
  25269. var tgt = e.target || e.srcElement,
  25270. cur = domUtils.findParent (tgt , function (node) {
  25271. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25272. } , true);
  25273. if (!cur) {
  25274. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25275. menu.hide ()
  25276. }
  25277. }
  25278. }
  25279. domUtils.on (document , 'mousedown' , function (e) {
  25280. hideAllMenu (e);
  25281. });
  25282. domUtils.on (window , 'scroll' , function (e) {
  25283. hideAllMenu (e);
  25284. });
  25285. }) ();
  25286. // ui/breakline.js
  25287. (function (){
  25288. var utils = baidu.editor.utils,
  25289. UIBase = baidu.editor.ui.UIBase,
  25290. Breakline = baidu.editor.ui.Breakline = function (options){
  25291. this.initOptions(options);
  25292. this.initSeparator();
  25293. };
  25294. Breakline.prototype = {
  25295. uiName: 'Breakline',
  25296. initSeparator: function (){
  25297. this.initUIBase();
  25298. },
  25299. getHtmlTpl: function (){
  25300. return '<br/>';
  25301. }
  25302. };
  25303. utils.inherits(Breakline, UIBase);
  25304. })();
  25305. // ui/message.js
  25306. ///import core
  25307. ///import uicore
  25308. (function () {
  25309. var utils = baidu.editor.utils,
  25310. domUtils = baidu.editor.dom.domUtils,
  25311. UIBase = baidu.editor.ui.UIBase,
  25312. Message = baidu.editor.ui.Message = function (options){
  25313. this.initOptions(options);
  25314. this.initMessage();
  25315. };
  25316. Message.prototype = {
  25317. initMessage: function (){
  25318. this.initUIBase();
  25319. },
  25320. getHtmlTpl: function (){
  25321. return '<div id="##" class="edui-message %%">' +
  25322. ' <div id="##_closer" class="edui-message-closer">×</div>' +
  25323. ' <div id="##_body" class="edui-message-body edui-message-type-info">' +
  25324. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  25325. ' <div class="edui-shadow"></div>' +
  25326. ' <div id="##_content" class="edui-message-content">' +
  25327. ' </div>' +
  25328. ' </div>' +
  25329. '</div>';
  25330. },
  25331. reset: function(opt){
  25332. var me = this;
  25333. if (!opt.keepshow) {
  25334. clearTimeout(this.timer);
  25335. me.timer = setTimeout(function(){
  25336. me.hide();
  25337. }, opt.timeout || 4000);
  25338. }
  25339. opt.content !== undefined && me.setContent(opt.content);
  25340. opt.type !== undefined && me.setType(opt.type);
  25341. me.show();
  25342. },
  25343. postRender: function(){
  25344. var me = this,
  25345. closer = this.getDom('closer');
  25346. closer && domUtils.on(closer, 'click', function(){
  25347. me.hide();
  25348. });
  25349. },
  25350. setContent: function(content){
  25351. this.getDom('content').innerHTML = content;
  25352. },
  25353. setType: function(type){
  25354. type = type || 'info';
  25355. var body = this.getDom('body');
  25356. body.className = body.className.replace(/edui-message-type-[\w-]+/, 'edui-message-type-' + type);
  25357. },
  25358. getContent: function(){
  25359. return this.getDom('content').innerHTML;
  25360. },
  25361. getType: function(){
  25362. var arr = this.getDom('body').match(/edui-message-type-([\w-]+)/);
  25363. return arr ? arr[1]:'';
  25364. },
  25365. show: function (){
  25366. this.getDom().style.display = 'block';
  25367. },
  25368. hide: function (){
  25369. var dom = this.getDom();
  25370. if (dom) {
  25371. dom.style.display = 'none';
  25372. dom.parentNode && dom.parentNode.removeChild(dom);
  25373. }
  25374. }
  25375. };
  25376. utils.inherits(Message, UIBase);
  25377. })();
  25378. // adapter/editorui.js
  25379. //ui跟编辑器的适配層
  25380. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  25381. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  25382. (function () {
  25383. var utils = baidu.editor.utils;
  25384. var editorui = baidu.editor.ui;
  25385. var _Dialog = editorui.Dialog;
  25386. editorui.buttons = {};
  25387. editorui.Dialog = function (options) {
  25388. var dialog = new _Dialog(options);
  25389. dialog.addListener('hide', function () {
  25390. if (dialog.editor) {
  25391. var editor = dialog.editor;
  25392. try {
  25393. if (browser.gecko) {
  25394. var y = editor.window.scrollY,
  25395. x = editor.window.scrollX;
  25396. editor.body.focus();
  25397. editor.window.scrollTo(x, y);
  25398. } else {
  25399. editor.focus();
  25400. }
  25401. } catch (ex) {
  25402. }
  25403. }
  25404. });
  25405. return dialog;
  25406. };
  25407. var iframeUrlMap = {
  25408. 'anchor':'~/dialogs/anchor/anchor.html',
  25409. 'insertimage':'~/dialogs/image/image.html',
  25410. 'link':'~/dialogs/link/link.html',
  25411. 'spechars':'~/dialogs/spechars/spechars.html',
  25412. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  25413. 'map':'~/dialogs/map/map.html',
  25414. 'gmap':'~/dialogs/gmap/gmap.html',
  25415. 'insertvideo':'~/dialogs/video/video.html',
  25416. 'help':'~/dialogs/help/help.html',
  25417. 'preview':'~/dialogs/preview/preview.html',
  25418. 'emotion':'~/dialogs/emotion/emotion.html',
  25419. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  25420. 'attachment':'~/dialogs/attachment/attachment.html',
  25421. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  25422. 'edittip':'~/dialogs/table/edittip.html',
  25423. 'edittable':'~/dialogs/table/edittable.html',
  25424. 'edittd':'~/dialogs/table/edittd.html',
  25425. 'webapp':'~/dialogs/webapp/webapp.html',
  25426. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  25427. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  25428. 'music':'~/dialogs/music/music.html',
  25429. 'template':'~/dialogs/template/template.html',
  25430. 'background':'~/dialogs/background/background.html',
  25431. 'charts': '~/dialogs/charts/charts.html'
  25432. };
  25433. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  25434. var btnCmds = ['undo', 'redo', 'formatmatch',
  25435. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  25436. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  25437. 'blockquote', 'pasteplain', 'pagebreak',
  25438. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  25439. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  25440. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  25441. for (var i = 0, ci; ci = btnCmds[i++];) {
  25442. ci = ci.toLowerCase();
  25443. editorui[ci] = function (cmd) {
  25444. return function (editor) {
  25445. var ui = new editorui.Button({
  25446. className:'edui-for-' + cmd,
  25447. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25448. onclick:function () {
  25449. editor.execCommand(cmd);
  25450. },
  25451. theme:editor.options.theme,
  25452. showText:false
  25453. });
  25454. editorui.buttons[cmd] = ui;
  25455. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25456. var state = editor.queryCommandState(cmd);
  25457. if (state == -1) {
  25458. ui.setDisabled(true);
  25459. ui.setChecked(false);
  25460. } else {
  25461. if (!uiReady) {
  25462. ui.setDisabled(false);
  25463. ui.setChecked(state);
  25464. }
  25465. }
  25466. });
  25467. return ui;
  25468. };
  25469. }(ci);
  25470. }
  25471. //清除文档
  25472. editorui.cleardoc = function (editor) {
  25473. var ui = new editorui.Button({
  25474. className:'edui-for-cleardoc',
  25475. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  25476. theme:editor.options.theme,
  25477. onclick:function () {
  25478. if (confirm(editor.getLang("confirmClear"))) {
  25479. editor.execCommand('cleardoc');
  25480. }
  25481. }
  25482. });
  25483. editorui.buttons["cleardoc"] = ui;
  25484. editor.addListener('selectionchange', function () {
  25485. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  25486. });
  25487. return ui;
  25488. };
  25489. //排版,图片排版,文字方向
  25490. var typeset = {
  25491. 'justify':['left', 'right', 'center', 'justify'],
  25492. 'imagefloat':['none', 'left', 'center', 'right'],
  25493. 'directionality':['ltr', 'rtl']
  25494. };
  25495. for (var p in typeset) {
  25496. (function (cmd, val) {
  25497. for (var i = 0, ci; ci = val[i++];) {
  25498. (function (cmd2) {
  25499. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  25500. var ui = new editorui.Button({
  25501. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  25502. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  25503. theme:editor.options.theme,
  25504. onclick:function () {
  25505. editor.execCommand(cmd, cmd2);
  25506. }
  25507. });
  25508. editorui.buttons[cmd] = ui;
  25509. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25510. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25511. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  25512. });
  25513. return ui;
  25514. };
  25515. })(ci)
  25516. }
  25517. })(p, typeset[p])
  25518. }
  25519. //字体颜色和背景颜色
  25520. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  25521. editorui[ci] = function (cmd) {
  25522. return function (editor) {
  25523. var ui = new editorui.ColorButton({
  25524. className:'edui-for-' + cmd,
  25525. color:'default',
  25526. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25527. editor:editor,
  25528. onpickcolor:function (t, color) {
  25529. editor.execCommand(cmd, color);
  25530. },
  25531. onpicknocolor:function () {
  25532. editor.execCommand(cmd, 'default');
  25533. this.setColor('transparent');
  25534. this.color = 'default';
  25535. },
  25536. onbuttonclick:function () {
  25537. editor.execCommand(cmd, this.color);
  25538. }
  25539. });
  25540. editorui.buttons[cmd] = ui;
  25541. editor.addListener('selectionchange', function () {
  25542. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25543. });
  25544. return ui;
  25545. };
  25546. }(ci);
  25547. }
  25548. var dialogBtns = {
  25549. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  25550. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  25551. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  25552. };
  25553. for (var p in dialogBtns) {
  25554. (function (type, vals) {
  25555. for (var i = 0, ci; ci = vals[i++];) {
  25556. //todo opera下存在问题
  25557. if (browser.opera && ci === "searchreplace") {
  25558. continue;
  25559. }
  25560. (function (cmd) {
  25561. editorui[cmd] = function (editor, iframeUrl, title) {
  25562. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  25563. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  25564. var dialog;
  25565. //没有iframeUrl不创建dialog
  25566. if (iframeUrl) {
  25567. dialog = new editorui.Dialog(utils.extend({
  25568. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25569. editor:editor,
  25570. className:'edui-for-' + cmd,
  25571. title:title,
  25572. holdScroll: cmd === 'insertimage',
  25573. fullscreen: /charts|preview/.test(cmd),
  25574. closeDialog:editor.getLang("closeDialog")
  25575. }, type == 'ok' ? {
  25576. buttons:[
  25577. {
  25578. className:'edui-okbutton',
  25579. label:editor.getLang("ok"),
  25580. editor:editor,
  25581. onclick:function () {
  25582. dialog.close(true);
  25583. }
  25584. },
  25585. {
  25586. className:'edui-cancelbutton',
  25587. label:editor.getLang("cancel"),
  25588. editor:editor,
  25589. onclick:function () {
  25590. dialog.close(false);
  25591. }
  25592. }
  25593. ]
  25594. } : {}));
  25595. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  25596. }
  25597. var ui = new editorui.Button({
  25598. className:'edui-for-' + cmd,
  25599. title:title,
  25600. onclick:function () {
  25601. if (dialog) {
  25602. switch (cmd) {
  25603. case "wordimage":
  25604. var images = editor.execCommand("wordimage");
  25605. if (images && images.length) {
  25606. dialog.render();
  25607. dialog.open();
  25608. }
  25609. break;
  25610. case "scrawl":
  25611. if (editor.queryCommandState("scrawl") != -1) {
  25612. dialog.render();
  25613. dialog.open();
  25614. }
  25615. break;
  25616. default:
  25617. dialog.render();
  25618. dialog.open();
  25619. }
  25620. }
  25621. },
  25622. theme:editor.options.theme,
  25623. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  25624. });
  25625. editorui.buttons[cmd] = ui;
  25626. editor.addListener('selectionchange', function () {
  25627. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  25628. var unNeedCheckState = {'edittable':1};
  25629. if (cmd in unNeedCheckState)return;
  25630. var state = editor.queryCommandState(cmd);
  25631. if (ui.getDom()) {
  25632. ui.setDisabled(state == -1);
  25633. ui.setChecked(state);
  25634. }
  25635. });
  25636. return ui;
  25637. };
  25638. })(ci.toLowerCase())
  25639. }
  25640. })(p, dialogBtns[p]);
  25641. }
  25642. editorui.snapscreen = function (editor, iframeUrl, title) {
  25643. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  25644. var ui = new editorui.Button({
  25645. className:'edui-for-snapscreen',
  25646. title:title,
  25647. onclick:function () {
  25648. editor.execCommand("snapscreen");
  25649. },
  25650. theme:editor.options.theme
  25651. });
  25652. editorui.buttons['snapscreen'] = ui;
  25653. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  25654. if (iframeUrl) {
  25655. var dialog = new editorui.Dialog({
  25656. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25657. editor:editor,
  25658. className:'edui-for-snapscreen',
  25659. title:title,
  25660. buttons:[
  25661. {
  25662. className:'edui-okbutton',
  25663. label:editor.getLang("ok"),
  25664. editor:editor,
  25665. onclick:function () {
  25666. dialog.close(true);
  25667. }
  25668. },
  25669. {
  25670. className:'edui-cancelbutton',
  25671. label:editor.getLang("cancel"),
  25672. editor:editor,
  25673. onclick:function () {
  25674. dialog.close(false);
  25675. }
  25676. }
  25677. ]
  25678. });
  25679. dialog.render();
  25680. editor.ui._dialogs["snapscreenDialog"] = dialog;
  25681. }
  25682. editor.addListener('selectionchange', function () {
  25683. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  25684. });
  25685. return ui;
  25686. };
  25687. editorui.insertcode = function (editor, list, title) {
  25688. list = editor.options['insertcode'] || [];
  25689. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  25690. // if (!list.length) return;
  25691. var items = [];
  25692. utils.each(list,function(key,val){
  25693. items.push({
  25694. label:key,
  25695. value:val,
  25696. theme:editor.options.theme,
  25697. renderLabelHtml:function () {
  25698. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  25699. }
  25700. });
  25701. });
  25702. var ui = new editorui.Combox({
  25703. editor:editor,
  25704. items:items,
  25705. onselect:function (t, index) {
  25706. editor.execCommand('insertcode', this.items[index].value);
  25707. },
  25708. onbuttonclick:function () {
  25709. this.showPopup();
  25710. },
  25711. title:title,
  25712. initValue:title,
  25713. className:'edui-for-insertcode',
  25714. indexByValue:function (value) {
  25715. if (value) {
  25716. for (var i = 0, ci; ci = this.items[i]; i++) {
  25717. if (ci.value.indexOf(value) != -1)
  25718. return i;
  25719. }
  25720. }
  25721. return -1;
  25722. }
  25723. });
  25724. editorui.buttons['insertcode'] = ui;
  25725. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25726. if (!uiReady) {
  25727. var state = editor.queryCommandState('insertcode');
  25728. if (state == -1) {
  25729. ui.setDisabled(true);
  25730. } else {
  25731. ui.setDisabled(false);
  25732. var value = editor.queryCommandValue('insertcode');
  25733. if(!value){
  25734. ui.setValue(title);
  25735. return;
  25736. }
  25737. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25738. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25739. ui.setValue(value);
  25740. }
  25741. }
  25742. });
  25743. return ui;
  25744. };
  25745. editorui.fontfamily = function (editor, list, title) {
  25746. list = editor.options['fontfamily'] || [];
  25747. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  25748. if (!list.length) return;
  25749. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  25750. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  25751. (function (key, val) {
  25752. items.push({
  25753. label:key,
  25754. value:val,
  25755. theme:editor.options.theme,
  25756. renderLabelHtml:function () {
  25757. return '<div class="edui-label %%-label" style="font-family:' +
  25758. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  25759. }
  25760. });
  25761. })(ci.label || langLabel, ci.val)
  25762. }
  25763. var ui = new editorui.Combox({
  25764. editor:editor,
  25765. items:items,
  25766. onselect:function (t, index) {
  25767. editor.execCommand('FontFamily', this.items[index].value);
  25768. },
  25769. onbuttonclick:function () {
  25770. this.showPopup();
  25771. },
  25772. title:title,
  25773. initValue:title,
  25774. className:'edui-for-fontfamily',
  25775. indexByValue:function (value) {
  25776. if (value) {
  25777. for (var i = 0, ci; ci = this.items[i]; i++) {
  25778. if (ci.value.indexOf(value) != -1)
  25779. return i;
  25780. }
  25781. }
  25782. return -1;
  25783. }
  25784. });
  25785. editorui.buttons['fontfamily'] = ui;
  25786. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25787. if (!uiReady) {
  25788. var state = editor.queryCommandState('FontFamily');
  25789. if (state == -1) {
  25790. ui.setDisabled(true);
  25791. } else {
  25792. ui.setDisabled(false);
  25793. var value = editor.queryCommandValue('FontFamily');
  25794. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25795. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25796. ui.setValue(value);
  25797. }
  25798. }
  25799. });
  25800. return ui;
  25801. };
  25802. editorui.fontsize = function (editor, list, title) {
  25803. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  25804. list = list || editor.options['fontsize'] || [];
  25805. if (!list.length) return;
  25806. var items = [];
  25807. for (var i = 0; i < list.length; i++) {
  25808. var size = list[i] + 'px';
  25809. items.push({
  25810. label:size,
  25811. value:size,
  25812. theme:editor.options.theme,
  25813. renderLabelHtml:function () {
  25814. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  25815. this.value + '">' + (this.label || '') + '</div>';
  25816. }
  25817. });
  25818. }
  25819. var ui = new editorui.Combox({
  25820. editor:editor,
  25821. items:items,
  25822. title:title,
  25823. initValue:title,
  25824. onselect:function (t, index) {
  25825. editor.execCommand('FontSize', this.items[index].value);
  25826. },
  25827. onbuttonclick:function () {
  25828. this.showPopup();
  25829. },
  25830. className:'edui-for-fontsize'
  25831. });
  25832. editorui.buttons['fontsize'] = ui;
  25833. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25834. if (!uiReady) {
  25835. var state = editor.queryCommandState('FontSize');
  25836. if (state == -1) {
  25837. ui.setDisabled(true);
  25838. } else {
  25839. ui.setDisabled(false);
  25840. ui.setValue(editor.queryCommandValue('FontSize'));
  25841. }
  25842. }
  25843. });
  25844. return ui;
  25845. };
  25846. editorui.paragraph = function (editor, list, title) {
  25847. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  25848. list = editor.options['paragraph'] || [];
  25849. if (utils.isEmptyObject(list)) return;
  25850. var items = [];
  25851. for (var i in list) {
  25852. items.push({
  25853. value:i,
  25854. label:list[i] || editor.getLang("paragraph")[i],
  25855. theme:editor.options.theme,
  25856. renderLabelHtml:function () {
  25857. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  25858. }
  25859. })
  25860. }
  25861. var ui = new editorui.Combox({
  25862. editor:editor,
  25863. items:items,
  25864. title:title,
  25865. initValue:title,
  25866. className:'edui-for-paragraph',
  25867. onselect:function (t, index) {
  25868. editor.execCommand('Paragraph', this.items[index].value);
  25869. },
  25870. onbuttonclick:function () {
  25871. this.showPopup();
  25872. }
  25873. });
  25874. editorui.buttons['paragraph'] = ui;
  25875. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25876. if (!uiReady) {
  25877. var state = editor.queryCommandState('Paragraph');
  25878. if (state == -1) {
  25879. ui.setDisabled(true);
  25880. } else {
  25881. ui.setDisabled(false);
  25882. var value = editor.queryCommandValue('Paragraph');
  25883. var index = ui.indexByValue(value);
  25884. if (index != -1) {
  25885. ui.setValue(value);
  25886. } else {
  25887. ui.setValue(ui.initValue);
  25888. }
  25889. }
  25890. }
  25891. });
  25892. return ui;
  25893. };
  25894. //自定义标题
  25895. editorui.customstyle = function (editor) {
  25896. var list = editor.options['customstyle'] || [],
  25897. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  25898. if (!list.length)return;
  25899. var langCs = editor.getLang('customstyle');
  25900. for (var i = 0, items = [], t; t = list[i++];) {
  25901. (function (t) {
  25902. var ck = {};
  25903. ck.label = t.label ? t.label : langCs[t.name];
  25904. ck.style = t.style;
  25905. ck.className = t.className;
  25906. ck.tag = t.tag;
  25907. items.push({
  25908. label:ck.label,
  25909. value:ck,
  25910. theme:editor.options.theme,
  25911. renderLabelHtml:function () {
  25912. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  25913. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  25914. + '</div>';
  25915. }
  25916. });
  25917. })(t);
  25918. }
  25919. var ui = new editorui.Combox({
  25920. editor:editor,
  25921. items:items,
  25922. title:title,
  25923. initValue:title,
  25924. className:'edui-for-customstyle',
  25925. onselect:function (t, index) {
  25926. editor.execCommand('customstyle', this.items[index].value);
  25927. },
  25928. onbuttonclick:function () {
  25929. this.showPopup();
  25930. },
  25931. indexByValue:function (value) {
  25932. for (var i = 0, ti; ti = this.items[i++];) {
  25933. if (ti.label == value) {
  25934. return i - 1
  25935. }
  25936. }
  25937. return -1;
  25938. }
  25939. });
  25940. editorui.buttons['customstyle'] = ui;
  25941. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25942. if (!uiReady) {
  25943. var state = editor.queryCommandState('customstyle');
  25944. if (state == -1) {
  25945. ui.setDisabled(true);
  25946. } else {
  25947. ui.setDisabled(false);
  25948. var value = editor.queryCommandValue('customstyle');
  25949. var index = ui.indexByValue(value);
  25950. if (index != -1) {
  25951. ui.setValue(value);
  25952. } else {
  25953. ui.setValue(ui.initValue);
  25954. }
  25955. }
  25956. }
  25957. });
  25958. return ui;
  25959. };
  25960. editorui.inserttable = function (editor, iframeUrl, title) {
  25961. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  25962. var ui = new editorui.TableButton({
  25963. editor:editor,
  25964. title:title,
  25965. className:'edui-for-inserttable',
  25966. onpicktable:function (t, numCols, numRows) {
  25967. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  25968. },
  25969. onbuttonclick:function () {
  25970. this.showPopup();
  25971. }
  25972. });
  25973. editorui.buttons['inserttable'] = ui;
  25974. editor.addListener('selectionchange', function () {
  25975. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  25976. });
  25977. return ui;
  25978. };
  25979. editorui.lineheight = function (editor) {
  25980. var val = editor.options.lineheight || [];
  25981. if (!val.length)return;
  25982. for (var i = 0, ci, items = []; ci = val[i++];) {
  25983. items.push({
  25984. //todo:写死了
  25985. label:ci,
  25986. value:ci,
  25987. theme:editor.options.theme,
  25988. onclick:function () {
  25989. editor.execCommand("lineheight", this.value);
  25990. }
  25991. })
  25992. }
  25993. var ui = new editorui.MenuButton({
  25994. editor:editor,
  25995. className:'edui-for-lineheight',
  25996. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  25997. items:items,
  25998. onbuttonclick:function () {
  25999. var value = editor.queryCommandValue('LineHeight') || this.value;
  26000. editor.execCommand("LineHeight", value);
  26001. }
  26002. });
  26003. editorui.buttons['lineheight'] = ui;
  26004. editor.addListener('selectionchange', function () {
  26005. var state = editor.queryCommandState('LineHeight');
  26006. if (state == -1) {
  26007. ui.setDisabled(true);
  26008. } else {
  26009. ui.setDisabled(false);
  26010. var value = editor.queryCommandValue('LineHeight');
  26011. value && ui.setValue((value + '').replace(/cm/, ''));
  26012. ui.setChecked(state)
  26013. }
  26014. });
  26015. return ui;
  26016. };
  26017. var rowspacings = ['top', 'bottom'];
  26018. for (var r = 0, ri; ri = rowspacings[r++];) {
  26019. (function (cmd) {
  26020. editorui['rowspacing' + cmd] = function (editor) {
  26021. var val = editor.options['rowspacing' + cmd] || [];
  26022. if (!val.length) return null;
  26023. for (var i = 0, ci, items = []; ci = val[i++];) {
  26024. items.push({
  26025. label:ci,
  26026. value:ci,
  26027. theme:editor.options.theme,
  26028. onclick:function () {
  26029. editor.execCommand("rowspacing", this.value, cmd);
  26030. }
  26031. })
  26032. }
  26033. var ui = new editorui.MenuButton({
  26034. editor:editor,
  26035. className:'edui-for-rowspacing' + cmd,
  26036. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  26037. items:items,
  26038. onbuttonclick:function () {
  26039. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  26040. editor.execCommand("rowspacing", value, cmd);
  26041. }
  26042. });
  26043. editorui.buttons[cmd] = ui;
  26044. editor.addListener('selectionchange', function () {
  26045. var state = editor.queryCommandState('rowspacing', cmd);
  26046. if (state == -1) {
  26047. ui.setDisabled(true);
  26048. } else {
  26049. ui.setDisabled(false);
  26050. var value = editor.queryCommandValue('rowspacing', cmd);
  26051. value && ui.setValue((value + '').replace(/%/, ''));
  26052. ui.setChecked(state)
  26053. }
  26054. });
  26055. return ui;
  26056. }
  26057. })(ri)
  26058. }
  26059. //有序,无序列表
  26060. var lists = ['insertorderedlist', 'insertunorderedlist'];
  26061. for (var l = 0, cl; cl = lists[l++];) {
  26062. (function (cmd) {
  26063. editorui[cmd] = function (editor) {
  26064. var vals = editor.options[cmd],
  26065. _onMenuClick = function () {
  26066. editor.execCommand(cmd, this.value);
  26067. }, items = [];
  26068. for (var i in vals) {
  26069. items.push({
  26070. label:vals[i] || editor.getLang()[cmd][i] || "",
  26071. value:i,
  26072. theme:editor.options.theme,
  26073. onclick:_onMenuClick
  26074. })
  26075. }
  26076. var ui = new editorui.MenuButton({
  26077. editor:editor,
  26078. className:'edui-for-' + cmd,
  26079. title:editor.getLang("labelMap." + cmd) || '',
  26080. 'items':items,
  26081. onbuttonclick:function () {
  26082. var value = editor.queryCommandValue(cmd) || this.value;
  26083. editor.execCommand(cmd, value);
  26084. }
  26085. });
  26086. editorui.buttons[cmd] = ui;
  26087. editor.addListener('selectionchange', function () {
  26088. var state = editor.queryCommandState(cmd);
  26089. if (state == -1) {
  26090. ui.setDisabled(true);
  26091. } else {
  26092. ui.setDisabled(false);
  26093. var value = editor.queryCommandValue(cmd);
  26094. ui.setValue(value);
  26095. ui.setChecked(state)
  26096. }
  26097. });
  26098. return ui;
  26099. };
  26100. })(cl)
  26101. }
  26102. editorui.fullscreen = function (editor, title) {
  26103. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  26104. var ui = new editorui.Button({
  26105. className:'edui-for-fullscreen',
  26106. title:title,
  26107. theme:editor.options.theme,
  26108. onclick:function () {
  26109. if (editor.ui) {
  26110. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  26111. }
  26112. this.setChecked(editor.ui.isFullScreen());
  26113. }
  26114. });
  26115. editorui.buttons['fullscreen'] = ui;
  26116. editor.addListener('selectionchange', function () {
  26117. var state = editor.queryCommandState('fullscreen');
  26118. ui.setDisabled(state == -1);
  26119. ui.setChecked(editor.ui.isFullScreen());
  26120. });
  26121. return ui;
  26122. };
  26123. // 表情
  26124. editorui["emotion"] = function (editor, iframeUrl) {
  26125. var cmd = "emotion";
  26126. var ui = new editorui.MultiMenuPop({
  26127. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  26128. editor:editor,
  26129. className:'edui-for-' + cmd,
  26130. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  26131. });
  26132. editorui.buttons[cmd] = ui;
  26133. editor.addListener('selectionchange', function () {
  26134. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  26135. });
  26136. return ui;
  26137. };
  26138. editorui.autotypeset = function (editor) {
  26139. var ui = new editorui.AutoTypeSetButton({
  26140. editor:editor,
  26141. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  26142. className:'edui-for-autotypeset',
  26143. onbuttonclick:function () {
  26144. editor.execCommand('autotypeset')
  26145. }
  26146. });
  26147. editorui.buttons['autotypeset'] = ui;
  26148. editor.addListener('selectionchange', function () {
  26149. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  26150. });
  26151. return ui;
  26152. };
  26153. /* 简单上传插件 */
  26154. editorui["simpleupload"] = function (editor) {
  26155. var name = 'simpleupload',
  26156. ui = new editorui.Button({
  26157. className:'edui-for-' + name,
  26158. title:editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  26159. onclick:function () {},
  26160. theme:editor.options.theme,
  26161. showText:false
  26162. });
  26163. editorui.buttons[name] = ui;
  26164. editor.addListener('ready', function() {
  26165. var b = ui.getDom('body'),
  26166. iconSpan = b.children[0];
  26167. editor.fireEvent('simpleuploadbtnready', iconSpan);
  26168. });
  26169. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26170. var state = editor.queryCommandState(name);
  26171. if (state == -1) {
  26172. ui.setDisabled(true);
  26173. ui.setChecked(false);
  26174. } else {
  26175. if (!uiReady) {
  26176. ui.setDisabled(false);
  26177. ui.setChecked(state);
  26178. }
  26179. }
  26180. });
  26181. return ui;
  26182. };
  26183. })();
  26184. // adapter/editor.js
  26185. ///import core
  26186. ///commands 全屏
  26187. ///commandsName FullScreen
  26188. ///commandsTitle 全屏
  26189. (function () {
  26190. var utils = baidu.editor.utils,
  26191. uiUtils = baidu.editor.ui.uiUtils,
  26192. UIBase = baidu.editor.ui.UIBase,
  26193. domUtils = baidu.editor.dom.domUtils;
  26194. var nodeStack = [];
  26195. function EditorUI(options) {
  26196. this.initOptions(options);
  26197. this.initEditorUI();
  26198. }
  26199. EditorUI.prototype = {
  26200. uiName:'editor',
  26201. initEditorUI:function () {
  26202. this.editor.ui = this;
  26203. this._dialogs = {};
  26204. this.initUIBase();
  26205. this._initToolbars();
  26206. var editor = this.editor,
  26207. me = this;
  26208. editor.addListener('ready', function () {
  26209. //提供getDialog方法
  26210. editor.getDialog = function (name) {
  26211. return editor.ui._dialogs[name + "Dialog"];
  26212. };
  26213. domUtils.on(editor.window, 'scroll', function (evt) {
  26214. baidu.editor.ui.Popup.postHide(evt);
  26215. });
  26216. //提供编辑器实时宽高(全屏时宽高不变化)
  26217. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  26218. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  26219. //display bottom-bar label based on config
  26220. if (editor.options.elementPathEnabled) {
  26221. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  26222. }
  26223. if (editor.options.wordCount) {
  26224. function countFn() {
  26225. setCount(editor,me);
  26226. domUtils.un(editor.document, "click", arguments.callee);
  26227. }
  26228. domUtils.on(editor.document, "click", countFn);
  26229. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  26230. }
  26231. editor.ui._scale();
  26232. if (editor.options.scaleEnabled) {
  26233. if (editor.autoHeightEnabled) {
  26234. editor.disableAutoHeight();
  26235. }
  26236. me.enableScale();
  26237. } else {
  26238. me.disableScale();
  26239. }
  26240. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  26241. editor.ui.getDom('elementpath').style.display = "none";
  26242. editor.ui.getDom('wordcount').style.display = "none";
  26243. editor.ui.getDom('scale').style.display = "none";
  26244. }
  26245. if (!editor.selection.isFocus())return;
  26246. editor.fireEvent('selectionchange', false, true);
  26247. });
  26248. editor.addListener('mousedown', function (t, evt) {
  26249. var el = evt.target || evt.srcElement;
  26250. baidu.editor.ui.Popup.postHide(evt, el);
  26251. baidu.editor.ui.ShortCutMenu.postHide(evt);
  26252. });
  26253. editor.addListener("delcells", function () {
  26254. if (UE.ui['edittip']) {
  26255. new UE.ui['edittip'](editor);
  26256. }
  26257. editor.getDialog('edittip').open();
  26258. });
  26259. var pastePop, isPaste = false, timer;
  26260. editor.addListener("afterpaste", function () {
  26261. if(editor.queryCommandState('pasteplain'))
  26262. return;
  26263. if(baidu.editor.ui.PastePicker){
  26264. pastePop = new baidu.editor.ui.Popup({
  26265. content:new baidu.editor.ui.PastePicker({editor:editor}),
  26266. editor:editor,
  26267. className:'edui-wordpastepop'
  26268. });
  26269. pastePop.render();
  26270. }
  26271. isPaste = true;
  26272. });
  26273. editor.addListener("afterinserthtml", function () {
  26274. clearTimeout(timer);
  26275. timer = setTimeout(function () {
  26276. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  26277. if(pastePop.isHidden()){
  26278. var span = domUtils.createElement(editor.document, 'span', {
  26279. 'style':"line-height:0px;",
  26280. 'innerHTML':'\ufeff'
  26281. }),
  26282. range = editor.selection.getRange();
  26283. range.insertNode(span);
  26284. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  26285. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  26286. domUtils.remove(span);
  26287. }else{
  26288. pastePop.show();
  26289. }
  26290. delete editor.ui._isTransfer;
  26291. isPaste = false;
  26292. }
  26293. }, 200)
  26294. });
  26295. editor.addListener('contextmenu', function (t, evt) {
  26296. baidu.editor.ui.Popup.postHide(evt);
  26297. });
  26298. editor.addListener('keydown', function (t, evt) {
  26299. if (pastePop) pastePop.dispose(evt);
  26300. var keyCode = evt.keyCode || evt.which;
  26301. if(evt.altKey&&keyCode==90){
  26302. UE.ui.buttons['fullscreen'].onclick();
  26303. }
  26304. });
  26305. editor.addListener('wordcount', function (type) {
  26306. setCount(this,me);
  26307. });
  26308. function setCount(editor,ui) {
  26309. editor.setOpt({
  26310. wordCount:true,
  26311. maximumWords:10000,
  26312. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  26313. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  26314. });
  26315. var opt = editor.options,
  26316. max = opt.maximumWords,
  26317. msg = opt.wordCountMsg ,
  26318. errMsg = opt.wordOverFlowMsg,
  26319. countDom = ui.getDom('wordcount');
  26320. if (!opt.wordCount) {
  26321. return;
  26322. }
  26323. var count = editor.getContentLength(true);
  26324. if (count > max) {
  26325. countDom.innerHTML = errMsg;
  26326. editor.fireEvent("wordcountoverflow");
  26327. } else {
  26328. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  26329. }
  26330. }
  26331. editor.addListener('selectionchange', function () {
  26332. if (editor.options.elementPathEnabled) {
  26333. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  26334. }
  26335. if (editor.options.scaleEnabled) {
  26336. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  26337. }
  26338. });
  26339. var popup = new baidu.editor.ui.Popup({
  26340. editor:editor,
  26341. content:'',
  26342. className:'edui-bubble',
  26343. _onEditButtonClick:function () {
  26344. this.hide();
  26345. editor.ui._dialogs.linkDialog.open();
  26346. },
  26347. _onImgEditButtonClick:function (name) {
  26348. this.hide();
  26349. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  26350. },
  26351. _onImgSetFloat:function (value) {
  26352. this.hide();
  26353. editor.execCommand("imagefloat", value);
  26354. },
  26355. _setIframeAlign:function (value) {
  26356. var frame = popup.anchorEl;
  26357. var newFrame = frame.cloneNode(true);
  26358. switch (value) {
  26359. case -2:
  26360. newFrame.setAttribute("align", "");
  26361. break;
  26362. case -1:
  26363. newFrame.setAttribute("align", "left");
  26364. break;
  26365. case 1:
  26366. newFrame.setAttribute("align", "right");
  26367. break;
  26368. }
  26369. frame.parentNode.insertBefore(newFrame, frame);
  26370. domUtils.remove(frame);
  26371. popup.anchorEl = newFrame;
  26372. popup.showAnchor(popup.anchorEl);
  26373. },
  26374. _updateIframe:function () {
  26375. var frame = editor._iframe = popup.anchorEl;
  26376. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  26377. editor.selection.getRange().selectNode(frame).select();
  26378. editor.ui._dialogs.mapDialog.open();
  26379. popup.hide();
  26380. } else {
  26381. editor.ui._dialogs.insertframeDialog.open();
  26382. popup.hide();
  26383. }
  26384. },
  26385. _onRemoveButtonClick:function (cmdName) {
  26386. editor.execCommand(cmdName);
  26387. this.hide();
  26388. },
  26389. queryAutoHide:function (el) {
  26390. if (el && el.ownerDocument == editor.document) {
  26391. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  26392. return el !== popup.anchorEl;
  26393. }
  26394. }
  26395. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  26396. }
  26397. });
  26398. popup.render();
  26399. if (editor.options.imagePopup) {
  26400. editor.addListener('mouseover', function (t, evt) {
  26401. evt = evt || window.event;
  26402. var el = evt.target || evt.srcElement;
  26403. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  26404. var html = popup.formatHtml(
  26405. '<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;' +
  26406. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  26407. if (html) {
  26408. popup.getDom('content').innerHTML = html;
  26409. popup.anchorEl = el;
  26410. popup.showAnchor(popup.anchorEl);
  26411. } else {
  26412. popup.hide();
  26413. }
  26414. }
  26415. });
  26416. editor.addListener('selectionchange', function (t, causeByUi) {
  26417. if (!causeByUi) return;
  26418. var html = '', str = "",
  26419. img = editor.selection.getRange().getClosedNode(),
  26420. dialogs = editor.ui._dialogs;
  26421. if (img && img.tagName == 'IMG') {
  26422. var dialogName = 'insertimageDialog';
  26423. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  26424. dialogName = "insertvideoDialog"
  26425. }
  26426. if (img.className.indexOf("edui-faked-webapp") != -1) {
  26427. dialogName = "webappDialog"
  26428. }
  26429. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  26430. dialogName = "mapDialog"
  26431. }
  26432. if (img.className.indexOf("edui-faked-music") != -1) {
  26433. dialogName = "musicDialog"
  26434. }
  26435. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  26436. dialogName = "gmapDialog"
  26437. }
  26438. if (img.getAttribute("anchorname")) {
  26439. dialogName = "anchorDialog";
  26440. html = popup.formatHtml(
  26441. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  26442. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  26443. }
  26444. if (img.getAttribute("word_img")) {
  26445. //todo 放到dialog去做查询
  26446. editor.word_img = [img.getAttribute("word_img")];
  26447. dialogName = "wordimageDialog"
  26448. }
  26449. if(domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  26450. dialogName = "";
  26451. }
  26452. if (!dialogs[dialogName]) {
  26453. return;
  26454. }
  26455. str = '<nobr>' + editor.getLang("property") + ': '+
  26456. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  26457. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  26458. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26459. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  26460. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  26461. !html && (html = popup.formatHtml(str))
  26462. }
  26463. if (editor.ui._dialogs.linkDialog) {
  26464. var link = editor.queryCommandValue('link');
  26465. var url;
  26466. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  26467. var txt = url;
  26468. if (url.length > 30) {
  26469. txt = url.substring(0, 20) + "...";
  26470. }
  26471. if (html) {
  26472. html += '<div style="height:5px;"></div>'
  26473. }
  26474. html += popup.formatHtml(
  26475. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  26476. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  26477. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  26478. popup.showAnchor(link);
  26479. }
  26480. }
  26481. if (html) {
  26482. popup.getDom('content').innerHTML = html;
  26483. popup.anchorEl = img || link;
  26484. popup.showAnchor(popup.anchorEl);
  26485. } else {
  26486. popup.hide();
  26487. }
  26488. });
  26489. }
  26490. },
  26491. _initToolbars:function () {
  26492. var editor = this.editor;
  26493. var toolbars = this.toolbars || [];
  26494. var toolbarUis = [];
  26495. for (var i = 0; i < toolbars.length; i++) {
  26496. var toolbar = toolbars[i];
  26497. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  26498. for (var j = 0; j < toolbar.length; j++) {
  26499. var toolbarItem = toolbar[j];
  26500. var toolbarItemUi = null;
  26501. if (typeof toolbarItem == 'string') {
  26502. toolbarItem = toolbarItem.toLowerCase();
  26503. if (toolbarItem == '|') {
  26504. toolbarItem = 'Separator';
  26505. }
  26506. if(toolbarItem == '||'){
  26507. toolbarItem = 'Breakline';
  26508. }
  26509. if (baidu.editor.ui[toolbarItem]) {
  26510. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  26511. }
  26512. //fullscreen这里单独处理一下,放到首行去
  26513. if (toolbarItem == 'fullscreen') {
  26514. if (toolbarUis && toolbarUis[0]) {
  26515. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  26516. } else {
  26517. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  26518. }
  26519. continue;
  26520. }
  26521. } else {
  26522. toolbarItemUi = toolbarItem;
  26523. }
  26524. if (toolbarItemUi && toolbarItemUi.id) {
  26525. toolbarUi.add(toolbarItemUi);
  26526. }
  26527. }
  26528. toolbarUis[i] = toolbarUi;
  26529. }
  26530. //接受外部定制的UI(修复因 utils.each 无法准确的循环出对象的全部元素而导致的自定义 UI 不符合预期的 BUG by HaoChuan9421)
  26531. // utils.each(UE._customizeUI,function(obj,key){
  26532. // var itemUI,index;
  26533. // if(obj.id && obj.id != editor.key){
  26534. // return false;
  26535. // }
  26536. // itemUI = obj.execFn.call(editor,editor,key);
  26537. // if(itemUI){
  26538. // index = obj.index;
  26539. // if(index === undefined){
  26540. // index = toolbarUi.items.length;
  26541. // }
  26542. // toolbarUi.add(itemUI,index)
  26543. // }
  26544. // });
  26545. for(var key in UE._customizeUI){
  26546. var obj = UE._customizeUI[key]
  26547. var itemUI,index;
  26548. if(!obj.id || obj.id == editor.key){
  26549. itemUI = obj.execFn.call(editor,editor,key);
  26550. if(itemUI){
  26551. index = obj.index;
  26552. if(index === undefined){
  26553. index = toolbarUi.items.length;
  26554. }
  26555. toolbarUi.add(itemUI,index)
  26556. }
  26557. }
  26558. }
  26559. this.toolbars = toolbarUis;
  26560. },
  26561. getHtmlTpl:function () {
  26562. return '<div id="##" class="%%">' +
  26563. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  26564. (this.toolbars.length ?
  26565. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  26566. this.renderToolbarBoxHtml() +
  26567. '</div></div>' : '') +
  26568. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  26569. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  26570. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  26571. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  26572. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  26573. '</div>' +
  26574. '<div id="##_message_holder" class="%%-messageholder"></div>' +
  26575. '</div>' +
  26576. '<div id="##_iframeholder" class="%%-iframeholder">' +
  26577. '</div>' +
  26578. //modify wdcount by matao
  26579. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  26580. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  26581. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  26582. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  26583. '</tr></table></div>' +
  26584. '<div id="##_scalelayer"></div>' +
  26585. '</div>';
  26586. },
  26587. showWordImageDialog:function () {
  26588. this._dialogs['wordimageDialog'].open();
  26589. },
  26590. renderToolbarBoxHtml:function () {
  26591. var buff = [];
  26592. for (var i = 0; i < this.toolbars.length; i++) {
  26593. buff.push(this.toolbars[i].renderHtml());
  26594. }
  26595. return buff.join('');
  26596. },
  26597. setFullScreen:function (fullscreen) {
  26598. var editor = this.editor,
  26599. container = editor.container.parentNode.parentNode;
  26600. if (this._fullscreen != fullscreen) {
  26601. this._fullscreen = fullscreen;
  26602. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  26603. if (baidu.editor.browser.gecko) {
  26604. var bk = editor.selection.getRange().createBookmark();
  26605. }
  26606. if (fullscreen) {
  26607. while (container.tagName != "BODY") {
  26608. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  26609. nodeStack.push(position);
  26610. container.style.position = "static";
  26611. container = container.parentNode;
  26612. }
  26613. this._bakHtmlOverflow = document.documentElement.style.overflow;
  26614. this._bakBodyOverflow = document.body.style.overflow;
  26615. this._bakAutoHeight = this.editor.autoHeightEnabled;
  26616. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  26617. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  26618. if (this._bakAutoHeight) {
  26619. //当全屏时不能执行自动长高
  26620. editor.autoHeightEnabled = false;
  26621. this.editor.disableAutoHeight();
  26622. }
  26623. document.documentElement.style.overflow = 'hidden';
  26624. //修复,滚动条不收起的问题
  26625. window.scrollTo(0,window.scrollY);
  26626. this._bakCssText = this.getDom().style.cssText;
  26627. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  26628. editor.iframe.parentNode.style.width = '';
  26629. this._updateFullScreen();
  26630. } else {
  26631. while (container.tagName != "BODY") {
  26632. container.style.position = nodeStack.shift();
  26633. container = container.parentNode;
  26634. }
  26635. this.getDom().style.cssText = this._bakCssText;
  26636. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  26637. if (this._bakAutoHeight) {
  26638. editor.autoHeightEnabled = true;
  26639. this.editor.enableAutoHeight();
  26640. }
  26641. document.documentElement.style.overflow = this._bakHtmlOverflow;
  26642. document.body.style.overflow = this._bakBodyOverflow;
  26643. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  26644. window.scrollTo(0, this._bakScrollTop);
  26645. }
  26646. if (browser.gecko && editor.body.contentEditable === 'true') {
  26647. var input = document.createElement('input');
  26648. document.body.appendChild(input);
  26649. editor.body.contentEditable = false;
  26650. setTimeout(function () {
  26651. input.focus();
  26652. setTimeout(function () {
  26653. editor.body.contentEditable = true;
  26654. editor.fireEvent('fullscreenchanged', fullscreen);
  26655. editor.selection.getRange().moveToBookmark(bk).select(true);
  26656. baidu.editor.dom.domUtils.remove(input);
  26657. fullscreen && window.scroll(0, 0);
  26658. }, 0)
  26659. }, 0)
  26660. }
  26661. if(editor.body.contentEditable === 'true'){
  26662. this.editor.fireEvent('fullscreenchanged', fullscreen);
  26663. this.triggerLayout();
  26664. }
  26665. }
  26666. },
  26667. _updateFullScreen:function () {
  26668. if (this._fullscreen) {
  26669. var vpRect = uiUtils.getViewportRect();
  26670. 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);
  26671. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  26672. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
  26673. //不手动调一下,会导致全屏失效
  26674. if(browser.gecko){
  26675. try{
  26676. window.onresize();
  26677. }catch(e){
  26678. }
  26679. }
  26680. }
  26681. },
  26682. _updateElementPath:function () {
  26683. var bottom = this.getDom('elementpath'), list;
  26684. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  26685. var buff = [];
  26686. for (var i = 0, ci; ci = list[i]; i++) {
  26687. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  26688. }
  26689. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  26690. } else {
  26691. bottom.style.display = 'none'
  26692. }
  26693. },
  26694. disableElementPath:function () {
  26695. var bottom = this.getDom('elementpath');
  26696. bottom.innerHTML = '';
  26697. bottom.style.display = 'none';
  26698. this.elementPathEnabled = false;
  26699. },
  26700. enableElementPath:function () {
  26701. var bottom = this.getDom('elementpath');
  26702. bottom.style.display = '';
  26703. this.elementPathEnabled = true;
  26704. this._updateElementPath();
  26705. },
  26706. _scale:function () {
  26707. var doc = document,
  26708. editor = this.editor,
  26709. editorHolder = editor.container,
  26710. editorDocument = editor.document,
  26711. toolbarBox = this.getDom("toolbarbox"),
  26712. bottombar = this.getDom("bottombar"),
  26713. scale = this.getDom("scale"),
  26714. scalelayer = this.getDom("scalelayer");
  26715. var isMouseMove = false,
  26716. position = null,
  26717. minEditorHeight = 0,
  26718. minEditorWidth = editor.options.minFrameWidth,
  26719. pageX = 0,
  26720. pageY = 0,
  26721. scaleWidth = 0,
  26722. scaleHeight = 0;
  26723. function down() {
  26724. position = domUtils.getXY(editorHolder);
  26725. if (!minEditorHeight) {
  26726. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  26727. }
  26728. 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:"
  26729. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  26730. domUtils.on(doc, "mousemove", move);
  26731. domUtils.on(editorDocument, "mouseup", up);
  26732. domUtils.on(doc, "mouseup", up);
  26733. }
  26734. var me = this;
  26735. //by xuheng 全屏时关掉缩放
  26736. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  26737. if (fullScreen) {
  26738. me.disableScale();
  26739. } else {
  26740. if (me.editor.options.scaleEnabled) {
  26741. me.enableScale();
  26742. var tmpNode = me.editor.document.createElement('span');
  26743. me.editor.body.appendChild(tmpNode);
  26744. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  26745. domUtils.remove(tmpNode)
  26746. }
  26747. }
  26748. });
  26749. function move(event) {
  26750. clearSelection();
  26751. var e = event || window.event;
  26752. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  26753. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  26754. scaleWidth = pageX - position.x;
  26755. scaleHeight = pageY - position.y;
  26756. if (scaleWidth >= minEditorWidth) {
  26757. isMouseMove = true;
  26758. scalelayer.style.width = scaleWidth + 'px';
  26759. }
  26760. if (scaleHeight >= minEditorHeight) {
  26761. isMouseMove = true;
  26762. scalelayer.style.height = scaleHeight + "px";
  26763. }
  26764. }
  26765. function up() {
  26766. if (isMouseMove) {
  26767. isMouseMove = false;
  26768. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  26769. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  26770. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2,true);
  26771. }
  26772. if (scalelayer) {
  26773. scalelayer.style.display = "none";
  26774. }
  26775. clearSelection();
  26776. domUtils.un(doc, "mousemove", move);
  26777. domUtils.un(editorDocument, "mouseup", up);
  26778. domUtils.un(doc, "mouseup", up);
  26779. }
  26780. function clearSelection() {
  26781. if (browser.ie)
  26782. doc.selection.clear();
  26783. else
  26784. window.getSelection().removeAllRanges();
  26785. }
  26786. this.enableScale = function () {
  26787. //trace:2868
  26788. if (editor.queryCommandState("source") == 1) return;
  26789. scale.style.display = "";
  26790. this.scaleEnabled = true;
  26791. domUtils.on(scale, "mousedown", down);
  26792. };
  26793. this.disableScale = function () {
  26794. scale.style.display = "none";
  26795. this.scaleEnabled = false;
  26796. domUtils.un(scale, "mousedown", down);
  26797. };
  26798. },
  26799. isFullScreen:function () {
  26800. return this._fullscreen;
  26801. },
  26802. postRender:function () {
  26803. UIBase.prototype.postRender.call(this);
  26804. for (var i = 0; i < this.toolbars.length; i++) {
  26805. this.toolbars[i].postRender();
  26806. }
  26807. var me = this;
  26808. var timerId,
  26809. domUtils = baidu.editor.dom.domUtils,
  26810. updateFullScreenTime = function () {
  26811. clearTimeout(timerId);
  26812. timerId = setTimeout(function () {
  26813. me._updateFullScreen();
  26814. });
  26815. };
  26816. domUtils.on(window, 'resize', updateFullScreenTime);
  26817. me.addListener('destroy', function () {
  26818. domUtils.un(window, 'resize', updateFullScreenTime);
  26819. clearTimeout(timerId);
  26820. })
  26821. },
  26822. showToolbarMsg:function (msg, flag) {
  26823. this.getDom('toolbarmsg_label').innerHTML = msg;
  26824. this.getDom('toolbarmsg').style.display = '';
  26825. //
  26826. if (!flag) {
  26827. var w = this.getDom('upload_dialog');
  26828. w.style.display = 'none';
  26829. }
  26830. },
  26831. hideToolbarMsg:function () {
  26832. this.getDom('toolbarmsg').style.display = 'none';
  26833. },
  26834. mapUrl:function (url) {
  26835. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  26836. },
  26837. triggerLayout:function () {
  26838. var dom = this.getDom();
  26839. if (dom.style.zoom == '1') {
  26840. dom.style.zoom = '100%';
  26841. } else {
  26842. dom.style.zoom = '1';
  26843. }
  26844. }
  26845. };
  26846. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  26847. var instances = {};
  26848. UE.ui.Editor = function (options) {
  26849. var editor = new UE.Editor(options);
  26850. editor.options.editor = editor;
  26851. utils.loadFile(document, {
  26852. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  26853. tag:"link",
  26854. type:"text/css",
  26855. rel:"stylesheet"
  26856. });
  26857. var oldRender = editor.render;
  26858. editor.render = function (holder) {
  26859. if (holder.constructor === String) {
  26860. editor.key = holder;
  26861. instances[holder] = editor;
  26862. }
  26863. utils.domReady(function () {
  26864. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  26865. function renderUI() {
  26866. editor.setOpt({
  26867. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  26868. });
  26869. new EditorUI(editor.options);
  26870. if (holder) {
  26871. if (holder.constructor === String) {
  26872. holder = document.getElementById(holder);
  26873. }
  26874. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  26875. if (holder && /script|textarea/ig.test(holder.tagName)) {
  26876. var newDiv = document.createElement('div');
  26877. holder.parentNode.insertBefore(newDiv, holder);
  26878. var cont = holder.value || holder.innerHTML;
  26879. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  26880. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  26881. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  26882. .replace(/>[\n\r\t]+</g, '><');
  26883. holder.className && (newDiv.className = holder.className);
  26884. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  26885. if (/textarea/i.test(holder.tagName)) {
  26886. editor.textarea = holder;
  26887. editor.textarea.style.display = 'none';
  26888. } else {
  26889. holder.parentNode.removeChild(holder);
  26890. }
  26891. if(holder.id){
  26892. newDiv.id = holder.id;
  26893. domUtils.removeAttributes(holder,'id');
  26894. }
  26895. holder = newDiv;
  26896. holder.innerHTML = '';
  26897. }
  26898. }
  26899. domUtils.addClass(holder, "edui-" + editor.options.theme);
  26900. editor.ui.render(holder);
  26901. var opt = editor.options;
  26902. //给实例添加一个编辑器的容器引用
  26903. editor.container = editor.ui.getDom();
  26904. var parents = domUtils.findParents(holder,true);
  26905. var displays = [];
  26906. for(var i = 0 ,ci;ci=parents[i];i++){
  26907. displays[i] = ci.style.display;
  26908. ci.style.display = 'block'
  26909. }
  26910. if (opt.initialFrameWidth) {
  26911. opt.minFrameWidth = opt.initialFrameWidth;
  26912. } else {
  26913. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  26914. var styleWidth = holder.style.width;
  26915. if(/%$/.test(styleWidth)) {
  26916. opt.initialFrameWidth = styleWidth;
  26917. }
  26918. }
  26919. if (opt.initialFrameHeight) {
  26920. opt.minFrameHeight = opt.initialFrameHeight;
  26921. } else {
  26922. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  26923. }
  26924. for(var i = 0 ,ci;ci=parents[i];i++){
  26925. ci.style.display = displays[i]
  26926. }
  26927. //编辑器最外容器设置了高度,会导致,编辑器不占位
  26928. //todo 先去掉,没有找到原因
  26929. if(holder.style.height){
  26930. holder.style.height = ''
  26931. }
  26932. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  26933. editor.container.style.zIndex = opt.zIndex;
  26934. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  26935. editor.fireEvent("afteruiready");
  26936. }
  26937. })
  26938. };
  26939. return editor;
  26940. };
  26941. /**
  26942. * @file
  26943. * @name UE
  26944. * @short UE
  26945. * @desc UEditor的顶部命名空间
  26946. */
  26947. /**
  26948. * @name getEditor
  26949. * @since 1.2.4+
  26950. * @grammar UE.getEditor(id,[opt]) => Editor实例
  26951. * @desc 提供一个全局的方法得到编辑器实例
  26952. *
  26953. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  26954. * * ''opt'' 编辑器的可选参数
  26955. * @example
  26956. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  26957. * this.setContent('hello')
  26958. * }});
  26959. * UE.getEditor('containerId'); //返回刚创建的实例
  26960. *
  26961. */
  26962. UE.getEditor = function (id, opt) {
  26963. var editor = instances[id];
  26964. if (!editor) {
  26965. editor = instances[id] = new UE.ui.Editor(opt);
  26966. editor.render(id);
  26967. }
  26968. return editor;
  26969. };
  26970. UE.delEditor = function (id) {
  26971. var editor;
  26972. if (editor = instances[id]) {
  26973. editor.key && editor.destroy();
  26974. delete instances[id]
  26975. }
  26976. };
  26977. UE.registerUI = function(uiName,fn,index,editorId){
  26978. utils.each(uiName.split(/\s+/), function (name) {
  26979. UE._customizeUI[name] = {
  26980. id : editorId,
  26981. execFn:fn,
  26982. index:index
  26983. };
  26984. })
  26985. }
  26986. })();
  26987. // adapter/message.js
  26988. UE.registerUI('message', function(editor) {
  26989. var editorui = baidu.editor.ui;
  26990. var Message = editorui.Message;
  26991. var holder;
  26992. var _messageItems = [];
  26993. var me = editor;
  26994. me.addListener('ready', function(){
  26995. holder = document.getElementById(me.ui.id + '_message_holder');
  26996. updateHolderPos();
  26997. // HaoChuan9421
  26998. // setTimeout(function(){
  26999. // updateHolderPos();
  27000. // }, 500);
  27001. });
  27002. me.addListener('showmessage', function(type, opt){
  27003. opt = utils.isString(opt) ? {
  27004. 'content': opt
  27005. } : opt;
  27006. var message = new Message({
  27007. 'timeout': opt.timeout,
  27008. 'type': opt.type,
  27009. 'content': opt.content,
  27010. 'keepshow': opt.keepshow,
  27011. 'editor': me
  27012. }),
  27013. mid = opt.id || ('msg_' + (+new Date()).toString(36));
  27014. message.render(holder);
  27015. _messageItems[mid] = message;
  27016. message.reset(opt);
  27017. updateHolderPos();
  27018. return mid;
  27019. });
  27020. me.addListener('updatemessage',function(type, id, opt){
  27021. opt = utils.isString(opt) ? {
  27022. 'content': opt
  27023. } : opt;
  27024. var message = _messageItems[id];
  27025. message.render(holder);
  27026. message && message.reset(opt);
  27027. });
  27028. me.addListener('hidemessage',function(type, id){
  27029. var message = _messageItems[id];
  27030. message && message.hide();
  27031. });
  27032. function updateHolderPos(){
  27033. var toolbarbox = me.ui.getDom('toolbarbox');
  27034. if (toolbarbox) {
  27035. holder.style.top = toolbarbox.offsetHeight + 3 + 'px';
  27036. }
  27037. holder.style.zIndex = Math.max(me.options.zIndex, me.iframe.style.zIndex) + 1;
  27038. }
  27039. });
  27040. // adapter/autosave.js
  27041. UE.registerUI('autosave', function(editor) {
  27042. var timer = null,uid = null;
  27043. editor.on('afterautosave',function(){
  27044. clearTimeout(timer);
  27045. timer = setTimeout(function(){
  27046. if(uid){
  27047. editor.trigger('hidemessage',uid);
  27048. }
  27049. uid = editor.trigger('showmessage',{
  27050. content : editor.getLang('autosave.success'),
  27051. timeout : 2000
  27052. });
  27053. },2000)
  27054. })
  27055. });
  27056. })();