umeditor.js 380 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002
  1. /*!
  2. * UEditor Mini版本
  3. * version: 1.2.2
  4. * build: Thu Dec 22 2016 16:33:28 GMT+0800 (CST)
  5. */
  6. (function($){
  7. UMEDITOR_CONFIG = window.UMEDITOR_CONFIG || {};
  8. window.UM = {
  9. plugins : {},
  10. commands : {},
  11. I18N : {},
  12. version : "1.2.2"
  13. };
  14. var dom = UM.dom = {};
  15. /**
  16. * 浏览器判断模块
  17. * @file
  18. * @module UE.browser
  19. * @since 1.2.6.1
  20. */
  21. /**
  22. * 提供浏览器检测的模块
  23. * @unfile
  24. * @module UE.browser
  25. */
  26. var browser = UM.browser = function(){
  27. var agent = navigator.userAgent.toLowerCase(),
  28. opera = window.opera,
  29. browser = {
  30. /**
  31. * @property {boolean} ie 检测当前浏览器是否为IE
  32. * @example
  33. * ```javascript
  34. * if ( UE.browser.ie ) {
  35. * console.log( '当前浏览器是IE' );
  36. * }
  37. * ```
  38. */
  39. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  40. /**
  41. * @property {boolean} opera 检测当前浏览器是否为Opera
  42. * @example
  43. * ```javascript
  44. * if ( UE.browser.opera ) {
  45. * console.log( '当前浏览器是Opera' );
  46. * }
  47. * ```
  48. */
  49. opera : ( !!opera && opera.version ),
  50. /**
  51. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  52. * @example
  53. * ```javascript
  54. * if ( UE.browser.webkit ) {
  55. * console.log( '当前浏览器是webkit内核浏览器' );
  56. * }
  57. * ```
  58. */
  59. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  60. /**
  61. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  62. * @example
  63. * ```javascript
  64. * if ( UE.browser.mac ) {
  65. * console.log( '当前浏览器运行在mac平台下' );
  66. * }
  67. * ```
  68. */
  69. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  70. /**
  71. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  72. * @example
  73. * ```javascript
  74. * if ( UE.browser.quirks ) {
  75. * console.log( '当前浏览器运行处于“怪异模式”' );
  76. * }
  77. * ```
  78. */
  79. quirks : ( document.compatMode == 'BackCompat' )
  80. };
  81. /**
  82. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  83. * @example
  84. * ```javascript
  85. * if ( UE.browser.gecko ) {
  86. * console.log( '当前浏览器内核是gecko内核' );
  87. * }
  88. * ```
  89. */
  90. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  91. var version = 0;
  92. // Internet Explorer 6.0+
  93. if ( browser.ie ){
  94. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  95. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  96. if(v1 && v2 && v1[1] && v2[1]){
  97. version = Math.max(v1[1]*1,v2[1]*1);
  98. }else if(v1 && v1[1]){
  99. version = v1[1]*1;
  100. }else if(v2 && v2[1]){
  101. version = v2[1]*1;
  102. }else{
  103. version = 0;
  104. }
  105. browser.ie11Compat = document.documentMode == 11;
  106. /**
  107. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  108. * @warning 如果浏览器不是IE, 则该值为undefined
  109. * @example
  110. * ```javascript
  111. * if ( UE.browser.ie9Compat ) {
  112. * console.log( '当前浏览器运行在IE9兼容模式下' );
  113. * }
  114. * ```
  115. */
  116. browser.ie9Compat = document.documentMode == 9;
  117. /**
  118. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  119. * @warning 如果浏览器不是IE, 则该值为undefined
  120. * @example
  121. * ```javascript
  122. * if ( UE.browser.ie8 ) {
  123. * console.log( '当前浏览器是IE8浏览器' );
  124. * }
  125. * ```
  126. */
  127. browser.ie8 = !!document.documentMode;
  128. /**
  129. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  130. * @warning 如果浏览器不是IE, 则该值为undefined
  131. * @example
  132. * ```javascript
  133. * if ( UE.browser.ie8Compat ) {
  134. * console.log( '当前浏览器运行在IE8兼容模式下' );
  135. * }
  136. * ```
  137. */
  138. browser.ie8Compat = document.documentMode == 8;
  139. /**
  140. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  141. * @warning 如果浏览器不是IE, 则该值为undefined
  142. * @example
  143. * ```javascript
  144. * if ( UE.browser.ie7Compat ) {
  145. * console.log( '当前浏览器运行在IE7兼容模式下' );
  146. * }
  147. * ```
  148. */
  149. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  150. || document.documentMode == 7 );
  151. /**
  152. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  153. * @warning 如果浏览器不是IE, 则该值为undefined
  154. * @example
  155. * ```javascript
  156. * if ( UE.browser.ie6Compat ) {
  157. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  158. * }
  159. * ```
  160. */
  161. browser.ie6Compat = ( version < 7 || browser.quirks );
  162. browser.ie9above = version > 8;
  163. browser.ie9below = version < 9;
  164. }
  165. // Gecko.
  166. if ( browser.gecko ){
  167. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  168. if ( geckoRelease )
  169. {
  170. geckoRelease = geckoRelease[1].split( '.' );
  171. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  172. }
  173. }
  174. /**
  175. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  176. * @warning 如果浏览器不是chrome, 则该值为undefined
  177. * @example
  178. * ```javascript
  179. * if ( UE.browser.chrome ) {
  180. * console.log( '当前浏览器是Chrome' );
  181. * }
  182. * ```
  183. */
  184. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  185. browser.chrome = + RegExp['\x241'];
  186. }
  187. /**
  188. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  189. * @warning 如果浏览器不是safari, 则该值为undefined
  190. * @example
  191. * ```javascript
  192. * if ( UE.browser.safari ) {
  193. * console.log( '当前浏览器是Safari' );
  194. * }
  195. * ```
  196. */
  197. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  198. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  199. }
  200. // Opera 9.50+
  201. if ( browser.opera )
  202. version = parseFloat( opera.version() );
  203. // WebKit 522+ (Safari 3+)
  204. if ( browser.webkit )
  205. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  206. /**
  207. * @property { Number } version 检测当前浏览器版本号
  208. * @remind
  209. * <ul>
  210. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  211. * <li>gecko系列会返回10900,158900等</li>
  212. * <li>webkit系列会返回其build号 (如 522等)</li>
  213. * </ul>
  214. * @example
  215. * ```javascript
  216. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  217. * ```
  218. */
  219. browser.version = version;
  220. /**
  221. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  222. * @example
  223. * ```javascript
  224. * if ( UE.browser.isCompatible ) {
  225. * console.log( '浏览器与UEditor能够良好兼容' );
  226. * }
  227. * ```
  228. */
  229. browser.isCompatible =
  230. !browser.mobile && (
  231. ( browser.ie && version >= 6 ) ||
  232. ( browser.gecko && version >= 10801 ) ||
  233. ( browser.opera && version >= 9.5 ) ||
  234. ( browser.air && version >= 1 ) ||
  235. ( browser.webkit && version >= 522 ) ||
  236. false );
  237. return browser;
  238. }();
  239. //快捷方式
  240. var ie = browser.ie,
  241. webkit = browser.webkit,
  242. gecko = browser.gecko,
  243. opera = browser.opera;
  244. /**
  245. * @file
  246. * @name UM.Utils
  247. * @short Utils
  248. * @desc UEditor封装使用的静态工具函数
  249. * @import editor.js
  250. */
  251. var utils = UM.utils = {
  252. /**
  253. * 遍历数组,对象,nodeList
  254. * @name each
  255. * @grammar UM.utils.each(obj,iterator,[context])
  256. * @since 1.2.4+
  257. * @desc
  258. * * obj 要遍历的对象
  259. * * iterator 遍历的方法,方法的第一个是遍历的值,第二个是索引,第三个是obj
  260. * * context iterator的上下文
  261. * @example
  262. * UM.utils.each([1,2],function(v,i){
  263. * console.log(v)//值
  264. * console.log(i)//索引
  265. * })
  266. * UM.utils.each(document.getElementsByTagName('*'),function(n){
  267. * console.log(n.tagName)
  268. * })
  269. */
  270. each : function(obj, iterator, context) {
  271. if (obj == null) return;
  272. if (obj.length === +obj.length) {
  273. for (var i = 0, l = obj.length; i < l; i++) {
  274. if(iterator.call(context, obj[i], i, obj) === false)
  275. return false;
  276. }
  277. } else {
  278. for (var key in obj) {
  279. if (obj.hasOwnProperty(key)) {
  280. if(iterator.call(context, obj[key], key, obj) === false)
  281. return false;
  282. }
  283. }
  284. }
  285. },
  286. makeInstance:function (obj) {
  287. var noop = new Function();
  288. noop.prototype = obj;
  289. obj = new noop;
  290. noop.prototype = null;
  291. return obj;
  292. },
  293. /**
  294. * 将source对象中的属性扩展到target对象上
  295. * @name extend
  296. * @grammar UM.utils.extend(target,source) => Object //覆盖扩展
  297. * @grammar UM.utils.extend(target,source,true) ==> Object //保留扩展
  298. */
  299. extend:function (t, s, b) {
  300. if (s) {
  301. for (var k in s) {
  302. if (!b || !t.hasOwnProperty(k)) {
  303. t[k] = s[k];
  304. }
  305. }
  306. }
  307. return t;
  308. },
  309. extend2:function (t) {
  310. var a = arguments;
  311. for (var i = 1; i < a.length; i++) {
  312. var x = a[i];
  313. for (var k in x) {
  314. if (!t.hasOwnProperty(k)) {
  315. t[k] = x[k];
  316. }
  317. }
  318. }
  319. return t;
  320. },
  321. /**
  322. * 模拟继承机制,subClass继承superClass
  323. * @name inherits
  324. * @grammar UM.utils.inherits(subClass,superClass) => subClass
  325. * @example
  326. * function SuperClass(){
  327. * this.name = "小李";
  328. * }
  329. * SuperClass.prototype = {
  330. * hello:function(str){
  331. * console.log(this.name + str);
  332. * }
  333. * }
  334. * function SubClass(){
  335. * this.name = "小张";
  336. * }
  337. * UM.utils.inherits(SubClass,SuperClass);
  338. * var sub = new SubClass();
  339. * sub.hello("早上好!"); ==> "小张早上好!"
  340. */
  341. inherits:function (subClass, superClass) {
  342. var oldP = subClass.prototype,
  343. newP = utils.makeInstance(superClass.prototype);
  344. utils.extend(newP, oldP, true);
  345. subClass.prototype = newP;
  346. return (newP.constructor = subClass);
  347. },
  348. /**
  349. * 用指定的context作为fn上下文,也就是this
  350. * @name bind
  351. * @grammar UM.utils.bind(fn,context) => fn
  352. */
  353. bind:function (fn, context) {
  354. return function () {
  355. return fn.apply(context, arguments);
  356. };
  357. },
  358. /**
  359. * 创建延迟delay执行的函数fn
  360. * @name defer
  361. * @grammar UM.utils.defer(fn,delay) =>fn //延迟delay毫秒执行fn,返回fn
  362. * @grammar UM.utils.defer(fn,delay,exclusion) =>fn //延迟delay毫秒执行fn,若exclusion为真,则互斥执行fn
  363. * @example
  364. * function test(){
  365. * console.log("延迟输出!");
  366. * }
  367. * //非互斥延迟执行
  368. * var testDefer = UM.utils.defer(test,1000);
  369. * testDefer(); => "延迟输出!";
  370. * testDefer(); => "延迟输出!";
  371. * //互斥延迟执行
  372. * var testDefer1 = UM.utils.defer(test,1000,true);
  373. * testDefer1(); => //本次不执行
  374. * testDefer1(); => "延迟输出!";
  375. */
  376. defer:function (fn, delay, exclusion) {
  377. var timerID;
  378. return function () {
  379. if (exclusion) {
  380. clearTimeout(timerID);
  381. }
  382. timerID = setTimeout(fn, delay);
  383. };
  384. },
  385. /**
  386. * 查找元素item在数组array中的索引, 若找不到返回-1
  387. * @name indexOf
  388. * @grammar UM.utils.indexOf(array,item) => index|-1 //默认从数组开头部开始搜索
  389. * @grammar UM.utils.indexOf(array,item,start) => index|-1 //start指定开始查找的位置
  390. */
  391. indexOf:function (array, item, start) {
  392. var index = -1;
  393. start = this.isNumber(start) ? start : 0;
  394. this.each(array, function (v, i) {
  395. if (i >= start && v === item) {
  396. index = i;
  397. return false;
  398. }
  399. });
  400. return index;
  401. },
  402. /**
  403. * 移除数组array中的元素item
  404. * @name removeItem
  405. * @grammar UM.utils.removeItem(array,item)
  406. */
  407. removeItem:function (array, item) {
  408. for (var i = 0, l = array.length; i < l; i++) {
  409. if (array[i] === item) {
  410. array.splice(i, 1);
  411. i--;
  412. }
  413. }
  414. },
  415. /**
  416. * 删除字符串str的首尾空格
  417. * @name trim
  418. * @grammar UM.utils.trim(str) => String
  419. */
  420. trim:function (str) {
  421. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  422. },
  423. /**
  424. * 将字符串list(以','分隔)或者数组list转成哈希对象
  425. * @name listToMap
  426. * @grammar UM.utils.listToMap(list) => Object //Object形如{test:1,br:1,textarea:1}
  427. */
  428. listToMap:function (list) {
  429. if (!list)return {};
  430. list = utils.isArray(list) ? list : list.split(',');
  431. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  432. obj[ci.toUpperCase()] = obj[ci] = 1;
  433. }
  434. return obj;
  435. },
  436. /**
  437. * 将str中的html符号转义,默认将转义''&<">''四个字符,可自定义reg来确定需要转义的字符
  438. * @name unhtml
  439. * @grammar UM.utils.unhtml(str); => String
  440. * @grammar UM.utils.unhtml(str,reg) => String
  441. * @example
  442. * var html = '<body>You say:"你好!Baidu & UEditor!"</body>';
  443. * UM.utils.unhtml(html); ==> &lt;body&gt;You say:&quot;你好!Baidu &amp; UEditor!&quot;&lt;/body&gt;
  444. * UM.utils.unhtml(html,/[<>]/g) ==> &lt;body&gt;You say:"你好!Baidu & UEditor!"&lt;/body&gt;
  445. */
  446. unhtml:function (str, reg) {
  447. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) {
  448. if (b) {
  449. return a;
  450. } else {
  451. return {
  452. '<':'&lt;',
  453. '&':'&amp;',
  454. '"':'&quot;',
  455. '>':'&gt;',
  456. "'":'&#39;'
  457. }[a]
  458. }
  459. }) : '';
  460. },
  461. /**
  462. * 将str中的转义字符还原成html字符
  463. * @name html
  464. * @grammar UM.utils.html(str) => String //详细参见<code><a href = '#unhtml'>unhtml</a></code>
  465. */
  466. html:function (str) {
  467. return str ? str.replace(/&((g|l|quo)t|amp|#39);/g, function (m) {
  468. return {
  469. '&lt;':'<',
  470. '&amp;':'&',
  471. '&quot;':'"',
  472. '&gt;':'>',
  473. '&#39;':"'"
  474. }[m]
  475. }) : '';
  476. },
  477. /**
  478. * 将css样式转换为驼峰的形式。如font-size => fontSize
  479. * @name cssStyleToDomStyle
  480. * @grammar UM.utils.cssStyleToDomStyle(cssName) => String
  481. */
  482. cssStyleToDomStyle:function () {
  483. var test = document.createElement('div').style,
  484. cache = {
  485. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  486. };
  487. return function (cssName) {
  488. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  489. return match.charAt(1).toUpperCase();
  490. }));
  491. };
  492. }(),
  493. /**
  494. * 动态加载文件到doc中,并依据obj来设置属性,加载成功后执行回调函数fn
  495. * @name loadFile
  496. * @grammar UM.utils.loadFile(doc,obj)
  497. * @grammar UM.utils.loadFile(doc,obj,fn)
  498. * @example
  499. * //指定加载到当前document中一个script文件,加载成功后执行function
  500. * utils.loadFile( document, {
  501. * src:"test.js",
  502. * tag:"script",
  503. * type:"text/javascript",
  504. * defer:"defer"
  505. * }, function () {
  506. * console.log('加载成功!')
  507. * });
  508. */
  509. loadFile:function () {
  510. var tmpList = [];
  511. function getItem(doc, obj) {
  512. try {
  513. for (var i = 0, ci; ci = tmpList[i++];) {
  514. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  515. return ci;
  516. }
  517. }
  518. } catch (e) {
  519. return null;
  520. }
  521. }
  522. return function (doc, obj, fn) {
  523. var item = getItem(doc, obj);
  524. if (item) {
  525. if (item.ready) {
  526. fn && fn();
  527. } else {
  528. item.funs.push(fn)
  529. }
  530. return;
  531. }
  532. tmpList.push({
  533. doc:doc,
  534. url:obj.src || obj.href,
  535. funs:[fn]
  536. });
  537. if (!doc.body) {
  538. var html = [];
  539. for (var p in obj) {
  540. if (p == 'tag')continue;
  541. html.push(p + '="' + obj[p] + '"')
  542. }
  543. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  544. return;
  545. }
  546. if (obj.id && doc.getElementById(obj.id)) {
  547. return;
  548. }
  549. var element = doc.createElement(obj.tag);
  550. delete obj.tag;
  551. for (var p in obj) {
  552. element.setAttribute(p, obj[p]);
  553. }
  554. element.onload = element.onreadystatechange = function () {
  555. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  556. item = getItem(doc, obj);
  557. if (item.funs.length > 0) {
  558. item.ready = 1;
  559. for (var fi; fi = item.funs.pop();) {
  560. fi();
  561. }
  562. }
  563. element.onload = element.onreadystatechange = null;
  564. }
  565. };
  566. element.onerror = function () {
  567. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file umeditor.config.js ')
  568. };
  569. doc.getElementsByTagName("head")[0].appendChild(element);
  570. }
  571. }(),
  572. /**
  573. * 判断obj对象是否为空
  574. * @name isEmptyObject
  575. * @grammar UM.utils.isEmptyObject(obj) => true|false
  576. * @example
  577. * UM.utils.isEmptyObject({}) ==>true
  578. * UM.utils.isEmptyObject([]) ==>true
  579. * UM.utils.isEmptyObject("") ==>true
  580. */
  581. isEmptyObject:function (obj) {
  582. if (obj == null) return true;
  583. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  584. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  585. return true;
  586. },
  587. /**
  588. * 统一将颜色值使用16进制形式表示
  589. * @name fixColor
  590. * @grammar UM.utils.fixColor(name,value) => value
  591. * @example
  592. * rgb(255,255,255) => "#ffffff"
  593. */
  594. fixColor:function (name, value) {
  595. if (/color/i.test(name) && /rgba?/.test(value)) {
  596. var array = value.split(",");
  597. if (array.length > 3)
  598. return "";
  599. value = "#";
  600. for (var i = 0, color; color = array[i++];) {
  601. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  602. value += color.length == 1 ? "0" + color : color;
  603. }
  604. value = value.toUpperCase();
  605. }
  606. return value;
  607. },
  608. /**
  609. * 深度克隆对象,从source到target
  610. * @name clone
  611. * @grammar UM.utils.clone(source) => anthorObj 新的对象是完整的source的副本
  612. * @grammar UM.utils.clone(source,target) => target包含了source的所有内容,重名会覆盖
  613. */
  614. clone:function (source, target) {
  615. var tmp;
  616. target = target || {};
  617. for (var i in source) {
  618. if (source.hasOwnProperty(i)) {
  619. tmp = source[i];
  620. if (typeof tmp == 'object') {
  621. target[i] = utils.isArray(tmp) ? [] : {};
  622. utils.clone(source[i], target[i])
  623. } else {
  624. target[i] = tmp;
  625. }
  626. }
  627. }
  628. return target;
  629. },
  630. /**
  631. * 转换cm/pt到px
  632. * @name transUnitToPx
  633. * @grammar UM.utils.transUnitToPx('20pt') => '27px'
  634. * @grammar UM.utils.transUnitToPx('0pt') => '0'
  635. */
  636. transUnitToPx:function (val) {
  637. if (!/(pt|cm)/.test(val)) {
  638. return val
  639. }
  640. var unit;
  641. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  642. val = v;
  643. unit = u;
  644. });
  645. switch (unit) {
  646. case 'cm':
  647. val = parseFloat(val) * 25;
  648. break;
  649. case 'pt':
  650. val = Math.round(parseFloat(val) * 96 / 72);
  651. }
  652. return val + (val ? 'px' : '');
  653. },
  654. /**
  655. * 动态添加css样式
  656. * @name cssRule
  657. * @grammar UM.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  658. * @grammar UM.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  659. * @grammar UM.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  660. * @grammar UM.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  661. */
  662. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  663. var indexList, index;
  664. doc = doc || document;
  665. if (doc.indexList) {
  666. indexList = doc.indexList;
  667. } else {
  668. indexList = doc.indexList = {};
  669. }
  670. var sheetStyle;
  671. if (!indexList[key]) {
  672. if (style === undefined) {
  673. return ''
  674. }
  675. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  676. indexList[key] = index;
  677. } else {
  678. sheetStyle = doc.styleSheets[indexList[key]];
  679. }
  680. if (style === undefined) {
  681. return sheetStyle.cssText
  682. }
  683. sheetStyle.cssText = style || ''
  684. } : function (key, style, doc) {
  685. doc = doc || document;
  686. var head = doc.getElementsByTagName('head')[0], node;
  687. if (!(node = doc.getElementById(key))) {
  688. if (style === undefined) {
  689. return ''
  690. }
  691. node = doc.createElement('style');
  692. node.id = key;
  693. head.appendChild(node)
  694. }
  695. if (style === undefined) {
  696. return node.innerHTML
  697. }
  698. if (style !== '') {
  699. node.innerHTML = style;
  700. } else {
  701. head.removeChild(node)
  702. }
  703. }
  704. };
  705. /**
  706. * 判断str是否为字符串
  707. * @name isString
  708. * @grammar UM.utils.isString(str) => true|false
  709. */
  710. /**
  711. * 判断array是否为数组
  712. * @name isArray
  713. * @grammar UM.utils.isArray(obj) => true|false
  714. */
  715. /**
  716. * 判断obj对象是否为方法
  717. * @name isFunction
  718. * @grammar UM.utils.isFunction(obj) => true|false
  719. */
  720. /**
  721. * 判断obj对象是否为数字
  722. * @name isNumber
  723. * @grammar UM.utils.isNumber(obj) => true|false
  724. */
  725. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'], function (v) {
  726. UM.utils['is' + v] = function (obj) {
  727. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  728. }
  729. });
  730. /**
  731. * @file
  732. * @name UM.EventBase
  733. * @short EventBase
  734. * @import editor.js,core/utils.js
  735. * @desc UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  736. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  737. */
  738. var EventBase = UM.EventBase = function () {};
  739. EventBase.prototype = {
  740. /**
  741. * 注册事件监听器
  742. * @name addListener
  743. * @grammar editor.addListener(types,fn) //types为事件名称,多个可用空格分隔
  744. * @example
  745. * editor.addListener('selectionchange',function(){
  746. * console.log("选区已经变化!");
  747. * })
  748. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  749. * if(type == 'beforegetcontent'){
  750. * //do something
  751. * }else{
  752. * //do something
  753. * }
  754. * console.log(this.getContent) // this是注册的事件的编辑器实例
  755. * })
  756. */
  757. addListener:function (types, listener) {
  758. types = utils.trim(types).split(' ');
  759. for (var i = 0, ti; ti = types[i++];) {
  760. getListener(this, ti, true).push(listener);
  761. }
  762. },
  763. /**
  764. * 移除事件监听器
  765. * @name removeListener
  766. * @grammar editor.removeListener(types,fn) //types为事件名称,多个可用空格分隔
  767. * @example
  768. * //changeCallback为方法体
  769. * editor.removeListener("selectionchange",changeCallback);
  770. */
  771. removeListener:function (types, listener) {
  772. types = utils.trim(types).split(' ');
  773. for (var i = 0, ti; ti = types[i++];) {
  774. utils.removeItem(getListener(this, ti) || [], listener);
  775. }
  776. },
  777. /**
  778. * 触发事件
  779. * @name fireEvent
  780. * @grammar editor.fireEvent(types) //types为事件名称,多个可用空格分隔
  781. * @example
  782. * editor.fireEvent("selectionchange");
  783. */
  784. fireEvent:function () {
  785. var types = arguments[0];
  786. types = utils.trim(types).split(' ');
  787. for (var i = 0, ti; ti = types[i++];) {
  788. var listeners = getListener(this, ti),
  789. r, t, k;
  790. if (listeners) {
  791. k = listeners.length;
  792. while (k--) {
  793. if(!listeners[k])continue;
  794. t = listeners[k].apply(this, arguments);
  795. if(t === true){
  796. return t;
  797. }
  798. if (t !== undefined) {
  799. r = t;
  800. }
  801. }
  802. }
  803. if (t = this['on' + ti.toLowerCase()]) {
  804. r = t.apply(this, arguments);
  805. }
  806. }
  807. return r;
  808. }
  809. };
  810. /**
  811. * 获得对象所拥有监听类型的所有监听器
  812. * @public
  813. * @function
  814. * @param {Object} obj 查询监听器的对象
  815. * @param {String} type 事件类型
  816. * @param {Boolean} force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  817. * @returns {Array} 监听器数组
  818. */
  819. function getListener(obj, type, force) {
  820. var allListeners;
  821. type = type.toLowerCase();
  822. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  823. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  824. }
  825. ///import editor.js
  826. ///import core/dom/dom.js
  827. ///import core/utils.js
  828. /**
  829. * dtd html语义化的体现类
  830. * @constructor
  831. * @namespace dtd
  832. */
  833. var dtd = dom.dtd = (function() {
  834. function _( s ) {
  835. for (var k in s) {
  836. s[k.toUpperCase()] = s[k];
  837. }
  838. return s;
  839. }
  840. var X = utils.extend2;
  841. var A = _({isindex:1,fieldset:1}),
  842. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  843. C = X( _({a:1}), B ),
  844. D = X( {iframe:1}, C ),
  845. 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}),
  846. F = _({ins:1,del:1,script:1,style:1}),
  847. 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 ),
  848. 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 ),
  849. I = X( _({p:1}), H ),
  850. J = X( _({iframe:1}), H, B ),
  851. 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}),
  852. L = X( _({a:0}), J ),//a不能被切开,所以把他
  853. M = _({tr:1}),
  854. N = _({'#':1}),
  855. O = X( _({param:1}), K ),
  856. P = X( _({form:1}), A, D, E, I ),
  857. Q = _({li:1,ol:1,ul:1}),
  858. R = _({style:1,script:1}),
  859. S = _({base:1,link:1,meta:1,title:1}),
  860. T = X( S, R ),
  861. U = _({head:1,body:1}),
  862. V = _({html:1});
  863. 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}),
  864. 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});
  865. return _({
  866. // $ 表示自定的属性
  867. // body外的元素列表.
  868. $nonBodyContent: X( V, U, S ),
  869. //块结构元素列表
  870. $block : block,
  871. //内联元素列表
  872. $inline : L,
  873. $inlineWithA : X(_({a:1}),L),
  874. $body : X( _({script:1,style:1}), block ),
  875. $cdata : _({script:1,style:1}),
  876. //自闭和元素
  877. $empty : empty,
  878. //不是自闭合,但不能让range选中里边
  879. $nonChild : _({iframe:1,textarea:1}),
  880. //列表元素列表
  881. $listItem : _({dd:1,dt:1,li:1}),
  882. //列表根元素列表
  883. $list: _({ul:1,ol:1,dl:1}),
  884. //不能认为是空的元素
  885. $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}),
  886. //如果没有子节点就可以删除的元素列表,像span,a
  887. $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}),
  888. $removeEmptyBlock : _({'p':1,'div':1}),
  889. //在table元素里的元素列表
  890. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  891. //不转换的标签
  892. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  893. html: U,
  894. head: T,
  895. style: N,
  896. script: N,
  897. body: P,
  898. base: {},
  899. link: {},
  900. meta: {},
  901. title: N,
  902. col : {},
  903. tr : _({td:1,th:1}),
  904. img : {},
  905. embed: {},
  906. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  907. noscript : P,
  908. td : P,
  909. br : {},
  910. th : P,
  911. center : P,
  912. kbd : L,
  913. button : X( I, E ),
  914. basefont : {},
  915. h5 : L,
  916. h4 : L,
  917. samp : L,
  918. h6 : L,
  919. ol : Q,
  920. h1 : L,
  921. h3 : L,
  922. option : N,
  923. h2 : L,
  924. form : X( A, D, E, I ),
  925. select : _({optgroup:1,option:1}),
  926. font : L,
  927. ins : L,
  928. menu : Q,
  929. abbr : L,
  930. label : L,
  931. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  932. code : L,
  933. tfoot : M,
  934. cite : L,
  935. li : P,
  936. input : {},
  937. iframe : P,
  938. strong : L,
  939. textarea : N,
  940. noframes : P,
  941. big : L,
  942. small : L,
  943. //trace:
  944. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  945. hr : L,
  946. dt : L,
  947. sub : L,
  948. optgroup : _({option:1}),
  949. param : {},
  950. bdo : L,
  951. 'var' : L,
  952. div : P,
  953. object : O,
  954. sup : L,
  955. dd : P,
  956. strike : L,
  957. area : {},
  958. dir : Q,
  959. map : X( _({area:1,form:1,p:1}), A, F, E ),
  960. applet : O,
  961. dl : _({dt:1,dd:1}),
  962. del : L,
  963. isindex : {},
  964. fieldset : X( _({legend:1}), K ),
  965. thead : M,
  966. ul : Q,
  967. acronym : L,
  968. b : L,
  969. a : X( _({a:1}), J ),
  970. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  971. caption : L,
  972. i : L,
  973. u : L,
  974. tbody : M,
  975. s : L,
  976. address : X( D, I ),
  977. tt : L,
  978. legend : L,
  979. q : L,
  980. pre : X( G, C ),
  981. p : X(_({'a':1}),L),
  982. em :L,
  983. dfn : L
  984. });
  985. })();
  986. /**
  987. * @file
  988. * @name UM.dom.domUtils
  989. * @short DomUtils
  990. * @import editor.js, core/utils.js,core/browser.js,core/dom/dtd.js
  991. * @desc UEditor封装的底层dom操作库
  992. */
  993. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  994. var tmpNode = startFromChild && node[start],
  995. parent;
  996. !tmpNode && (tmpNode = node[ltr]);
  997. while (!tmpNode && (parent = (parent || node).parentNode)) {
  998. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  999. return null;
  1000. }
  1001. tmpNode = parent[ltr];
  1002. }
  1003. if (tmpNode && fn && !fn(tmpNode)) {
  1004. return getDomNode(tmpNode, start, ltr, false, fn);
  1005. }
  1006. return tmpNode;
  1007. }
  1008. var attrFix = ie && browser.version < 9 ? {
  1009. tabindex: "tabIndex",
  1010. readonly: "readOnly",
  1011. "for": "htmlFor",
  1012. "class": "className",
  1013. maxlength: "maxLength",
  1014. cellspacing: "cellSpacing",
  1015. cellpadding: "cellPadding",
  1016. rowspan: "rowSpan",
  1017. colspan: "colSpan",
  1018. usemap: "useMap",
  1019. frameborder: "frameBorder"
  1020. } : {
  1021. tabindex: "tabIndex",
  1022. readonly: "readOnly"
  1023. },
  1024. styleBlock = utils.listToMap([
  1025. '-webkit-box', '-moz-box', 'block' ,
  1026. 'list-item' , 'table' , 'table-row-group' ,
  1027. 'table-header-group', 'table-footer-group' ,
  1028. 'table-row' , 'table-column-group' , 'table-column' ,
  1029. 'table-cell' , 'table-caption'
  1030. ]);
  1031. var domUtils = dom.domUtils = {
  1032. //节点常量
  1033. NODE_ELEMENT: 1,
  1034. NODE_DOCUMENT: 9,
  1035. NODE_TEXT: 3,
  1036. NODE_COMMENT: 8,
  1037. NODE_DOCUMENT_FRAGMENT: 11,
  1038. //位置关系
  1039. POSITION_IDENTICAL: 0,
  1040. POSITION_DISCONNECTED: 1,
  1041. POSITION_FOLLOWING: 2,
  1042. POSITION_PRECEDING: 4,
  1043. POSITION_IS_CONTAINED: 8,
  1044. POSITION_CONTAINS: 16,
  1045. //ie6使用其他的会有一段空白出现
  1046. fillChar: ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1047. //-------------------------Node部分--------------------------------
  1048. keys: {
  1049. /*Backspace*/ 8: 1, /*Delete*/ 46: 1,
  1050. /*Shift*/ 16: 1, /*Ctrl*/ 17: 1, /*Alt*/ 18: 1,
  1051. 37: 1, 38: 1, 39: 1, 40: 1,
  1052. 13: 1 /*enter*/
  1053. },
  1054. breakParent:function (node, parent) {
  1055. var tmpNode,
  1056. parentClone = node,
  1057. clone = node,
  1058. leftNodes,
  1059. rightNodes;
  1060. do {
  1061. parentClone = parentClone.parentNode;
  1062. if (leftNodes) {
  1063. tmpNode = parentClone.cloneNode(false);
  1064. tmpNode.appendChild(leftNodes);
  1065. leftNodes = tmpNode;
  1066. tmpNode = parentClone.cloneNode(false);
  1067. tmpNode.appendChild(rightNodes);
  1068. rightNodes = tmpNode;
  1069. } else {
  1070. leftNodes = parentClone.cloneNode(false);
  1071. rightNodes = leftNodes.cloneNode(false);
  1072. }
  1073. while (tmpNode = clone.previousSibling) {
  1074. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  1075. }
  1076. while (tmpNode = clone.nextSibling) {
  1077. rightNodes.appendChild(tmpNode);
  1078. }
  1079. clone = parentClone;
  1080. } while (parent !== parentClone);
  1081. tmpNode = parent.parentNode;
  1082. tmpNode.insertBefore(leftNodes, parent);
  1083. tmpNode.insertBefore(rightNodes, parent);
  1084. tmpNode.insertBefore(node, rightNodes);
  1085. domUtils.remove(parent);
  1086. return node;
  1087. },
  1088. trimWhiteTextNode:function (node) {
  1089. function remove(dir) {
  1090. var child;
  1091. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  1092. node.removeChild(child);
  1093. }
  1094. }
  1095. remove('firstChild');
  1096. remove('lastChild');
  1097. },
  1098. /**
  1099. * 获取节点A相对于节点B的位置关系
  1100. * @name getPosition
  1101. * @grammar UM.dom.domUtils.getPosition(nodeA,nodeB) => Number
  1102. * @example
  1103. * switch (returnValue) {
  1104. * case 0: //相等,同一节点
  1105. * case 1: //无关,节点不相连
  1106. * case 2: //跟随,即节点A头部位于节点B头部的后面
  1107. * case 4: //前置,即节点A头部位于节点B头部的前面
  1108. * case 8: //被包含,即节点A被节点B包含
  1109. * case 10://组合类型,即节点A满足跟随节点B且被节点B包含。实际上,如果被包含,必定跟随,所以returnValue事实上不会存在8的情况。
  1110. * case 16://包含,即节点A包含节点B
  1111. * case 20://组合类型,即节点A满足前置节点A且包含节点B。同样,如果包含,必定前置,所以returnValue事实上也不会存在16的情况
  1112. * }
  1113. */
  1114. getPosition: function (nodeA, nodeB) {
  1115. // 如果两个节点是同一个节点
  1116. if (nodeA === nodeB) {
  1117. // domUtils.POSITION_IDENTICAL
  1118. return 0;
  1119. }
  1120. var node,
  1121. parentsA = [nodeA],
  1122. parentsB = [nodeB];
  1123. node = nodeA;
  1124. while (node = node.parentNode) {
  1125. // 如果nodeB是nodeA的祖先节点
  1126. if (node === nodeB) {
  1127. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1128. return 10;
  1129. }
  1130. parentsA.push(node);
  1131. }
  1132. node = nodeB;
  1133. while (node = node.parentNode) {
  1134. // 如果nodeA是nodeB的祖先节点
  1135. if (node === nodeA) {
  1136. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1137. return 20;
  1138. }
  1139. parentsB.push(node);
  1140. }
  1141. parentsA.reverse();
  1142. parentsB.reverse();
  1143. if (parentsA[0] !== parentsB[0]) {
  1144. // domUtils.POSITION_DISCONNECTED
  1145. return 1;
  1146. }
  1147. var i = -1;
  1148. while (i++, parentsA[i] === parentsB[i]) {
  1149. }
  1150. nodeA = parentsA[i];
  1151. nodeB = parentsB[i];
  1152. while (nodeA = nodeA.nextSibling) {
  1153. if (nodeA === nodeB) {
  1154. // domUtils.POSITION_PRECEDING
  1155. return 4
  1156. }
  1157. }
  1158. // domUtils.POSITION_FOLLOWING
  1159. return 2;
  1160. },
  1161. /**
  1162. * 返回节点node在父节点中的索引位置
  1163. * @name getNodeIndex
  1164. * @grammar UM.dom.domUtils.getNodeIndex(node) => Number //索引值从0开始
  1165. */
  1166. getNodeIndex: function (node, ignoreTextNode) {
  1167. var preNode = node,
  1168. i = 0;
  1169. while (preNode = preNode.previousSibling) {
  1170. if (ignoreTextNode && preNode.nodeType == 3) {
  1171. if (preNode.nodeType != preNode.nextSibling.nodeType) {
  1172. i++;
  1173. }
  1174. continue;
  1175. }
  1176. i++;
  1177. }
  1178. return i;
  1179. },
  1180. /**
  1181. * 检测节点node是否在节点doc的树上,实质上是检测是否被doc包含
  1182. * @name inDoc
  1183. * @grammar UM.dom.domUtils.inDoc(node,doc) => true|false
  1184. */
  1185. inDoc: function (node, doc) {
  1186. return domUtils.getPosition(node, doc) == 10;
  1187. },
  1188. /**
  1189. * 查找node节点的祖先节点
  1190. * @name findParent
  1191. * @grammar UM.dom.domUtils.findParent(node) => Element // 直接返回node节点的父节点
  1192. * @grammar UM.dom.domUtils.findParent(node,filterFn) => Element //filterFn为过滤函数,node作为参数,返回true时才会将node作为符合要求的节点返回
  1193. * @grammar UM.dom.domUtils.findParent(node,filterFn,includeSelf) => Element //includeSelf指定是否包含自身
  1194. */
  1195. findParent: function (node, filterFn, includeSelf) {
  1196. if (node && !domUtils.isBody(node)) {
  1197. node = includeSelf ? node : node.parentNode;
  1198. while (node) {
  1199. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1200. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1201. }
  1202. node = node.parentNode;
  1203. }
  1204. }
  1205. return null;
  1206. },
  1207. /**
  1208. * 通过tagName查找node节点的祖先节点
  1209. * @name findParentByTagName
  1210. * @grammar UM.dom.domUtils.findParentByTagName(node,tagNames) => Element //tagNames支持数组,区分大小写
  1211. * @grammar UM.dom.domUtils.findParentByTagName(node,tagNames,includeSelf) => Element //includeSelf指定是否包含自身
  1212. * @grammar UM.dom.domUtils.findParentByTagName(node,tagNames,includeSelf,excludeFn) => Element //excludeFn指定例外过滤条件,返回true时忽略该节点
  1213. */
  1214. findParentByTagName: function (node, tagNames, includeSelf, excludeFn) {
  1215. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  1216. return domUtils.findParent(node, function (node) {
  1217. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  1218. }, includeSelf);
  1219. },
  1220. /**
  1221. * 查找节点node的祖先节点集合
  1222. * @name findParents
  1223. * @grammar UM.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  1224. * @grammar UM.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  1225. * @grammar UM.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  1226. * @grammar UM.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  1227. */
  1228. findParents: function (node, includeSelf, filterFn, closerFirst) {
  1229. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  1230. while (node = domUtils.findParent(node, filterFn)) {
  1231. parents.push(node);
  1232. }
  1233. return closerFirst ? parents : parents.reverse();
  1234. },
  1235. /**
  1236. * 在节点node后面插入新节点newNode
  1237. * @name insertAfter
  1238. * @grammar UM.dom.domUtils.insertAfter(node,newNode) => newNode
  1239. */
  1240. insertAfter: function (node, newNode) {
  1241. return node.parentNode.insertBefore(newNode, node.nextSibling);
  1242. },
  1243. /**
  1244. * 删除节点node,并根据keepChildren指定是否保留子节点
  1245. * @name remove
  1246. * @grammar UM.dom.domUtils.remove(node) => node
  1247. * @grammar UM.dom.domUtils.remove(node,keepChildren) => node
  1248. */
  1249. remove: function (node, keepChildren) {
  1250. var parent = node.parentNode,
  1251. child;
  1252. if (parent) {
  1253. if (keepChildren && node.hasChildNodes()) {
  1254. while (child = node.firstChild) {
  1255. parent.insertBefore(child, node);
  1256. }
  1257. }
  1258. parent.removeChild(node);
  1259. }
  1260. return node;
  1261. },
  1262. /**
  1263. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  1264. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  1265. * @method getNextDomNode
  1266. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1267. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1268. * @example
  1269. * ```html
  1270. * <body>
  1271. * <div id="test">
  1272. * <span></span>
  1273. * </div>
  1274. * <i>xxx</i>
  1275. * </body>
  1276. * <script>
  1277. *
  1278. * //output: i节点
  1279. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1280. *
  1281. * </script>
  1282. * ```
  1283. * @example
  1284. * ```html
  1285. * <body>
  1286. * <div>
  1287. * <span></span>
  1288. * <i id="test">xxx</i>
  1289. * </div>
  1290. * <b>xxx</b>
  1291. * </body>
  1292. * <script>
  1293. *
  1294. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  1295. * //output: b节点
  1296. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1297. *
  1298. * </script>
  1299. * ```
  1300. */
  1301. /**
  1302. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  1303. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  1304. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  1305. * @method getNextDomNode
  1306. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1307. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  1308. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1309. * @see UE.dom.domUtils.getNextDomNode(Node)
  1310. */
  1311. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  1312. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  1313. },
  1314. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  1315. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  1316. },
  1317. /**
  1318. * 检测节点node是否属于bookmark节点
  1319. * @name isBookmarkNode
  1320. * @grammar UM.dom.domUtils.isBookmarkNode(node) => true|false
  1321. */
  1322. isBookmarkNode: function (node) {
  1323. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  1324. },
  1325. /**
  1326. * 获取节点node所在的window对象
  1327. * @name getWindow
  1328. * @grammar UM.dom.domUtils.getWindow(node) => window对象
  1329. */
  1330. getWindow: function (node) {
  1331. var doc = node.ownerDocument || node;
  1332. return doc.defaultView || doc.parentWindow;
  1333. },
  1334. /**
  1335. * 获取离nodeA与nodeB最近的公共的祖先节点
  1336. * @method getCommonAncestor
  1337. * @param { Node } nodeA 第一个节点
  1338. * @param { Node } nodeB 第二个节点
  1339. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  1340. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  1341. * @example
  1342. * ```javascript
  1343. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  1344. * //output: true
  1345. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  1346. * ```
  1347. */
  1348. getCommonAncestor:function (nodeA, nodeB) {
  1349. if (nodeA === nodeB)
  1350. return nodeA;
  1351. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  1352. while (parent = parent.parentNode) {
  1353. if (parent === nodeB) {
  1354. return parent;
  1355. }
  1356. parentsA.push(parent);
  1357. }
  1358. parent = nodeB;
  1359. while (parent = parent.parentNode) {
  1360. if (parent === nodeA)
  1361. return parent;
  1362. parentsB.push(parent);
  1363. }
  1364. parentsA.reverse();
  1365. parentsB.reverse();
  1366. while (i++, parentsA[i] === parentsB[i]) {
  1367. }
  1368. return i == 0 ? null : parentsA[i - 1];
  1369. },
  1370. /**
  1371. * 清除node节点左右连续为空的兄弟inline节点
  1372. * @method clearEmptySibling
  1373. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  1374. * 则这些兄弟节点将被删除
  1375. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  1376. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  1377. * @example
  1378. * ```html
  1379. * <body>
  1380. * <div></div>
  1381. * <span id="test"></span>
  1382. * <i></i>
  1383. * <b></b>
  1384. * <em>xxx</em>
  1385. * <span></span>
  1386. * </body>
  1387. * <script>
  1388. *
  1389. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  1390. *
  1391. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  1392. * console.log( document.body.innerHTML );
  1393. *
  1394. * </script>
  1395. * ```
  1396. */
  1397. /**
  1398. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  1399. * 则忽略对右边兄弟节点的操作。
  1400. * @method clearEmptySibling
  1401. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  1402. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  1403. * 则这些兄弟节点将被删除
  1404. * @see UE.dom.domUtils.clearEmptySibling(Node)
  1405. */
  1406. /**
  1407. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  1408. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  1409. * @method clearEmptySibling
  1410. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  1411. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  1412. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  1413. * 则这些兄弟节点将被删除
  1414. * @see UE.dom.domUtils.clearEmptySibling(Node)
  1415. */
  1416. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  1417. function clear(next, dir) {
  1418. var tmpNode;
  1419. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  1420. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  1421. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  1422. tmpNode = next[dir];
  1423. domUtils.remove(next);
  1424. next = tmpNode;
  1425. }
  1426. }
  1427. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  1428. !ignorePre && clear(node.previousSibling, 'previousSibling');
  1429. },
  1430. /**
  1431. * 将一个文本节点node拆分成两个文本节点,offset指定拆分位置
  1432. * @name split
  1433. * @grammar UM.dom.domUtils.split(node,offset) => TextNode //返回从切分位置开始的后一个文本节点
  1434. */
  1435. split: function (node, offset) {
  1436. var doc = node.ownerDocument;
  1437. if (browser.ie && offset == node.nodeValue.length) {
  1438. var next = doc.createTextNode('');
  1439. return domUtils.insertAfter(node, next);
  1440. }
  1441. var retval = node.splitText(offset);
  1442. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  1443. if (browser.ie8) {
  1444. var tmpNode = doc.createTextNode('');
  1445. domUtils.insertAfter(retval, tmpNode);
  1446. domUtils.remove(tmpNode);
  1447. }
  1448. return retval;
  1449. },
  1450. /**
  1451. * 检测节点node是否为空节点(包括空格、换行、占位符等字符)
  1452. * @name isWhitespace
  1453. * @grammar UM.dom.domUtils.isWhitespace(node) => true|false
  1454. */
  1455. isWhitespace: function (node) {
  1456. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  1457. },
  1458. /**
  1459. * 获取元素element相对于viewport的位置坐标
  1460. * @name getXY
  1461. * @grammar UM.dom.domUtils.getXY(element) => Object //返回坐标对象{x:left,y:top}
  1462. */
  1463. getXY: function (element) {
  1464. var x = 0, y = 0;
  1465. while (element.offsetParent) {
  1466. y += element.offsetTop;
  1467. x += element.offsetLeft;
  1468. element = element.offsetParent;
  1469. }
  1470. return { 'x': x, 'y': y};
  1471. },
  1472. /**
  1473. * 检查节点node是否是空inline节点
  1474. * @name isEmptyInlineElement
  1475. * @grammar UM.dom.domUtils.isEmptyInlineElement(node) => 1|0
  1476. * @example
  1477. * <b><i></i></b> => 1
  1478. * <b><i></i><u></u></b> => 1
  1479. * <b></b> => 1
  1480. * <b>xx<i></i></b> => 0
  1481. */
  1482. isEmptyInlineElement: function (node) {
  1483. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  1484. return 0;
  1485. }
  1486. node = node.firstChild;
  1487. while (node) {
  1488. //如果是创建的bookmark就跳过
  1489. if (domUtils.isBookmarkNode(node)) {
  1490. return 0;
  1491. }
  1492. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  1493. node.nodeType == 3 && !domUtils.isWhitespace(node)
  1494. ) {
  1495. return 0;
  1496. }
  1497. node = node.nextSibling;
  1498. }
  1499. return 1;
  1500. },
  1501. /**
  1502. * 检查节点node是否为块元素
  1503. * @name isBlockElm
  1504. * @grammar UM.dom.domUtils.isBlockElm(node) => true|false
  1505. */
  1506. isBlockElm: function (node) {
  1507. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  1508. },
  1509. /**
  1510. * 原生方法getElementsByTagName的封装
  1511. * @name getElementsByTagName
  1512. * @grammar UM.dom.domUtils.getElementsByTagName(node,tagName) => Array //节点集合数组
  1513. */
  1514. getElementsByTagName: function (node, name, filter) {
  1515. if (filter && utils.isString(filter)) {
  1516. var className = filter;
  1517. filter = function (node) {
  1518. var result = false;
  1519. $.each(utils.trim(className).replace(/[ ]{2,}/g, ' ').split(' '), function (i, v) {
  1520. if ($(node).hasClass(v)) {
  1521. result = true;
  1522. return false;
  1523. }
  1524. })
  1525. return result;
  1526. }
  1527. }
  1528. name = utils.trim(name).replace(/[ ]{2,}/g, ' ').split(' ');
  1529. var arr = [];
  1530. for (var n = 0, ni; ni = name[n++];) {
  1531. var list = node.getElementsByTagName(ni);
  1532. for (var i = 0, ci; ci = list[i++];) {
  1533. if (!filter || filter(ci))
  1534. arr.push(ci);
  1535. }
  1536. }
  1537. return arr;
  1538. },
  1539. /**
  1540. * 设置节点node及其子节点不会被选中
  1541. * @name unSelectable
  1542. * @grammar UM.dom.domUtils.unSelectable(node)
  1543. */
  1544. unSelectable: ie && browser.ie9below || browser.opera ? function (node) {
  1545. //for ie9
  1546. node.onselectstart = function () {
  1547. return false;
  1548. };
  1549. node.onclick = node.onkeyup = node.onkeydown = function () {
  1550. return false;
  1551. };
  1552. node.unselectable = 'on';
  1553. node.setAttribute("unselectable", "on");
  1554. for (var i = 0, ci; ci = node.all[i++];) {
  1555. switch (ci.tagName.toLowerCase()) {
  1556. case 'iframe' :
  1557. case 'textarea' :
  1558. case 'input' :
  1559. case 'select' :
  1560. break;
  1561. default :
  1562. ci.unselectable = 'on';
  1563. node.setAttribute("unselectable", "on");
  1564. }
  1565. }
  1566. } : function (node) {
  1567. node.style.MozUserSelect =
  1568. node.style.webkitUserSelect =
  1569. node.style.msUserSelect =
  1570. node.style.KhtmlUserSelect = 'none';
  1571. },
  1572. /**
  1573. * 删除节点node上的属性attrNames,attrNames为属性名称数组
  1574. * @name removeAttributes
  1575. * @grammar UM.dom.domUtils.removeAttributes(node,attrNames)
  1576. * @example
  1577. * //Before remove
  1578. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  1579. * //Remove
  1580. * UM.dom.domUtils.removeAttributes(node,["id","name"]);
  1581. * //After remove
  1582. * <span style="font-size:14px;">xxxxx</span>
  1583. */
  1584. removeAttributes: function (node, attrNames) {
  1585. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g, ' ').split(' ');
  1586. for (var i = 0, ci; ci = attrNames[i++];) {
  1587. ci = attrFix[ci] || ci;
  1588. switch (ci) {
  1589. case 'className':
  1590. node[ci] = '';
  1591. break;
  1592. case 'style':
  1593. node.style.cssText = '';
  1594. !browser.ie && node.removeAttributeNode(node.getAttributeNode('style'))
  1595. }
  1596. node.removeAttribute(ci);
  1597. }
  1598. },
  1599. /**
  1600. * 在doc下创建一个标签名为tag,属性为attrs的元素
  1601. * @name createElement
  1602. * @grammar UM.dom.domUtils.createElement(doc,tag,attrs) => Node //返回创建的节点
  1603. */
  1604. createElement: function (doc, tag, attrs) {
  1605. return domUtils.setAttributes(doc.createElement(tag), attrs)
  1606. },
  1607. /**
  1608. * 为节点node添加属性attrs,attrs为属性键值对
  1609. * @name setAttributes
  1610. * @grammar UM.dom.domUtils.setAttributes(node,attrs) => node
  1611. */
  1612. setAttributes: function (node, attrs) {
  1613. for (var attr in attrs) {
  1614. if (attrs.hasOwnProperty(attr)) {
  1615. var value = attrs[attr];
  1616. switch (attr) {
  1617. case 'class':
  1618. //ie下要这样赋值,setAttribute不起作用
  1619. node.className = value;
  1620. break;
  1621. case 'style' :
  1622. node.style.cssText = node.style.cssText + ";" + value;
  1623. break;
  1624. case 'innerHTML':
  1625. node[attr] = value;
  1626. break;
  1627. case 'value':
  1628. node.value = value;
  1629. break;
  1630. default:
  1631. node.setAttribute(attrFix[attr] || attr, value);
  1632. }
  1633. }
  1634. }
  1635. return node;
  1636. },
  1637. /**
  1638. * 获取元素element的计算样式
  1639. * @name getComputedStyle
  1640. * @grammar UM.dom.domUtils.getComputedStyle(element,styleName) => String //返回对应样式名称的样式值
  1641. * @example
  1642. * getComputedStyle(document.body,"font-size") => "15px"
  1643. * getComputedStyle(form,"color") => "#ffccdd"
  1644. */
  1645. getComputedStyle: function (element, styleName) {
  1646. return utils.transUnitToPx(utils.fixColor(styleName, $(element).css(styleName)));
  1647. },
  1648. /**
  1649. * 阻止事件默认行为
  1650. * @param {Event} evt 需要组织的事件对象
  1651. */
  1652. preventDefault: function (evt) {
  1653. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  1654. },
  1655. /**
  1656. * 删除元素element指定的样式
  1657. * @method removeStyle
  1658. * @param { Element } element 需要删除样式的元素
  1659. * @param { String } styleName 需要删除的样式名
  1660. * @example
  1661. * ```html
  1662. * <span id="test" style="color: red; background: blue;"></span>
  1663. *
  1664. * <script>
  1665. *
  1666. * var testNode = document.getElementById("test");
  1667. *
  1668. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  1669. *
  1670. * //output: background: blue;
  1671. * console.log( testNode.style.cssText );
  1672. *
  1673. * </script>
  1674. * ```
  1675. */
  1676. removeStyle:function (element, name) {
  1677. if(browser.ie ){
  1678. //针对color先单独处理一下
  1679. if(name == 'color'){
  1680. name = '(^|;)' + name;
  1681. }
  1682. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  1683. }else{
  1684. if (element.style.removeProperty) {
  1685. element.style.removeProperty (name);
  1686. }else {
  1687. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  1688. }
  1689. }
  1690. if (!element.style.cssText) {
  1691. domUtils.removeAttributes(element, ['style']);
  1692. }
  1693. },
  1694. /**
  1695. * 获取元素element的某个样式值
  1696. * @name getStyle
  1697. * @grammar UM.dom.domUtils.getStyle(element,name) => String
  1698. */
  1699. getStyle: function (element, name) {
  1700. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  1701. return utils.fixColor(name, value);
  1702. },
  1703. /**
  1704. * 为元素element设置样式属性值
  1705. * @name setStyle
  1706. * @grammar UM.dom.domUtils.setStyle(element,name,value)
  1707. */
  1708. setStyle: function (element, name, value) {
  1709. element.style[utils.cssStyleToDomStyle(name)] = value;
  1710. if (!utils.trim(element.style.cssText)) {
  1711. this.removeAttributes(element, 'style')
  1712. }
  1713. },
  1714. /**
  1715. * 删除_moz_dirty属性
  1716. * @function
  1717. */
  1718. removeDirtyAttr: function (node) {
  1719. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  1720. ci.removeAttribute('_moz_dirty');
  1721. }
  1722. node.removeAttribute('_moz_dirty');
  1723. },
  1724. /**
  1725. * 返回子节点的数量
  1726. * @function
  1727. * @param {Node} node 父节点
  1728. * @param {Function} fn 过滤子节点的规则,若为空,则得到所有子节点的数量
  1729. * @return {Number} 符合条件子节点的数量
  1730. */
  1731. getChildCount: function (node, fn) {
  1732. var count = 0, first = node.firstChild;
  1733. fn = fn || function () {
  1734. return 1;
  1735. };
  1736. while (first) {
  1737. if (fn(first)) {
  1738. count++;
  1739. }
  1740. first = first.nextSibling;
  1741. }
  1742. return count;
  1743. },
  1744. /**
  1745. * 判断是否为空节点
  1746. * @function
  1747. * @param {Node} node 节点
  1748. * @return {Boolean} 是否为空节点
  1749. */
  1750. isEmptyNode: function (node) {
  1751. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  1752. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  1753. }) == 0
  1754. },
  1755. /**
  1756. * 判断节点是否为br
  1757. * @function
  1758. * @param {Node} node 节点
  1759. */
  1760. isBr: function (node) {
  1761. return node.nodeType == 1 && node.tagName == 'BR';
  1762. },
  1763. isEmptyBlock: function (node, reg) {
  1764. if (node.nodeType != 1)
  1765. return 0;
  1766. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  1767. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  1768. return 0;
  1769. }
  1770. for (var n in dtd.$isNotEmpty) {
  1771. if (node.getElementsByTagName(n).length) {
  1772. return 0;
  1773. }
  1774. }
  1775. return 1;
  1776. },
  1777. //判断是否是编辑器自定义的参数
  1778. isCustomeNode: function (node) {
  1779. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  1780. },
  1781. fillNode: function (doc, node) {
  1782. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  1783. node.innerHTML = '';
  1784. node.appendChild(tmpNode);
  1785. },
  1786. isBoundaryNode: function (node, dir) {
  1787. var tmp;
  1788. while (!domUtils.isBody(node)) {
  1789. tmp = node;
  1790. node = node.parentNode;
  1791. if (tmp !== node[dir]) {
  1792. return false;
  1793. }
  1794. }
  1795. return true;
  1796. },
  1797. isFillChar: function (node, isInStart) {
  1798. return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length
  1799. },
  1800. isBody: function(node){
  1801. return $(node).hasClass('edui-body-container');
  1802. }
  1803. };
  1804. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  1805. ///import editor.js
  1806. ///import core/utils.js
  1807. ///import core/browser.js
  1808. ///import core/dom/dom.js
  1809. ///import core/dom/dtd.js
  1810. ///import core/dom/domUtils.js
  1811. /**
  1812. * @file
  1813. * @name UM.dom.Range
  1814. * @anthor zhanyi
  1815. * @short Range
  1816. * @import editor.js,core/utils.js,core/browser.js,core/dom/domUtils.js,core/dom/dtd.js
  1817. * @desc Range范围实现类,本类是UEditor底层核心类,统一w3cRange和ieRange之间的差异,包括接口和属性
  1818. */
  1819. (function () {
  1820. var guid = 0,
  1821. fillChar = domUtils.fillChar,
  1822. fillData;
  1823. /**
  1824. * 更新range的collapse状态
  1825. * @param {Range} range range对象
  1826. */
  1827. function updateCollapse(range) {
  1828. range.collapsed =
  1829. range.startContainer && range.endContainer &&
  1830. range.startContainer === range.endContainer &&
  1831. range.startOffset == range.endOffset;
  1832. }
  1833. function selectOneNode(rng){
  1834. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  1835. }
  1836. function setEndPoint(toStart, node, offset, range) {
  1837. //如果node是自闭合标签要处理
  1838. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  1839. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  1840. node = node.parentNode;
  1841. }
  1842. if (toStart) {
  1843. range.startContainer = node;
  1844. range.startOffset = offset;
  1845. if (!range.endContainer) {
  1846. range.collapse(true);
  1847. }
  1848. } else {
  1849. range.endContainer = node;
  1850. range.endOffset = offset;
  1851. if (!range.startContainer) {
  1852. range.collapse(false);
  1853. }
  1854. }
  1855. updateCollapse(range);
  1856. return range;
  1857. }
  1858. /**
  1859. * @name Range
  1860. * @grammar new UM.dom.Range(document) => Range 实例
  1861. * @desc 创建一个跟document绑定的空的Range实例
  1862. * - ***startContainer*** 开始边界的容器节点,可以是elementNode或者是textNode
  1863. * - ***startOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  1864. * - ***endContainer*** 结束边界的容器节点,可以是elementNode或者是textNode
  1865. * - ***endOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  1866. * - ***document*** 跟range关联的document对象
  1867. * - ***collapsed*** 是否是闭合状态
  1868. */
  1869. var Range = dom.Range = function (document,body) {
  1870. var me = this;
  1871. me.startContainer =
  1872. me.startOffset =
  1873. me.endContainer =
  1874. me.endOffset = null;
  1875. me.document = document;
  1876. me.collapsed = true;
  1877. me.body = body;
  1878. };
  1879. /**
  1880. * 删除fillData
  1881. * @param doc
  1882. * @param excludeNode
  1883. */
  1884. function removeFillData(doc, excludeNode) {
  1885. try {
  1886. if (fillData && domUtils.inDoc(fillData, doc)) {
  1887. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  1888. var tmpNode = fillData.parentNode;
  1889. domUtils.remove(fillData);
  1890. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  1891. //safari的contains有bug
  1892. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  1893. ) {
  1894. fillData = tmpNode.parentNode;
  1895. domUtils.remove(tmpNode);
  1896. tmpNode = fillData;
  1897. }
  1898. } else {
  1899. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  1900. }
  1901. }
  1902. } catch (e) {
  1903. }
  1904. }
  1905. /**
  1906. *
  1907. * @param node
  1908. * @param dir
  1909. */
  1910. function mergeSibling(node, dir) {
  1911. var tmpNode;
  1912. node = node[dir];
  1913. while (node && domUtils.isFillChar(node)) {
  1914. tmpNode = node[dir];
  1915. domUtils.remove(node);
  1916. node = tmpNode;
  1917. }
  1918. }
  1919. function execContentsAction(range, action) {
  1920. //调整边界
  1921. //range.includeBookmark();
  1922. var start = range.startContainer,
  1923. end = range.endContainer,
  1924. startOffset = range.startOffset,
  1925. endOffset = range.endOffset,
  1926. doc = range.document,
  1927. frag = doc.createDocumentFragment(),
  1928. tmpStart, tmpEnd;
  1929. if (start.nodeType == 1) {
  1930. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  1931. }
  1932. if (end.nodeType == 1) {
  1933. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  1934. }
  1935. if (start === end && start.nodeType == 3) {
  1936. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  1937. //is not clone
  1938. if (action) {
  1939. start.deleteData(startOffset, endOffset - startOffset);
  1940. range.collapse(true);
  1941. }
  1942. return frag;
  1943. }
  1944. var current, currentLevel, clone = frag,
  1945. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  1946. for (var i = 0; startParents[i] == endParents[i];) {
  1947. i++;
  1948. }
  1949. for (var j = i, si; si = startParents[j]; j++) {
  1950. current = si.nextSibling;
  1951. if (si == start) {
  1952. if (!tmpStart) {
  1953. if (range.startContainer.nodeType == 3) {
  1954. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  1955. //is not clone
  1956. if (action) {
  1957. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  1958. }
  1959. } else {
  1960. clone.appendChild(!action ? start.cloneNode(true) : start);
  1961. }
  1962. }
  1963. } else {
  1964. currentLevel = si.cloneNode(false);
  1965. clone.appendChild(currentLevel);
  1966. }
  1967. while (current) {
  1968. if (current === end || current === endParents[j]) {
  1969. break;
  1970. }
  1971. si = current.nextSibling;
  1972. clone.appendChild(!action ? current.cloneNode(true) : current);
  1973. current = si;
  1974. }
  1975. clone = currentLevel;
  1976. }
  1977. clone = frag;
  1978. if (!startParents[i]) {
  1979. clone.appendChild(startParents[i - 1].cloneNode(false));
  1980. clone = clone.firstChild;
  1981. }
  1982. for (var j = i, ei; ei = endParents[j]; j++) {
  1983. current = ei.previousSibling;
  1984. if (ei == end) {
  1985. if (!tmpEnd && range.endContainer.nodeType == 3) {
  1986. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  1987. //is not clone
  1988. if (action) {
  1989. end.deleteData(0, endOffset);
  1990. }
  1991. }
  1992. } else {
  1993. currentLevel = ei.cloneNode(false);
  1994. clone.appendChild(currentLevel);
  1995. }
  1996. //如果两端同级,右边第一次已经被开始做了
  1997. if (j != i || !startParents[i]) {
  1998. while (current) {
  1999. if (current === start) {
  2000. break;
  2001. }
  2002. ei = current.previousSibling;
  2003. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  2004. current = ei;
  2005. }
  2006. }
  2007. clone = currentLevel;
  2008. }
  2009. if (action) {
  2010. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  2011. }
  2012. tmpStart && domUtils.remove(tmpStart);
  2013. tmpEnd && domUtils.remove(tmpEnd);
  2014. return frag;
  2015. }
  2016. Range.prototype = {
  2017. /**
  2018. * @name deleteContents
  2019. * @grammar range.deleteContents() => Range
  2020. * @desc 删除当前选区范围中的所有内容并返回range实例,这时的range已经变成了闭合状态
  2021. * @example
  2022. * DOM Element :
  2023. * <b>x<i>x[x<i>xx]x</b>
  2024. * //执行方法后
  2025. * <b>x<i>x<i>|x</b>
  2026. * 注意range改变了
  2027. * range.startContainer => b
  2028. * range.startOffset => 2
  2029. * range.endContainer => b
  2030. * range.endOffset => 2
  2031. * range.collapsed => true
  2032. */
  2033. deleteContents:function () {
  2034. var txt;
  2035. if (!this.collapsed) {
  2036. execContentsAction(this, 1);
  2037. }
  2038. if (browser.webkit) {
  2039. txt = this.startContainer;
  2040. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  2041. this.setStartBefore(txt).collapse(true);
  2042. domUtils.remove(txt);
  2043. }
  2044. }
  2045. return this;
  2046. },
  2047. inFillChar : function(){
  2048. var start = this.startContainer;
  2049. if(this.collapsed && start.nodeType == 3
  2050. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  2051. ){
  2052. return true;
  2053. }
  2054. return false;
  2055. },
  2056. /**
  2057. * @name setStart
  2058. * @grammar range.setStart(node,offset) => Range
  2059. * @desc 设置range的开始位置位于node节点内,偏移量为offset
  2060. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2061. */
  2062. setStart:function (node, offset) {
  2063. return setEndPoint(true, node, offset, this);
  2064. },
  2065. /**
  2066. * 设置range的结束位置位于node节点,偏移量为offset
  2067. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2068. * @name setEnd
  2069. * @grammar range.setEnd(node,offset) => Range
  2070. */
  2071. setEnd:function (node, offset) {
  2072. return setEndPoint(false, node, offset, this);
  2073. },
  2074. /**
  2075. * 将Range开始位置设置到node节点之后
  2076. * @name setStartAfter
  2077. * @grammar range.setStartAfter(node) => Range
  2078. * @example
  2079. * <b>xx<i>x|x</i>x</b>
  2080. * 执行setStartAfter(i)后
  2081. * range.startContainer =>b
  2082. * range.startOffset =>2
  2083. */
  2084. setStartAfter:function (node) {
  2085. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2086. },
  2087. /**
  2088. * 将Range开始位置设置到node节点之前
  2089. * @name setStartBefore
  2090. * @grammar range.setStartBefore(node) => Range
  2091. * @example
  2092. * <b>xx<i>x|x</i>x</b>
  2093. * 执行setStartBefore(i)后
  2094. * range.startContainer =>b
  2095. * range.startOffset =>1
  2096. */
  2097. setStartBefore:function (node) {
  2098. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  2099. },
  2100. /**
  2101. * 将Range结束位置设置到node节点之后
  2102. * @name setEndAfter
  2103. * @grammar range.setEndAfter(node) => Range
  2104. * @example
  2105. * <b>xx<i>x|x</i>x</b>
  2106. * setEndAfter(i)后
  2107. * range.endContainer =>b
  2108. * range.endtOffset =>2
  2109. */
  2110. setEndAfter:function (node) {
  2111. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2112. },
  2113. /**
  2114. * 将Range结束位置设置到node节点之前
  2115. * @name setEndBefore
  2116. * @grammar range.setEndBefore(node) => Range
  2117. * @example
  2118. * <b>xx<i>x|x</i>x</b>
  2119. * 执行setEndBefore(i)后
  2120. * range.endContainer =>b
  2121. * range.endtOffset =>1
  2122. */
  2123. setEndBefore:function (node) {
  2124. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  2125. },
  2126. /**
  2127. * 将Range开始位置设置到node节点内的开始位置
  2128. * @name setStartAtFirst
  2129. * @grammar range.setStartAtFirst(node) => Range
  2130. */
  2131. setStartAtFirst:function (node) {
  2132. return this.setStart(node, 0);
  2133. },
  2134. /**
  2135. * 将Range开始位置设置到node节点内的结束位置
  2136. * @name setStartAtLast
  2137. * @grammar range.setStartAtLast(node) => Range
  2138. */
  2139. setStartAtLast:function (node) {
  2140. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2141. },
  2142. /**
  2143. * 将Range结束位置设置到node节点内的开始位置
  2144. * @name setEndAtFirst
  2145. * @grammar range.setEndAtFirst(node) => Range
  2146. */
  2147. setEndAtFirst:function (node) {
  2148. return this.setEnd(node, 0);
  2149. },
  2150. /**
  2151. * 将Range结束位置设置到node节点内的结束位置
  2152. * @name setEndAtLast
  2153. * @grammar range.setEndAtLast(node) => Range
  2154. */
  2155. setEndAtLast:function (node) {
  2156. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2157. },
  2158. /**
  2159. * 选中完整的指定节点,并返回包含该节点的range
  2160. * @name selectNode
  2161. * @grammar range.selectNode(node) => Range
  2162. */
  2163. selectNode:function (node) {
  2164. return this.setStartBefore(node).setEndAfter(node);
  2165. },
  2166. /**
  2167. * 选中node内部的所有节点,并返回对应的range
  2168. * @name selectNodeContents
  2169. * @grammar range.selectNodeContents(node) => Range
  2170. * @example
  2171. * <b>xx[x<i>xxx</i>]xxx</b>
  2172. * 执行后
  2173. * <b>[xxx<i>xxx</i>xxx]</b>
  2174. * range.startContainer =>b
  2175. * range.startOffset =>0
  2176. * range.endContainer =>b
  2177. * range.endOffset =>3
  2178. */
  2179. selectNodeContents:function (node) {
  2180. return this.setStart(node, 0).setEndAtLast(node);
  2181. },
  2182. /**
  2183. * 克隆一个新的range对象
  2184. * @name cloneRange
  2185. * @grammar range.cloneRange() => Range
  2186. */
  2187. cloneRange:function () {
  2188. var me = this;
  2189. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  2190. },
  2191. /**
  2192. * 让选区闭合到尾部,若toStart为真,则闭合到头部
  2193. * @name collapse
  2194. * @grammar range.collapse() => Range
  2195. * @grammar range.collapse(true) => Range //闭合选区到头部
  2196. */
  2197. collapse:function (toStart) {
  2198. var me = this;
  2199. if (toStart) {
  2200. me.endContainer = me.startContainer;
  2201. me.endOffset = me.startOffset;
  2202. } else {
  2203. me.startContainer = me.endContainer;
  2204. me.startOffset = me.endOffset;
  2205. }
  2206. me.collapsed = true;
  2207. return me;
  2208. },
  2209. /**
  2210. * 调整range的边界,使其"收缩"到最小的位置
  2211. * @name shrinkBoundary
  2212. * @grammar range.shrinkBoundary() => Range //range开始位置和结束位置都调整,参见<code><a href="#adjustmentboundary">adjustmentBoundary</a></code>
  2213. * @grammar range.shrinkBoundary(true) => Range //仅调整开始位置,忽略结束位置
  2214. * @example
  2215. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  2216. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx]</b><i>xxx</i>
  2217. * [<b><i>xxxx</i>xxxxxxx</b>] ==> <b><i>[xxxx</i>xxxxxxx]</b>
  2218. */
  2219. shrinkBoundary:function (ignoreEnd) {
  2220. var me = this, child,
  2221. collapsed = me.collapsed;
  2222. function check(node){
  2223. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  2224. }
  2225. while (me.startContainer.nodeType == 1 //是element
  2226. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  2227. && check(child)) {
  2228. me.setStart(child, 0);
  2229. }
  2230. if (collapsed) {
  2231. return me.collapse(true);
  2232. }
  2233. if (!ignoreEnd) {
  2234. while (me.endContainer.nodeType == 1//是element
  2235. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  2236. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  2237. && check(child)) {
  2238. me.setEnd(child, child.childNodes.length);
  2239. }
  2240. }
  2241. return me;
  2242. },
  2243. /**
  2244. * 调整边界容器,如果是textNode,就调整到elementNode上
  2245. * @name trimBoundary
  2246. * @grammar range.trimBoundary([ignoreEnd]) => Range //true忽略结束边界
  2247. * @example
  2248. * DOM Element :
  2249. * <b>|xxx</b>
  2250. * startContainer = xxx; startOffset = 0
  2251. * //执行后本方法后
  2252. * startContainer = <b>; startOffset = 0
  2253. * @example
  2254. * Dom Element :
  2255. * <b>xx|x</b>
  2256. * startContainer = xxx; startOffset = 2
  2257. * //执行本方法后,xxx被实实在在地切分成两个TextNode
  2258. * startContainer = <b>; startOffset = 1
  2259. */
  2260. trimBoundary:function (ignoreEnd) {
  2261. this.txtToElmBoundary();
  2262. var start = this.startContainer,
  2263. offset = this.startOffset,
  2264. collapsed = this.collapsed,
  2265. end = this.endContainer;
  2266. if (start.nodeType == 3) {
  2267. if (offset == 0) {
  2268. this.setStartBefore(start);
  2269. } else {
  2270. if (offset >= start.nodeValue.length) {
  2271. this.setStartAfter(start);
  2272. } else {
  2273. var textNode = domUtils.split(start, offset);
  2274. //跟新结束边界
  2275. if (start === end) {
  2276. this.setEnd(textNode, this.endOffset - offset);
  2277. } else if (start.parentNode === end) {
  2278. this.endOffset += 1;
  2279. }
  2280. this.setStartBefore(textNode);
  2281. }
  2282. }
  2283. if (collapsed) {
  2284. return this.collapse(true);
  2285. }
  2286. }
  2287. if (!ignoreEnd) {
  2288. offset = this.endOffset;
  2289. end = this.endContainer;
  2290. if (end.nodeType == 3) {
  2291. if (offset == 0) {
  2292. this.setEndBefore(end);
  2293. } else {
  2294. offset < end.nodeValue.length && domUtils.split(end, offset);
  2295. this.setEndAfter(end);
  2296. }
  2297. }
  2298. }
  2299. return this;
  2300. },
  2301. /**
  2302. * 如果选区在文本的边界上,就扩展选区到文本的父节点上
  2303. * @name txtToElmBoundary
  2304. * @example
  2305. * Dom Element :
  2306. * <b> |xxx</b>
  2307. * startContainer = xxx; startOffset = 0
  2308. * //本方法执行后
  2309. * startContainer = <b>; startOffset = 0
  2310. * @example
  2311. * Dom Element :
  2312. * <b> xxx| </b>
  2313. * startContainer = xxx; startOffset = 3
  2314. * //本方法执行后
  2315. * startContainer = <b>; startOffset = 1
  2316. */
  2317. txtToElmBoundary:function (ignoreCollapsed) {
  2318. function adjust(r, c) {
  2319. var container = r[c + 'Container'],
  2320. offset = r[c + 'Offset'];
  2321. if (container.nodeType == 3) {
  2322. if (!offset) {
  2323. r['set' + c.replace(/(\w)/, function (a) {
  2324. return a.toUpperCase();
  2325. }) + 'Before'](container);
  2326. } else if (offset >= container.nodeValue.length) {
  2327. r['set' + c.replace(/(\w)/, function (a) {
  2328. return a.toUpperCase();
  2329. }) + 'After' ](container);
  2330. }
  2331. }
  2332. }
  2333. if (ignoreCollapsed || !this.collapsed) {
  2334. adjust(this, 'start');
  2335. adjust(this, 'end');
  2336. }
  2337. return this;
  2338. },
  2339. /**
  2340. * 在当前选区的开始位置前插入一个节点或者fragment,range的开始位置会在插入节点的前边
  2341. * @name insertNode
  2342. * @grammar range.insertNode(node) => Range //node可以是textNode,elementNode,fragment
  2343. * @example
  2344. * Range :
  2345. * xxx[x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2346. * 待插入Node :
  2347. * <p>ssss</p>
  2348. * 执行本方法后的Range :
  2349. * xxx[<p>ssss</p>x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2350. */
  2351. insertNode:function (node) {
  2352. var first = node, length = 1;
  2353. if (node.nodeType == 11) {
  2354. first = node.firstChild;
  2355. length = node.childNodes.length;
  2356. }
  2357. this.trimBoundary(true);
  2358. var start = this.startContainer,
  2359. offset = this.startOffset;
  2360. var nextNode = start.childNodes[ offset ];
  2361. if (nextNode) {
  2362. start.insertBefore(node, nextNode);
  2363. } else {
  2364. start.appendChild(node);
  2365. }
  2366. if (first.parentNode === this.endContainer) {
  2367. this.endOffset = this.endOffset + length;
  2368. }
  2369. return this.setStartBefore(first);
  2370. },
  2371. /**
  2372. * 设置光标闭合位置,toEnd设置为true时光标将闭合到选区的结尾
  2373. * @name setCursor
  2374. * @grammar range.setCursor([toEnd]) => Range //toEnd为true时,光标闭合到选区的末尾
  2375. */
  2376. setCursor:function (toEnd, noFillData) {
  2377. return this.collapse(!toEnd).select(noFillData);
  2378. },
  2379. /**
  2380. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  2381. * @name createBookmark
  2382. * @grammar range.createBookmark([serialize]) => Object //{start:开始标记,end:结束标记,id:serialize} serialize为真时,开始结束标记是插入节点的id,否则是插入节点的引用
  2383. */
  2384. createBookmark:function (serialize, same) {
  2385. var endNode,
  2386. startNode = this.document.createElement('span');
  2387. startNode.style.cssText = 'display:none;line-height:0px;';
  2388. startNode.appendChild(this.document.createTextNode('\u200D'));
  2389. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  2390. if (!this.collapsed) {
  2391. endNode = startNode.cloneNode(true);
  2392. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  2393. }
  2394. this.insertNode(startNode);
  2395. if (endNode) {
  2396. this.collapse().insertNode(endNode).setEndBefore(endNode);
  2397. }
  2398. this.setStartAfter(startNode);
  2399. return {
  2400. start:serialize ? startNode.id : startNode,
  2401. end:endNode ? serialize ? endNode.id : endNode : null,
  2402. id:serialize
  2403. }
  2404. },
  2405. /**
  2406. * 移动边界到书签位置,并删除插入的书签节点
  2407. * @name moveToBookmark
  2408. * @grammar range.moveToBookmark(bookmark) => Range //让当前的range选到给定bookmark的位置,bookmark对象是由range.createBookmark创建的
  2409. */
  2410. moveToBookmark:function (bookmark) {
  2411. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  2412. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  2413. this.setStartBefore(start);
  2414. domUtils.remove(start);
  2415. if (end) {
  2416. this.setEndBefore(end);
  2417. domUtils.remove(end);
  2418. } else {
  2419. this.collapse(true);
  2420. }
  2421. return this;
  2422. },
  2423. /**
  2424. * 调整Range的边界,使其"缩小"到最合适的位置
  2425. * @name adjustmentBoundary
  2426. * @grammar range.adjustmentBoundary() => Range //参见<code><a href="#shrinkboundary">shrinkBoundary</a></code>
  2427. * @example
  2428. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  2429. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx</b>]<i>xxx</i>
  2430. */
  2431. adjustmentBoundary:function () {
  2432. if (!this.collapsed) {
  2433. while (!domUtils.isBody(this.startContainer) &&
  2434. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  2435. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  2436. ) {
  2437. this.setStartAfter(this.startContainer);
  2438. }
  2439. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  2440. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  2441. ) {
  2442. this.setEndBefore(this.endContainer);
  2443. }
  2444. }
  2445. return this;
  2446. },
  2447. /**
  2448. * 得到一个自闭合的节点,常用于获取自闭和的节点,例如图片节点
  2449. * @name getClosedNode
  2450. * @grammar range.getClosedNode() => node|null
  2451. * @example
  2452. * <b>xxxx[<img />]xxx</b>
  2453. */
  2454. getClosedNode:function () {
  2455. var node;
  2456. if (!this.collapsed) {
  2457. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  2458. if (selectOneNode(range)) {
  2459. var child = range.startContainer.childNodes[range.startOffset];
  2460. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  2461. node = child;
  2462. }
  2463. }
  2464. }
  2465. return node;
  2466. },
  2467. /**
  2468. * 根据当前range选中内容节点(在页面上表现为反白显示)
  2469. * @name select
  2470. * @grammar range.select(); => Range
  2471. */
  2472. select:browser.ie ? function (noFillData, textRange) {
  2473. var nativeRange;
  2474. if (!this.collapsed)
  2475. this.shrinkBoundary();
  2476. var node = this.getClosedNode();
  2477. if (node && !textRange) {
  2478. try {
  2479. nativeRange = this.document.body.createControlRange();
  2480. nativeRange.addElement(node);
  2481. nativeRange.select();
  2482. } catch (e) {}
  2483. return this;
  2484. }
  2485. var bookmark = this.createBookmark(),
  2486. start = bookmark.start,
  2487. end;
  2488. nativeRange = this.document.body.createTextRange();
  2489. nativeRange.moveToElementText(start);
  2490. nativeRange.moveStart('character', 1);
  2491. if (!this.collapsed) {
  2492. var nativeRangeEnd = this.document.body.createTextRange();
  2493. end = bookmark.end;
  2494. nativeRangeEnd.moveToElementText(end);
  2495. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  2496. } else {
  2497. if (!noFillData && this.startContainer.nodeType != 3) {
  2498. //使用<span>|x<span>固定住光标
  2499. var tmpText = this.document.createTextNode(fillChar),
  2500. tmp = this.document.createElement('span');
  2501. tmp.appendChild(this.document.createTextNode(fillChar));
  2502. start.parentNode.insertBefore(tmp, start);
  2503. start.parentNode.insertBefore(tmpText, start);
  2504. //当点b,i,u时,不能清除i上边的b
  2505. removeFillData(this.document, tmpText);
  2506. fillData = tmpText;
  2507. mergeSibling(tmp, 'previousSibling');
  2508. mergeSibling(start, 'nextSibling');
  2509. nativeRange.moveStart('character', -1);
  2510. nativeRange.collapse(true);
  2511. }
  2512. }
  2513. this.moveToBookmark(bookmark);
  2514. tmp && domUtils.remove(tmp);
  2515. //IE在隐藏状态下不支持range操作,catch一下
  2516. try {
  2517. nativeRange.select();
  2518. } catch (e) {
  2519. }
  2520. return this;
  2521. } : function (notInsertFillData) {
  2522. function checkOffset(rng){
  2523. function check(node,offset,dir){
  2524. if(node.nodeType == 3 && node.nodeValue.length < offset){
  2525. rng[dir + 'Offset'] = node.nodeValue.length
  2526. }
  2527. }
  2528. check(rng.startContainer,rng.startOffset,'start');
  2529. check(rng.endContainer,rng.endOffset,'end');
  2530. }
  2531. var win = domUtils.getWindow(this.document),
  2532. sel = win.getSelection(),
  2533. txtNode;
  2534. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  2535. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  2536. browser.gecko ? this.body.focus() : win.focus();
  2537. if (sel) {
  2538. sel.removeAllRanges();
  2539. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  2540. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  2541. if (this.collapsed && !notInsertFillData) {
  2542. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  2543. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  2544. // var tmp = this.document.createTextNode('');
  2545. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  2546. // }
  2547. //
  2548. //处理光标落在文本节点的情况
  2549. //处理以下的情况
  2550. //<b>|xxxx</b>
  2551. //<b>xxxx</b>|xxxx
  2552. //xxxx<b>|</b>
  2553. var start = this.startContainer,child = start;
  2554. if(start.nodeType == 1){
  2555. child = start.childNodes[this.startOffset];
  2556. }
  2557. if( !(start.nodeType == 3 && this.startOffset) &&
  2558. (child ?
  2559. (!child.previousSibling || child.previousSibling.nodeType != 3)
  2560. :
  2561. (!start.lastChild || start.lastChild.nodeType != 3)
  2562. )
  2563. ){
  2564. txtNode = this.document.createTextNode(fillChar);
  2565. //跟着前边走
  2566. this.insertNode(txtNode);
  2567. removeFillData(this.document, txtNode);
  2568. mergeSibling(txtNode, 'previousSibling');
  2569. mergeSibling(txtNode, 'nextSibling');
  2570. fillData = txtNode;
  2571. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  2572. }
  2573. }
  2574. var nativeRange = this.document.createRange();
  2575. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  2576. var child = this.startContainer.childNodes[this.startOffset];
  2577. if(!child){
  2578. //往前靠拢
  2579. child = this.startContainer.lastChild;
  2580. if( child && domUtils.isBr(child)){
  2581. this.setStartBefore(child).collapse(true);
  2582. }
  2583. }else{
  2584. //向后靠拢
  2585. while(child && domUtils.isBlockElm(child)){
  2586. if(child.nodeType == 1 && child.childNodes[0]){
  2587. child = child.childNodes[0]
  2588. }else{
  2589. break;
  2590. }
  2591. }
  2592. child && this.setStartBefore(child).collapse(true)
  2593. }
  2594. }
  2595. //是createAddress最后一位算的不准,现在这里进行微调
  2596. checkOffset(this);
  2597. nativeRange.setStart(this.startContainer, this.startOffset);
  2598. nativeRange.setEnd(this.endContainer, this.endOffset);
  2599. sel.addRange(nativeRange);
  2600. }
  2601. return this;
  2602. },
  2603. createAddress : function(ignoreEnd,ignoreTxt){
  2604. var addr = {},me = this;
  2605. function getAddress(isStart){
  2606. var node = isStart ? me.startContainer : me.endContainer;
  2607. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  2608. addrs = [];
  2609. for(var i = 0,ci;ci = parents[i++];){
  2610. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  2611. }
  2612. var firstIndex = 0;
  2613. if(ignoreTxt){
  2614. if(node.nodeType == 3){
  2615. var tmpNode = node.previousSibling;
  2616. while(tmpNode && tmpNode.nodeType == 3){
  2617. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  2618. tmpNode = tmpNode.previousSibling;
  2619. }
  2620. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  2621. }else{
  2622. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  2623. if(node){
  2624. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  2625. }else{
  2626. node = isStart ? me.startContainer : me.endContainer;
  2627. var first = node.firstChild;
  2628. while(first){
  2629. if(domUtils.isFillChar(first)){
  2630. first = first.nextSibling;
  2631. continue;
  2632. }
  2633. firstIndex++;
  2634. if(first.nodeType == 3){
  2635. while( first && first.nodeType == 3){
  2636. first = first.nextSibling;
  2637. }
  2638. }else{
  2639. first = first.nextSibling;
  2640. }
  2641. }
  2642. }
  2643. }
  2644. }else{
  2645. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  2646. }
  2647. if(firstIndex < 0){
  2648. firstIndex = 0;
  2649. }
  2650. addrs.push(firstIndex);
  2651. return addrs;
  2652. }
  2653. addr.startAddress = getAddress(true);
  2654. if(!ignoreEnd){
  2655. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  2656. }
  2657. return addr;
  2658. },
  2659. moveToAddress : function(addr,ignoreEnd){
  2660. var me = this;
  2661. function getNode(address,isStart){
  2662. var tmpNode = me.body,
  2663. parentNode,offset;
  2664. for(var i= 0,ci,l=address.length;i<l;i++){
  2665. ci = address[i];
  2666. parentNode = tmpNode;
  2667. tmpNode = tmpNode.childNodes[ci];
  2668. if(!tmpNode){
  2669. offset = ci;
  2670. break;
  2671. }
  2672. }
  2673. if(isStart){
  2674. if(tmpNode){
  2675. me.setStartBefore(tmpNode)
  2676. }else{
  2677. me.setStart(parentNode,offset)
  2678. }
  2679. }else{
  2680. if(tmpNode){
  2681. me.setEndBefore(tmpNode)
  2682. }else{
  2683. me.setEnd(parentNode,offset)
  2684. }
  2685. }
  2686. }
  2687. getNode(addr.startAddress,true);
  2688. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  2689. return me;
  2690. },
  2691. equals : function(rng){
  2692. for(var p in this){
  2693. if(this.hasOwnProperty(p)){
  2694. if(this[p] !== rng[p])
  2695. return false
  2696. }
  2697. }
  2698. return true;
  2699. },
  2700. scrollIntoView : function(){
  2701. var $span = $('<span style="padding:0;margin:0;display:block;border:0">&nbsp;</span>');
  2702. this.cloneRange().insertNode($span.get(0));
  2703. var winScrollTop = $(window).scrollTop(),
  2704. winHeight = $(window).height(),
  2705. spanTop = $span.offset().top;
  2706. if(spanTop < winScrollTop-winHeight || spanTop > winScrollTop + winHeight ){
  2707. if(spanTop > winScrollTop + winHeight){
  2708. window.scrollTo(0,spanTop - winHeight + $span.height())
  2709. }else{
  2710. window.scrollTo(0,winScrollTop - spanTop)
  2711. }
  2712. }
  2713. $span.remove();
  2714. },
  2715. getOffset : function(){
  2716. var bk = this.createBookmark();
  2717. var offset = $(bk.start).css('display','inline-block').offset();
  2718. this.moveToBookmark(bk);
  2719. return offset
  2720. }
  2721. };
  2722. })();
  2723. ///import editor.js
  2724. ///import core/browser.js
  2725. ///import core/dom/dom.js
  2726. ///import core/dom/dtd.js
  2727. ///import core/dom/domUtils.js
  2728. ///import core/dom/Range.js
  2729. /**
  2730. * @class UM.dom.Selection Selection类
  2731. */
  2732. (function () {
  2733. function getBoundaryInformation( range, start ) {
  2734. var getIndex = domUtils.getNodeIndex;
  2735. range = range.duplicate();
  2736. range.collapse( start );
  2737. var parent = range.parentElement();
  2738. //如果节点里没有子节点,直接退出
  2739. if ( !parent.hasChildNodes() ) {
  2740. return {container:parent, offset:0};
  2741. }
  2742. var siblings = parent.children,
  2743. child,
  2744. testRange = range.duplicate(),
  2745. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  2746. distance;
  2747. while ( startIndex <= endIndex ) {
  2748. index = Math.floor( (startIndex + endIndex) / 2 );
  2749. child = siblings[index];
  2750. testRange.moveToElementText( child );
  2751. var position = testRange.compareEndPoints( 'StartToStart', range );
  2752. if ( position > 0 ) {
  2753. endIndex = index - 1;
  2754. } else if ( position < 0 ) {
  2755. startIndex = index + 1;
  2756. } else {
  2757. //trace:1043
  2758. return {container:parent, offset:getIndex( child )};
  2759. }
  2760. }
  2761. if ( index == -1 ) {
  2762. testRange.moveToElementText( parent );
  2763. testRange.setEndPoint( 'StartToStart', range );
  2764. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  2765. siblings = parent.childNodes;
  2766. if ( !distance ) {
  2767. child = siblings[siblings.length - 1];
  2768. return {container:child, offset:child.nodeValue.length};
  2769. }
  2770. var i = siblings.length;
  2771. while ( distance > 0 ){
  2772. distance -= siblings[ --i ].nodeValue.length;
  2773. }
  2774. return {container:siblings[i], offset:-distance};
  2775. }
  2776. testRange.collapse( position > 0 );
  2777. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  2778. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  2779. if ( !distance ) {
  2780. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  2781. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  2782. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  2783. }
  2784. while ( distance > 0 ) {
  2785. try {
  2786. var pre = child;
  2787. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  2788. distance -= child.nodeValue.length;
  2789. } catch ( e ) {
  2790. return {container:parent, offset:getIndex( pre )};
  2791. }
  2792. }
  2793. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  2794. }
  2795. /**
  2796. * 将ieRange转换为Range对象
  2797. * @param {Range} ieRange ieRange对象
  2798. * @param {Range} range Range对象
  2799. * @return {Range} range 返回转换后的Range对象
  2800. */
  2801. function transformIERangeToRange( ieRange, range ) {
  2802. if ( ieRange.item ) {
  2803. range.selectNode( ieRange.item( 0 ) );
  2804. } else {
  2805. var bi = getBoundaryInformation( ieRange, true );
  2806. range.setStart( bi.container, bi.offset );
  2807. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  2808. bi = getBoundaryInformation( ieRange, false );
  2809. range.setEnd( bi.container, bi.offset );
  2810. }
  2811. }
  2812. return range;
  2813. }
  2814. /**
  2815. * 获得ieRange
  2816. * @param {Selection} sel Selection对象
  2817. * @return {ieRange} 得到ieRange
  2818. */
  2819. function _getIERange( sel,txtRange ) {
  2820. var ieRange;
  2821. //ie下有可能报错
  2822. try {
  2823. ieRange = sel.getNative(txtRange).createRange();
  2824. } catch ( e ) {
  2825. return null;
  2826. }
  2827. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  2828. if ( ( el.ownerDocument || el ) === sel.document ) {
  2829. return ieRange;
  2830. }
  2831. return null;
  2832. }
  2833. var Selection = dom.Selection = function ( doc,body ) {
  2834. var me = this;
  2835. me.document = doc;
  2836. me.body = body;
  2837. if ( browser.ie9below ) {
  2838. $( body).on('beforedeactivate', function () {
  2839. me._bakIERange = me.getIERange();
  2840. } ).on('activate', function () {
  2841. try {
  2842. var ieNativRng = _getIERange( me );
  2843. if ( (!ieNativRng || !me.rangeInBody(ieNativRng)) && me._bakIERange ) {
  2844. me._bakIERange.select();
  2845. }
  2846. } catch ( ex ) {
  2847. }
  2848. me._bakIERange = null;
  2849. } );
  2850. }
  2851. };
  2852. Selection.prototype = {
  2853. hasNativeRange : function(){
  2854. var rng;
  2855. if(!browser.ie || browser.ie9above){
  2856. var nativeSel = this.getNative();
  2857. if(!nativeSel.rangeCount){
  2858. return false;
  2859. }
  2860. rng = nativeSel.getRangeAt(0);
  2861. }else{
  2862. rng = _getIERange(this);
  2863. }
  2864. return this.rangeInBody(rng);
  2865. },
  2866. /**
  2867. * 获取原生seleciton对象
  2868. * @public
  2869. * @function
  2870. * @name UM.dom.Selection.getNative
  2871. * @return {Selection} 获得selection对象
  2872. */
  2873. getNative:function (txtRange) {
  2874. var doc = this.document;
  2875. try {
  2876. return !doc ? null : browser.ie9below || txtRange? doc.selection : domUtils.getWindow( doc ).getSelection();
  2877. } catch ( e ) {
  2878. return null;
  2879. }
  2880. },
  2881. /**
  2882. * 获得ieRange
  2883. * @public
  2884. * @function
  2885. * @name UM.dom.Selection.getIERange
  2886. * @return {ieRange} 返回ie原生的Range
  2887. */
  2888. getIERange:function (txtRange) {
  2889. var ieRange = _getIERange( this,txtRange );
  2890. if ( !ieRange || !this.rangeInBody(ieRange,txtRange)) {
  2891. if ( this._bakIERange ) {
  2892. return this._bakIERange;
  2893. }
  2894. }
  2895. return ieRange;
  2896. },
  2897. rangeInBody : function(rng,txtRange){
  2898. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  2899. return node === this.body || domUtils.inDoc(node,this.body);
  2900. },
  2901. /**
  2902. * 缓存当前选区的range和选区的开始节点
  2903. * @public
  2904. * @function
  2905. * @name UM.dom.Selection.cache
  2906. */
  2907. cache:function () {
  2908. this.clear();
  2909. this._cachedRange = this.getRange();
  2910. this._cachedStartElement = this.getStart();
  2911. this._cachedStartElementPath = this.getStartElementPath();
  2912. },
  2913. getStartElementPath:function () {
  2914. if ( this._cachedStartElementPath ) {
  2915. return this._cachedStartElementPath;
  2916. }
  2917. var start = this.getStart();
  2918. if ( start ) {
  2919. return domUtils.findParents( start, true, null, true )
  2920. }
  2921. return [];
  2922. },
  2923. /**
  2924. * 清空缓存
  2925. * @public
  2926. * @function
  2927. * @name UM.dom.Selection.clear
  2928. */
  2929. clear:function () {
  2930. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  2931. },
  2932. /**
  2933. * 编辑器是否得到了选区
  2934. */
  2935. isFocus:function () {
  2936. return this.hasNativeRange()
  2937. },
  2938. /**
  2939. * 获取选区对应的Range
  2940. * @public
  2941. * @function
  2942. * @name UM.dom.Selection.getRange
  2943. * @returns {UM.dom.Range} 得到Range对象
  2944. */
  2945. getRange:function () {
  2946. var me = this;
  2947. function optimze( range ) {
  2948. var child = me.body.firstChild,
  2949. collapsed = range.collapsed;
  2950. while ( child && child.firstChild ) {
  2951. range.setStart( child, 0 );
  2952. child = child.firstChild;
  2953. }
  2954. if ( !range.startContainer ) {
  2955. range.setStart( me.body, 0 )
  2956. }
  2957. if ( collapsed ) {
  2958. range.collapse( true );
  2959. }
  2960. }
  2961. if ( me._cachedRange != null ) {
  2962. return this._cachedRange;
  2963. }
  2964. var range = new dom.Range( me.document,me.body );
  2965. if ( browser.ie9below ) {
  2966. var nativeRange = me.getIERange();
  2967. if ( nativeRange && this.rangeInBody(nativeRange)) {
  2968. try{
  2969. transformIERangeToRange( nativeRange, range );
  2970. }catch(e){
  2971. optimze( range );
  2972. }
  2973. } else {
  2974. optimze( range );
  2975. }
  2976. } else {
  2977. var sel = me.getNative();
  2978. if ( sel && sel.rangeCount && me.rangeInBody(sel.getRangeAt( 0 ))) {
  2979. var firstRange = sel.getRangeAt( 0 );
  2980. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  2981. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  2982. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  2983. optimze( range );
  2984. }
  2985. } else {
  2986. //trace:1734 有可能已经不在dom树上了,标识的节点
  2987. if ( this._bakRange && (this._bakRange.startContainer === this.body || domUtils.inDoc( this._bakRange.startContainer, this.body )) ){
  2988. return this._bakRange;
  2989. }
  2990. optimze( range );
  2991. }
  2992. }
  2993. return this._bakRange = range;
  2994. },
  2995. /**
  2996. * 获取开始元素,用于状态反射
  2997. * @public
  2998. * @function
  2999. * @name UM.dom.Selection.getStart
  3000. * @return {Element} 获得开始元素
  3001. */
  3002. getStart:function () {
  3003. if ( this._cachedStartElement ) {
  3004. return this._cachedStartElement;
  3005. }
  3006. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  3007. tmpRange,
  3008. start, tmp, parent;
  3009. if ( browser.ie9below ) {
  3010. if ( !range ) {
  3011. //todo 给第一个值可能会有问题
  3012. return this.document.body.firstChild;
  3013. }
  3014. //control元素
  3015. if ( range.item ){
  3016. return range.item( 0 );
  3017. }
  3018. tmpRange = range.duplicate();
  3019. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  3020. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  3021. tmpRange.collapse( 1 );
  3022. start = tmpRange.parentElement();
  3023. parent = tmp = range.parentElement();
  3024. while ( tmp = tmp.parentNode ) {
  3025. if ( tmp == start ) {
  3026. start = parent;
  3027. break;
  3028. }
  3029. }
  3030. } else {
  3031. start = range.startContainer;
  3032. if ( start.nodeType == 1 && start.hasChildNodes() ){
  3033. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  3034. }
  3035. if ( start.nodeType == 3 ){
  3036. return start.parentNode;
  3037. }
  3038. }
  3039. return start;
  3040. },
  3041. /**
  3042. * 得到选区中的文本
  3043. * @public
  3044. * @function
  3045. * @name UM.dom.Selection.getText
  3046. * @return {String} 选区中包含的文本
  3047. */
  3048. getText:function () {
  3049. var nativeSel, nativeRange;
  3050. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  3051. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  3052. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  3053. }
  3054. return '';
  3055. }
  3056. };
  3057. })();
  3058. /**
  3059. * @file
  3060. * @name UM.Editor
  3061. * @short Editor
  3062. * @import editor.js,core/utils.js,core/EventBase.js,core/browser.js,core/dom/dtd.js,core/dom/domUtils.js,core/dom/Range.js,core/dom/Selection.js,plugins/serialize.js
  3063. * @desc 编辑器主类,包含编辑器提供的大部分公用接口
  3064. */
  3065. (function () {
  3066. var uid = 0, _selectionChangeTimer;
  3067. /**
  3068. * @private
  3069. * @ignore
  3070. * @param form 编辑器所在的form元素
  3071. * @param editor 编辑器实例对象
  3072. */
  3073. function setValue(form, editor) {
  3074. var textarea;
  3075. if (editor.textarea) {
  3076. if (utils.isString(editor.textarea)) {
  3077. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  3078. if (ti.id == 'umeditor_textarea_' + editor.options.textarea) {
  3079. textarea = ti;
  3080. break;
  3081. }
  3082. }
  3083. } else {
  3084. textarea = editor.textarea;
  3085. }
  3086. }
  3087. if (!textarea) {
  3088. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  3089. 'name': editor.options.textarea,
  3090. 'id': 'umeditor_textarea_' + editor.options.textarea,
  3091. 'style': "display:none"
  3092. }));
  3093. //不要产生多个textarea
  3094. editor.textarea = textarea;
  3095. }
  3096. textarea.value = editor.hasContents() ?
  3097. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  3098. ''
  3099. }
  3100. function loadPlugins(me){
  3101. //初始化插件
  3102. for (var pi in UM.plugins) {
  3103. if(me.options.excludePlugins.indexOf(pi) == -1){
  3104. UM.plugins[pi].call(me);
  3105. me.plugins[pi] = 1;
  3106. }
  3107. }
  3108. me.langIsReady = true;
  3109. me.fireEvent("langReady");
  3110. }
  3111. function checkCurLang(I18N){
  3112. for(var lang in I18N){
  3113. return lang
  3114. }
  3115. }
  3116. /**
  3117. * UEditor编辑器类
  3118. * @name Editor
  3119. * @desc 创建一个跟编辑器实例
  3120. * - ***container*** 编辑器容器对象
  3121. * - ***iframe*** 编辑区域所在的iframe对象
  3122. * - ***window*** 编辑区域所在的window
  3123. * - ***document*** 编辑区域所在的document对象
  3124. * - ***body*** 编辑区域所在的body对象
  3125. * - ***selection*** 编辑区域的选区对象
  3126. */
  3127. var Editor = UM.Editor = function (options) {
  3128. var me = this;
  3129. me.uid = uid++;
  3130. EventBase.call(me);
  3131. me.commands = {};
  3132. me.options = utils.extend(utils.clone(options || {}), UMEDITOR_CONFIG, true);
  3133. me.shortcutkeys = {};
  3134. me.inputRules = [];
  3135. me.outputRules = [];
  3136. //设置默认的常用属性
  3137. me.setOpt({
  3138. isShow: true,
  3139. initialContent: '',
  3140. initialStyle:'',
  3141. autoClearinitialContent: false,
  3142. textarea: 'editorValue',
  3143. focus: false,
  3144. focusInEnd: true,
  3145. autoClearEmptyNode: true,
  3146. fullscreen: false,
  3147. readonly: false,
  3148. zIndex: 999,
  3149. enterTag: 'p',
  3150. lang: 'zh-cn',
  3151. langPath: me.options.UMEDITOR_HOME_URL + 'lang/',
  3152. theme: 'default',
  3153. themePath: me.options.UMEDITOR_HOME_URL + 'themes/',
  3154. allHtmlEnabled: false,
  3155. autoSyncData : true,
  3156. autoHeightEnabled : true,
  3157. excludePlugins:''
  3158. });
  3159. me.plugins = {};
  3160. if(!utils.isEmptyObject(UM.I18N)){
  3161. //修改默认的语言类型
  3162. me.options.lang = checkCurLang(UM.I18N);
  3163. loadPlugins(me)
  3164. }else{
  3165. utils.loadFile(document, {
  3166. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  3167. tag: "script",
  3168. type: "text/javascript",
  3169. defer: "defer"
  3170. }, function () {
  3171. loadPlugins(me)
  3172. });
  3173. }
  3174. };
  3175. Editor.prototype = {
  3176. /**
  3177. * 当编辑器ready后执行传入的fn,如果编辑器已经完成ready,就马上执行fn,fn的中的this是编辑器实例。
  3178. * 大部分的实例接口都需要放在该方法内部执行,否则在IE下可能会报错。
  3179. * @name ready
  3180. * @grammar editor.ready(fn) fn是当编辑器渲染好后执行的function
  3181. * @example
  3182. * var editor = new UM.ui.Editor();
  3183. * editor.render("myEditor");
  3184. * editor.ready(function(){
  3185. * editor.setContent("欢迎使用UEditor!");
  3186. * })
  3187. */
  3188. ready: function (fn) {
  3189. var me = this;
  3190. if (fn) {
  3191. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  3192. }
  3193. },
  3194. /**
  3195. * 为编辑器设置默认参数值。若用户配置为空,则以默认配置为准
  3196. * @grammar editor.setOpt(key,value); //传入一个键、值对
  3197. * @grammar editor.setOpt({ key:value}); //传入一个json对象
  3198. */
  3199. setOpt: function (key, val) {
  3200. var obj = {};
  3201. if (utils.isString(key)) {
  3202. obj[key] = val
  3203. } else {
  3204. obj = key;
  3205. }
  3206. utils.extend(this.options, obj, true);
  3207. },
  3208. getOpt:function(key){
  3209. return this.options[key] || ''
  3210. },
  3211. /**
  3212. * 销毁编辑器实例对象
  3213. * @name destroy
  3214. * @grammar editor.destroy();
  3215. */
  3216. destroy: function () {
  3217. var me = this;
  3218. me.fireEvent('destroy');
  3219. var container = me.container.parentNode;
  3220. if(container === document.body){
  3221. container = me.container;
  3222. }
  3223. var textarea = me.textarea;
  3224. if (!textarea) {
  3225. textarea = document.createElement('textarea');
  3226. container.parentNode.insertBefore(textarea, container);
  3227. } else {
  3228. textarea.style.display = ''
  3229. }
  3230. textarea.style.width = me.body.offsetWidth + 'px';
  3231. textarea.style.height = me.body.offsetHeight + 'px';
  3232. textarea.value = me.getContent();
  3233. textarea.id = me.key;
  3234. if(container.contains(textarea)){
  3235. $(textarea).insertBefore(container);
  3236. }
  3237. container.innerHTML = '';
  3238. domUtils.remove(container);
  3239. UM.clearCache(me.id);
  3240. //trace:2004
  3241. for (var p in me) {
  3242. if (me.hasOwnProperty(p)) {
  3243. delete this[p];
  3244. }
  3245. }
  3246. },
  3247. initialCont : function(holder){
  3248. if(holder){
  3249. holder.getAttribute('name') && ( this.options.textarea = holder.getAttribute('name'));
  3250. if (holder && /script|textarea/ig.test(holder.tagName)) {
  3251. var newDiv = document.createElement('div');
  3252. holder.parentNode.insertBefore(newDiv, holder);
  3253. this.options.initialContent = UM.htmlparser(holder.value || holder.innerHTML|| this.options.initialContent).toHtml();
  3254. holder.className && (newDiv.className = holder.className);
  3255. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  3256. if (/textarea/i.test(holder.tagName)) {
  3257. this.textarea = holder;
  3258. this.textarea.style.display = 'none';
  3259. } else {
  3260. holder.parentNode.removeChild(holder);
  3261. holder.id && (newDiv.id = holder.id);
  3262. }
  3263. holder = newDiv;
  3264. holder.innerHTML = '';
  3265. }
  3266. return holder;
  3267. }else{
  3268. return null;
  3269. }
  3270. },
  3271. /**
  3272. * 渲染编辑器的DOM到指定容器,必须且只能调用一次
  3273. * @name render
  3274. * @grammar editor.render(containerId); //可以指定一个容器ID
  3275. * @grammar editor.render(containerDom); //也可以直接指定容器对象
  3276. */
  3277. render: function (container) {
  3278. var me = this,
  3279. options = me.options,
  3280. getStyleValue=function(attr){
  3281. return parseInt($(container).css(attr));
  3282. };
  3283. if (utils.isString(container)) {
  3284. container = document.getElementById(container);
  3285. }
  3286. if (container) {
  3287. this.id = container.getAttribute('id');
  3288. UM.setEditor(this);
  3289. utils.cssRule('edui-style-body',me.options.initialStyle,document);
  3290. container = this.initialCont(container);
  3291. container.className += ' edui-body-container';
  3292. if(options.initialFrameWidth){
  3293. options.minFrameWidth = options.initialFrameWidth
  3294. }else{
  3295. //都没给值,先写死了
  3296. options.minFrameWidth = options.initialFrameWidth = $(container).width() || UM.defaultWidth;
  3297. }
  3298. if(options.initialFrameHeight){
  3299. options.minFrameHeight = options.initialFrameHeight
  3300. }else{
  3301. options.initialFrameHeight = options.minFrameHeight = $(container).height() || UM.defaultHeight;
  3302. }
  3303. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth -
  3304. getStyleValue("padding-left")-
  3305. getStyleValue("padding-right") +'px';
  3306. var height = /%$/.test(options.initialFrameHeight) ? '100%' : (options.initialFrameHeight - getStyleValue("padding-top")- getStyleValue("padding-bottom") );
  3307. if(this.options.autoHeightEnabled){
  3308. container.style.minHeight = height +'px';
  3309. container.style.height = '';
  3310. if(browser.ie && browser.version <= 6){
  3311. container.style.height = height ;
  3312. container.style.setExpression('height', 'this.scrollHeight <= ' + height + ' ? "' + height + 'px" : "auto"');
  3313. }
  3314. }else{
  3315. $(container).height(height)
  3316. }
  3317. container.style.zIndex = options.zIndex;
  3318. this._setup(container);
  3319. }
  3320. },
  3321. /**
  3322. * 编辑器初始化
  3323. * @private
  3324. * @ignore
  3325. * @param {Element} doc 编辑器Iframe中的文档对象
  3326. */
  3327. _setup: function (cont) {
  3328. var me = this,
  3329. options = me.options;
  3330. cont.contentEditable = true;
  3331. document.body.spellcheck = false;
  3332. me.document = document;
  3333. me.window = document.defaultView || document.parentWindow;
  3334. me.body = cont;
  3335. me.$body = $(cont);
  3336. me.selection = new dom.Selection(document,me.body);
  3337. me._isEnabled = false;
  3338. //gecko初始化就能得到range,无法判断isFocus了
  3339. var geckoSel;
  3340. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  3341. geckoSel.removeAllRanges();
  3342. }
  3343. this._initEvents();
  3344. //为form提交提供一个隐藏的textarea
  3345. for (var form = cont.parentNode; form && !domUtils.isBody(form); form = form.parentNode) {
  3346. if (form.tagName == 'FORM') {
  3347. me.form = form;
  3348. if(me.options.autoSyncData){
  3349. $(cont).on('blur',function(){
  3350. setValue(form,me);
  3351. })
  3352. }else{
  3353. $(form).on('submit', function () {
  3354. setValue(this, me);
  3355. })
  3356. }
  3357. break;
  3358. }
  3359. }
  3360. if (options.initialContent) {
  3361. if (options.autoClearinitialContent) {
  3362. var oldExecCommand = me.execCommand;
  3363. me.execCommand = function () {
  3364. me.fireEvent('firstBeforeExecCommand');
  3365. return oldExecCommand.apply(me, arguments);
  3366. };
  3367. this._setDefaultContent(options.initialContent);
  3368. } else
  3369. this.setContent(options.initialContent, false, true);
  3370. }
  3371. //编辑器不能为空内容
  3372. if (domUtils.isEmptyNode(me.body)) {
  3373. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  3374. }
  3375. //如果要求focus, 就把光标定位到内容开始
  3376. if (options.focus) {
  3377. setTimeout(function () {
  3378. me.focus(me.options.focusInEnd);
  3379. //如果自动清除开着,就不需要做selectionchange;
  3380. !me.options.autoClearinitialContent && me._selectionChange();
  3381. }, 0);
  3382. }
  3383. if (!me.container) {
  3384. me.container = cont.parentNode;
  3385. }
  3386. me._bindshortcutKeys();
  3387. me.isReady = 1;
  3388. me.fireEvent('ready');
  3389. options.onready && options.onready.call(me);
  3390. if(!browser.ie || browser.ie9above){
  3391. $(me.body).on( 'blur focus', function (e) {
  3392. var nSel = me.selection.getNative();
  3393. //chrome下会出现alt+tab切换时,导致选区位置不对
  3394. if (e.type == 'blur') {
  3395. if(nSel.rangeCount > 0 ){
  3396. me._bakRange = nSel.getRangeAt(0);
  3397. }
  3398. } else {
  3399. try {
  3400. me._bakRange && nSel.addRange(me._bakRange)
  3401. } catch (e) {
  3402. }
  3403. me._bakRange = null;
  3404. }
  3405. });
  3406. }
  3407. !options.isShow && me.setHide();
  3408. options.readonly && me.setDisabled();
  3409. },
  3410. /**
  3411. * 同步编辑器的数据,为提交数据做准备,主要用于你是手动提交的情况
  3412. * @name sync
  3413. * @grammar editor.sync(); //从编辑器的容器向上查找,如果找到就同步数据
  3414. * @grammar editor.sync(formID); //formID制定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  3415. * @desc
  3416. * 后台取得数据得键值使用你容器上得''name''属性,如果没有就使用参数传入的''textarea''
  3417. * @example
  3418. * editor.sync();
  3419. * form.sumbit(); //form变量已经指向了form元素
  3420. *
  3421. */
  3422. sync: function (formId) {
  3423. var me = this,
  3424. form = formId ? document.getElementById(formId) :
  3425. domUtils.findParent(me.body.parentNode, function (node) {
  3426. return node.tagName == 'FORM'
  3427. }, true);
  3428. form && setValue(form, me);
  3429. },
  3430. /**
  3431. * 设置编辑器高度
  3432. * @name setHeight
  3433. * @grammar editor.setHeight(number); //纯数值,不带单位
  3434. */
  3435. setHeight: function (height,notSetHeight) {
  3436. !notSetHeight && (this.options.initialFrameHeight = height);
  3437. if(this.options.autoHeightEnabled){
  3438. $(this.body).css({
  3439. 'min-height':height + 'px'
  3440. });
  3441. if(browser.ie && browser.version <= 6 && this.container){
  3442. this.container.style.height = height ;
  3443. this.container.style.setExpression('height', 'this.scrollHeight <= ' + height + ' ? "' + height + 'px" : "auto"');
  3444. }
  3445. }else{
  3446. $(this.body).height(height)
  3447. }
  3448. this.fireEvent('resize');
  3449. },
  3450. /**
  3451. * 设置编辑器宽度
  3452. * @name setWidth
  3453. * @grammar editor.setWidth(number); //纯数值,不带单位
  3454. */
  3455. setWidth:function(width){
  3456. this.$container && this.$container.width(width);
  3457. $(this.body).width(width - $(this.body).css('padding-left').replace('px','') * 1 - $(this.body).css('padding-right').replace('px','') * 1);
  3458. this.fireEvent('resize');
  3459. },
  3460. addshortcutkey: function (cmd, keys) {
  3461. var obj = {};
  3462. if (keys) {
  3463. obj[cmd] = keys
  3464. } else {
  3465. obj = cmd;
  3466. }
  3467. utils.extend(this.shortcutkeys, obj)
  3468. },
  3469. _bindshortcutKeys: function () {
  3470. var me = this, shortcutkeys = this.shortcutkeys;
  3471. me.addListener('keydown', function (type, e) {
  3472. var keyCode = e.keyCode || e.which;
  3473. for (var i in shortcutkeys) {
  3474. var tmp = shortcutkeys[i].split(',');
  3475. for (var t = 0, ti; ti = tmp[t++];) {
  3476. ti = ti.split(':');
  3477. var key = ti[0], param = ti[1];
  3478. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  3479. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  3480. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  3481. && keyCode == RegExp.$3
  3482. ) ||
  3483. keyCode == RegExp.$1
  3484. ) {
  3485. if (me.queryCommandState(i,param) != -1)
  3486. me.execCommand(i, param);
  3487. domUtils.preventDefault(e);
  3488. }
  3489. }
  3490. }
  3491. }
  3492. });
  3493. },
  3494. /**
  3495. * 获取编辑器内容
  3496. * @name getContent
  3497. * @grammar editor.getContent() => String //若编辑器中只包含字符"&lt;p&gt;&lt;br /&gt;&lt;/p/&gt;"会返回空。
  3498. * @grammar editor.getContent(fn) => String
  3499. * @example
  3500. * getContent默认是会现调用hasContents来判断编辑器是否为空,如果是,就直接返回空字符串
  3501. * 你也可以传入一个fn来接替hasContents的工作,定制判断的规则
  3502. * editor.getContent(function(){
  3503. * return false //编辑器没有内容 ,getContent直接返回空
  3504. * })
  3505. */
  3506. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  3507. var me = this;
  3508. if (cmd && utils.isFunction(cmd)) {
  3509. fn = cmd;
  3510. cmd = '';
  3511. }
  3512. if (fn ? !fn() : !this.hasContents()) {
  3513. return '';
  3514. }
  3515. me.fireEvent('beforegetcontent');
  3516. var root = UM.htmlparser(me.body.innerHTML,ignoreBlank);
  3517. me.filterOutputRule(root);
  3518. me.fireEvent('aftergetcontent',root);
  3519. return root.toHtml(formatter);
  3520. },
  3521. /**
  3522. * 取得完整的html代码,可以直接显示成完整的html文档
  3523. * @name getAllHtml
  3524. * @grammar editor.getAllHtml() => String
  3525. */
  3526. getAllHtml: function () {
  3527. var me = this,
  3528. headHtml = [],
  3529. html = '';
  3530. me.fireEvent('getAllHtml', headHtml);
  3531. if (browser.ie && browser.version > 8) {
  3532. var headHtmlForIE9 = '';
  3533. utils.each(me.document.styleSheets, function (si) {
  3534. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  3535. });
  3536. utils.each(me.document.getElementsByTagName('script'), function (si) {
  3537. headHtmlForIE9 += si.outerHTML;
  3538. });
  3539. }
  3540. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  3541. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  3542. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  3543. },
  3544. /**
  3545. * 得到编辑器的纯文本内容,但会保留段落格式
  3546. * @name getPlainTxt
  3547. * @grammar editor.getPlainTxt() => String
  3548. */
  3549. getPlainTxt: function () {
  3550. var reg = new RegExp(domUtils.fillChar, 'g'),
  3551. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  3552. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  3553. .replace(/<br\/?>/gi, '\n')
  3554. .replace(/<[^>/]+>/g, '')
  3555. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  3556. return dtd.$block[c] ? '\n' : b ? b : '';
  3557. });
  3558. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  3559. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  3560. },
  3561. /**
  3562. * 获取编辑器中的纯文本内容,没有段落格式
  3563. * @name getContentTxt
  3564. * @grammar editor.getContentTxt() => String
  3565. */
  3566. getContentTxt: function () {
  3567. var reg = new RegExp(domUtils.fillChar, 'g');
  3568. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  3569. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  3570. },
  3571. /**
  3572. * 将html设置到编辑器中, 如果是用于初始化时给编辑器赋初值,则必须放在ready方法内部执行
  3573. * @name setContent
  3574. * @grammar editor.setContent(html)
  3575. * @example
  3576. * var editor = new UM.ui.Editor()
  3577. * editor.ready(function(){
  3578. * //需要ready后执行,否则可能报错
  3579. * editor.setContent("欢迎使用UEditor!");
  3580. * })
  3581. */
  3582. setContent: function (html, isAppendTo, notFireSelectionchange) {
  3583. var me = this;
  3584. me.fireEvent('beforesetcontent', html);
  3585. var root = UM.htmlparser(html);
  3586. me.filterInputRule(root);
  3587. html = root.toHtml();
  3588. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  3589. function isCdataDiv(node){
  3590. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  3591. }
  3592. //给文本或者inline节点套p标签
  3593. if (me.options.enterTag == 'p') {
  3594. var child = this.body.firstChild, tmpNode;
  3595. if (!child || child.nodeType == 1 &&
  3596. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  3597. domUtils.isCustomeNode(child)
  3598. )
  3599. && child === this.body.lastChild) {
  3600. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  3601. } else {
  3602. var p = me.document.createElement('p');
  3603. while (child) {
  3604. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  3605. tmpNode = child.nextSibling;
  3606. p.appendChild(child);
  3607. child = tmpNode;
  3608. }
  3609. if (p.firstChild) {
  3610. if (!child) {
  3611. me.body.appendChild(p);
  3612. break;
  3613. } else {
  3614. child.parentNode.insertBefore(p, child);
  3615. p = me.document.createElement('p');
  3616. }
  3617. }
  3618. child = child.nextSibling;
  3619. }
  3620. }
  3621. }
  3622. me.fireEvent('aftersetcontent');
  3623. me.fireEvent('contentchange');
  3624. !notFireSelectionchange && me._selectionChange();
  3625. //清除保存的选区
  3626. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  3627. //trace:1742 setContent后gecko能得到焦点问题
  3628. var geckoSel;
  3629. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  3630. geckoSel.removeAllRanges();
  3631. }
  3632. if(me.options.autoSyncData){
  3633. me.form && setValue(me.form,me);
  3634. }
  3635. },
  3636. /**
  3637. * 让编辑器获得焦点,toEnd确定focus位置
  3638. * @name focus
  3639. * @grammar editor.focus([toEnd]) //默认focus到编辑器头部,toEnd为true时focus到内容尾部
  3640. */
  3641. focus: function (toEnd) {
  3642. try {
  3643. var me = this,
  3644. rng = me.selection.getRange();
  3645. if (toEnd) {
  3646. rng.setStartAtLast(me.body.lastChild).setCursor(false, true);
  3647. } else {
  3648. rng.select(true);
  3649. }
  3650. this.fireEvent('focus');
  3651. } catch (e) {
  3652. }
  3653. },
  3654. /**
  3655. * 使编辑区域失去焦点
  3656. */
  3657. blur:function(){
  3658. var sel = this.selection.getNative();
  3659. sel.empty ? sel.empty() : sel.removeAllRanges();
  3660. this.fireEvent('blur')
  3661. },
  3662. /**
  3663. * 判断编辑器当前是否获得了焦点
  3664. */
  3665. isFocus : function(){
  3666. if(this.fireEvent('isfocus')===true){
  3667. return true;
  3668. }
  3669. return this.selection.isFocus();
  3670. },
  3671. /**
  3672. * 初始化UE事件及部分事件代理
  3673. * @private
  3674. * @ignore
  3675. */
  3676. _initEvents: function () {
  3677. var me = this,
  3678. cont = me.body,
  3679. _proxyDomEvent = function(){
  3680. me._proxyDomEvent.apply(me, arguments);
  3681. };
  3682. $(cont)
  3683. .on( 'click contextmenu mousedown keydown keyup keypress mouseup mouseover mouseout selectstart', _proxyDomEvent)
  3684. .on( 'focus blur', _proxyDomEvent)
  3685. .on('mouseup keydown', function (evt) {
  3686. //特殊键不触发selectionchange
  3687. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  3688. return;
  3689. }
  3690. if (evt.button == 2)return;
  3691. me._selectionChange(250, evt);
  3692. });
  3693. },
  3694. /**
  3695. * 触发事件代理
  3696. * @private
  3697. * @ignore
  3698. */
  3699. _proxyDomEvent: function (evt) {
  3700. return this.fireEvent(evt.type.replace(/^on/, ''), evt);
  3701. },
  3702. /**
  3703. * 变化选区
  3704. * @private
  3705. * @ignore
  3706. */
  3707. _selectionChange: function (delay, evt) {
  3708. var me = this;
  3709. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  3710. // if ( !me.selection.isFocus() ){
  3711. // return;
  3712. // }
  3713. var hackForMouseUp = false;
  3714. var mouseX, mouseY;
  3715. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  3716. var range = this.selection.getRange();
  3717. if (!range.collapsed) {
  3718. hackForMouseUp = true;
  3719. mouseX = evt.clientX;
  3720. mouseY = evt.clientY;
  3721. }
  3722. }
  3723. clearTimeout(_selectionChangeTimer);
  3724. _selectionChangeTimer = setTimeout(function () {
  3725. if (!me.selection.getNative()) {
  3726. return;
  3727. }
  3728. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  3729. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  3730. var ieRange;
  3731. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  3732. ieRange = me.document.body.createTextRange();
  3733. try {
  3734. ieRange.moveToPoint(mouseX, mouseY);
  3735. } catch (ex) {
  3736. ieRange = null;
  3737. }
  3738. }
  3739. var bakGetIERange;
  3740. if (ieRange) {
  3741. bakGetIERange = me.selection.getIERange;
  3742. me.selection.getIERange = function () {
  3743. return ieRange;
  3744. };
  3745. }
  3746. me.selection.cache();
  3747. if (bakGetIERange) {
  3748. me.selection.getIERange = bakGetIERange;
  3749. }
  3750. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  3751. me.fireEvent('beforeselectionchange');
  3752. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  3753. me.fireEvent('selectionchange', !!evt);
  3754. me.fireEvent('afterselectionchange');
  3755. me.selection.clear();
  3756. }
  3757. }, delay || 50);
  3758. },
  3759. _callCmdFn: function (fnName, args) {
  3760. args = Array.prototype.slice.call(args,0);
  3761. var cmdName = args.shift().toLowerCase(),
  3762. cmd, cmdFn;
  3763. cmd = this.commands[cmdName] || UM.commands[cmdName];
  3764. cmdFn = cmd && cmd[fnName];
  3765. //没有querycommandstate或者没有command的都默认返回0
  3766. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  3767. return 0;
  3768. } else if (cmdFn) {
  3769. return cmdFn.apply(this, [cmdName].concat(args));
  3770. }
  3771. },
  3772. /**
  3773. * 执行编辑命令cmdName,完成富文本编辑效果
  3774. * @name execCommand
  3775. * @grammar editor.execCommand(cmdName) => {*}
  3776. */
  3777. execCommand: function (cmdName) {
  3778. if(!this.isFocus()){
  3779. var bakRange = this.selection._bakRange;
  3780. if(bakRange){
  3781. bakRange.select()
  3782. }else{
  3783. this.focus(true)
  3784. }
  3785. }
  3786. cmdName = cmdName.toLowerCase();
  3787. var me = this,
  3788. result,
  3789. cmd = me.commands[cmdName] || UM.commands[cmdName];
  3790. if (!cmd || !cmd.execCommand) {
  3791. return null;
  3792. }
  3793. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  3794. me.__hasEnterExecCommand = true;
  3795. if (me.queryCommandState.apply(me,arguments) != -1) {
  3796. me.fireEvent('saveScene');
  3797. me.fireEvent('beforeexeccommand', cmdName);
  3798. result = this._callCmdFn('execCommand', arguments);
  3799. (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  3800. me.fireEvent('afterexeccommand', cmdName);
  3801. me.fireEvent('saveScene');
  3802. }
  3803. me.__hasEnterExecCommand = false;
  3804. } else {
  3805. result = this._callCmdFn('execCommand', arguments);
  3806. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  3807. }
  3808. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  3809. return result;
  3810. },
  3811. /**
  3812. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  3813. * @name queryCommandState
  3814. * @grammar editor.queryCommandState(cmdName) => (-1|0|1)
  3815. * @desc
  3816. * * ''-1'' 当前命令不可用
  3817. * * ''0'' 当前命令可用
  3818. * * ''1'' 当前命令已经执行过了
  3819. */
  3820. queryCommandState: function (cmdName) {
  3821. try{
  3822. return this._callCmdFn('queryCommandState', arguments);
  3823. }catch(e){
  3824. return 0
  3825. }
  3826. },
  3827. /**
  3828. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  3829. * @name queryCommandValue
  3830. * @grammar editor.queryCommandValue(cmdName) => {*}
  3831. */
  3832. queryCommandValue: function (cmdName) {
  3833. try{
  3834. return this._callCmdFn('queryCommandValue', arguments);
  3835. }catch(e){
  3836. return null
  3837. }
  3838. },
  3839. /**
  3840. * 检查编辑区域中是否有内容,若包含tags中的节点类型,直接返回true
  3841. * @name hasContents
  3842. * @desc
  3843. * 默认有文本内容,或者有以下节点都不认为是空
  3844. * <code>{table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1}</code>
  3845. * @grammar editor.hasContents() => (true|false)
  3846. * @grammar editor.hasContents(tags) => (true|false) //若文档中包含tags数组里对应的tag,直接返回true
  3847. * @example
  3848. * editor.hasContents(['span']) //如果编辑器里有这些,不认为是空
  3849. */
  3850. hasContents: function (tags) {
  3851. if (tags) {
  3852. for (var i = 0, ci; ci = tags[i++];) {
  3853. if (this.body.getElementsByTagName(ci).length > 0) {
  3854. return true;
  3855. }
  3856. }
  3857. }
  3858. if (!domUtils.isEmptyBlock(this.body)) {
  3859. return true
  3860. }
  3861. //随时添加,定义的特殊标签如果存在,不能认为是空
  3862. tags = ['div'];
  3863. for (i = 0; ci = tags[i++];) {
  3864. var nodes = domUtils.getElementsByTagName(this.body, ci);
  3865. for (var n = 0, cn; cn = nodes[n++];) {
  3866. if (domUtils.isCustomeNode(cn)) {
  3867. return true;
  3868. }
  3869. }
  3870. }
  3871. return false;
  3872. },
  3873. /**
  3874. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  3875. * @name reset
  3876. * @desc
  3877. * * 清空编辑器内容
  3878. * * 清空回退列表
  3879. * @grammar editor.reset()
  3880. */
  3881. reset: function () {
  3882. this.fireEvent('reset');
  3883. },
  3884. isEnabled: function(){
  3885. return this._isEnabled != true;
  3886. },
  3887. setEnabled: function () {
  3888. var me = this, range;
  3889. me.body.contentEditable = true;
  3890. /* 恢复选区 */
  3891. if (me.lastBk) {
  3892. range = me.selection.getRange();
  3893. try {
  3894. range.moveToBookmark(me.lastBk);
  3895. delete me.lastBk
  3896. } catch (e) {
  3897. range.setStartAtFirst(me.body).collapse(true)
  3898. }
  3899. range.select(true);
  3900. }
  3901. /* 恢复query函数 */
  3902. if (me.bkqueryCommandState) {
  3903. me.queryCommandState = me.bkqueryCommandState;
  3904. delete me.bkqueryCommandState;
  3905. }
  3906. /* 恢复原生事件 */
  3907. if (me._bkproxyDomEvent) {
  3908. me._proxyDomEvent = me._bkproxyDomEvent;
  3909. delete me._bkproxyDomEvent;
  3910. }
  3911. /* 触发事件 */
  3912. me.fireEvent('setEnabled');
  3913. },
  3914. /**
  3915. * 设置当前编辑区域可以编辑
  3916. * @name enable
  3917. * @grammar editor.enable()
  3918. */
  3919. enable: function () {
  3920. return this.setEnabled();
  3921. },
  3922. setDisabled: function (except, keepDomEvent) {
  3923. var me = this;
  3924. me.body.contentEditable = false;
  3925. me._except = except ? utils.isArray(except) ? except : [except] : [];
  3926. /* 备份最后的选区 */
  3927. if (!me.lastBk) {
  3928. me.lastBk = me.selection.getRange().createBookmark(true);
  3929. }
  3930. /* 备份并重置query函数 */
  3931. if(!me.bkqueryCommandState) {
  3932. me.bkqueryCommandState = me.queryCommandState;
  3933. me.queryCommandState = function (type) {
  3934. if (utils.indexOf(me._except, type) != -1) {
  3935. return me.bkqueryCommandState.apply(me, arguments);
  3936. }
  3937. return -1;
  3938. };
  3939. }
  3940. /* 备份并墙原生事件 */
  3941. if(!keepDomEvent && !me._bkproxyDomEvent) {
  3942. me._bkproxyDomEvent = me._proxyDomEvent;
  3943. me._proxyDomEvent = function () {
  3944. return false;
  3945. };
  3946. }
  3947. /* 触发事件 */
  3948. me.fireEvent('selectionchange');
  3949. me.fireEvent('setDisabled', me._except);
  3950. },
  3951. /** 设置当前编辑区域不可编辑,except中的命令除外
  3952. * @name disable
  3953. * @grammar editor.disable()
  3954. * @grammar editor.disable(except) //例外的命令,也即即使设置了disable,此处配置的命令仍然可以执行
  3955. * @example
  3956. * //禁用工具栏中除加粗和插入图片之外的所有功能
  3957. * editor.disable(['bold','insertimage']);//可以是单一的String,也可以是Array
  3958. */
  3959. disable: function (except) {
  3960. return this.setDisabled(except);
  3961. },
  3962. /**
  3963. * 设置默认内容
  3964. * @ignore
  3965. * @private
  3966. * @param {String} cont 要存入的内容
  3967. */
  3968. _setDefaultContent: function () {
  3969. function clear() {
  3970. var me = this;
  3971. if (me.document.getElementById('initContent')) {
  3972. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  3973. me.removeListener('firstBeforeExecCommand focus', clear);
  3974. setTimeout(function () {
  3975. me.focus();
  3976. me._selectionChange();
  3977. }, 0)
  3978. }
  3979. }
  3980. return function (cont) {
  3981. var me = this;
  3982. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  3983. me.addListener('firstBeforeExecCommand focus', clear);
  3984. }
  3985. }(),
  3986. /**
  3987. * show方法的兼容版本
  3988. * @private
  3989. * @ignore
  3990. */
  3991. setShow: function () {
  3992. var me = this, range = me.selection.getRange();
  3993. if (me.container.style.display == 'none') {
  3994. //有可能内容丢失了
  3995. try {
  3996. range.moveToBookmark(me.lastBk);
  3997. delete me.lastBk
  3998. } catch (e) {
  3999. range.setStartAtFirst(me.body).collapse(true)
  4000. }
  4001. //ie下focus实效,所以做了个延迟
  4002. setTimeout(function () {
  4003. range.select(true);
  4004. }, 100);
  4005. me.container.style.display = '';
  4006. }
  4007. },
  4008. /**
  4009. * 显示编辑器
  4010. * @name show
  4011. * @grammar editor.show()
  4012. */
  4013. show: function () {
  4014. return this.setShow();
  4015. },
  4016. /**
  4017. * hide方法的兼容版本
  4018. * @private
  4019. * @ignore
  4020. */
  4021. setHide: function () {
  4022. var me = this;
  4023. if (!me.lastBk) {
  4024. me.lastBk = me.selection.getRange().createBookmark(true);
  4025. }
  4026. me.container.style.display = 'none'
  4027. },
  4028. /**
  4029. * 隐藏编辑器
  4030. * @name hide
  4031. * @grammar editor.hide()
  4032. */
  4033. hide: function () {
  4034. return this.setHide();
  4035. },
  4036. /**
  4037. * 根据制定的路径,获取对应的语言资源
  4038. * @name getLang
  4039. * @grammar editor.getLang(path) => (JSON|String) 路径根据的是lang目录下的语言文件的路径结构
  4040. * @example
  4041. * editor.getLang('contextMenu.delete') //如果当前是中文,那返回是的是删除
  4042. */
  4043. getLang: function (path) {
  4044. var lang = UM.I18N[this.options.lang];
  4045. if (!lang) {
  4046. throw Error("not import language file");
  4047. }
  4048. path = (path || "").split(".");
  4049. for (var i = 0, ci; ci = path[i++];) {
  4050. lang = lang[ci];
  4051. if (!lang)break;
  4052. }
  4053. return lang;
  4054. },
  4055. /**
  4056. * 计算编辑器当前内容的长度
  4057. * @name getContentLength
  4058. * @grammar editor.getContentLength(ingoneHtml,tagNames) =>
  4059. * @example
  4060. * editor.getLang(true)
  4061. */
  4062. getContentLength: function (ingoneHtml, tagNames) {
  4063. var count = this.getContent(false,false,true).length;
  4064. if (ingoneHtml) {
  4065. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  4066. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  4067. for (var i = 0, ci; ci = tagNames[i++];) {
  4068. count += this.body.getElementsByTagName(ci).length;
  4069. }
  4070. }
  4071. return count;
  4072. },
  4073. addInputRule: function (rule,ignoreUndo) {
  4074. rule.ignoreUndo = ignoreUndo;
  4075. this.inputRules.push(rule);
  4076. },
  4077. filterInputRule: function (root,isUndoLoad) {
  4078. for (var i = 0, ci; ci = this.inputRules[i++];) {
  4079. if(isUndoLoad && ci.ignoreUndo){
  4080. continue;
  4081. }
  4082. ci.call(this, root)
  4083. }
  4084. },
  4085. addOutputRule: function (rule,ignoreUndo) {
  4086. rule.ignoreUndo = ignoreUndo;
  4087. this.outputRules.push(rule)
  4088. },
  4089. filterOutputRule: function (root,isUndoLoad) {
  4090. for (var i = 0, ci; ci = this.outputRules[i++];) {
  4091. if(isUndoLoad && ci.ignoreUndo){
  4092. continue;
  4093. }
  4094. ci.call(this, root)
  4095. }
  4096. }
  4097. };
  4098. utils.inherits(Editor, EventBase);
  4099. })();
  4100. /**
  4101. * @file
  4102. * @name UM.filterWord
  4103. * @short filterWord
  4104. * @desc 用来过滤word粘贴过来的字符串
  4105. * @import editor.js,core/utils.js
  4106. * @anthor zhanyi
  4107. */
  4108. var filterWord = UM.filterWord = function () {
  4109. //是否是word过来的内容
  4110. function isWordDocument( str ) {
  4111. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  4112. }
  4113. //去掉小数
  4114. function transUnit( v ) {
  4115. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  4116. return utils.transUnitToPx(m);
  4117. } );
  4118. return v;
  4119. }
  4120. function filterPasteWord( str ) {
  4121. return str.replace(/[\t\r\n]+/g,' ')
  4122. .replace( /<!--[\s\S]*?-->/ig, "" )
  4123. //转换图片
  4124. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  4125. //opera能自己解析出image所这里直接返回空
  4126. if(browser.opera){
  4127. return '';
  4128. }
  4129. try{
  4130. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  4131. if(/Bitmap/i.test(str)){
  4132. return '';
  4133. }
  4134. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  4135. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  4136. src = str.match(/src=\s*"([^"]*)"/i)[1];
  4137. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  4138. } catch(e){
  4139. return '';
  4140. }
  4141. })
  4142. //针对wps添加的多余标签处理
  4143. .replace(/<\/?div[^>]*>/g,'')
  4144. //去掉多余的属性
  4145. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  4146. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  4147. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  4148. //去掉多余的属性
  4149. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  4150. //保留list的标示
  4151. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  4152. })
  4153. //清除多余的font/span不能匹配&nbsp;有可能是空格
  4154. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  4155. return c.replace(/[\t\r\n ]+/g,' ')
  4156. })
  4157. //处理style的问题
  4158. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  4159. var n = [],
  4160. s = style.replace( /^\s+|\s+$/, '' )
  4161. .replace(/&#39;/g,'\'')
  4162. .replace( /&quot;/gi, "'" )
  4163. .split( /;\s*/g );
  4164. for ( var i = 0,v; v = s[i];i++ ) {
  4165. var name, value,
  4166. parts = v.split( ":" );
  4167. if ( parts.length == 2 ) {
  4168. name = parts[0].toLowerCase();
  4169. value = parts[1].toLowerCase();
  4170. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  4171. ||
  4172. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  4173. ){
  4174. continue;
  4175. }
  4176. switch ( name ) {
  4177. case "mso-padding-alt":
  4178. case "mso-padding-top-alt":
  4179. case "mso-padding-right-alt":
  4180. case "mso-padding-bottom-alt":
  4181. case "mso-padding-left-alt":
  4182. case "mso-margin-alt":
  4183. case "mso-margin-top-alt":
  4184. case "mso-margin-right-alt":
  4185. case "mso-margin-bottom-alt":
  4186. case "mso-margin-left-alt":
  4187. //ie下会出现挤到一起的情况
  4188. //case "mso-table-layout-alt":
  4189. case "mso-height":
  4190. case "mso-width":
  4191. case "mso-vertical-align-alt":
  4192. //trace:1819 ff下会解析出padding在table上
  4193. if(!/<table/.test(tag))
  4194. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  4195. continue;
  4196. case "horiz-align":
  4197. n[i] = "text-align:" + value;
  4198. continue;
  4199. case "vert-align":
  4200. n[i] = "vertical-align:" + value;
  4201. continue;
  4202. case "font-color":
  4203. case "mso-foreground":
  4204. n[i] = "color:" + value;
  4205. continue;
  4206. case "mso-background":
  4207. case "mso-highlight":
  4208. n[i] = "background:" + value;
  4209. continue;
  4210. case "mso-default-height":
  4211. n[i] = "min-height:" + transUnit( value );
  4212. continue;
  4213. case "mso-default-width":
  4214. n[i] = "min-width:" + transUnit( value );
  4215. continue;
  4216. case "mso-padding-between-alt":
  4217. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  4218. continue;
  4219. case "text-line-through":
  4220. if ( (value == "single") || (value == "double") ) {
  4221. n[i] = "text-decoration:line-through";
  4222. }
  4223. continue;
  4224. case "mso-zero-height":
  4225. if ( value == "yes" ) {
  4226. n[i] = "display:none";
  4227. }
  4228. continue;
  4229. // case 'background':
  4230. // break;
  4231. case 'margin':
  4232. if ( !/[1-9]/.test( value ) ) {
  4233. continue;
  4234. }
  4235. }
  4236. 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 )
  4237. ||
  4238. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  4239. ) {
  4240. continue;
  4241. }
  4242. n[i] = name + ":" + parts[1];
  4243. }
  4244. }
  4245. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  4246. })
  4247. .replace(/[\d.]+(cm|pt)/g,function(str){
  4248. return utils.transUnitToPx(str)
  4249. })
  4250. }
  4251. return function ( html ) {
  4252. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  4253. };
  4254. }();
  4255. ///import editor.js
  4256. ///import core/utils.js
  4257. ///import core/dom/dom.js
  4258. ///import core/dom/dtd.js
  4259. ///import core/htmlparser.js
  4260. //模拟的节点类
  4261. //by zhanyi
  4262. (function () {
  4263. var uNode = UM.uNode = function (obj) {
  4264. this.type = obj.type;
  4265. this.data = obj.data;
  4266. this.tagName = obj.tagName;
  4267. this.parentNode = obj.parentNode;
  4268. this.attrs = obj.attrs || {};
  4269. this.children = obj.children;
  4270. };
  4271. var notTransAttrs = {
  4272. 'href':1,
  4273. 'src':1,
  4274. '_src':1,
  4275. '_href':1,
  4276. 'cdata_data':1
  4277. };
  4278. var notTransTagName = {
  4279. style:1,
  4280. script:1
  4281. };
  4282. var indentChar = ' ',
  4283. breakChar = '\n';
  4284. function insertLine(arr, current, begin) {
  4285. arr.push(breakChar);
  4286. return current + (begin ? 1 : -1);
  4287. }
  4288. function insertIndent(arr, current) {
  4289. //插入缩进
  4290. for (var i = 0; i < current; i++) {
  4291. arr.push(indentChar);
  4292. }
  4293. }
  4294. //创建uNode的静态方法
  4295. //支持标签和html
  4296. uNode.createElement = function (html) {
  4297. if (/[<>]/.test(html)) {
  4298. return UM.htmlparser(html).children[0]
  4299. } else {
  4300. return new uNode({
  4301. type:'element',
  4302. children:[],
  4303. tagName:html
  4304. })
  4305. }
  4306. };
  4307. uNode.createText = function (data,noTrans) {
  4308. return new UM.uNode({
  4309. type:'text',
  4310. 'data':noTrans ? data : utils.unhtml(data || '')
  4311. })
  4312. };
  4313. function nodeToHtml(node, arr, formatter, current) {
  4314. switch (node.type) {
  4315. case 'root':
  4316. for (var i = 0, ci; ci = node.children[i++];) {
  4317. //插入新行
  4318. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  4319. insertLine(arr, current, true);
  4320. insertIndent(arr, current)
  4321. }
  4322. nodeToHtml(ci, arr, formatter, current)
  4323. }
  4324. break;
  4325. case 'text':
  4326. isText(node, arr);
  4327. break;
  4328. case 'element':
  4329. isElement(node, arr, formatter, current);
  4330. break;
  4331. case 'comment':
  4332. isComment(node, arr, formatter);
  4333. }
  4334. return arr;
  4335. }
  4336. function isText(node, arr) {
  4337. if(node.parentNode.tagName == 'pre'){
  4338. //源码模式下输入html标签,不能做转换处理,直接输出
  4339. arr.push(node.data)
  4340. }else{
  4341. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  4342. }
  4343. }
  4344. function isElement(node, arr, formatter, current) {
  4345. var attrhtml = '';
  4346. if (node.attrs) {
  4347. attrhtml = [];
  4348. var attrs = node.attrs;
  4349. for (var a in attrs) {
  4350. //这里就针对
  4351. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  4352. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  4353. //有可能做的不够
  4354. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  4355. return '&quot;'
  4356. }) : utils.unhtml(attrs[a])) + '"' : ''))
  4357. }
  4358. attrhtml = attrhtml.join(' ');
  4359. }
  4360. arr.push('<' + node.tagName +
  4361. (attrhtml ? ' ' + attrhtml : '') +
  4362. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  4363. );
  4364. //插入新行
  4365. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  4366. if(node.children && node.children.length){
  4367. current = insertLine(arr, current, true);
  4368. insertIndent(arr, current)
  4369. }
  4370. }
  4371. if (node.children && node.children.length) {
  4372. for (var i = 0, ci; ci = node.children[i++];) {
  4373. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  4374. insertLine(arr, current);
  4375. insertIndent(arr, current)
  4376. }
  4377. nodeToHtml(ci, arr, formatter, current)
  4378. }
  4379. }
  4380. if (!dtd.$empty[node.tagName]) {
  4381. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  4382. if(node.children && node.children.length){
  4383. current = insertLine(arr, current);
  4384. insertIndent(arr, current)
  4385. }
  4386. }
  4387. arr.push('<\/' + node.tagName + '>');
  4388. }
  4389. }
  4390. function isComment(node, arr) {
  4391. arr.push('<!--' + node.data + '-->');
  4392. }
  4393. function getNodeById(root, id) {
  4394. var node;
  4395. if (root.type == 'element' && root.getAttr('id') == id) {
  4396. return root;
  4397. }
  4398. if (root.children && root.children.length) {
  4399. for (var i = 0, ci; ci = root.children[i++];) {
  4400. if (node = getNodeById(ci, id)) {
  4401. return node;
  4402. }
  4403. }
  4404. }
  4405. }
  4406. function getNodesByTagName(node, tagName, arr) {
  4407. if (node.type == 'element' && node.tagName == tagName) {
  4408. arr.push(node);
  4409. }
  4410. if (node.children && node.children.length) {
  4411. for (var i = 0, ci; ci = node.children[i++];) {
  4412. getNodesByTagName(ci, tagName, arr)
  4413. }
  4414. }
  4415. }
  4416. function nodeTraversal(root,fn){
  4417. if(root.children && root.children.length){
  4418. for(var i= 0,ci;ci=root.children[i];){
  4419. nodeTraversal(ci,fn);
  4420. //ci被替换的情况,这里就不再走 fn了
  4421. if(ci.parentNode ){
  4422. if(ci.children && ci.children.length){
  4423. fn(ci)
  4424. }
  4425. if(ci.parentNode) i++
  4426. }
  4427. }
  4428. }else{
  4429. fn(root)
  4430. }
  4431. }
  4432. uNode.prototype = {
  4433. /**
  4434. * 当前节点对象,转换成html文本
  4435. * @method toHtml
  4436. * @return { String } 返回转换后的html字符串
  4437. * @example
  4438. * ```javascript
  4439. * node.toHtml();
  4440. * ```
  4441. */
  4442. /**
  4443. * 当前节点对象,转换成html文本
  4444. * @method toHtml
  4445. * @param { Boolean } formatter 是否格式化返回值
  4446. * @return { String } 返回转换后的html字符串
  4447. * @example
  4448. * ```javascript
  4449. * node.toHtml( true );
  4450. * ```
  4451. */
  4452. toHtml:function (formatter) {
  4453. var arr = [];
  4454. nodeToHtml(this, arr, formatter, 0);
  4455. return arr.join('')
  4456. },
  4457. /**
  4458. * 获取节点的html内容
  4459. * @method innerHTML
  4460. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4461. * @return { String } 返回节点的html内容
  4462. * @example
  4463. * ```javascript
  4464. * var htmlstr = node.innerHTML();
  4465. * ```
  4466. */
  4467. /**
  4468. * 设置节点的html内容
  4469. * @method innerHTML
  4470. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4471. * @param { String } htmlstr 传入要设置的html内容
  4472. * @return { UM.uNode } 返回节点本身
  4473. * @example
  4474. * ```javascript
  4475. * node.innerHTML('<span>text</span>');
  4476. * ```
  4477. */
  4478. innerHTML:function (htmlstr) {
  4479. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  4480. return this;
  4481. }
  4482. if (utils.isString(htmlstr)) {
  4483. if(this.children){
  4484. for (var i = 0, ci; ci = this.children[i++];) {
  4485. ci.parentNode = null;
  4486. }
  4487. }
  4488. this.children = [];
  4489. var tmpRoot = UM.htmlparser(htmlstr);
  4490. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  4491. this.children.push(ci);
  4492. ci.parentNode = this;
  4493. }
  4494. return this;
  4495. } else {
  4496. var tmpRoot = new UM.uNode({
  4497. type:'root',
  4498. children:this.children
  4499. });
  4500. return tmpRoot.toHtml();
  4501. }
  4502. },
  4503. /**
  4504. * 获取节点的纯文本内容
  4505. * @method innerText
  4506. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4507. * @return { String } 返回节点的存文本内容
  4508. * @example
  4509. * ```javascript
  4510. * var textStr = node.innerText();
  4511. * ```
  4512. */
  4513. /**
  4514. * 设置节点的纯文本内容
  4515. * @method innerText
  4516. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4517. * @param { String } textStr 传入要设置的文本内容
  4518. * @return { UM.uNode } 返回节点本身
  4519. * @example
  4520. * ```javascript
  4521. * node.innerText('<span>text</span>');
  4522. * ```
  4523. */
  4524. innerText:function (textStr,noTrans) {
  4525. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  4526. return this;
  4527. }
  4528. if (textStr) {
  4529. if(this.children){
  4530. for (var i = 0, ci; ci = this.children[i++];) {
  4531. ci.parentNode = null;
  4532. }
  4533. }
  4534. this.children = [];
  4535. this.appendChild(uNode.createText(textStr,noTrans));
  4536. return this;
  4537. } else {
  4538. return this.toHtml().replace(/<[^>]+>/g, '');
  4539. }
  4540. },
  4541. /**
  4542. * 获取当前对象的data属性
  4543. * @method getData
  4544. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  4545. * @example
  4546. * ```javascript
  4547. * node.getData();
  4548. * ```
  4549. */
  4550. getData:function () {
  4551. if (this.type == 'element')
  4552. return '';
  4553. return this.data
  4554. },
  4555. /**
  4556. * 获取当前节点下的第一个子节点
  4557. * @method firstChild
  4558. * @return { UM.uNode } 返回第一个子节点
  4559. * @example
  4560. * ```javascript
  4561. * node.firstChild(); //返回第一个子节点
  4562. * ```
  4563. */
  4564. firstChild:function () {
  4565. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  4566. // return this;
  4567. // }
  4568. return this.children ? this.children[0] : null;
  4569. },
  4570. /**
  4571. * 获取当前节点下的最后一个子节点
  4572. * @method lastChild
  4573. * @return { UM.uNode } 返回最后一个子节点
  4574. * @example
  4575. * ```javascript
  4576. * node.lastChild(); //返回最后一个子节点
  4577. * ```
  4578. */
  4579. lastChild:function () {
  4580. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  4581. // return this;
  4582. // }
  4583. return this.children ? this.children[this.children.length - 1] : null;
  4584. },
  4585. /**
  4586. * 获取和当前节点有相同父亲节点的前一个节点
  4587. * @method previousSibling
  4588. * @return { UM.uNode } 返回前一个节点
  4589. * @example
  4590. * ```javascript
  4591. * node.children[2].previousSibling(); //返回子节点node.children[1]
  4592. * ```
  4593. */
  4594. previousSibling : function(){
  4595. var parent = this.parentNode;
  4596. for (var i = 0, ci; ci = parent.children[i]; i++) {
  4597. if (ci === this) {
  4598. return i == 0 ? null : parent.children[i-1];
  4599. }
  4600. }
  4601. },
  4602. /**
  4603. * 获取和当前节点有相同父亲节点的后一个节点
  4604. * @method nextSibling
  4605. * @return { UM.uNode } 返回后一个节点,找不到返回null
  4606. * @example
  4607. * ```javascript
  4608. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  4609. * ```
  4610. */
  4611. nextSibling : function(){
  4612. var parent = this.parentNode;
  4613. for (var i = 0, ci; ci = parent.children[i++];) {
  4614. if (ci === this) {
  4615. return parent.children[i];
  4616. }
  4617. }
  4618. },
  4619. /**
  4620. * 用新的节点替换当前节点
  4621. * @method replaceChild
  4622. * @param { UM.uNode } target 要替换成该节点参数
  4623. * @param { UM.uNode } source 要被替换掉的节点
  4624. * @return { UM.uNode } 返回替换之后的节点对象
  4625. * @example
  4626. * ```javascript
  4627. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  4628. * ```
  4629. */
  4630. replaceChild:function (target, source) {
  4631. if (this.children) {
  4632. if(target.parentNode){
  4633. target.parentNode.removeChild(target);
  4634. }
  4635. for (var i = 0, ci; ci = this.children[i]; i++) {
  4636. if (ci === source) {
  4637. this.children.splice(i, 1, target);
  4638. source.parentNode = null;
  4639. target.parentNode = this;
  4640. return target;
  4641. }
  4642. }
  4643. }
  4644. },
  4645. /**
  4646. * 在节点的子节点列表最后位置插入一个节点
  4647. * @method appendChild
  4648. * @param { UM.uNode } node 要插入的节点
  4649. * @return { UM.uNode } 返回刚插入的子节点
  4650. * @example
  4651. * ```javascript
  4652. * node.appendChild( newNode ); //在node内插入子节点newNode
  4653. * ```
  4654. */
  4655. appendChild:function (node) {
  4656. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  4657. if (!this.children) {
  4658. this.children = []
  4659. }
  4660. if(node.parentNode){
  4661. node.parentNode.removeChild(node);
  4662. }
  4663. for (var i = 0, ci; ci = this.children[i]; i++) {
  4664. if (ci === node) {
  4665. this.children.splice(i, 1);
  4666. break;
  4667. }
  4668. }
  4669. this.children.push(node);
  4670. node.parentNode = this;
  4671. return node;
  4672. }
  4673. },
  4674. /**
  4675. * 在传入节点的前面插入一个节点
  4676. * @method insertBefore
  4677. * @param { UM.uNode } target 要插入的节点
  4678. * @param { UM.uNode } source 在该参数节点前面插入
  4679. * @return { UM.uNode } 返回刚插入的子节点
  4680. * @example
  4681. * ```javascript
  4682. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  4683. * ```
  4684. */
  4685. insertBefore:function (target, source) {
  4686. if (this.children) {
  4687. if(target.parentNode){
  4688. target.parentNode.removeChild(target);
  4689. }
  4690. for (var i = 0, ci; ci = this.children[i]; i++) {
  4691. if (ci === source) {
  4692. this.children.splice(i, 0, target);
  4693. target.parentNode = this;
  4694. return target;
  4695. }
  4696. }
  4697. }
  4698. },
  4699. /**
  4700. * 在传入节点的后面插入一个节点
  4701. * @method insertAfter
  4702. * @param { UM.uNode } target 要插入的节点
  4703. * @param { UM.uNode } source 在该参数节点后面插入
  4704. * @return { UM.uNode } 返回刚插入的子节点
  4705. * @example
  4706. * ```javascript
  4707. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  4708. * ```
  4709. */
  4710. insertAfter:function (target, source) {
  4711. if (this.children) {
  4712. if(target.parentNode){
  4713. target.parentNode.removeChild(target);
  4714. }
  4715. for (var i = 0, ci; ci = this.children[i]; i++) {
  4716. if (ci === source) {
  4717. this.children.splice(i + 1, 0, target);
  4718. target.parentNode = this;
  4719. return target;
  4720. }
  4721. }
  4722. }
  4723. },
  4724. /**
  4725. * 从当前节点的子节点列表中,移除节点
  4726. * @method removeChild
  4727. * @param { UM.uNode } node 要移除的节点引用
  4728. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  4729. * @return { * } 返回刚移除的子节点
  4730. * @example
  4731. * ```javascript
  4732. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  4733. * ```
  4734. */
  4735. removeChild:function (node,keepChildren) {
  4736. if (this.children) {
  4737. for (var i = 0, ci; ci = this.children[i]; i++) {
  4738. if (ci === node) {
  4739. this.children.splice(i, 1);
  4740. ci.parentNode = null;
  4741. if(keepChildren && ci.children && ci.children.length){
  4742. for(var j= 0,cj;cj=ci.children[j];j++){
  4743. this.children.splice(i+j,0,cj);
  4744. cj.parentNode = this;
  4745. }
  4746. }
  4747. return ci;
  4748. }
  4749. }
  4750. }
  4751. },
  4752. /**
  4753. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  4754. * @method getAttr
  4755. * @param { String } attrName 要获取的属性名称
  4756. * @return { * } 返回attrs对象下的属性值
  4757. * @example
  4758. * ```javascript
  4759. * node.getAttr('title');
  4760. * ```
  4761. */
  4762. getAttr:function (attrName) {
  4763. return this.attrs && this.attrs[attrName.toLowerCase()]
  4764. },
  4765. /**
  4766. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  4767. * @method setAttr
  4768. * @param { String } attrName 要设置的属性名称
  4769. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  4770. * @return { * } 返回attrs对象下的属性值
  4771. * @example
  4772. * ```javascript
  4773. * node.setAttr('title','标题');
  4774. * ```
  4775. */
  4776. setAttr:function (attrName, attrVal) {
  4777. if (!attrName) {
  4778. delete this.attrs;
  4779. return;
  4780. }
  4781. if(!this.attrs){
  4782. this.attrs = {};
  4783. }
  4784. if (utils.isObject(attrName)) {
  4785. for (var a in attrName) {
  4786. if (!attrName[a]) {
  4787. delete this.attrs[a]
  4788. } else {
  4789. this.attrs[a.toLowerCase()] = attrName[a];
  4790. }
  4791. }
  4792. } else {
  4793. if (!attrVal) {
  4794. delete this.attrs[attrName]
  4795. } else {
  4796. this.attrs[attrName.toLowerCase()] = attrVal;
  4797. }
  4798. }
  4799. },
  4800. hasAttr: function( attrName ){
  4801. var attrVal = this.getAttr( attrName );
  4802. return ( attrVal !== null ) && ( attrVal !== undefined );
  4803. },
  4804. /**
  4805. * 获取当前节点在父节点下的位置索引
  4806. * @method getIndex
  4807. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  4808. * @example
  4809. * ```javascript
  4810. * node.getIndex();
  4811. * ```
  4812. */
  4813. getIndex:function(){
  4814. var parent = this.parentNode;
  4815. for(var i= 0,ci;ci=parent.children[i];i++){
  4816. if(ci === this){
  4817. return i;
  4818. }
  4819. }
  4820. return -1;
  4821. },
  4822. /**
  4823. * 在当前节点下,根据id查找节点
  4824. * @method getNodeById
  4825. * @param { String } id 要查找的id
  4826. * @return { UM.uNode } 返回找到的节点
  4827. * @example
  4828. * ```javascript
  4829. * node.getNodeById('textId');
  4830. * ```
  4831. */
  4832. getNodeById:function (id) {
  4833. var node;
  4834. if (this.children && this.children.length) {
  4835. for (var i = 0, ci; ci = this.children[i++];) {
  4836. if (node = getNodeById(ci, id)) {
  4837. return node;
  4838. }
  4839. }
  4840. }
  4841. },
  4842. /**
  4843. * 在当前节点下,根据元素名称查找节点列表
  4844. * @method getNodesByTagName
  4845. * @param { String } tagNames 要查找的元素名称
  4846. * @return { Array } 返回找到的节点列表
  4847. * @example
  4848. * ```javascript
  4849. * node.getNodesByTagName('span');
  4850. * ```
  4851. */
  4852. getNodesByTagName:function (tagNames) {
  4853. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  4854. var arr = [], me = this;
  4855. utils.each(tagNames, function (tagName) {
  4856. if (me.children && me.children.length) {
  4857. for (var i = 0, ci; ci = me.children[i++];) {
  4858. getNodesByTagName(ci, tagName, arr)
  4859. }
  4860. }
  4861. });
  4862. return arr;
  4863. },
  4864. /**
  4865. * 根据样式名称,获取节点的样式值
  4866. * @method getStyle
  4867. * @param { String } name 要获取的样式名称
  4868. * @return { String } 返回样式值
  4869. * @example
  4870. * ```javascript
  4871. * node.getStyle('font-size');
  4872. * ```
  4873. */
  4874. getStyle:function (name) {
  4875. var cssStyle = this.getAttr('style');
  4876. if (!cssStyle) {
  4877. return ''
  4878. }
  4879. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  4880. var match = cssStyle.match(reg);
  4881. if (match && match[0]) {
  4882. return match[2]
  4883. }
  4884. return '';
  4885. },
  4886. /**
  4887. * 给节点设置样式
  4888. * @method setStyle
  4889. * @param { String } name 要设置的的样式名称
  4890. * @param { String } val 要设置的的样值
  4891. * @example
  4892. * ```javascript
  4893. * node.setStyle('font-size', '12px');
  4894. * ```
  4895. */
  4896. setStyle:function (name, val) {
  4897. function exec(name, val) {
  4898. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  4899. cssStyle = cssStyle.replace(reg, '$1');
  4900. if (val) {
  4901. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  4902. }
  4903. }
  4904. var cssStyle = this.getAttr('style');
  4905. if (!cssStyle) {
  4906. cssStyle = '';
  4907. }
  4908. if (utils.isObject(name)) {
  4909. for (var a in name) {
  4910. exec(a, name[a])
  4911. }
  4912. } else {
  4913. exec(name, val)
  4914. }
  4915. this.setAttr('style', utils.trim(cssStyle))
  4916. },
  4917. hasClass: function( className ){
  4918. if( this.hasAttr('class') ) {
  4919. var classNames = this.getAttr('class').split(/\s+/),
  4920. hasClass = false;
  4921. $.each(classNames, function(key, item){
  4922. if( item === className ) {
  4923. hasClass = true;
  4924. }
  4925. });
  4926. return hasClass;
  4927. } else {
  4928. return false;
  4929. }
  4930. },
  4931. addClass: function( className ){
  4932. var classes = null,
  4933. hasClass = false;
  4934. if( this.hasAttr('class') ) {
  4935. classes = this.getAttr('class');
  4936. classes = classes.split(/\s+/);
  4937. classes.forEach( function( item ){
  4938. if( item===className ) {
  4939. hasClass = true;
  4940. return;
  4941. }
  4942. } );
  4943. !hasClass && classes.push( className );
  4944. this.setAttr('class', classes.join(" "));
  4945. } else {
  4946. this.setAttr('class', className);
  4947. }
  4948. },
  4949. removeClass: function( className ){
  4950. if( this.hasAttr('class') ) {
  4951. var cl = this.getAttr('class');
  4952. cl = cl.replace(new RegExp('\\b' + className + '\\b', 'g'),'');
  4953. this.setAttr('class', utils.trim(cl).replace(/[ ]{2,}/g,' '));
  4954. }
  4955. },
  4956. /**
  4957. * 传入一个函数,递归遍历当前节点下的所有节点
  4958. * @method traversal
  4959. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  4960. * @example
  4961. * ```javascript
  4962. * traversal(node, function(){
  4963. * console.log(node.type);
  4964. * });
  4965. * ```
  4966. */
  4967. traversal:function(fn){
  4968. if(this.children && this.children.length){
  4969. nodeTraversal(this,fn);
  4970. }
  4971. return this;
  4972. }
  4973. }
  4974. })();
  4975. //html字符串转换成uNode节点
  4976. //by zhanyi
  4977. var htmlparser = UM.htmlparser = function (htmlstr,ignoreBlank) {
  4978. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  4979. //先去掉了,加上的原因忘了,这里先记录
  4980. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  4981. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  4982. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  4983. var allowEmptyTags = {
  4984. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  4985. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  4986. };
  4987. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  4988. if(!ignoreBlank){
  4989. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  4990. //br暂时单独处理
  4991. if(b && allowEmptyTags[b.toLowerCase()]){
  4992. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  4993. }
  4994. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  4995. });
  4996. }
  4997. var notTransAttrs = {
  4998. 'href':1,
  4999. 'src':1
  5000. };
  5001. var uNode = UM.uNode,
  5002. needParentNode = {
  5003. 'td':'tr',
  5004. 'tr':['tbody','thead','tfoot'],
  5005. 'tbody':'table',
  5006. 'th':'tr',
  5007. 'thead':'table',
  5008. 'tfoot':'table',
  5009. 'caption':'table',
  5010. 'li':['ul', 'ol'],
  5011. 'dt':'dl',
  5012. 'dd':'dl',
  5013. 'option':'select'
  5014. },
  5015. needChild = {
  5016. 'ol':'li',
  5017. 'ul':'li'
  5018. };
  5019. function text(parent, data) {
  5020. if(needChild[parent.tagName]){
  5021. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  5022. parent.appendChild(tmpNode);
  5023. tmpNode.appendChild(uNode.createText(data));
  5024. parent = tmpNode;
  5025. }else{
  5026. parent.appendChild(uNode.createText(data));
  5027. }
  5028. }
  5029. function element(parent, tagName, htmlattr) {
  5030. var needParentTag;
  5031. if (needParentTag = needParentNode[tagName]) {
  5032. var tmpParent = parent,hasParent;
  5033. while(tmpParent.type != 'root'){
  5034. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  5035. parent = tmpParent;
  5036. hasParent = true;
  5037. break;
  5038. }
  5039. tmpParent = tmpParent.parentNode;
  5040. }
  5041. if(!hasParent){
  5042. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  5043. }
  5044. }
  5045. //按dtd处理嵌套
  5046. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  5047. // parent = parent.parentNode;
  5048. var elm = new uNode({
  5049. parentNode:parent,
  5050. type:'element',
  5051. tagName:tagName.toLowerCase(),
  5052. //是自闭合的处理一下
  5053. children:dtd.$empty[tagName] ? null : []
  5054. });
  5055. //如果属性存在,处理属性
  5056. if (htmlattr) {
  5057. var attrs = {}, match;
  5058. while (match = re_attr.exec(htmlattr)) {
  5059. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  5060. }
  5061. elm.attrs = attrs;
  5062. }
  5063. parent.children.push(elm);
  5064. //如果是自闭合节点返回父亲节点
  5065. return dtd.$empty[tagName] ? parent : elm
  5066. }
  5067. function comment(parent, data) {
  5068. parent.children.push(new uNode({
  5069. type:'comment',
  5070. data:data,
  5071. parentNode:parent
  5072. }));
  5073. }
  5074. var match, currentIndex = 0, nextIndex = 0;
  5075. //设置根节点
  5076. var root = new uNode({
  5077. type:'root',
  5078. children:[]
  5079. });
  5080. var currentParent = root;
  5081. while (match = re_tag.exec(htmlstr)) {
  5082. currentIndex = match.index;
  5083. try{
  5084. if (currentIndex > nextIndex) {
  5085. //text node
  5086. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  5087. }
  5088. if (match[3]) {
  5089. if(dtd.$cdata[currentParent.tagName]){
  5090. text(currentParent, match[0]);
  5091. }else{
  5092. //start tag
  5093. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  5094. }
  5095. } else if (match[1]) {
  5096. if(currentParent.type != 'root'){
  5097. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  5098. text(currentParent, match[0]);
  5099. }else{
  5100. var tmpParent = currentParent;
  5101. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  5102. currentParent = currentParent.parentNode;
  5103. if(currentParent.type == 'root'){
  5104. currentParent = tmpParent;
  5105. throw 'break'
  5106. }
  5107. }
  5108. //end tag
  5109. currentParent = currentParent.parentNode;
  5110. }
  5111. }
  5112. } else if (match[2]) {
  5113. //comment
  5114. comment(currentParent, match[2])
  5115. }
  5116. }catch(e){}
  5117. nextIndex = re_tag.lastIndex;
  5118. }
  5119. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  5120. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  5121. if (nextIndex < htmlstr.length) {
  5122. text(currentParent, htmlstr.slice(nextIndex));
  5123. }
  5124. return root;
  5125. };
  5126. /**
  5127. * @file
  5128. * @name UM.filterNode
  5129. * @short filterNode
  5130. * @desc 根据给定的规则过滤节点
  5131. * @import editor.js,core/utils.js
  5132. * @anthor zhanyi
  5133. */
  5134. var filterNode = UM.filterNode = function () {
  5135. function filterNode(node,rules){
  5136. switch (node.type) {
  5137. case 'text':
  5138. break;
  5139. case 'element':
  5140. var val;
  5141. if(val = rules[node.tagName]){
  5142. if(val === '-'){
  5143. node.parentNode.removeChild(node)
  5144. }else if(utils.isFunction(val)){
  5145. var parentNode = node.parentNode,
  5146. index = node.getIndex();
  5147. val(node);
  5148. if(node.parentNode){
  5149. if(node.children){
  5150. for(var i = 0,ci;ci=node.children[i];){
  5151. filterNode(ci,rules);
  5152. if(ci.parentNode){
  5153. i++;
  5154. }
  5155. }
  5156. }
  5157. }else{
  5158. for(var i = index,ci;ci=parentNode.children[i];){
  5159. filterNode(ci,rules);
  5160. if(ci.parentNode){
  5161. i++;
  5162. }
  5163. }
  5164. }
  5165. }else{
  5166. var attrs = val['$'];
  5167. if(attrs && node.attrs){
  5168. var tmpAttrs = {},tmpVal;
  5169. for(var a in attrs){
  5170. tmpVal = node.getAttr(a);
  5171. //todo 只先对style单独处理
  5172. if(a == 'style' && utils.isArray(attrs[a])){
  5173. var tmpCssStyle = [];
  5174. utils.each(attrs[a],function(v){
  5175. var tmp;
  5176. if(tmp = node.getStyle(v)){
  5177. tmpCssStyle.push(v + ':' + tmp);
  5178. }
  5179. });
  5180. tmpVal = tmpCssStyle.join(';')
  5181. }
  5182. if(tmpVal){
  5183. tmpAttrs[a] = tmpVal;
  5184. }
  5185. }
  5186. node.attrs = tmpAttrs;
  5187. }
  5188. if(node.children){
  5189. for(var i = 0,ci;ci=node.children[i];){
  5190. filterNode(ci,rules);
  5191. if(ci.parentNode){
  5192. i++;
  5193. }
  5194. }
  5195. }
  5196. }
  5197. }else{
  5198. //如果不在名单里扣出子节点并删除该节点,cdata除外
  5199. if(dtd.$cdata[node.tagName]){
  5200. node.parentNode.removeChild(node)
  5201. }else{
  5202. var parentNode = node.parentNode,
  5203. index = node.getIndex();
  5204. node.parentNode.removeChild(node,true);
  5205. for(var i = index,ci;ci=parentNode.children[i];){
  5206. filterNode(ci,rules);
  5207. if(ci.parentNode){
  5208. i++;
  5209. }
  5210. }
  5211. }
  5212. }
  5213. break;
  5214. case 'comment':
  5215. node.parentNode.removeChild(node)
  5216. }
  5217. }
  5218. return function(root,rules){
  5219. if(utils.isEmptyObject(rules)){
  5220. return root;
  5221. }
  5222. var val;
  5223. if(val = rules['-']){
  5224. utils.each(val.split(' '),function(k){
  5225. rules[k] = '-'
  5226. })
  5227. }
  5228. for(var i= 0,ci;ci=root.children[i];){
  5229. filterNode(ci,rules);
  5230. if(ci.parentNode){
  5231. i++;
  5232. }
  5233. }
  5234. return root;
  5235. }
  5236. }();
  5237. ///import core
  5238. /**
  5239. * @description 插入内容
  5240. * @name baidu.editor.execCommand
  5241. * @param {String} cmdName inserthtml插入内容的命令
  5242. * @param {String} html 要插入的内容
  5243. * @author zhanyi
  5244. */
  5245. UM.commands['inserthtml'] = {
  5246. execCommand: function (command,html,notNeedFilter){
  5247. var me = this,
  5248. range,
  5249. div;
  5250. if(!html){
  5251. return;
  5252. }
  5253. if(me.fireEvent('beforeinserthtml',html) === true){
  5254. return;
  5255. }
  5256. range = me.selection.getRange();
  5257. div = range.document.createElement( 'div' );
  5258. div.style.display = 'inline';
  5259. if (!notNeedFilter) {
  5260. var root = UM.htmlparser(html);
  5261. //如果给了过滤规则就先进行过滤
  5262. if(me.options.filterRules){
  5263. UM.filterNode(root,me.options.filterRules);
  5264. }
  5265. //执行默认的处理
  5266. me.filterInputRule(root);
  5267. html = root.toHtml()
  5268. }
  5269. div.innerHTML = utils.trim( html );
  5270. if ( !range.collapsed ) {
  5271. var tmpNode = range.startContainer;
  5272. if(domUtils.isFillChar(tmpNode)){
  5273. range.setStartBefore(tmpNode)
  5274. }
  5275. tmpNode = range.endContainer;
  5276. if(domUtils.isFillChar(tmpNode)){
  5277. range.setEndAfter(tmpNode)
  5278. }
  5279. range.txtToElmBoundary();
  5280. //结束边界可能放到了br的前边,要把br包含进来
  5281. // x[xxx]<br/>
  5282. if(range.endContainer && range.endContainer.nodeType == 1){
  5283. tmpNode = range.endContainer.childNodes[range.endOffset];
  5284. if(tmpNode && domUtils.isBr(tmpNode)){
  5285. range.setEndAfter(tmpNode);
  5286. }
  5287. }
  5288. if(range.startOffset == 0){
  5289. tmpNode = range.startContainer;
  5290. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  5291. tmpNode = range.endContainer;
  5292. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  5293. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  5294. range.setStart(me.body.firstChild,0).collapse(true)
  5295. }
  5296. }
  5297. }
  5298. !range.collapsed && range.deleteContents();
  5299. if(range.startContainer.nodeType == 1){
  5300. var child = range.startContainer.childNodes[range.startOffset],pre;
  5301. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  5302. range.setEnd(pre,pre.childNodes.length).collapse();
  5303. while(child.firstChild){
  5304. pre.appendChild(child.firstChild);
  5305. }
  5306. domUtils.remove(child);
  5307. }
  5308. }
  5309. }
  5310. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  5311. //如果当前位置选中了fillchar要干掉,要不会产生空行
  5312. if(range.inFillChar()){
  5313. child = range.startContainer;
  5314. if(domUtils.isFillChar(child)){
  5315. range.setStartBefore(child).collapse(true);
  5316. domUtils.remove(child);
  5317. }else if(domUtils.isFillChar(child,true)){
  5318. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  5319. range.startOffset--;
  5320. range.collapsed && range.collapse(true)
  5321. }
  5322. }
  5323. while ( child = div.firstChild ) {
  5324. if(hadBreak){
  5325. var p = me.document.createElement('p');
  5326. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  5327. nextNode = child.nextSibling;
  5328. p.appendChild(child);
  5329. child = nextNode;
  5330. }
  5331. if(p.firstChild){
  5332. child = p
  5333. }
  5334. }
  5335. range.insertNode( child );
  5336. nextNode = child.nextSibling;
  5337. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  5338. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  5339. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  5340. if(!dtd[parent.tagName][child.nodeName]){
  5341. pre = parent;
  5342. }else{
  5343. tmp = child.parentNode;
  5344. while (tmp !== parent){
  5345. pre = tmp;
  5346. tmp = tmp.parentNode;
  5347. }
  5348. }
  5349. domUtils.breakParent( child, pre || tmp );
  5350. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  5351. var pre = child.previousSibling;
  5352. domUtils.trimWhiteTextNode(pre);
  5353. if(!pre.childNodes.length){
  5354. domUtils.remove(pre);
  5355. }
  5356. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  5357. if(!browser.ie &&
  5358. (next = child.nextSibling) &&
  5359. domUtils.isBlockElm(next) &&
  5360. next.lastChild &&
  5361. !domUtils.isBr(next.lastChild)){
  5362. next.appendChild(me.document.createElement('br'));
  5363. }
  5364. hadBreak = 1;
  5365. }
  5366. }
  5367. var next = child.nextSibling;
  5368. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  5369. range.setStart(next,0).collapse(true);
  5370. break;
  5371. }
  5372. range.setEndAfter( child ).collapse();
  5373. }
  5374. child = range.startContainer;
  5375. if(nextNode && domUtils.isBr(nextNode)){
  5376. domUtils.remove(nextNode)
  5377. }
  5378. //用chrome可能有空白展位符
  5379. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  5380. if(nextNode = child.nextSibling){
  5381. domUtils.remove(child);
  5382. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  5383. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  5384. }
  5385. }else{
  5386. try{
  5387. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  5388. }catch(e){
  5389. range.setStartBefore(child);
  5390. domUtils.remove(child)
  5391. }
  5392. }
  5393. }
  5394. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  5395. try{
  5396. if(browser.ie9below && range.startContainer.nodeType == 1 && !range.startContainer.childNodes[range.startOffset]){
  5397. var start = range.startContainer,pre = start.childNodes[range.startOffset-1];
  5398. if(pre && pre.nodeType == 1 && dtd.$empty[pre.tagName]){
  5399. var txt = this.document.createTextNode(domUtils.fillChar);
  5400. range.insertNode(txt).setStart(txt,0).collapse(true);
  5401. }
  5402. }
  5403. setTimeout(function(){
  5404. range.select(true);
  5405. })
  5406. }catch(e){}
  5407. setTimeout(function(){
  5408. range = me.selection.getRange();
  5409. range.scrollIntoView();
  5410. me.fireEvent('afterinserthtml');
  5411. },200);
  5412. }
  5413. };
  5414. ///import core
  5415. ///import plugins\inserthtml.js
  5416. ///commands 插入图片,操作图片的对齐方式
  5417. ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter
  5418. ///commandsTitle 图片,默认,居左,居右,居中
  5419. ///commandsDialog dialogs\image
  5420. /**
  5421. * Created by .
  5422. * User: zhanyi
  5423. * for image
  5424. */
  5425. UM.commands['insertimage'] = {
  5426. execCommand:function (cmd, opt) {
  5427. opt = utils.isArray(opt) ? opt : [opt];
  5428. if (!opt.length) {
  5429. return;
  5430. }
  5431. var me = this;
  5432. var html = [], str = '', ci;
  5433. ci = opt[0];
  5434. if (opt.length == 1) {
  5435. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  5436. (ci.width ? 'width="' + ci.width + '" ' : '') +
  5437. (ci.height ? ' height="' + ci.height + '" ' : '') +
  5438. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  5439. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  5440. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  5441. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  5442. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  5443. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  5444. if (ci['floatStyle'] == 'center') {
  5445. str = '<p style="text-align: center">' + str + '</p>';
  5446. }
  5447. html.push(str);
  5448. } else {
  5449. for (var i = 0; ci = opt[i++];) {
  5450. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  5451. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  5452. (ci.height ? ' height="' + ci.height + '" ' : '') +
  5453. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  5454. (ci.border || '') + '" ' +
  5455. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  5456. html.push(str);
  5457. }
  5458. }
  5459. me.execCommand('insertHtml', html.join(''), true);
  5460. }
  5461. };
  5462. ///import core
  5463. ///commands 段落格式,居左,居右,居中,两端对齐
  5464. ///commandsName JustifyLeft,JustifyCenter,JustifyRight,JustifyJustify
  5465. ///commandsTitle 居左对齐,居中对齐,居右对齐,两端对齐
  5466. /**
  5467. * @description 居左右中
  5468. * @name UM.execCommand
  5469. * @param {String} cmdName justify执行对齐方式的命令
  5470. * @param {String} align 对齐方式:left居左,right居右,center居中,justify两端对齐
  5471. * @author zhanyi
  5472. */
  5473. UM.plugins['justify']=function(){
  5474. var me = this;
  5475. $.each('justifyleft justifyright justifycenter justifyfull'.split(' '),function(i,cmdName){
  5476. me.commands[cmdName] = {
  5477. execCommand:function (cmdName) {
  5478. return this.document.execCommand(cmdName);
  5479. },
  5480. queryCommandValue: function (cmdName) {
  5481. var val = this.document.queryCommandValue(cmdName);
  5482. return val === true || val === 'true' ? cmdName.replace(/justify/,'') : '';
  5483. },
  5484. queryCommandState: function (cmdName) {
  5485. return this.document.queryCommandState(cmdName) ? 1 : 0
  5486. }
  5487. };
  5488. })
  5489. };
  5490. ///import core
  5491. ///import plugins\removeformat.js
  5492. ///commands 字体颜色,背景色,字号,字体,下划线,删除线
  5493. ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough
  5494. ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线
  5495. /**
  5496. * @description 字体
  5497. * @name UM.execCommand
  5498. * @param {String} cmdName 执行的功能名称
  5499. * @param {String} value 传入的值
  5500. */
  5501. UM.plugins['font'] = function () {
  5502. var me = this,
  5503. fonts = {
  5504. 'forecolor': 'forecolor',
  5505. 'backcolor': 'backcolor',
  5506. 'fontsize': 'fontsize',
  5507. 'fontfamily': 'fontname'
  5508. },
  5509. cmdNameToStyle = {
  5510. 'forecolor': 'color',
  5511. 'backcolor': 'background-color',
  5512. 'fontsize': 'font-size',
  5513. 'fontfamily': 'font-family'
  5514. },
  5515. cmdNameToAttr = {
  5516. 'forecolor': 'color',
  5517. 'fontsize': 'size',
  5518. 'fontfamily': 'face'
  5519. };
  5520. me.setOpt({
  5521. 'fontfamily': [
  5522. { name: 'songti', val: '宋体,SimSun'},
  5523. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  5524. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  5525. { name: 'heiti', val: '黑体, SimHei'},
  5526. { name: 'lishu', val: '隶书, SimLi'},
  5527. { name: 'andaleMono', val: 'andale mono'},
  5528. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  5529. { name: 'arialBlack', val: 'arial black,avant garde'},
  5530. { name: 'comicSansMs', val: 'comic sans ms'},
  5531. { name: 'impact', val: 'impact,chicago'},
  5532. { name: 'timesNewRoman', val: 'times new roman'},
  5533. { name: 'sans-serif',val:'sans-serif'}
  5534. ],
  5535. 'fontsize': [10, 12, 16, 18,24, 32,48]
  5536. });
  5537. me.addOutputRule(function (root) {
  5538. utils.each(root.getNodesByTagName('font'), function (node) {
  5539. if (node.tagName == 'font') {
  5540. var cssStyle = [];
  5541. for (var p in node.attrs) {
  5542. switch (p) {
  5543. case 'size':
  5544. var val = node.attrs[p];
  5545. $.each({
  5546. '10':'1',
  5547. '12':'2',
  5548. '16':'3',
  5549. '18':'4',
  5550. '24':'5',
  5551. '32':'6',
  5552. '48':'7'
  5553. },function(k,v){
  5554. if(v == val){
  5555. val = k;
  5556. return false;
  5557. }
  5558. });
  5559. cssStyle.push('font-size:' + val + 'px');
  5560. break;
  5561. case 'color':
  5562. cssStyle.push('color:' + node.attrs[p]);
  5563. break;
  5564. case 'face':
  5565. cssStyle.push('font-family:' + node.attrs[p]);
  5566. break;
  5567. case 'style':
  5568. cssStyle.push(node.attrs[p]);
  5569. }
  5570. }
  5571. node.attrs = {
  5572. 'style': cssStyle.join(';')
  5573. };
  5574. }
  5575. node.tagName = 'span';
  5576. if(node.parentNode.tagName == 'span' && node.parentNode.children.length == 1){
  5577. $.each(node.attrs,function(k,v){
  5578. node.parentNode.attrs[k] = k == 'style' ? node.parentNode.attrs[k] + v : v;
  5579. })
  5580. node.parentNode.removeChild(node,true);
  5581. }
  5582. });
  5583. });
  5584. for(var p in fonts){
  5585. (function (cmd) {
  5586. me.commands[cmd] = {
  5587. execCommand: function (cmdName,value) {
  5588. if(value == 'transparent'){
  5589. return;
  5590. }
  5591. var rng = this.selection.getRange();
  5592. if(rng.collapsed){
  5593. var span = $('<span></span>').css(cmdNameToStyle[cmdName],value)[0];
  5594. rng.insertNode(span).setStart(span,0).setCursor();
  5595. }else{
  5596. if(cmdName == 'fontsize'){
  5597. value = {
  5598. '10':'1',
  5599. '12':'2',
  5600. '16':'3',
  5601. '18':'4',
  5602. '24':'5',
  5603. '32':'6',
  5604. '48':'7'
  5605. }[(value+"").replace(/px/,'')]
  5606. }
  5607. this.document.execCommand(fonts[cmdName],false, value);
  5608. if(browser.gecko){
  5609. $.each(this.$body.find('a'),function(i,a){
  5610. var parent = a.parentNode;
  5611. if(parent.lastChild === parent.firstChild && /FONT|SPAN/.test(parent.tagName)){
  5612. var cloneNode = parent.cloneNode(false);
  5613. cloneNode.innerHTML = a.innerHTML;
  5614. $(a).html('').append(cloneNode).insertBefore(parent);
  5615. $(parent).remove();
  5616. }
  5617. });
  5618. }
  5619. if(!browser.ie){
  5620. var nativeRange = this.selection.getNative().getRangeAt(0);
  5621. var common = nativeRange.commonAncestorContainer;
  5622. var rng = this.selection.getRange(),
  5623. bk = rng.createBookmark(true);
  5624. $(common).find('a').each(function(i,n){
  5625. var parent = n.parentNode;
  5626. if(parent.nodeName == 'FONT'){
  5627. var font = parent.cloneNode(false);
  5628. font.innerHTML = n.innerHTML;
  5629. $(n).html('').append(font);
  5630. }
  5631. });
  5632. rng.moveToBookmark(bk).select()
  5633. }
  5634. return true
  5635. }
  5636. },
  5637. queryCommandValue: function (cmdName) {
  5638. var start = me.selection.getStart();
  5639. var val = $(start).css(cmdNameToStyle[cmdName]);
  5640. if(val === undefined){
  5641. val = $(start).attr(cmdNameToAttr[cmdName])
  5642. }
  5643. return val ? utils.fixColor(cmdName,val).replace(/px/,'') : '';
  5644. },
  5645. queryCommandState: function (cmdName) {
  5646. return this.queryCommandValue(cmdName)
  5647. }
  5648. };
  5649. })(p);
  5650. }
  5651. };
  5652. ///import core
  5653. ///commands 超链接,取消链接
  5654. ///commandsName Link,Unlink
  5655. ///commandsTitle 超链接,取消链接
  5656. ///commandsDialog dialogs\link
  5657. /**
  5658. * 超链接
  5659. * @function
  5660. * @name UM.execCommand
  5661. * @param {String} cmdName link插入超链接
  5662. * @param {Object} options url地址,title标题,target是否打开新页
  5663. * @author zhanyi
  5664. */
  5665. /**
  5666. * 取消链接
  5667. * @function
  5668. * @name UM.execCommand
  5669. * @param {String} cmdName unlink取消链接
  5670. * @author zhanyi
  5671. */
  5672. UM.plugins['link'] = function(){
  5673. var me = this;
  5674. me.setOpt('autourldetectinie',false);
  5675. //在ie下禁用autolink
  5676. if(browser.ie && this.options.autourldetectinie === false){
  5677. this.addListener('keyup',function(cmd,evt){
  5678. var me = this,keyCode = evt.keyCode;
  5679. if(keyCode == 13 || keyCode == 32){
  5680. var rng = me.selection.getRange();
  5681. var start = rng.startContainer;
  5682. if(keyCode == 13){
  5683. if(start.nodeName == 'P'){
  5684. var pre = start.previousSibling;
  5685. if(pre && pre.nodeType == 1){
  5686. var pre = pre.lastChild;
  5687. if(pre && pre.nodeName == 'A' && !pre.getAttribute('_href')){
  5688. domUtils.remove(pre,true);
  5689. }
  5690. }
  5691. }
  5692. }else if(keyCode == 32){
  5693. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  5694. start = start.previousSibling;
  5695. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  5696. domUtils.remove(start,true);
  5697. }
  5698. }
  5699. }
  5700. }
  5701. });
  5702. }
  5703. this.addOutputRule(function(root){
  5704. $.each(root.getNodesByTagName('a'),function(i,a){
  5705. var _href = a.getAttr('_href');
  5706. if(!/^(ftp|https?|\/|file)/.test(_href)){
  5707. _href = 'http://' + _href;
  5708. }
  5709. a.setAttr('href', _href);
  5710. a.setAttr('_href')
  5711. if(a.getAttr('title')==''){
  5712. a.setAttr('title')
  5713. }
  5714. })
  5715. });
  5716. this.addInputRule(function(root){
  5717. $.each(root.getNodesByTagName('a'),function(i,a){
  5718. a.setAttr('_href', a.getAttr('href'));
  5719. })
  5720. });
  5721. me.commands['link'] = {
  5722. execCommand : function( cmdName, opt ) {
  5723. var me = this;
  5724. var rng = me.selection.getRange();
  5725. opt._href && (opt._href = utils.unhtml(opt._href, /[<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g));
  5726. opt.href && (opt.href = utils.unhtml(opt.href, /[<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g));
  5727. if(rng.collapsed){
  5728. var start = rng.startContainer;
  5729. if(start = domUtils.findParentByTagName(start,'a',true)){
  5730. $(start).attr(opt);
  5731. rng.selectNode(start).select()
  5732. }else{
  5733. rng.insertNode($('<a>' + opt.href +'</a>').attr(opt)[0]).select()
  5734. }
  5735. }else{
  5736. me.document.execCommand('createlink',false,'_umeditor_link');
  5737. utils.each(domUtils.getElementsByTagName(me.body,'a',function(n){
  5738. return n.getAttribute('href') == '_umeditor_link'
  5739. }),function(l){
  5740. if($(l).text() == '_umeditor_link'){
  5741. $(l).text(opt.href);
  5742. }
  5743. domUtils.setAttributes(l,opt);
  5744. rng.selectNode(l).select()
  5745. })
  5746. }
  5747. },
  5748. queryCommandState:function(){
  5749. return this.queryCommandValue('link') ? 1 : 0;
  5750. },
  5751. queryCommandValue:function(){
  5752. var path = this.selection.getStartElementPath();
  5753. var result;
  5754. $.each(path,function(i,n){
  5755. if(n.nodeName == "A"){
  5756. result = n;
  5757. return false;
  5758. }
  5759. })
  5760. return result;
  5761. }
  5762. };
  5763. me.commands['unlink'] = {
  5764. execCommand : function() {
  5765. this.document.execCommand('unlink');
  5766. }
  5767. };
  5768. };
  5769. ///import core
  5770. ///commands 打印
  5771. ///commandsName Print
  5772. ///commandsTitle 打印
  5773. /**
  5774. * @description 打印
  5775. * @name baidu.editor.execCommand
  5776. * @param {String} cmdName print打印编辑器内容
  5777. * @author zhanyi
  5778. */
  5779. UM.commands['print'] = {
  5780. execCommand : function(){
  5781. var me = this,
  5782. id = 'editor_print_' + +new Date();
  5783. $('<iframe src="" id="' + id + '" name="' + id + '" frameborder="0"></iframe>').attr('id', id)
  5784. .css({
  5785. width:'0px',
  5786. height:'0px',
  5787. 'overflow':'hidden',
  5788. 'float':'left',
  5789. 'position':'absolute',
  5790. top:'-10000px',
  5791. left:'-10000px'
  5792. })
  5793. .appendTo(me.$container.find('.edui-dialog-container'));
  5794. var w = window.open('', id, ''),
  5795. d = w.document;
  5796. d.open();
  5797. d.write('<html><head></head><body><div>'+this.getContent(null,null,true)+'</div><script>' +
  5798. "setTimeout(function(){" +
  5799. "window.print();" +
  5800. "setTimeout(function(){" +
  5801. "window.parent.$('#" + id + "').remove();" +
  5802. "},100);" +
  5803. "},200);" +
  5804. '</script></body></html>');
  5805. d.close();
  5806. },
  5807. notNeedUndo : 1
  5808. };
  5809. ///import core
  5810. ///commands 格式
  5811. ///commandsName Paragraph
  5812. ///commandsTitle 段落格式
  5813. /**
  5814. * 段落样式
  5815. * @function
  5816. * @name UM.execCommand
  5817. * @param {String} cmdName paragraph插入段落执行命令
  5818. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  5819. * @param {String} attrs 标签的属性
  5820. * @author zhanyi
  5821. */
  5822. UM.plugins['paragraph'] = function() {
  5823. var me = this;
  5824. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  5825. me.commands['paragraph'] = {
  5826. execCommand : function( cmdName, style ) {
  5827. return this.document.execCommand('formatBlock',false,'<' + style + '>');
  5828. },
  5829. queryCommandValue : function() {
  5830. try{
  5831. var val = this.document.queryCommandValue('formatBlock')
  5832. }catch(e){
  5833. }
  5834. return val ;
  5835. }
  5836. };
  5837. };
  5838. ///import core
  5839. ///import plugins\inserthtml.js
  5840. ///commands 分割线
  5841. ///commandsName Horizontal
  5842. ///commandsTitle 分隔线
  5843. /**
  5844. * 分割线
  5845. * @function
  5846. * @name UM.execCommand
  5847. * @param {String} cmdName horizontal插入分割线
  5848. */
  5849. UM.plugins['horizontal'] = function(){
  5850. var me = this;
  5851. me.commands['horizontal'] = {
  5852. execCommand : function( ) {
  5853. this.document.execCommand('insertHorizontalRule');
  5854. var rng = me.selection.getRange().txtToElmBoundary(true),
  5855. start = rng.startContainer;
  5856. if(domUtils.isBody(rng.startContainer)){
  5857. var next = rng.startContainer.childNodes[rng.startOffset];
  5858. if(!next){
  5859. next = $('<p></p>').appendTo(rng.startContainer).html(browser.ie ? '&nbsp;' : '<br/>')[0]
  5860. }
  5861. rng.setStart(next,0).setCursor()
  5862. }else{
  5863. while(dtd.$inline[start.tagName] && start.lastChild === start.firstChild){
  5864. var parent = start.parentNode;
  5865. parent.appendChild(start.firstChild);
  5866. parent.removeChild(start);
  5867. start = parent;
  5868. }
  5869. while(dtd.$inline[start.tagName]){
  5870. start = start.parentNode;
  5871. }
  5872. if(start.childNodes.length == 1 && start.lastChild.nodeName == 'HR'){
  5873. var hr = start.lastChild;
  5874. $(hr).insertBefore(start);
  5875. rng.setStart(start,0).setCursor();
  5876. }else{
  5877. hr = $('hr',start)[0];
  5878. domUtils.breakParent(hr,start);
  5879. var pre = hr.previousSibling;
  5880. if(pre && domUtils.isEmptyBlock(pre)){
  5881. $(pre).remove()
  5882. }
  5883. rng.setStart(hr.nextSibling,0).setCursor();
  5884. }
  5885. }
  5886. }
  5887. };
  5888. };
  5889. ///import core
  5890. ///commands 清空文档
  5891. ///commandsName ClearDoc
  5892. ///commandsTitle 清空文档
  5893. /**
  5894. *
  5895. * 清空文档
  5896. * @function
  5897. * @name UM.execCommand
  5898. * @param {String} cmdName cleardoc清空文档
  5899. */
  5900. UM.commands['cleardoc'] = {
  5901. execCommand : function() {
  5902. var me = this,
  5903. range = me.selection.getRange();
  5904. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  5905. range.setStart(me.body.firstChild,0).setCursor(false,true);
  5906. setTimeout(function(){
  5907. me.fireEvent("clearDoc");
  5908. },0);
  5909. }
  5910. };
  5911. ///import core
  5912. ///commands 撤销和重做
  5913. ///commandsName Undo,Redo
  5914. ///commandsTitle 撤销,重做
  5915. /**
  5916. * @description 回退
  5917. * @author zhanyi
  5918. */
  5919. UM.plugins['undo'] = function () {
  5920. var saveSceneTimer;
  5921. var me = this,
  5922. maxUndoCount = me.options.maxUndoCount || 20,
  5923. maxInputCount = me.options.maxInputCount || 20,
  5924. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  5925. var noNeedFillCharTags = {
  5926. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  5927. };
  5928. var orgState = me.options.autoClearEmptyNode;
  5929. function compareAddr(indexA, indexB) {
  5930. if (indexA.length != indexB.length)
  5931. return 0;
  5932. for (var i = 0, l = indexA.length; i < l; i++) {
  5933. if (indexA[i] != indexB[i])
  5934. return 0
  5935. }
  5936. return 1;
  5937. }
  5938. function compareRangeAddress(rngAddrA, rngAddrB) {
  5939. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  5940. return 0;
  5941. }
  5942. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  5943. return 0;
  5944. }
  5945. return 1;
  5946. }
  5947. function UndoManager() {
  5948. this.list = [];
  5949. this.index = 0;
  5950. this.hasUndo = false;
  5951. this.hasRedo = false;
  5952. this.undo = function () {
  5953. if (this.hasUndo) {
  5954. if (!this.list[this.index - 1] && this.list.length == 1) {
  5955. this.reset();
  5956. return;
  5957. }
  5958. while (this.list[this.index].content == this.list[this.index - 1].content) {
  5959. this.index--;
  5960. if (this.index == 0) {
  5961. return this.restore(0);
  5962. }
  5963. }
  5964. this.restore(--this.index);
  5965. }
  5966. };
  5967. this.redo = function () {
  5968. if (this.hasRedo) {
  5969. while (this.list[this.index].content == this.list[this.index + 1].content) {
  5970. this.index++;
  5971. if (this.index == this.list.length - 1) {
  5972. return this.restore(this.index);
  5973. }
  5974. }
  5975. this.restore(++this.index);
  5976. }
  5977. };
  5978. this.restore = function () {
  5979. var me = this.editor;
  5980. var scene = this.list[this.index];
  5981. var root = UM.htmlparser(scene.content.replace(fillchar, ''));
  5982. me.options.autoClearEmptyNode = false;
  5983. me.filterInputRule(root,true);
  5984. me.options.autoClearEmptyNode = orgState;
  5985. //trace:873
  5986. //去掉展位符
  5987. me.body.innerHTML = root.toHtml();
  5988. me.fireEvent('afterscencerestore');
  5989. //处理undo后空格不展位的问题
  5990. if (browser.ie) {
  5991. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  5992. if(domUtils.isEmptyNode(node)){
  5993. domUtils.fillNode(me.document, node);
  5994. }
  5995. })
  5996. }
  5997. try{
  5998. var rng = new dom.Range(me.document,me.body).moveToAddress(scene.address);
  5999. if(browser.ie && rng.collapsed && rng.startContainer.nodeType == 1){
  6000. var tmpNode = rng.startContainer.childNodes[rng.startOffset];
  6001. if( !tmpNode || tmpNode.nodeType == 1 && dtd.$empty[tmpNode]){
  6002. rng.insertNode(me.document.createTextNode(' ')).collapse(true);
  6003. }
  6004. }
  6005. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  6006. }catch(e){}
  6007. this.update();
  6008. this.clearKey();
  6009. //不能把自己reset了
  6010. me.fireEvent('reset', true);
  6011. };
  6012. this.getScene = function () {
  6013. var me = this.editor;
  6014. var rng = me.selection.getRange(),
  6015. rngAddress = rng.createAddress(false,true);
  6016. me.fireEvent('beforegetscene');
  6017. var root = UM.htmlparser(me.body.innerHTML,true);
  6018. me.options.autoClearEmptyNode = false;
  6019. me.filterOutputRule(root,true);
  6020. me.options.autoClearEmptyNode = orgState;
  6021. var cont = root.toHtml();
  6022. browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  6023. me.fireEvent('aftergetscene');
  6024. return {
  6025. address:rngAddress,
  6026. content:cont
  6027. }
  6028. };
  6029. this.save = function (notCompareRange,notSetCursor) {
  6030. clearTimeout(saveSceneTimer);
  6031. var currentScene = this.getScene(notSetCursor),
  6032. lastScene = this.list[this.index];
  6033. //内容相同位置相同不存
  6034. if (lastScene && lastScene.content == currentScene.content &&
  6035. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  6036. ) {
  6037. return;
  6038. }
  6039. this.list = this.list.slice(0, this.index + 1);
  6040. this.list.push(currentScene);
  6041. //如果大于最大数量了,就把最前的剔除
  6042. if (this.list.length > maxUndoCount) {
  6043. this.list.shift();
  6044. }
  6045. this.index = this.list.length - 1;
  6046. this.clearKey();
  6047. //跟新undo/redo状态
  6048. this.update();
  6049. };
  6050. this.update = function () {
  6051. this.hasRedo = !!this.list[this.index + 1];
  6052. this.hasUndo = !!this.list[this.index - 1];
  6053. };
  6054. this.reset = function () {
  6055. this.list = [];
  6056. this.index = 0;
  6057. this.hasUndo = false;
  6058. this.hasRedo = false;
  6059. this.clearKey();
  6060. };
  6061. this.clearKey = function () {
  6062. keycont = 0;
  6063. lastKeyCode = null;
  6064. };
  6065. }
  6066. me.undoManger = new UndoManager();
  6067. me.undoManger.editor = me;
  6068. function saveScene() {
  6069. this.undoManger.save();
  6070. }
  6071. me.addListener('saveScene', function () {
  6072. var args = Array.prototype.splice.call(arguments,1);
  6073. this.undoManger.save.apply(this.undoManger,args);
  6074. });
  6075. me.addListener('beforeexeccommand', saveScene);
  6076. me.addListener('afterexeccommand', saveScene);
  6077. me.addListener('reset', function (type, exclude) {
  6078. if (!exclude) {
  6079. this.undoManger.reset();
  6080. }
  6081. });
  6082. me.commands['redo'] = me.commands['undo'] = {
  6083. execCommand:function (cmdName) {
  6084. this.undoManger[cmdName]();
  6085. },
  6086. queryCommandState:function (cmdName) {
  6087. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  6088. },
  6089. notNeedUndo:1
  6090. };
  6091. var keys = {
  6092. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  6093. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  6094. 37:1, 38:1, 39:1, 40:1
  6095. },
  6096. keycont = 0,
  6097. lastKeyCode;
  6098. //输入法状态下不计算字符数
  6099. var inputType = false;
  6100. me.addListener('ready', function () {
  6101. $(this.body).on('compositionstart', function () {
  6102. inputType = true;
  6103. }).on('compositionend', function () {
  6104. inputType = false;
  6105. })
  6106. });
  6107. //快捷键
  6108. me.addshortcutkey({
  6109. "Undo":"ctrl+90", //undo
  6110. "Redo":"ctrl+89,shift+ctrl+z" //redo
  6111. });
  6112. var isCollapsed = true;
  6113. me.addListener('keydown', function (type, evt) {
  6114. var me = this;
  6115. var keyCode = evt.keyCode || evt.which;
  6116. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  6117. if (inputType)
  6118. return;
  6119. if(!me.selection.getRange().collapsed){
  6120. me.undoManger.save(false,true);
  6121. isCollapsed = false;
  6122. return;
  6123. }
  6124. if (me.undoManger.list.length == 0) {
  6125. me.undoManger.save(true);
  6126. }
  6127. clearTimeout(saveSceneTimer);
  6128. function save(cont){
  6129. if (cont.selection.getRange().collapsed)
  6130. cont.fireEvent('contentchange');
  6131. cont.undoManger.save(false,true);
  6132. cont.fireEvent('selectionchange');
  6133. }
  6134. saveSceneTimer = setTimeout(function(){
  6135. if(inputType){
  6136. var interalTimer = setInterval(function(){
  6137. if(!inputType){
  6138. save(me);
  6139. clearInterval(interalTimer)
  6140. }
  6141. },300)
  6142. return;
  6143. }
  6144. save(me);
  6145. },200);
  6146. lastKeyCode = keyCode;
  6147. keycont++;
  6148. if (keycont >= maxInputCount ) {
  6149. save(me)
  6150. }
  6151. }
  6152. });
  6153. me.addListener('keyup', function (type, evt) {
  6154. var keyCode = evt.keyCode || evt.which;
  6155. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  6156. if (inputType)
  6157. return;
  6158. if(!isCollapsed){
  6159. this.undoManger.save(false,true);
  6160. isCollapsed = true;
  6161. }
  6162. }
  6163. });
  6164. };
  6165. ///import core
  6166. ///import plugins/inserthtml.js
  6167. ///import plugins/undo.js
  6168. ///import plugins/serialize.js
  6169. ///commands 粘贴
  6170. ///commandsName PastePlain
  6171. ///commandsTitle 纯文本粘贴模式
  6172. /**
  6173. * @description 粘贴
  6174. * @author zhanyi
  6175. */
  6176. UM.plugins['paste'] = function () {
  6177. function getClipboardData(callback) {
  6178. var doc = this.document;
  6179. if (doc.getElementById('baidu_pastebin')) {
  6180. return;
  6181. }
  6182. var range = this.selection.getRange(),
  6183. bk = range.createBookmark(),
  6184. //创建剪贴的容器div
  6185. pastebin = doc.createElement('div');
  6186. pastebin.id = 'baidu_pastebin';
  6187. // Safari 要求div必须有内容,才能粘贴内容进来
  6188. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  6189. this.body.appendChild(pastebin);
  6190. //trace:717 隐藏的span不能得到top
  6191. //bk.start.innerHTML = '&nbsp;';
  6192. bk.start.style.display = '';
  6193. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  6194. //要在现在光标平行的位置加入,否则会出现跳动的问题
  6195. $(bk.start).position().top + 'px';
  6196. range.selectNodeContents(pastebin).select(true);
  6197. setTimeout(function () {
  6198. if (browser.webkit) {
  6199. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  6200. if (domUtils.isEmptyNode(pi)) {
  6201. domUtils.remove(pi);
  6202. } else {
  6203. pastebin = pi;
  6204. break;
  6205. }
  6206. }
  6207. }
  6208. try {
  6209. pastebin.parentNode.removeChild(pastebin);
  6210. } catch (e) {
  6211. }
  6212. range.moveToBookmark(bk).select(true);
  6213. callback(pastebin);
  6214. }, 0);
  6215. }
  6216. var me = this;
  6217. function filter(div) {
  6218. var html;
  6219. if (div.firstChild) {
  6220. //去掉cut中添加的边界值
  6221. var nodes = domUtils.getElementsByTagName(div, 'span');
  6222. for (var i = 0, ni; ni = nodes[i++];) {
  6223. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  6224. domUtils.remove(ni);
  6225. }
  6226. }
  6227. if (browser.webkit) {
  6228. var brs = div.querySelectorAll('div br');
  6229. for (var i = 0, bi; bi = brs[i++];) {
  6230. var pN = bi.parentNode;
  6231. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  6232. pN.innerHTML = '<p><br/></p>';
  6233. domUtils.remove(pN);
  6234. }
  6235. }
  6236. var divs = div.querySelectorAll('#baidu_pastebin');
  6237. for (var i = 0, di; di = divs[i++];) {
  6238. var tmpP = me.document.createElement('p');
  6239. di.parentNode.insertBefore(tmpP, di);
  6240. while (di.firstChild) {
  6241. tmpP.appendChild(di.firstChild);
  6242. }
  6243. domUtils.remove(di);
  6244. }
  6245. var metas = div.querySelectorAll('meta');
  6246. for (var i = 0, ci; ci = metas[i++];) {
  6247. domUtils.remove(ci);
  6248. }
  6249. var brs = div.querySelectorAll('br');
  6250. for (i = 0; ci = brs[i++];) {
  6251. if (/^apple-/i.test(ci.className)) {
  6252. domUtils.remove(ci);
  6253. }
  6254. }
  6255. }
  6256. if (browser.gecko) {
  6257. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  6258. for (i = 0; ci = dirtyNodes[i++];) {
  6259. ci.removeAttribute('_moz_dirty');
  6260. }
  6261. }
  6262. if (!browser.ie) {
  6263. var spans = div.querySelectorAll('span.Apple-style-span');
  6264. for (var i = 0, ci; ci = spans[i++];) {
  6265. domUtils.remove(ci, true);
  6266. }
  6267. }
  6268. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  6269. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  6270. //过滤word粘贴过来的冗余属性
  6271. html = UM.filterWord(html);
  6272. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  6273. var root = UM.htmlparser(html);
  6274. //如果给了过滤规则就先进行过滤
  6275. if (me.options.filterRules) {
  6276. UM.filterNode(root, me.options.filterRules);
  6277. }
  6278. //执行默认的处理
  6279. me.filterInputRule(root);
  6280. //针对chrome的处理
  6281. if (browser.webkit) {
  6282. var br = root.lastChild();
  6283. if (br && br.type == 'element' && br.tagName == 'br') {
  6284. root.removeChild(br)
  6285. }
  6286. utils.each(me.body.querySelectorAll('div'), function (node) {
  6287. if (domUtils.isEmptyBlock(node)) {
  6288. domUtils.remove(node)
  6289. }
  6290. })
  6291. }
  6292. html = {'html': root.toHtml()};
  6293. me.fireEvent('beforepaste', html, root);
  6294. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  6295. if(!html.html){
  6296. return;
  6297. }
  6298. me.execCommand('insertHtml', html.html, true);
  6299. me.fireEvent("afterpaste", html);
  6300. }
  6301. }
  6302. me.addListener('ready', function () {
  6303. $(me.body).on( 'cut', function () {
  6304. var range = me.selection.getRange();
  6305. if (!range.collapsed && me.undoManger) {
  6306. me.undoManger.save();
  6307. }
  6308. }).on(browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  6309. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  6310. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  6311. return;
  6312. }
  6313. getClipboardData.call(me, function (div) {
  6314. filter(div);
  6315. });
  6316. });
  6317. });
  6318. };
  6319. ///import core
  6320. ///commands 有序列表,无序列表
  6321. ///commandsName InsertOrderedList,InsertUnorderedList
  6322. ///commandsTitle 有序列表,无序列表
  6323. /**
  6324. * 有序列表
  6325. * @function
  6326. * @name UM.execCommand
  6327. * @param {String} cmdName insertorderlist插入有序列表
  6328. * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman
  6329. * @author zhanyi
  6330. */
  6331. /**
  6332. * 无序链接
  6333. * @function
  6334. * @name UM.execCommand
  6335. * @param {String} cmdName insertunorderlist插入无序列表
  6336. * * @param {String} style 值为:circle,disc,square
  6337. * @author zhanyi
  6338. */
  6339. UM.plugins['list'] = function () {
  6340. var me = this;
  6341. me.setOpt( {
  6342. 'insertorderedlist':{
  6343. 'decimal':'',
  6344. 'lower-alpha':'',
  6345. 'lower-roman':'',
  6346. 'upper-alpha':'',
  6347. 'upper-roman':''
  6348. },
  6349. 'insertunorderedlist':{
  6350. 'circle':'',
  6351. 'disc':'',
  6352. 'square':''
  6353. }
  6354. } );
  6355. this.addInputRule(function(root){
  6356. utils.each(root.getNodesByTagName('li'), function (node) {
  6357. if(node.children.length == 0){
  6358. node.parentNode.removeChild(node);
  6359. }
  6360. })
  6361. });
  6362. me.commands['insertorderedlist'] =
  6363. me.commands['insertunorderedlist'] = {
  6364. execCommand:function (cmdName) {
  6365. this.document.execCommand(cmdName);
  6366. var rng = this.selection.getRange(),
  6367. bk = rng.createBookmark(true);
  6368. this.$body.find('ol,ul').each(function(i,n){
  6369. var parent = n.parentNode;
  6370. if(parent.tagName == 'P' && parent.lastChild === parent.firstChild){
  6371. $(n).children().each(function(j,li){
  6372. var p = parent.cloneNode(false);
  6373. $(p).append(li.innerHTML);
  6374. $(li).html('').append(p);
  6375. });
  6376. $(n).insertBefore(parent);
  6377. $(parent).remove();
  6378. }
  6379. if(dtd.$inline[parent.tagName]){
  6380. if(parent.tagName == 'SPAN'){
  6381. $(n).children().each(function(k,li){
  6382. var span = parent.cloneNode(false);
  6383. if(li.firstChild.nodeName != 'P'){
  6384. while(li.firstChild){
  6385. span.appendChild(li.firstChild)
  6386. };
  6387. $('<p></p>').appendTo(li).append(span);
  6388. }else{
  6389. while(li.firstChild){
  6390. span.appendChild(li.firstChild)
  6391. };
  6392. $(li.firstChild).append(span);
  6393. }
  6394. })
  6395. }
  6396. domUtils.remove(parent,true)
  6397. }
  6398. });
  6399. rng.moveToBookmark(bk).select();
  6400. return true;
  6401. },
  6402. queryCommandState:function (cmdName) {
  6403. return this.document.queryCommandState(cmdName);
  6404. }
  6405. };
  6406. };
  6407. ///import core
  6408. ///import plugins/serialize.js
  6409. ///import plugins/undo.js
  6410. ///commands 查看源码
  6411. ///commandsName Source
  6412. ///commandsTitle 查看源码
  6413. (function (){
  6414. var sourceEditors = {
  6415. textarea: function (editor, holder){
  6416. var textarea = holder.ownerDocument.createElement('textarea');
  6417. textarea.style.cssText = 'resize:none;border:0;padding:0;margin:0;overflow-y:auto;outline:0';
  6418. // todo: IE下只有onresize属性可用... 很纠结
  6419. if (browser.ie && browser.version < 8) {
  6420. textarea.style.width = holder.offsetWidth + 'px';
  6421. textarea.style.height = holder.offsetHeight + 'px';
  6422. holder.onresize = function (){
  6423. textarea.style.width = holder.offsetWidth + 'px';
  6424. textarea.style.height = holder.offsetHeight + 'px';
  6425. };
  6426. }
  6427. holder.appendChild(textarea);
  6428. return {
  6429. container : textarea,
  6430. setContent: function (content){
  6431. textarea.value = content;
  6432. },
  6433. getContent: function (){
  6434. return textarea.value;
  6435. },
  6436. select: function (){
  6437. var range;
  6438. if (browser.ie) {
  6439. range = textarea.createTextRange();
  6440. range.collapse(true);
  6441. range.select();
  6442. } else {
  6443. //todo: chrome下无法设置焦点
  6444. textarea.setSelectionRange(0, 0);
  6445. textarea.focus();
  6446. }
  6447. },
  6448. dispose: function (){
  6449. holder.removeChild(textarea);
  6450. // todo
  6451. holder.onresize = null;
  6452. textarea = null;
  6453. holder = null;
  6454. }
  6455. };
  6456. }
  6457. };
  6458. UM.plugins['source'] = function (){
  6459. var me = this;
  6460. var opt = this.options;
  6461. var sourceMode = false;
  6462. var sourceEditor;
  6463. opt.sourceEditor = 'textarea';
  6464. me.setOpt({
  6465. sourceEditorFirst:false
  6466. });
  6467. function createSourceEditor(holder){
  6468. return sourceEditors.textarea(me, holder);
  6469. }
  6470. var bakCssText;
  6471. //解决在源码模式下getContent不能得到最新的内容问题
  6472. var oldGetContent = me.getContent,
  6473. bakAddress;
  6474. me.commands['source'] = {
  6475. execCommand: function (){
  6476. sourceMode = !sourceMode;
  6477. if (sourceMode) {
  6478. bakAddress = me.selection.getRange().createAddress(false,true);
  6479. me.undoManger && me.undoManger.save(true);
  6480. if(browser.gecko){
  6481. me.body.contentEditable = false;
  6482. }
  6483. // bakCssText = me.body.style.cssText;
  6484. me.body.style.cssText += ';position:absolute;left:-32768px;top:-32768px;';
  6485. me.fireEvent('beforegetcontent');
  6486. var root = UM.htmlparser(me.body.innerHTML);
  6487. me.filterOutputRule(root);
  6488. root.traversal(function (node) {
  6489. if (node.type == 'element') {
  6490. switch (node.tagName) {
  6491. case 'td':
  6492. case 'th':
  6493. case 'caption':
  6494. if(node.children && node.children.length == 1){
  6495. if(node.firstChild().tagName == 'br' ){
  6496. node.removeChild(node.firstChild())
  6497. }
  6498. };
  6499. break;
  6500. case 'pre':
  6501. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  6502. }
  6503. }
  6504. });
  6505. me.fireEvent('aftergetcontent');
  6506. var content = root.toHtml(true);
  6507. sourceEditor = createSourceEditor(me.body.parentNode);
  6508. sourceEditor.setContent(content);
  6509. var getStyleValue=function(attr){
  6510. return parseInt($(me.body).css(attr));
  6511. };
  6512. $(sourceEditor.container).width($(me.body).width()+getStyleValue("padding-left")+getStyleValue("padding-right"))
  6513. .height($(me.body).height());
  6514. setTimeout(function (){
  6515. sourceEditor.select();
  6516. });
  6517. //重置getContent,源码模式下取值也能是最新的数据
  6518. me.getContent = function (){
  6519. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  6520. };
  6521. } else {
  6522. me.$body.css({
  6523. 'position':'',
  6524. 'left':'',
  6525. 'top':''
  6526. });
  6527. // me.body.style.cssText = bakCssText;
  6528. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  6529. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  6530. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  6531. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  6532. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  6533. }
  6534. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  6535. });
  6536. me.setContent(cont);
  6537. sourceEditor.dispose();
  6538. sourceEditor = null;
  6539. //还原getContent方法
  6540. me.getContent = oldGetContent;
  6541. var first = me.body.firstChild;
  6542. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  6543. if(!first){
  6544. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  6545. }
  6546. //要在ifm为显示时ff才能取到selection,否则报错
  6547. //这里不能比较位置了
  6548. me.undoManger && me.undoManger.save(true);
  6549. if(browser.gecko){
  6550. me.body.contentEditable = true;
  6551. }
  6552. try{
  6553. me.selection.getRange().moveToAddress(bakAddress).select();
  6554. }catch(e){}
  6555. }
  6556. this.fireEvent('sourcemodechanged', sourceMode);
  6557. },
  6558. queryCommandState: function (){
  6559. return sourceMode|0;
  6560. },
  6561. notNeedUndo : 1
  6562. };
  6563. var oldQueryCommandState = me.queryCommandState;
  6564. me.queryCommandState = function (cmdName){
  6565. cmdName = cmdName.toLowerCase();
  6566. if (sourceMode) {
  6567. //源码模式下可以开启的命令
  6568. return cmdName in {
  6569. 'source' : 1,
  6570. 'fullscreen' : 1
  6571. } ? oldQueryCommandState.apply(this, arguments) : -1
  6572. }
  6573. return oldQueryCommandState.apply(this, arguments);
  6574. };
  6575. };
  6576. })();
  6577. ///import core
  6578. ///import plugins/undo.js
  6579. ///commands 设置回车标签p或br
  6580. ///commandsName EnterKey
  6581. ///commandsTitle 设置回车标签p或br
  6582. /**
  6583. * @description 处理回车
  6584. * @author zhanyi
  6585. */
  6586. UM.plugins['enterkey'] = function() {
  6587. var hTag,
  6588. me = this,
  6589. tag = me.options.enterTag;
  6590. me.addListener('keyup', function(type, evt) {
  6591. var keyCode = evt.keyCode || evt.which;
  6592. if (keyCode == 13) {
  6593. var range = me.selection.getRange(),
  6594. start = range.startContainer,
  6595. doSave;
  6596. //修正在h1-h6里边回车后不能嵌套p的问题
  6597. if (!browser.ie) {
  6598. if (/h\d/i.test(hTag)) {
  6599. if (browser.gecko) {
  6600. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  6601. if (!h) {
  6602. me.document.execCommand('formatBlock', false, '<p>');
  6603. doSave = 1;
  6604. }
  6605. } else {
  6606. //chrome remove div
  6607. if (start.nodeType == 1) {
  6608. var tmp = me.document.createTextNode(''),div;
  6609. range.insertNode(tmp);
  6610. div = domUtils.findParentByTagName(tmp, 'div', true);
  6611. if (div) {
  6612. var p = me.document.createElement('p');
  6613. while (div.firstChild) {
  6614. p.appendChild(div.firstChild);
  6615. }
  6616. div.parentNode.insertBefore(p, div);
  6617. domUtils.remove(div);
  6618. range.setStartBefore(tmp).setCursor();
  6619. doSave = 1;
  6620. }
  6621. domUtils.remove(tmp);
  6622. }
  6623. }
  6624. if (me.undoManger && doSave) {
  6625. me.undoManger.save();
  6626. }
  6627. }
  6628. //没有站位符,会出现多行的问题
  6629. browser.opera && range.select();
  6630. }else{
  6631. me.fireEvent('saveScene',true,true)
  6632. }
  6633. }
  6634. });
  6635. me.addListener('keydown', function(type, evt) {
  6636. var keyCode = evt.keyCode || evt.which;
  6637. if (keyCode == 13) {//回车
  6638. if(me.fireEvent('beforeenterkeydown')){
  6639. domUtils.preventDefault(evt);
  6640. return;
  6641. }
  6642. me.fireEvent('saveScene',true,true);
  6643. hTag = '';
  6644. var range = me.selection.getRange();
  6645. if (!range.collapsed) {
  6646. //跨td不能删
  6647. var start = range.startContainer,
  6648. end = range.endContainer,
  6649. startTd = domUtils.findParentByTagName(start, 'td', true),
  6650. endTd = domUtils.findParentByTagName(end, 'td', true);
  6651. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  6652. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  6653. return;
  6654. }
  6655. }
  6656. if (tag == 'p') {
  6657. if (!browser.ie) {
  6658. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  6659. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  6660. //trace:2431
  6661. if (!start && !browser.opera) {
  6662. me.document.execCommand('formatBlock', false, '<p>');
  6663. if (browser.gecko) {
  6664. range = me.selection.getRange();
  6665. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  6666. start && domUtils.removeDirtyAttr(start);
  6667. }
  6668. } else {
  6669. hTag = start.tagName;
  6670. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  6671. }
  6672. }
  6673. }
  6674. }
  6675. });
  6676. browser.ie && me.addListener('setDisabled',function(){
  6677. $(me.body).find('p').each(function(i,p){
  6678. if(domUtils.isEmptyBlock(p)){
  6679. p.innerHTML = '&nbsp;'
  6680. }
  6681. })
  6682. })
  6683. };
  6684. ///import core
  6685. ///commands 预览
  6686. ///commandsName Preview
  6687. ///commandsTitle 预览
  6688. /**
  6689. * 预览
  6690. * @function
  6691. * @name UM.execCommand
  6692. * @param {String} cmdName preview预览编辑器内容
  6693. */
  6694. UM.commands['preview'] = {
  6695. execCommand : function(){
  6696. var w = window.open('', '_blank', ''),
  6697. d = w.document,
  6698. c = this.getContent(null,null,true),
  6699. path = this.getOpt('UMEDITOR_HOME_URL'),
  6700. formula = c.indexOf('mathquill-embedded-latex')!=-1 ?
  6701. '<link rel="stylesheet" href="' + path + 'third-party/mathquill/mathquill.css"/>' +
  6702. '<script src="' + path + 'third-party/jquery.min.js"></script>' +
  6703. '<script src="' + path + 'third-party/mathquill/mathquill.min.js"></script>':'';
  6704. d.open();
  6705. d.write('<html><head>' + formula + '</head><body><div>'+c+'</div></body></html>');
  6706. d.close();
  6707. },
  6708. notNeedUndo : 1
  6709. };
  6710. ///import core
  6711. ///commands 加粗,斜体,上标,下标
  6712. ///commandsName Bold,Italic,Subscript,Superscript
  6713. ///commandsTitle 加粗,加斜,下标,上标
  6714. /**
  6715. * b u i等基础功能实现
  6716. * @function
  6717. * @name UM.execCommands
  6718. * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。
  6719. */
  6720. UM.plugins['basestyle'] = function(){
  6721. var basestyles = ['bold','underline','superscript','subscript','italic','strikethrough'],
  6722. me = this;
  6723. //添加快捷键
  6724. me.addshortcutkey({
  6725. "Bold" : "ctrl+66",//^B
  6726. "Italic" : "ctrl+73", //^I
  6727. "Underline" : "ctrl+shift+85",//^U
  6728. "strikeThrough" : 'ctrl+shift+83' //^s
  6729. });
  6730. //过滤最后的产出数据
  6731. me.addOutputRule(function(root){
  6732. $.each(root.getNodesByTagName('b i u strike s'),function(i,node){
  6733. switch (node.tagName){
  6734. case 'b':
  6735. node.tagName = 'strong';
  6736. break;
  6737. case 'i':
  6738. node.tagName = 'em';
  6739. break;
  6740. case 'u':
  6741. node.tagName = 'span';
  6742. node.setStyle('text-decoration','underline');
  6743. break;
  6744. case 's':
  6745. case 'strike':
  6746. node.tagName = 'span';
  6747. node.setStyle('text-decoration','line-through')
  6748. }
  6749. });
  6750. });
  6751. $.each(basestyles,function(i,cmd){
  6752. me.commands[cmd] = {
  6753. execCommand : function( cmdName ) {
  6754. var rng = this.selection.getRange();
  6755. if(rng.collapsed && this.queryCommandState(cmdName) != 1){
  6756. var node = this.document.createElement({
  6757. 'bold':'strong',
  6758. 'underline':'u',
  6759. 'superscript':'sup',
  6760. 'subscript':'sub',
  6761. 'italic':'em',
  6762. 'strikethrough':'strike'
  6763. }[cmdName]);
  6764. rng.insertNode(node).setStart(node,0).setCursor(false);
  6765. return true;
  6766. }else{
  6767. return this.document.execCommand(cmdName)
  6768. }
  6769. },
  6770. queryCommandState : function(cmdName) {
  6771. if(browser.gecko){
  6772. return this.document.queryCommandState(cmdName)
  6773. }
  6774. var path = this.selection.getStartElementPath(),result = false;
  6775. $.each(path,function(i,n){
  6776. switch (cmdName){
  6777. case 'bold':
  6778. if(n.nodeName == 'STRONG' || n.nodeName == 'B'){
  6779. result = 1;
  6780. return false;
  6781. }
  6782. break;
  6783. case 'underline':
  6784. if(n.nodeName == 'U' || n.nodeName == 'SPAN' && $(n).css('text-decoration') == 'underline'){
  6785. result = 1;
  6786. return false;
  6787. }
  6788. break;
  6789. case 'superscript':
  6790. if(n.nodeName == 'SUP'){
  6791. result = 1;
  6792. return false;
  6793. }
  6794. break;
  6795. case 'subscript':
  6796. if(n.nodeName == 'SUB'){
  6797. result = 1;
  6798. return false;
  6799. }
  6800. break;
  6801. case 'italic':
  6802. if(n.nodeName == 'EM' || n.nodeName == 'I'){
  6803. result = 1;
  6804. return false;
  6805. }
  6806. break;
  6807. case 'strikethrough':
  6808. if(n.nodeName == 'S' || n.nodeName == 'STRIKE' || n.nodeName == 'SPAN' && $(n).css('text-decoration') == 'line-through'){
  6809. result = 1;
  6810. return false;
  6811. }
  6812. break;
  6813. }
  6814. })
  6815. return result
  6816. }
  6817. };
  6818. })
  6819. };
  6820. ///import core
  6821. ///import plugins/inserthtml.js
  6822. ///commands 视频
  6823. ///commandsName InsertVideo
  6824. ///commandsTitle 插入视频
  6825. ///commandsDialog dialogs\video
  6826. UM.plugins['video'] = function (){
  6827. var me =this,
  6828. div;
  6829. /**
  6830. * 创建插入视频字符窜
  6831. * @param url 视频地址
  6832. * @param width 视频宽度
  6833. * @param height 视频高度
  6834. * @param align 视频对齐
  6835. * @param toEmbed 是否以flash代替显示
  6836. * @param addParagraph 是否需要添加P 标签
  6837. */
  6838. function creatInsertStr(url,width,height,id,align,toEmbed){
  6839. return !toEmbed ?
  6840. '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-video"' +
  6841. ' src="' + me.options.UMEDITOR_HOME_URL+'themes/default/images/spacer.gif" style="background:url('+me.options.UMEDITOR_HOME_URL+'themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;'+(align ? 'float:' + align + ';': '')+'" />'
  6842. :
  6843. '<embed type="application/x-shockwave-flash" class="edui-faked-video" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  6844. ' src="' + url + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  6845. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  6846. }
  6847. function switchImgAndEmbed(root,img2embed){
  6848. utils.each(root.getNodesByTagName(img2embed ? 'img' : 'embed'),function(node){
  6849. if(node.getAttr('class') == 'edui-faked-video'){
  6850. var html = creatInsertStr( img2embed ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',img2embed);
  6851. node.parentNode.replaceChild(UM.uNode.createElement(html),node)
  6852. }
  6853. })
  6854. }
  6855. me.addOutputRule(function(root){
  6856. switchImgAndEmbed(root,true)
  6857. });
  6858. me.addInputRule(function(root){
  6859. switchImgAndEmbed(root)
  6860. });
  6861. me.commands["insertvideo"] = {
  6862. execCommand: function (cmd, videoObjs){
  6863. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  6864. var html = [],id = 'tmpVedio';
  6865. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  6866. vi = videoObjs[i];
  6867. vi.url = utils.unhtml(vi.url, /[<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g);
  6868. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i,vi.align,false));
  6869. }
  6870. me.execCommand("inserthtml",html.join(""),true);
  6871. },
  6872. queryCommandState : function(){
  6873. var img = me.selection.getRange().getClosedNode(),
  6874. flag = img && (img.className == "edui-faked-video");
  6875. return flag ? 1 : 0;
  6876. }
  6877. };
  6878. };
  6879. ///import core
  6880. ///commands 全选
  6881. ///commandsName SelectAll
  6882. ///commandsTitle 全选
  6883. /**
  6884. * 选中所有
  6885. * @function
  6886. * @name UM.execCommand
  6887. * @param {String} cmdName selectall选中编辑器里的所有内容
  6888. * @author zhanyi
  6889. */
  6890. UM.plugins['selectall'] = function(){
  6891. var me = this;
  6892. me.commands['selectall'] = {
  6893. execCommand : function(){
  6894. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  6895. var me = this,body = me.body,
  6896. range = me.selection.getRange();
  6897. range.selectNodeContents(body);
  6898. if(domUtils.isEmptyBlock(body)){
  6899. //opera不能自动合并到元素的里边,要手动处理一下
  6900. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  6901. range.setStartAtFirst(body.firstChild);
  6902. }
  6903. range.collapse(true);
  6904. }
  6905. range.select(true);
  6906. },
  6907. notNeedUndo : 1
  6908. };
  6909. //快捷键
  6910. me.addshortcutkey({
  6911. "selectAll" : "ctrl+65"
  6912. });
  6913. };
  6914. //UM.plugins['removeformat'] = function () {
  6915. // var me = this;
  6916. // me.commands['removeformat'] = {
  6917. // execCommand: function () {
  6918. // me.document.execCommand('removeformat');
  6919. //
  6920. // /* 处理ie8和firefox选区有链接时,清除格式的bug */
  6921. // if (browser.gecko || browser.ie8 || browser.webkit) {
  6922. // var nativeRange = this.selection.getNative().getRangeAt(0),
  6923. // common = nativeRange.commonAncestorContainer,
  6924. // rng = me.selection.getRange(),
  6925. // bk = rng.createBookmark();
  6926. //
  6927. // function isEleInBookmark(node, bk){
  6928. // if ( (domUtils.getPosition(node, bk.start) & domUtils.POSITION_FOLLOWING) &&
  6929. // (domUtils.getPosition(bk.end, node) & domUtils.POSITION_FOLLOWING) ) {
  6930. // return true;
  6931. // } else if ( (domUtils.getPosition(node, bk.start) & domUtils.POSITION_CONTAINS) ||
  6932. // (domUtils.getPosition(node, bk.end) & domUtils.POSITION_CONTAINS) ) {
  6933. // return true;
  6934. // }
  6935. // return false;
  6936. // }
  6937. //
  6938. // $(common).find('a').each(function (k, a) {
  6939. // if ( isEleInBookmark(a, bk) ) {
  6940. // a.removeAttribute('style');
  6941. // }
  6942. // });
  6943. //
  6944. // }
  6945. // }
  6946. // };
  6947. //
  6948. //};
  6949. //
  6950. UM.plugins['removeformat'] = function(){
  6951. var me = this;
  6952. me.setOpt({
  6953. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  6954. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  6955. });
  6956. me.commands['removeformat'] = {
  6957. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  6958. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  6959. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  6960. range = new dom.Range( this.document ),
  6961. bookmark,node,parent,
  6962. filter = function( node ) {
  6963. return node.nodeType == 1;
  6964. };
  6965. function isRedundantSpan (node) {
  6966. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  6967. return 0;
  6968. }
  6969. if (browser.ie) {
  6970. //ie 下判断实效,所以只能简单用style来判断
  6971. //return node.style.cssText == '' ? 1 : 0;
  6972. var attrs = node.attributes;
  6973. if ( attrs.length ) {
  6974. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  6975. if ( attrs[i].specified ) {
  6976. return 0;
  6977. }
  6978. }
  6979. return 1;
  6980. }
  6981. }
  6982. return !node.attributes.length;
  6983. }
  6984. function doRemove( range ) {
  6985. var bookmark1 = range.createBookmark();
  6986. if ( range.collapsed ) {
  6987. range.enlarge( true );
  6988. }
  6989. //不能把a标签切了
  6990. if(!notIncludeA){
  6991. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  6992. if(aNode){
  6993. range.setStartBefore(aNode);
  6994. }
  6995. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  6996. if(aNode){
  6997. range.setEndAfter(aNode);
  6998. }
  6999. }
  7000. bookmark = range.createBookmark();
  7001. node = bookmark.start;
  7002. //切开始
  7003. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7004. domUtils.breakParent( node, parent );
  7005. domUtils.clearEmptySibling( node );
  7006. }
  7007. if ( bookmark.end ) {
  7008. //切结束
  7009. node = bookmark.end;
  7010. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7011. domUtils.breakParent( node, parent );
  7012. domUtils.clearEmptySibling( node );
  7013. }
  7014. //开始去除样式
  7015. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  7016. next;
  7017. while ( current ) {
  7018. if ( current == bookmark.end ) {
  7019. break;
  7020. }
  7021. next = domUtils.getNextDomNode( current, true, filter );
  7022. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  7023. if ( tagReg.test( current.tagName ) ) {
  7024. if ( style ) {
  7025. domUtils.removeStyle( current, style );
  7026. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  7027. domUtils.remove( current, true );
  7028. }
  7029. } else {
  7030. domUtils.remove( current, true );
  7031. }
  7032. } else {
  7033. //trace:939 不能把list上的样式去掉
  7034. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  7035. domUtils.removeAttributes( current, removeFormatAttributes );
  7036. if ( isRedundantSpan( current ) ){
  7037. domUtils.remove( current, true );
  7038. }
  7039. }
  7040. }
  7041. }
  7042. current = next;
  7043. }
  7044. }
  7045. //trace:1035
  7046. //trace:1096 不能把td上的样式去掉,比如边框
  7047. var pN = bookmark.start.parentNode;
  7048. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  7049. domUtils.removeAttributes( pN,removeFormatAttributes );
  7050. }
  7051. pN = bookmark.end.parentNode;
  7052. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  7053. domUtils.removeAttributes( pN,removeFormatAttributes );
  7054. }
  7055. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  7056. //清除冗余的代码 <b><bookmark></b>
  7057. var node = range.startContainer,
  7058. tmp,
  7059. collapsed = range.collapsed;
  7060. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7061. tmp = node.parentNode;
  7062. range.setStartBefore(node);
  7063. //trace:937
  7064. //更新结束边界
  7065. if(range.startContainer === range.endContainer){
  7066. range.endOffset--;
  7067. }
  7068. domUtils.remove(node);
  7069. node = tmp;
  7070. }
  7071. if(!collapsed){
  7072. node = range.endContainer;
  7073. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7074. tmp = node.parentNode;
  7075. range.setEndBefore(node);
  7076. domUtils.remove(node);
  7077. node = tmp;
  7078. }
  7079. }
  7080. }
  7081. range = this.selection.getRange();
  7082. if(!range.collapsed) {
  7083. doRemove( range );
  7084. range.select();
  7085. }
  7086. }
  7087. };
  7088. };
  7089. /*
  7090. * 处理特殊键的兼容性问题
  7091. */
  7092. UM.plugins['keystrokes'] = function() {
  7093. var me = this;
  7094. var collapsed = true;
  7095. me.addListener('keydown', function(type, evt) {
  7096. var keyCode = evt.keyCode || evt.which,
  7097. rng = me.selection.getRange();
  7098. //处理全选的情况
  7099. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  7100. || keyCode >= 48 && keyCode <= 57 ||
  7101. keyCode >= 96 && keyCode <= 111 || {
  7102. 13:1,
  7103. 8:1,
  7104. 46:1
  7105. }[keyCode])
  7106. ){
  7107. var tmpNode = rng.startContainer;
  7108. if(domUtils.isFillChar(tmpNode)){
  7109. rng.setStartBefore(tmpNode)
  7110. }
  7111. tmpNode = rng.endContainer;
  7112. if(domUtils.isFillChar(tmpNode)){
  7113. rng.setEndAfter(tmpNode)
  7114. }
  7115. rng.txtToElmBoundary();
  7116. //结束边界可能放到了br的前边,要把br包含进来
  7117. // x[xxx]<br/>
  7118. if(rng.endContainer && rng.endContainer.nodeType == 1){
  7119. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  7120. if(tmpNode && domUtils.isBr(tmpNode)){
  7121. rng.setEndAfter(tmpNode);
  7122. }
  7123. }
  7124. if(rng.startOffset == 0){
  7125. tmpNode = rng.startContainer;
  7126. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  7127. tmpNode = rng.endContainer;
  7128. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  7129. me.fireEvent('saveScene');
  7130. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  7131. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  7132. me._selectionChange();
  7133. return;
  7134. }
  7135. }
  7136. }
  7137. }
  7138. //处理backspace
  7139. if (keyCode == 8) {
  7140. rng = me.selection.getRange();
  7141. collapsed = rng.collapsed;
  7142. if(me.fireEvent('delkeydown',evt)){
  7143. return;
  7144. }
  7145. var start,end;
  7146. //避免按两次删除才能生效的问题
  7147. if(rng.collapsed && rng.inFillChar()){
  7148. start = rng.startContainer;
  7149. if(domUtils.isFillChar(start)){
  7150. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  7151. domUtils.remove(start)
  7152. }else{
  7153. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  7154. rng.startOffset--;
  7155. rng.collapse(true).select(true)
  7156. }
  7157. }
  7158. //解决选中control元素不能删除的问题
  7159. if (start = rng.getClosedNode()) {
  7160. me.fireEvent('saveScene');
  7161. rng.setStartBefore(start);
  7162. domUtils.remove(start);
  7163. rng.setCursor();
  7164. me.fireEvent('saveScene');
  7165. domUtils.preventDefault(evt);
  7166. return;
  7167. }
  7168. //阻止在table上的删除
  7169. if (!browser.ie) {
  7170. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  7171. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  7172. if (start && !end || !start && end || start !== end) {
  7173. evt.preventDefault();
  7174. return;
  7175. }
  7176. }
  7177. start = rng.startContainer;
  7178. if(rng.collapsed && start.nodeType == 1){
  7179. var currentNode = start.childNodes[rng.startOffset-1];
  7180. if(currentNode && currentNode.nodeType == 1 && currentNode.tagName == 'BR'){
  7181. me.fireEvent('saveScene');
  7182. rng.setStartBefore(currentNode).collapse(true);
  7183. domUtils.remove(currentNode);
  7184. rng.select();
  7185. me.fireEvent('saveScene');
  7186. }
  7187. }
  7188. //trace:3613
  7189. if(browser.chrome){
  7190. if(rng.collapsed){
  7191. while(rng.startOffset == 0 && !domUtils.isEmptyBlock(rng.startContainer)){
  7192. rng.setStartBefore(rng.startContainer)
  7193. }
  7194. var pre = rng.startContainer.childNodes[rng.startOffset-1];
  7195. if(pre && pre.nodeName == 'BR'){
  7196. rng.setStartBefore(pre);
  7197. me.fireEvent('saveScene');
  7198. $(pre).remove();
  7199. rng.setCursor();
  7200. me.fireEvent('saveScene');
  7201. }
  7202. }
  7203. }
  7204. }
  7205. //trace:1634
  7206. //ff的del键在容器空的时候,也会删除
  7207. if(browser.gecko && keyCode == 46){
  7208. var range = me.selection.getRange();
  7209. if(range.collapsed){
  7210. start = range.startContainer;
  7211. if(domUtils.isEmptyBlock(start)){
  7212. var parent = start.parentNode;
  7213. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  7214. start = parent;
  7215. parent = parent.parentNode;
  7216. }
  7217. if(start === parent.lastChild)
  7218. evt.preventDefault();
  7219. return;
  7220. }
  7221. }
  7222. }
  7223. });
  7224. me.addListener('keyup', function(type, evt) {
  7225. var keyCode = evt.keyCode || evt.which,
  7226. rng,me = this;
  7227. if(keyCode == 8){
  7228. if(me.fireEvent('delkeyup')){
  7229. return;
  7230. }
  7231. rng = me.selection.getRange();
  7232. if(rng.collapsed){
  7233. var tmpNode,
  7234. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  7235. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  7236. if(domUtils.isEmptyBlock(tmpNode)){
  7237. var pre = tmpNode.previousSibling;
  7238. if(pre && pre.nodeName != 'TABLE'){
  7239. domUtils.remove(tmpNode);
  7240. rng.setStartAtLast(pre).setCursor(false,true);
  7241. return;
  7242. }else{
  7243. var next = tmpNode.nextSibling;
  7244. if(next && next.nodeName != 'TABLE'){
  7245. domUtils.remove(tmpNode);
  7246. rng.setStartAtFirst(next).setCursor(false,true);
  7247. return;
  7248. }
  7249. }
  7250. }
  7251. }
  7252. //处理当删除到body时,要重新给p标签展位
  7253. if(domUtils.isBody(rng.startContainer)){
  7254. var tmpNode = domUtils.createElement(me.document,'p',{
  7255. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  7256. });
  7257. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  7258. }
  7259. }
  7260. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  7261. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  7262. if(browser.ie){
  7263. var span = rng.document.createElement('span');
  7264. rng.insertNode(span).setStartBefore(span).collapse(true);
  7265. rng.select();
  7266. domUtils.remove(span)
  7267. }else{
  7268. rng.select()
  7269. }
  7270. }
  7271. }
  7272. })
  7273. };
  7274. /**
  7275. * 自动保存草稿
  7276. */
  7277. UM.plugins['autosave'] = function() {
  7278. var me = this,
  7279. //无限循环保护
  7280. lastSaveTime = new Date(),
  7281. //最小保存间隔时间
  7282. MIN_TIME = 20,
  7283. //auto save key
  7284. saveKey = null;
  7285. //默认间隔时间
  7286. me.setOpt('saveInterval', 500);
  7287. //存储媒介封装
  7288. var LocalStorage = UM.LocalStorage = ( function () {
  7289. var storage = window.localStorage || getUserData() || null,
  7290. LOCAL_FILE = "localStorage";
  7291. return {
  7292. saveLocalData: function ( key, data ) {
  7293. if ( storage && data) {
  7294. storage.setItem( key, data );
  7295. return true;
  7296. }
  7297. return false;
  7298. },
  7299. getLocalData: function ( key ) {
  7300. if ( storage ) {
  7301. return storage.getItem( key );
  7302. }
  7303. return null;
  7304. },
  7305. removeItem: function ( key ) {
  7306. storage && storage.removeItem( key );
  7307. }
  7308. };
  7309. function getUserData () {
  7310. var container = document.createElement( "div" );
  7311. container.style.display = "none";
  7312. if( !container.addBehavior ) {
  7313. return null;
  7314. }
  7315. container.addBehavior("#default#userdata");
  7316. return {
  7317. getItem: function ( key ) {
  7318. var result = null;
  7319. try {
  7320. document.body.appendChild( container );
  7321. container.load( LOCAL_FILE );
  7322. result = container.getAttribute( key );
  7323. document.body.removeChild( container );
  7324. } catch ( e ) {
  7325. }
  7326. return result;
  7327. },
  7328. setItem: function ( key, value ) {
  7329. document.body.appendChild( container );
  7330. container.setAttribute( key, value );
  7331. container.save( LOCAL_FILE );
  7332. document.body.removeChild( container );
  7333. },
  7334. // 暂时没有用到
  7335. // clear: function () {
  7336. //
  7337. // var expiresTime = new Date();
  7338. // expiresTime.setFullYear( expiresTime.getFullYear() - 1 );
  7339. // document.body.appendChild( container );
  7340. // container.expires = expiresTime.toUTCString();
  7341. // container.save( LOCAL_FILE );
  7342. // document.body.removeChild( container );
  7343. //
  7344. // },
  7345. removeItem: function ( key ) {
  7346. document.body.appendChild( container );
  7347. container.removeAttribute( key );
  7348. container.save( LOCAL_FILE );
  7349. document.body.removeChild( container );
  7350. }
  7351. };
  7352. }
  7353. } )();
  7354. function save ( editor ) {
  7355. var saveData = null;
  7356. if ( new Date() - lastSaveTime < MIN_TIME ) {
  7357. return;
  7358. }
  7359. if ( !editor.hasContents() ) {
  7360. //这里不能调用命令来删除, 会造成事件死循环
  7361. saveKey && LocalStorage.removeItem( saveKey );
  7362. return;
  7363. }
  7364. lastSaveTime = new Date();
  7365. editor._saveFlag = null;
  7366. saveData = me.body.innerHTML;
  7367. if ( editor.fireEvent( "beforeautosave", {
  7368. content: saveData
  7369. } ) === false ) {
  7370. return;
  7371. }
  7372. LocalStorage.saveLocalData( saveKey, saveData );
  7373. editor.fireEvent( "afterautosave", {
  7374. content: saveData
  7375. } );
  7376. }
  7377. me.addListener('ready', function(){
  7378. var _suffix = "-drafts-data",
  7379. key = null;
  7380. if ( me.key ) {
  7381. key = me.key + _suffix;
  7382. } else {
  7383. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  7384. }
  7385. //页面地址+编辑器ID 保持唯一
  7386. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  7387. });
  7388. me.addListener('contentchange', function(){
  7389. if ( !saveKey ) {
  7390. return;
  7391. }
  7392. if ( me._saveFlag ) {
  7393. window.clearTimeout( me._saveFlag );
  7394. }
  7395. if ( me.options.saveInterval > 0 ) {
  7396. me._saveFlag = window.setTimeout( function () {
  7397. save( me );
  7398. }, me.options.saveInterval );
  7399. } else {
  7400. save(me);
  7401. }
  7402. })
  7403. me.commands['clearlocaldata'] = {
  7404. execCommand:function (cmd, name) {
  7405. if ( saveKey && LocalStorage.getLocalData( saveKey ) ) {
  7406. LocalStorage.removeItem( saveKey )
  7407. }
  7408. },
  7409. notNeedUndo: true,
  7410. ignoreContentChange:true
  7411. };
  7412. me.commands['getlocaldata'] = {
  7413. execCommand:function (cmd, name) {
  7414. return saveKey ? LocalStorage.getLocalData( saveKey ) || '' : '';
  7415. },
  7416. notNeedUndo: true,
  7417. ignoreContentChange:true
  7418. };
  7419. me.commands['drafts'] = {
  7420. execCommand:function (cmd, name) {
  7421. if ( saveKey ) {
  7422. me.body.innerHTML = LocalStorage.getLocalData( saveKey ) || '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>';
  7423. me.focus(true);
  7424. }
  7425. },
  7426. queryCommandState: function () {
  7427. return saveKey ? ( LocalStorage.getLocalData( saveKey ) === null ? -1 : 0 ) : -1;
  7428. },
  7429. notNeedUndo: true,
  7430. ignoreContentChange:true
  7431. }
  7432. };
  7433. /**
  7434. * @description
  7435. * 1.拖放文件到编辑区域,自动上传并插入到选区
  7436. * 2.插入粘贴板的图片,自动上传并插入到选区
  7437. * @author Jinqn
  7438. * @date 2013-10-14
  7439. */
  7440. UM.plugins['autoupload'] = function () {
  7441. var me = this;
  7442. me.setOpt('pasteImageEnabled', true);
  7443. me.setOpt('dropFileEnabled', true);
  7444. var sendAndInsertImage = function (file, editor) {
  7445. //模拟数据
  7446. var fd = new FormData();
  7447. fd.append(editor.options.imageFieldName || 'upfile', file, file.name || ('blob.' + file.type.substr('image/'.length)));
  7448. fd.append('type', 'ajax');
  7449. var xhr = new XMLHttpRequest();
  7450. xhr.open("post", me.options.imageUrl, true);
  7451. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  7452. xhr.addEventListener('load', function (e) {
  7453. try {
  7454. var json = eval('('+e.target.response+')'),
  7455. link = json.url,
  7456. picLink = me.options.imagePath + link;
  7457. editor.execCommand('insertimage', {
  7458. src: picLink,
  7459. _src: picLink
  7460. });
  7461. } catch (er) {
  7462. }
  7463. });
  7464. xhr.send(fd);
  7465. };
  7466. function getPasteImage(e) {
  7467. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items : null;
  7468. }
  7469. function getDropImage(e) {
  7470. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : null;
  7471. }
  7472. me.addListener('ready', function () {
  7473. if (window.FormData && window.FileReader) {
  7474. var autoUploadHandler = function (e) {
  7475. var hasImg = false,
  7476. items;
  7477. //获取粘贴板文件列表或者拖放文件列表
  7478. items = e.type == 'paste' ? getPasteImage(e.originalEvent) : getDropImage(e.originalEvent);
  7479. if (items) {
  7480. var len = items.length,
  7481. file;
  7482. while (len--) {
  7483. file = items[len];
  7484. if (file.getAsFile) file = file.getAsFile();
  7485. if (file && file.size > 0 && /image\/\w+/i.test(file.type)) {
  7486. sendAndInsertImage(file, me);
  7487. hasImg = true;
  7488. }
  7489. }
  7490. if (hasImg) return false;
  7491. }
  7492. };
  7493. me.getOpt('pasteImageEnabled') && me.$body.on('paste', autoUploadHandler);
  7494. me.getOpt('dropFileEnabled') && me.$body.on('drop', autoUploadHandler);
  7495. //取消拖放图片时出现的文字光标位置提示
  7496. me.$body.on('dragover', function (e) {
  7497. if (e.originalEvent.dataTransfer.types[0] == 'Files') {
  7498. return false;
  7499. }
  7500. });
  7501. }
  7502. });
  7503. };
  7504. /**
  7505. * 公式插件
  7506. */
  7507. UM.plugins['formula'] = function () {
  7508. var me = this;
  7509. function getActiveIframe() {
  7510. return me.$body.find('iframe.edui-formula-active')[0] || null;
  7511. }
  7512. function blurActiveIframe(){
  7513. var iframe = getActiveIframe();
  7514. iframe && iframe.contentWindow.formula.blur();
  7515. }
  7516. me.addInputRule(function (root) {
  7517. $.each(root.getNodesByTagName('span'), function (i, node) {
  7518. if (node.hasClass('mathquill-embedded-latex')) {
  7519. var firstChild, latex = '';
  7520. while(firstChild = node.firstChild()){
  7521. latex += firstChild.data;
  7522. node.removeChild(firstChild);
  7523. }
  7524. node.tagName = 'iframe';
  7525. node.setAttr({
  7526. 'frameborder': '0',
  7527. 'src': me.getOpt('UMEDITOR_HOME_URL') + 'dialogs/formula/formula.html',
  7528. 'data-latex': utils.unhtml(latex)
  7529. });
  7530. }
  7531. });
  7532. });
  7533. me.addOutputRule(function (root) {
  7534. $.each(root.getNodesByTagName('iframe'), function (i, node) {
  7535. if (node.hasClass('mathquill-embedded-latex')) {
  7536. node.tagName = 'span';
  7537. node.appendChild(UM.uNode.createText(node.getAttr('data-latex')));
  7538. node.setAttr({
  7539. 'frameborder': '',
  7540. 'src': '',
  7541. 'data-latex': ''
  7542. });
  7543. }
  7544. });
  7545. });
  7546. me.addListener('click', function(){
  7547. blurActiveIframe();
  7548. });
  7549. me.addListener('afterexeccommand', function(type, cmd){
  7550. if(cmd != 'formula') {
  7551. blurActiveIframe();
  7552. }
  7553. });
  7554. me.commands['formula'] = {
  7555. execCommand: function (cmd, latex) {
  7556. var iframe = getActiveIframe();
  7557. if (iframe) {
  7558. iframe.contentWindow.formula.insertLatex(latex);
  7559. } else {
  7560. me.execCommand('inserthtml', '<span class="mathquill-embedded-latex">' + latex + '</span>');
  7561. browser.ie && browser.ie9below && setTimeout(function(){
  7562. var rng = me.selection.getRange(),
  7563. startContainer = rng.startContainer;
  7564. if(startContainer.nodeType == 1 && !startContainer.childNodes[rng.startOffset]){
  7565. rng.insertNode(me.document.createTextNode(' '));
  7566. rng.setCursor()
  7567. }
  7568. },100)
  7569. }
  7570. },
  7571. queryCommandState: function (cmd) {
  7572. return 0;
  7573. },
  7574. queryCommandValue: function (cmd) {
  7575. var iframe = getActiveIframe();
  7576. return iframe && iframe.contentWindow.formula.getLatex();
  7577. }
  7578. }
  7579. };
  7580. /**
  7581. * @file xssFilter.js
  7582. * @desc xss过滤器
  7583. * @author robbenmu
  7584. */
  7585. UM.plugins.xssFilter = function() {
  7586. var config = UMEDITOR_CONFIG;
  7587. var whiteList = config.whiteList;
  7588. function filter(node) {
  7589. var tagName = node.tagName;
  7590. var attrs = node.attrs;
  7591. if (!whiteList.hasOwnProperty(tagName)) {
  7592. node.parentNode.removeChild(node);
  7593. return false;
  7594. }
  7595. UM.utils.each(attrs, function (val, key) {
  7596. if (whiteList[tagName].indexOf(key) === -1) {
  7597. node.setAttr(key);
  7598. }
  7599. });
  7600. }
  7601. // 添加inserthtml\paste等操作用的过滤规则
  7602. if (whiteList && config.xssFilterRules) {
  7603. this.options.filterRules = function () {
  7604. var result = {};
  7605. UM.utils.each(whiteList, function(val, key) {
  7606. result[key] = function (node) {
  7607. return filter(node);
  7608. };
  7609. });
  7610. return result;
  7611. }();
  7612. }
  7613. var tagList = [];
  7614. UM.utils.each(whiteList, function (val, key) {
  7615. tagList.push(key);
  7616. });
  7617. // 添加input过滤规则
  7618. //
  7619. if (whiteList && config.inputXssFilter) {
  7620. this.addInputRule(function (root) {
  7621. root.traversal(function(node) {
  7622. if (node.type !== 'element') {
  7623. return false;
  7624. }
  7625. filter(node);
  7626. });
  7627. });
  7628. }
  7629. // 添加output过滤规则
  7630. //
  7631. if (whiteList && config.outputXssFilter) {
  7632. this.addOutputRule(function (root) {
  7633. root.traversal(function(node) {
  7634. if (node.type !== 'element') {
  7635. return false;
  7636. }
  7637. filter(node);
  7638. });
  7639. });
  7640. }
  7641. };
  7642. (function ($) {
  7643. //对jquery的扩展
  7644. $.parseTmpl = function parse(str, data) {
  7645. var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + 'with(obj||{}){__p.push(\'' + str.replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/<%=([\s\S]+?)%>/g,function (match, code) {
  7646. return "',obj." + code.replace(/\\'/g, "'") + ",'";
  7647. }).replace(/<%([\s\S]+?)%>/g,function (match, code) {
  7648. return "');" + code.replace(/\\'/g, "'").replace(/[\r\n\t]/g, ' ') + "__p.push('";
  7649. }).replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + "');}return __p.join('');";
  7650. var func = new Function('obj', tmpl);
  7651. return data ? func(data) : func;
  7652. };
  7653. $.extend2 = function (t, s) {
  7654. var a = arguments,
  7655. notCover = $.type(a[a.length - 1]) == 'boolean' ? a[a.length - 1] : false,
  7656. len = $.type(a[a.length - 1]) == 'boolean' ? a.length - 1 : a.length;
  7657. for (var i = 1; i < len; i++) {
  7658. var x = a[i];
  7659. for (var k in x) {
  7660. if (!notCover || !t.hasOwnProperty(k)) {
  7661. t[k] = x[k];
  7662. }
  7663. }
  7664. }
  7665. return t;
  7666. };
  7667. $.IE6 = !!window.ActiveXObject && parseFloat(navigator.userAgent.match(/msie (\d+)/i)[1]) == 6;
  7668. //所有ui的基类
  7669. var _eventHandler = [];
  7670. var _widget = function () {
  7671. };
  7672. var _prefix = 'edui';
  7673. _widget.prototype = {
  7674. on: function (ev, cb) {
  7675. this.root().on(ev, $.proxy(cb, this));
  7676. return this;
  7677. },
  7678. off: function (ev, cb) {
  7679. this.root().off(ev, $.proxy(cb, this));
  7680. return this;
  7681. },
  7682. trigger: function (ev, data) {
  7683. return this.root().trigger(ev, data) === false ? false : this;
  7684. },
  7685. root: function ($el) {
  7686. return this._$el || (this._$el = $el);
  7687. },
  7688. destroy: function () {
  7689. },
  7690. data: function (key, val) {
  7691. if (val !== undefined) {
  7692. this.root().data(_prefix + key, val);
  7693. return this;
  7694. } else {
  7695. return this.root().data(_prefix + key)
  7696. }
  7697. },
  7698. register: function (eventName, $el, fn) {
  7699. _eventHandler.push({
  7700. 'evtname': eventName,
  7701. '$els': $.isArray($el) ? $el : [$el],
  7702. handler: $.proxy(fn, $el)
  7703. })
  7704. }
  7705. };
  7706. //从jq实例上拿到绑定的widget实例
  7707. $.fn.edui = function (obj) {
  7708. return obj ? this.data('eduiwidget', obj) : this.data('eduiwidget');
  7709. };
  7710. function _createClass(ClassObj, properties, supperClass) {
  7711. ClassObj.prototype = $.extend2(
  7712. $.extend({}, properties),
  7713. (UM.ui[supperClass] || _widget).prototype,
  7714. true
  7715. );
  7716. ClassObj.prototype.supper = (UM.ui[supperClass] || _widget).prototype;
  7717. //父class的defaultOpt 合并
  7718. if( UM.ui[supperClass] && UM.ui[supperClass].prototype.defaultOpt ) {
  7719. var parentDefaultOptions = UM.ui[supperClass].prototype.defaultOpt,
  7720. subDefaultOptions = ClassObj.prototype.defaultOpt;
  7721. ClassObj.prototype.defaultOpt = $.extend( {}, parentDefaultOptions, subDefaultOptions || {} );
  7722. }
  7723. return ClassObj
  7724. }
  7725. var _guid = 1;
  7726. function mergeToJQ(ClassObj, className) {
  7727. $[_prefix + className] = ClassObj;
  7728. $.fn[_prefix + className] = function (opt) {
  7729. var result, args = Array.prototype.slice.call(arguments, 1);
  7730. this.each(function (i, el) {
  7731. var $this = $(el);
  7732. var obj = $this.edui();
  7733. if (!obj) {
  7734. ClassObj(!opt || !$.isPlainObject(opt) ? {} : opt, $this);
  7735. $this.edui(obj)
  7736. }
  7737. if ($.type(opt) == 'string') {
  7738. if (opt == 'this') {
  7739. result = obj;
  7740. } else {
  7741. result = obj[opt].apply(obj, args);
  7742. if (result !== obj && result !== undefined) {
  7743. return false;
  7744. }
  7745. result = null;
  7746. }
  7747. }
  7748. });
  7749. return result !== null ? result : this;
  7750. }
  7751. }
  7752. UM.ui = {
  7753. define: function (className, properties, supperClass) {
  7754. var ClassObj = UM.ui[className] = _createClass(function (options, $el) {
  7755. var _obj = function () {
  7756. };
  7757. $.extend(_obj.prototype, ClassObj.prototype, {
  7758. guid: className + _guid++,
  7759. widgetName: className
  7760. }
  7761. );
  7762. var obj = new _obj;
  7763. if ($.type(options) == 'string') {
  7764. obj.init && obj.init({});
  7765. obj.root().edui(obj);
  7766. obj.root().find('a').click(function (evt) {
  7767. evt.preventDefault()
  7768. });
  7769. return obj.root()[_prefix + className].apply(obj.root(), arguments)
  7770. } else {
  7771. $el && obj.root($el);
  7772. obj.init && obj.init(!options || $.isPlainObject(options) ? $.extend2(options || {}, obj.defaultOpt || {}, true) : options);
  7773. try{
  7774. obj.root().find('a').click(function (evt) {
  7775. evt.preventDefault()
  7776. });
  7777. }catch(e){
  7778. }
  7779. return obj.root().edui(obj);
  7780. }
  7781. },properties, supperClass);
  7782. mergeToJQ(ClassObj, className);
  7783. }
  7784. };
  7785. $(function () {
  7786. $(document).on('click mouseup mousedown dblclick mouseover', function (evt) {
  7787. $.each(_eventHandler, function (i, obj) {
  7788. if (obj.evtname == evt.type) {
  7789. $.each(obj.$els, function (i, $el) {
  7790. if ($el[0] !== evt.target && !$.contains($el[0], evt.target)) {
  7791. obj.handler(evt);
  7792. }
  7793. })
  7794. }
  7795. })
  7796. })
  7797. })
  7798. })(jQuery);
  7799. //button 类
  7800. UM.ui.define('button', {
  7801. tpl: '<<%if(!texttype){%>div class="edui-btn edui-btn-<%=icon%> <%if(name){%>edui-btn-name-<%=name%><%}%>" unselectable="on" onmousedown="return false" <%}else{%>a class="edui-text-btn"<%}%><% if(title) {%> data-original-title="<%=title%>" <%};%>> ' +
  7802. '<% if(icon) {%><div unselectable="on" class="edui-icon-<%=icon%> edui-icon"></div><% }; %><%if(text) {%><span unselectable="on" onmousedown="return false" class="edui-button-label"><%=text%></span><%}%>' +
  7803. '<%if(caret && text){%><span class="edui-button-spacing"></span><%}%>' +
  7804. '<% if(caret) {%><span unselectable="on" onmousedown="return false" class="edui-caret"></span><% };%></<%if(!texttype){%>div<%}else{%>a<%}%>>',
  7805. defaultOpt: {
  7806. text: '',
  7807. title: '',
  7808. icon: '',
  7809. width: '',
  7810. caret: false,
  7811. texttype: false,
  7812. click: function () {
  7813. }
  7814. },
  7815. init: function (options) {
  7816. var me = this;
  7817. me.root($($.parseTmpl(me.tpl, options)))
  7818. .click(function (evt) {
  7819. me.wrapclick(options.click, evt)
  7820. });
  7821. me.root().hover(function () {
  7822. if(!me.root().hasClass("edui-disabled")){
  7823. me.root().toggleClass('edui-hover')
  7824. }
  7825. })
  7826. return me;
  7827. },
  7828. wrapclick: function (fn, evt) {
  7829. if (!this.disabled()) {
  7830. this.root().trigger('wrapclick');
  7831. $.proxy(fn, this, evt)()
  7832. }
  7833. return this;
  7834. },
  7835. label: function (text) {
  7836. if (text === undefined) {
  7837. return this.root().find('.edui-button-label').text();
  7838. } else {
  7839. this.root().find('.edui-button-label').text(text);
  7840. return this;
  7841. }
  7842. },
  7843. disabled: function (state) {
  7844. if (state === undefined) {
  7845. return this.root().hasClass('edui-disabled')
  7846. }
  7847. this.root().toggleClass('edui-disabled', state);
  7848. if(this.root().hasClass('edui-disabled')){
  7849. this.root().removeClass('edui-hover')
  7850. }
  7851. return this;
  7852. },
  7853. active: function (state) {
  7854. if (state === undefined) {
  7855. return this.root().hasClass('edui-active')
  7856. }
  7857. this.root().toggleClass('edui-active', state)
  7858. return this;
  7859. },
  7860. mergeWith: function ($obj) {
  7861. var me = this;
  7862. me.data('$mergeObj', $obj);
  7863. $obj.edui().data('$mergeObj', me.root());
  7864. if (!$.contains(document.body, $obj[0])) {
  7865. $obj.appendTo(me.root());
  7866. }
  7867. me.on('click',function () {
  7868. me.wrapclick(function () {
  7869. $obj.edui().show();
  7870. })
  7871. }).register('click', me.root(), function (evt) {
  7872. $obj.hide()
  7873. });
  7874. }
  7875. });
  7876. //toolbar 类
  7877. (function () {
  7878. UM.ui.define('toolbar', {
  7879. tpl: '<div class="edui-toolbar" ><div class="edui-btn-toolbar" unselectable="on" onmousedown="return false" ></div></div>'
  7880. ,
  7881. init: function () {
  7882. var $root = this.root($(this.tpl));
  7883. this.data('$btnToolbar', $root.find('.edui-btn-toolbar'))
  7884. },
  7885. appendToBtnmenu : function(data){
  7886. var $cont = this.data('$btnToolbar');
  7887. data = $.isArray(data) ? data : [data];
  7888. $.each(data,function(i,$item){
  7889. $cont.append($item)
  7890. })
  7891. }
  7892. });
  7893. })();
  7894. //menu 类
  7895. UM.ui.define('menu',{
  7896. show : function($obj,dir,fnname,topOffset,leftOffset){
  7897. fnname = fnname || 'position';
  7898. if(this.trigger('beforeshow') === false){
  7899. return;
  7900. }else{
  7901. this.root().css($.extend({display:'block'},$obj ? {
  7902. top : $obj[fnname]().top + ( dir == 'right' ? 0 : $obj.outerHeight()) - (topOffset || 0),
  7903. left : $obj[fnname]().left + (dir == 'right' ? $obj.outerWidth() : 0) - (leftOffset || 0)
  7904. }:{}))
  7905. this.trigger('aftershow');
  7906. }
  7907. },
  7908. hide : function(all){
  7909. var $parentmenu;
  7910. if(this.trigger('beforehide') === false){
  7911. return;
  7912. } else {
  7913. if($parentmenu = this.root().data('parentmenu')){
  7914. if($parentmenu.data('parentmenu')|| all)
  7915. $parentmenu.edui().hide();
  7916. }
  7917. this.root().css('display','none');
  7918. this.trigger('afterhide');
  7919. }
  7920. },
  7921. attachTo : function($obj){
  7922. var me = this;
  7923. if(!$obj.data('$mergeObj')){
  7924. $obj.data('$mergeObj',me.root());
  7925. $obj.on('wrapclick',function(evt){
  7926. me.show()
  7927. });
  7928. me.register('click',$obj,function(evt){
  7929. me.hide()
  7930. });
  7931. me.data('$mergeObj',$obj)
  7932. }
  7933. }
  7934. });
  7935. //dropmenu 类
  7936. UM.ui.define('dropmenu', {
  7937. tmpl: '<ul class="edui-dropdown-menu" aria-labelledby="dropdownMenu" >' +
  7938. '<%for(var i=0,ci;ci=data[i++];){%>' +
  7939. '<%if(ci.divider){%><li class="edui-divider"></li><%}else{%>' +
  7940. '<li <%if(ci.active||ci.disabled){%>class="<%= ci.active|| \'\' %> <%=ci.disabled||\'\' %>" <%}%> data-value="<%= ci.value%>">' +
  7941. '<a href="#" tabindex="-1"><em class="edui-dropmenu-checkbox"><i class="edui-icon-ok"></i></em><%= ci.label%></a>' +
  7942. '</li><%}%>' +
  7943. '<%}%>' +
  7944. '</ul>',
  7945. defaultOpt: {
  7946. data: [],
  7947. click: function () {
  7948. }
  7949. },
  7950. init: function (options) {
  7951. var me = this;
  7952. var eventName = {
  7953. click: 1,
  7954. mouseover: 1,
  7955. mouseout: 1
  7956. };
  7957. this.root($($.parseTmpl(this.tmpl, options))).on('click', 'li[class!="edui-disabled edui-divider edui-dropdown-submenu"]',function (evt) {
  7958. $.proxy(options.click, me, evt, $(this).data('value'), $(this))()
  7959. }).find('li').each(function (i, el) {
  7960. var $this = $(this);
  7961. if (!$this.hasClass("edui-disabled edui-divider edui-dropdown-submenu")) {
  7962. var data = options.data[i];
  7963. $.each(eventName, function (k) {
  7964. data[k] && $this[k](function (evt) {
  7965. $.proxy(data[k], el)(evt, data, me.root)
  7966. })
  7967. })
  7968. }
  7969. })
  7970. },
  7971. disabled: function (cb) {
  7972. $('li[class!=edui-divider]', this.root()).each(function () {
  7973. var $el = $(this);
  7974. if (cb === true) {
  7975. $el.addClass('edui-disabled')
  7976. } else if ($.isFunction(cb)) {
  7977. $el.toggleClass('edui-disabled', cb(li))
  7978. } else {
  7979. $el.removeClass('edui-disabled')
  7980. }
  7981. });
  7982. },
  7983. val: function (val) {
  7984. var currentVal;
  7985. $('li[class!="edui-divider edui-disabled edui-dropdown-submenu"]', this.root()).each(function () {
  7986. var $el = $(this);
  7987. if (val === undefined) {
  7988. if ($el.find('em.edui-dropmenu-checked').length) {
  7989. currentVal = $el.data('value');
  7990. return false
  7991. }
  7992. } else {
  7993. $el.find('em').toggleClass('edui-dropmenu-checked', $el.data('value') == val)
  7994. }
  7995. });
  7996. if (val === undefined) {
  7997. return currentVal
  7998. }
  7999. },
  8000. addSubmenu: function (label, menu, index) {
  8001. index = index || 0;
  8002. var $list = $('li[class!=edui-divider]', this.root());
  8003. var $node = $('<li class="edui-dropdown-submenu"><a tabindex="-1" href="#">' + label + '</a></li>').append(menu);
  8004. if (index >= 0 && index < $list.length) {
  8005. $node.insertBefore($list[index]);
  8006. } else if (index < 0) {
  8007. $node.insertBefore($list[0]);
  8008. } else if (index >= $list.length) {
  8009. $node.appendTo($list);
  8010. }
  8011. }
  8012. }, 'menu');
  8013. //splitbutton 类
  8014. ///import button
  8015. UM.ui.define('splitbutton',{
  8016. tpl :'<div class="edui-splitbutton <%if (name){%>edui-splitbutton-<%= name %><%}%>" unselectable="on" <%if(title){%>data-original-title="<%=title%>"<%}%>><div class="edui-btn" unselectable="on" ><%if(icon){%><div unselectable="on" class="edui-icon-<%=icon%> edui-icon"></div><%}%><%if(text){%><%=text%><%}%></div>'+
  8017. '<div unselectable="on" class="edui-btn edui-dropdown-toggle" >'+
  8018. '<div unselectable="on" class="edui-caret"><\/div>'+
  8019. '</div>'+
  8020. '</div>',
  8021. defaultOpt:{
  8022. text:'',
  8023. title:'',
  8024. click:function(){}
  8025. },
  8026. init : function(options){
  8027. var me = this;
  8028. me.root( $($.parseTmpl(me.tpl,options)));
  8029. me.root().find('.edui-btn:first').click(function(evt){
  8030. if(!me.disabled()){
  8031. $.proxy(options.click,me)();
  8032. }
  8033. });
  8034. me.root().find('.edui-dropdown-toggle').click(function(){
  8035. if(!me.disabled()){
  8036. me.trigger('arrowclick')
  8037. }
  8038. });
  8039. me.root().hover(function () {
  8040. if(!me.root().hasClass("edui-disabled")){
  8041. me.root().toggleClass('edui-hover')
  8042. }
  8043. });
  8044. return me;
  8045. },
  8046. wrapclick:function(fn,evt){
  8047. if(!this.disabled()){
  8048. $.proxy(fn,this,evt)()
  8049. }
  8050. return this;
  8051. },
  8052. disabled : function(state){
  8053. if(state === undefined){
  8054. return this.root().hasClass('edui-disabled')
  8055. }
  8056. this.root().toggleClass('edui-disabled',state).find('.edui-btn').toggleClass('edui-disabled',state);
  8057. return this;
  8058. },
  8059. active:function(state){
  8060. if(state === undefined){
  8061. return this.root().hasClass('edui-active')
  8062. }
  8063. this.root().toggleClass('edui-active',state).find('.edui-btn:first').toggleClass('edui-active',state);
  8064. return this;
  8065. },
  8066. mergeWith:function($obj){
  8067. var me = this;
  8068. me.data('$mergeObj',$obj);
  8069. $obj.edui().data('$mergeObj',me.root());
  8070. if(!$.contains(document.body,$obj[0])){
  8071. $obj.appendTo(me.root());
  8072. }
  8073. me.root().delegate('.edui-dropdown-toggle','click',function(){
  8074. me.wrapclick(function(){
  8075. $obj.edui().show();
  8076. })
  8077. });
  8078. me.register('click',me.root().find('.edui-dropdown-toggle'),function(evt){
  8079. $obj.hide()
  8080. });
  8081. }
  8082. });
  8083. /**
  8084. * Created with JetBrains PhpStorm.
  8085. * User: hn
  8086. * Date: 13-7-10
  8087. * Time: 下午3:07
  8088. * To change this template use File | Settings | File Templates.
  8089. */
  8090. UM.ui.define('colorsplitbutton',{
  8091. tpl : '<div class="edui-splitbutton <%if (name){%>edui-splitbutton-<%= name %><%}%>" unselectable="on" <%if(title){%>data-original-title="<%=title%>"<%}%>><div class="edui-btn" unselectable="on" ><%if(icon){%><div unselectable="on" class="edui-icon-<%=icon%> edui-icon"></div><%}%><div class="edui-splitbutton-color-label" <%if (color) {%>style="background: <%=color%>"<%}%>></div><%if(text){%><%=text%><%}%></div>'+
  8092. '<div unselectable="on" class="edui-btn edui-dropdown-toggle" >'+
  8093. '<div unselectable="on" class="edui-caret"><\/div>'+
  8094. '</div>'+
  8095. '</div>',
  8096. defaultOpt: {
  8097. color: ''
  8098. },
  8099. init: function( options ){
  8100. var me = this;
  8101. me.supper.init.call( me, options );
  8102. },
  8103. colorLabel: function(){
  8104. return this.root().find('.edui-splitbutton-color-label');
  8105. }
  8106. }, 'splitbutton');
  8107. //popup 类
  8108. UM.ui.define('popup', {
  8109. tpl: '<div class="edui-dropdown-menu edui-popup"'+
  8110. '<%if(!<%=stopprop%>){%>onmousedown="return false"<%}%>'+
  8111. '><div class="edui-popup-body" unselectable="on" onmousedown="return false"><%=subtpl%></div>' +
  8112. '<div class="edui-popup-caret"></div>' +
  8113. '</div>',
  8114. defaultOpt: {
  8115. stopprop:false,
  8116. subtpl: '',
  8117. width: '',
  8118. height: ''
  8119. },
  8120. init: function (options) {
  8121. this.root($($.parseTmpl(this.tpl, options)));
  8122. return this;
  8123. },
  8124. mergeTpl: function (data) {
  8125. return $.parseTmpl(this.tpl, {subtpl: data});
  8126. },
  8127. show: function ($obj, posObj) {
  8128. if (!posObj) posObj = {};
  8129. var fnname = posObj.fnname || 'position';
  8130. if (this.trigger('beforeshow') === false) {
  8131. return;
  8132. } else {
  8133. this.root().css($.extend({display: 'block'}, $obj ? {
  8134. top: $obj[fnname]().top + ( posObj.dir == 'right' ? 0 : $obj.outerHeight()) - (posObj.offsetTop || 0),
  8135. left: $obj[fnname]().left + (posObj.dir == 'right' ? $obj.outerWidth() : 0) - (posObj.offsetLeft || 0),
  8136. position: 'absolute'
  8137. } : {}));
  8138. this.root().find('.edui-popup-caret').css({
  8139. top: posObj.caretTop || 0,
  8140. left: posObj.caretLeft || 0,
  8141. position: 'absolute'
  8142. }).addClass(posObj.caretDir || "up")
  8143. }
  8144. this.trigger("aftershow");
  8145. },
  8146. hide: function () {
  8147. this.root().css('display', 'none');
  8148. this.trigger('afterhide')
  8149. },
  8150. attachTo: function ($obj, posObj) {
  8151. var me = this
  8152. if (!$obj.data('$mergeObj')) {
  8153. $obj.data('$mergeObj', me.root());
  8154. $obj.on('wrapclick', function (evt) {
  8155. me.show($obj, posObj)
  8156. });
  8157. me.register('click', $obj, function (evt) {
  8158. me.hide()
  8159. });
  8160. me.data('$mergeObj', $obj)
  8161. }
  8162. },
  8163. getBodyContainer: function () {
  8164. return this.root().find(".edui-popup-body");
  8165. }
  8166. });
  8167. //scale 类
  8168. UM.ui.define('scale', {
  8169. tpl: '<div class="edui-scale" unselectable="on">' +
  8170. '<span class="edui-scale-hand0"></span>' +
  8171. '<span class="edui-scale-hand1"></span>' +
  8172. '<span class="edui-scale-hand2"></span>' +
  8173. '<span class="edui-scale-hand3"></span>' +
  8174. '<span class="edui-scale-hand4"></span>' +
  8175. '<span class="edui-scale-hand5"></span>' +
  8176. '<span class="edui-scale-hand6"></span>' +
  8177. '<span class="edui-scale-hand7"></span>' +
  8178. '</div>',
  8179. defaultOpt: {
  8180. $doc: $(document),
  8181. $wrap: $(document)
  8182. },
  8183. init: function (options) {
  8184. if(options.$doc) this.defaultOpt.$doc = options.$doc;
  8185. if(options.$wrap) this.defaultOpt.$wrap = options.$wrap;
  8186. this.root($($.parseTmpl(this.tpl, options)));
  8187. this.initStyle();
  8188. this.startPos = this.prePos = {x: 0, y: 0};
  8189. this.dragId = -1;
  8190. return this;
  8191. },
  8192. initStyle: function () {
  8193. utils.cssRule('edui-style-scale', '.edui-scale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;}' +
  8194. '.edui-scale span{position:absolute;left:0;top:0;width:7px;height:7px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  8195. + '.edui-scale .edui-scale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  8196. + '.edui-scale .edui-scale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  8197. + '.edui-scale .edui-scale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  8198. + '.edui-scale .edui-scale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  8199. + '.edui-scale .edui-scale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  8200. + '.edui-scale .edui-scale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  8201. + '.edui-scale .edui-scale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  8202. + '.edui-scale .edui-scale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  8203. },
  8204. _eventHandler: function (e) {
  8205. var me = this,
  8206. $doc = me.defaultOpt.$doc;
  8207. switch (e.type) {
  8208. case 'mousedown':
  8209. var hand = e.target || e.srcElement, hand;
  8210. if (hand.className.indexOf('edui-scale-hand') != -1) {
  8211. me.dragId = hand.className.slice(-1);
  8212. me.startPos.x = me.prePos.x = e.clientX;
  8213. me.startPos.y = me.prePos.y = e.clientY;
  8214. $doc.bind('mousemove', $.proxy(me._eventHandler, me));
  8215. }
  8216. break;
  8217. case 'mousemove':
  8218. if (me.dragId != -1) {
  8219. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  8220. me.prePos.x = e.clientX;
  8221. me.prePos.y = e.clientY;
  8222. me.updateTargetElement();
  8223. }
  8224. break;
  8225. case 'mouseup':
  8226. if (me.dragId != -1) {
  8227. me.dragId = -1;
  8228. me.updateTargetElement();
  8229. var $target = me.data('$scaleTarget');
  8230. if ($target.parent()) me.attachTo(me.data('$scaleTarget'));
  8231. }
  8232. $doc.unbind('mousemove', $.proxy(me._eventHandler, me));
  8233. break;
  8234. default:
  8235. break;
  8236. }
  8237. },
  8238. updateTargetElement: function () {
  8239. var me = this,
  8240. $root = me.root(),
  8241. $target = me.data('$scaleTarget');
  8242. $target.css({width: $root.width(), height: $root.height()});
  8243. me.attachTo($target);
  8244. },
  8245. updateContainerStyle: function (dir, offset) {
  8246. var me = this,
  8247. $dom = me.root(),
  8248. tmp,
  8249. rect = [
  8250. //[left, top, width, height]
  8251. [0, 0, -1, -1],
  8252. [0, 0, 0, -1],
  8253. [0, 0, 1, -1],
  8254. [0, 0, -1, 0],
  8255. [0, 0, 1, 0],
  8256. [0, 0, -1, 1],
  8257. [0, 0, 0, 1],
  8258. [0, 0, 1, 1]
  8259. ];
  8260. if (rect[dir][0] != 0) {
  8261. tmp = parseInt($dom.offset().left) + offset.x;
  8262. $dom.css('left', me._validScaledProp('left', tmp));
  8263. }
  8264. if (rect[dir][1] != 0) {
  8265. tmp = parseInt($dom.offset().top) + offset.y;
  8266. $dom.css('top', me._validScaledProp('top', tmp));
  8267. }
  8268. if (rect[dir][2] != 0) {
  8269. tmp = $dom.width() + rect[dir][2] * offset.x;
  8270. $dom.css('width', me._validScaledProp('width', tmp));
  8271. }
  8272. if (rect[dir][3] != 0) {
  8273. tmp = $dom.height() + rect[dir][3] * offset.y;
  8274. $dom.css('height', me._validScaledProp('height', tmp));
  8275. }
  8276. },
  8277. _validScaledProp: function (prop, value) {
  8278. var $ele = this.root(),
  8279. $wrap = this.defaultOpt.$doc,
  8280. calc = function(val, a, b){
  8281. return (val + a) > b ? b - a : value;
  8282. };
  8283. value = isNaN(value) ? 0 : value;
  8284. switch (prop) {
  8285. case 'left':
  8286. return value < 0 ? 0 : calc(value, $ele.width(), $wrap.width());
  8287. case 'top':
  8288. return value < 0 ? 0 : calc(value, $ele.height(),$wrap.height());
  8289. case 'width':
  8290. return value <= 0 ? 1 : calc(value, $ele.offset().left, $wrap.width());
  8291. case 'height':
  8292. return value <= 0 ? 1 : calc(value, $ele.offset().top, $wrap.height());
  8293. }
  8294. },
  8295. show: function ($obj) {
  8296. var me = this;
  8297. if ($obj) me.attachTo($obj);
  8298. me.root().bind('mousedown', $.proxy(me._eventHandler, me));
  8299. me.defaultOpt.$doc.bind('mouseup', $.proxy(me._eventHandler, me));
  8300. me.root().show();
  8301. me.trigger("aftershow");
  8302. },
  8303. hide: function () {
  8304. var me = this;
  8305. me.root().unbind('mousedown', $.proxy(me._eventHandler, me));
  8306. me.defaultOpt.$doc.unbind('mouseup', $.proxy(me._eventHandler, me));
  8307. me.root().hide();
  8308. me.trigger('afterhide')
  8309. },
  8310. attachTo: function ($obj) {
  8311. var me = this,
  8312. imgPos = $obj.offset(),
  8313. $root = me.root(),
  8314. $wrap = me.defaultOpt.$wrap,
  8315. posObj = $wrap.offset();
  8316. me.data('$scaleTarget', $obj);
  8317. me.root().css({
  8318. position: 'absolute',
  8319. width: $obj.width(),
  8320. height: $obj.height(),
  8321. left: imgPos.left - posObj.left - parseInt($wrap.css('border-left-width')) - parseInt($root.css('border-left-width')),
  8322. top: imgPos.top - posObj.top - parseInt($wrap.css('border-top-width')) - parseInt($root.css('border-top-width'))
  8323. });
  8324. },
  8325. getScaleTarget: function () {
  8326. return this.data('$scaleTarget')[0];
  8327. }
  8328. });
  8329. //colorpicker 类
  8330. UM.ui.define('colorpicker', {
  8331. tpl: function (opt) {
  8332. var COLORS = (
  8333. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  8334. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  8335. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  8336. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  8337. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  8338. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  8339. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  8340. var html = '<div unselectable="on" onmousedown="return false" class="edui-colorpicker<%if (name){%> edui-colorpicker-<%=name%><%}%>" >' +
  8341. '<table unselectable="on" onmousedown="return false">' +
  8342. '<tr><td colspan="10">'+opt.lang_themeColor+'</td> </tr>' +
  8343. '<tr class="edui-colorpicker-firstrow" >';
  8344. for (var i = 0; i < COLORS.length; i++) {
  8345. if (i && i % 10 === 0) {
  8346. html += '</tr>' + (i == 60 ? '<tr><td colspan="10">'+opt.lang_standardColor+'</td></tr>' : '') + '<tr' + (i == 60 ? ' class="edui-colorpicker-firstrow"' : '') + '>';
  8347. }
  8348. html += i < 70 ? '<td><a unselectable="on" onmousedown="return false" title="' + COLORS[i] + '" class="edui-colorpicker-colorcell"' +
  8349. ' data-color="#' + COLORS[i] + '"' +
  8350. ' style="background-color:#' + COLORS[i] + ';border:solid #ccc;' +
  8351. (i < 10 || i >= 60 ? 'border-width:1px;' :
  8352. i >= 10 && i < 20 ? 'border-width:1px 1px 0 1px;' :
  8353. 'border-width:0 1px 0 1px;') +
  8354. '"' +
  8355. '></a></td>' : '';
  8356. }
  8357. html += '</tr></table></div>';
  8358. return html;
  8359. },
  8360. init: function (options) {
  8361. var me = this;
  8362. me.root($($.parseTmpl(me.supper.mergeTpl(me.tpl(options)),options)));
  8363. me.root().on("click",function (e) {
  8364. me.trigger('pickcolor', $(e.target).data('color'));
  8365. });
  8366. }
  8367. }, 'popup');
  8368. /**
  8369. * Created with JetBrains PhpStorm.
  8370. * User: hn
  8371. * Date: 13-5-29
  8372. * Time: 下午8:01
  8373. * To change this template use File | Settings | File Templates.
  8374. */
  8375. (function(){
  8376. var widgetName = 'combobox',
  8377. itemClassName = 'edui-combobox-item',
  8378. HOVER_CLASS = 'edui-combobox-item-hover',
  8379. ICON_CLASS = 'edui-combobox-checked-icon',
  8380. labelClassName = 'edui-combobox-item-label';
  8381. UM.ui.define( widgetName, ( function(){
  8382. return {
  8383. tpl: "<ul class=\"dropdown-menu edui-combobox-menu<%if (comboboxName!=='') {%> edui-combobox-<%=comboboxName%><%}%>\" unselectable=\"on\" onmousedown=\"return false\" role=\"menu\" aria-labelledby=\"dropdownMenu\">" +
  8384. "<%if(autoRecord) {%>" +
  8385. "<%for( var i=0, len = recordStack.length; i<len; i++ ) {%>" +
  8386. "<%var index = recordStack[i];%>" +
  8387. "<li class=\"<%=itemClassName%><%if( selected == index ) {%> edui-combobox-checked<%}%>\" data-item-index=\"<%=index%>\" unselectable=\"on\" onmousedown=\"return false\">" +
  8388. "<span class=\"edui-combobox-icon\" unselectable=\"on\" onmousedown=\"return false\"></span>" +
  8389. "<label class=\"<%=labelClassName%>\" style=\"<%=itemStyles[ index ]%>\" unselectable=\"on\" onmousedown=\"return false\"><%=items[index]%></label>" +
  8390. "</li>" +
  8391. "<%}%>" +
  8392. "<%if( i ) {%>" +
  8393. "<li class=\"edui-combobox-item-separator\"></li>" +
  8394. "<%}%>" +
  8395. "<%}%>" +
  8396. "<%for( var i=0, label; label = items[i]; i++ ) {%>" +
  8397. "<li class=\"<%=itemClassName%><%if( selected == i ) {%> edui-combobox-checked<%}%> edui-combobox-item-<%=i%>\" data-item-index=\"<%=i%>\" unselectable=\"on\" onmousedown=\"return false\">" +
  8398. "<span class=\"edui-combobox-icon\" unselectable=\"on\" onmousedown=\"return false\"></span>" +
  8399. "<label class=\"<%=labelClassName%>\" style=\"<%=itemStyles[ i ]%>\" unselectable=\"on\" onmousedown=\"return false\"><%=label%></label>" +
  8400. "</li>" +
  8401. "<%}%>" +
  8402. "</ul>",
  8403. defaultOpt: {
  8404. //记录栈初始列表
  8405. recordStack: [],
  8406. //可用项列表
  8407. items: [],
  8408. //item对应的值列表
  8409. value: [],
  8410. comboboxName: '',
  8411. selected: '',
  8412. //自动记录
  8413. autoRecord: true,
  8414. //最多记录条数
  8415. recordCount: 5
  8416. },
  8417. init: function( options ){
  8418. var me = this;
  8419. $.extend( me._optionAdaptation( options ), me._createItemMapping( options.recordStack, options.items ), {
  8420. itemClassName: itemClassName,
  8421. iconClass: ICON_CLASS,
  8422. labelClassName: labelClassName
  8423. } );
  8424. this._transStack( options );
  8425. me.root( $( $.parseTmpl( me.tpl, options ) ) );
  8426. this.data( 'options', options ).initEvent();
  8427. },
  8428. initEvent: function(){
  8429. var me = this;
  8430. me.initSelectItem();
  8431. this.initItemActive();
  8432. },
  8433. /**
  8434. * 初始化选择项
  8435. */
  8436. initSelectItem: function(){
  8437. var me = this,
  8438. labelClass = "."+labelClassName;
  8439. me.root().delegate('.' + itemClassName, 'click', function(){
  8440. var $li = $(this),
  8441. index = $li.attr('data-item-index');
  8442. me.trigger('comboboxselect', {
  8443. index: index,
  8444. label: $li.find(labelClass).text(),
  8445. value: me.data('options').value[ index ]
  8446. }).select( index );
  8447. me.hide();
  8448. return false;
  8449. });
  8450. },
  8451. initItemActive: function(){
  8452. var fn = {
  8453. mouseenter: 'addClass',
  8454. mouseleave: 'removeClass'
  8455. };
  8456. if ($.IE6) {
  8457. this.root().delegate( '.'+itemClassName, 'mouseenter mouseleave', function( evt ){
  8458. $(this)[ fn[ evt.type ] ]( HOVER_CLASS );
  8459. }).one('afterhide', function(){
  8460. });
  8461. }
  8462. },
  8463. /**
  8464. * 选择给定索引的项
  8465. * @param index 项索引
  8466. * @returns {*} 如果存在对应索引的项,则返回该项;否则返回null
  8467. */
  8468. select: function( index ){
  8469. var itemCount = this.data('options').itemCount,
  8470. items = this.data('options').autowidthitem;
  8471. if ( items && !items.length ) {
  8472. items = this.data('options').items;
  8473. }
  8474. if( itemCount == 0 ) {
  8475. return null;
  8476. }
  8477. if( index < 0 ) {
  8478. index = itemCount + index % itemCount;
  8479. } else if ( index >= itemCount ) {
  8480. index = itemCount-1;
  8481. }
  8482. this.trigger( 'changebefore', items[ index ] );
  8483. this._update( index );
  8484. this.trigger( 'changeafter', items[ index ] );
  8485. return null;
  8486. },
  8487. selectItemByLabel: function( label ){
  8488. var itemMapping = this.data('options').itemMapping,
  8489. me = this,
  8490. index = null;
  8491. !$.isArray( label ) && ( label = [ label ] );
  8492. $.each( label, function( i, item ){
  8493. index = itemMapping[ item ];
  8494. if( index !== undefined ) {
  8495. me.select( index );
  8496. return false;
  8497. }
  8498. } );
  8499. },
  8500. /**
  8501. * 转换记录栈
  8502. */
  8503. _transStack: function( options ) {
  8504. var temp = [],
  8505. itemIndex = -1,
  8506. selected = -1;
  8507. $.each( options.recordStack, function( index, item ){
  8508. itemIndex = options.itemMapping[ item ];
  8509. if( $.isNumeric( itemIndex ) ) {
  8510. temp.push( itemIndex );
  8511. //selected的合法性检测
  8512. if( item == options.selected ) {
  8513. selected = itemIndex;
  8514. }
  8515. }
  8516. } );
  8517. options.recordStack = temp;
  8518. options.selected = selected;
  8519. temp = null;
  8520. },
  8521. _optionAdaptation: function( options ) {
  8522. if( !( 'itemStyles' in options ) ) {
  8523. options.itemStyles = [];
  8524. for( var i = 0, len = options.items.length; i < len; i++ ) {
  8525. options.itemStyles.push('');
  8526. }
  8527. }
  8528. options.autowidthitem = options.autowidthitem || options.items;
  8529. options.itemCount = options.items.length;
  8530. return options;
  8531. },
  8532. _createItemMapping: function( stackItem, items ){
  8533. var temp = {},
  8534. result = {
  8535. recordStack: [],
  8536. mapping: {}
  8537. };
  8538. $.each( items, function( index, item ){
  8539. temp[ item ] = index;
  8540. } );
  8541. result.itemMapping = temp;
  8542. $.each( stackItem, function( index, item ){
  8543. if( temp[ item ] !== undefined ) {
  8544. result.recordStack.push( temp[ item ] );
  8545. result.mapping[ item ] = temp[ item ];
  8546. }
  8547. } );
  8548. return result;
  8549. },
  8550. _update: function ( index ) {
  8551. var options = this.data("options"),
  8552. newStack = [],
  8553. newChilds = null;
  8554. $.each( options.recordStack, function( i, item ){
  8555. if( item != index ) {
  8556. newStack.push( item );
  8557. }
  8558. } );
  8559. //压入最新的记录
  8560. newStack.unshift( index );
  8561. if( newStack.length > options.recordCount ) {
  8562. newStack.length = options.recordCount;
  8563. }
  8564. options.recordStack = newStack;
  8565. options.selected = index;
  8566. newChilds = $( $.parseTmpl( this.tpl, options ) );
  8567. //重新渲染
  8568. this.root().html( newChilds.html() );
  8569. newChilds = null;
  8570. newStack = null;
  8571. }
  8572. };
  8573. } )(), 'menu' );
  8574. })();
  8575. /**
  8576. * Combox 抽象基类
  8577. * User: hn
  8578. * Date: 13-5-29
  8579. * Time: 下午8:01
  8580. * To change this template use File | Settings | File Templates.
  8581. */
  8582. (function(){
  8583. var widgetName = 'buttoncombobox';
  8584. UM.ui.define( widgetName, ( function(){
  8585. return {
  8586. defaultOpt: {
  8587. //按钮初始文字
  8588. label: '',
  8589. title: ''
  8590. },
  8591. init: function( options ) {
  8592. var me = this;
  8593. var btnWidget = $.eduibutton({
  8594. caret: true,
  8595. name: options.comboboxName,
  8596. title: options.title,
  8597. text: options.label,
  8598. click: function(){
  8599. me.show( this.root() );
  8600. }
  8601. });
  8602. me.supper.init.call( me, options );
  8603. //监听change, 改变button显示内容
  8604. me.on('changebefore', function( e, label ){
  8605. btnWidget.eduibutton('label', label );
  8606. });
  8607. me.data( 'button', btnWidget );
  8608. me.attachTo(btnWidget)
  8609. },
  8610. button: function(){
  8611. return this.data( 'button' );
  8612. }
  8613. }
  8614. } )(), 'combobox' );
  8615. })();
  8616. /*modal 类*/
  8617. UM.ui.define('modal', {
  8618. tpl: '<div class="edui-modal" tabindex="-1" >' +
  8619. '<div class="edui-modal-header">' +
  8620. '<div class="edui-close" data-hide="modal"></div>' +
  8621. '<h3 class="edui-title"><%=title%></h3>' +
  8622. '</div>' +
  8623. '<div class="edui-modal-body" style="<%if(width){%>width:<%=width%>px;<%}%>' +
  8624. '<%if(height){%>height:<%=height%>px;<%}%>">' +
  8625. ' </div>' +
  8626. '<% if(cancellabel || oklabel) {%>' +
  8627. '<div class="edui-modal-footer">' +
  8628. '<div class="edui-modal-tip"></div>' +
  8629. '<%if(oklabel){%><div class="edui-btn edui-btn-primary" data-ok="modal"><%=oklabel%></div><%}%>' +
  8630. '<%if(cancellabel){%><div class="edui-btn" data-hide="modal"><%=cancellabel%></div><%}%>' +
  8631. '</div>' +
  8632. '<%}%></div>',
  8633. defaultOpt: {
  8634. title: "",
  8635. cancellabel: "",
  8636. oklabel: "",
  8637. width: '',
  8638. height: '',
  8639. backdrop: true,
  8640. keyboard: true
  8641. },
  8642. init: function (options) {
  8643. var me = this;
  8644. me.root($($.parseTmpl(me.tpl, options || {})));
  8645. me.data("options", options);
  8646. if (options.okFn) {
  8647. me.on('ok', $.proxy(options.okFn, me))
  8648. }
  8649. if (options.cancelFn) {
  8650. me.on('beforehide', $.proxy(options.cancelFn, me))
  8651. }
  8652. me.root().delegate('[data-hide="modal"]', 'click', $.proxy(me.hide, me))
  8653. .delegate('[data-ok="modal"]', 'click', $.proxy(me.ok, me));
  8654. $('[data-hide="modal"],[data-ok="modal"]',me.root()).hover(function(){
  8655. $(this).toggleClass('edui-hover')
  8656. });
  8657. },
  8658. toggle: function () {
  8659. var me = this;
  8660. return me[!me.data("isShown") ? 'show' : 'hide']();
  8661. },
  8662. show: function () {
  8663. var me = this;
  8664. me.trigger("beforeshow");
  8665. if (me.data("isShown")) return;
  8666. me.data("isShown", true);
  8667. me.escape();
  8668. me.backdrop(function () {
  8669. me.autoCenter();
  8670. me.root()
  8671. .show()
  8672. .focus()
  8673. .trigger('aftershow');
  8674. })
  8675. },
  8676. showTip: function ( text ) {
  8677. $( '.edui-modal-tip', this.root() ).html( text ).fadeIn();
  8678. },
  8679. hideTip: function ( text ) {
  8680. $( '.edui-modal-tip', this.root() ).fadeOut( function (){
  8681. $(this).html('');
  8682. } );
  8683. },
  8684. autoCenter: function () {
  8685. //ie6下不用处理了
  8686. !$.IE6 && this.root().css("margin-left", -(this.root().width() / 2));
  8687. },
  8688. hide: function () {
  8689. var me = this;
  8690. me.trigger("beforehide");
  8691. if (!me.data("isShown")) return;
  8692. me.data("isShown", false);
  8693. me.escape();
  8694. me.hideModal();
  8695. },
  8696. escape: function () {
  8697. var me = this;
  8698. if (me.data("isShown") && me.data("options").keyboard) {
  8699. me.root().on('keyup', function (e) {
  8700. e.which == 27 && me.hide();
  8701. })
  8702. }
  8703. else if (!me.data("isShown")) {
  8704. me.root().off('keyup');
  8705. }
  8706. },
  8707. hideModal: function () {
  8708. var me = this;
  8709. me.root().hide();
  8710. me.backdrop(function () {
  8711. me.removeBackdrop();
  8712. me.trigger('afterhide');
  8713. })
  8714. },
  8715. removeBackdrop: function () {
  8716. this.$backdrop && this.$backdrop.remove();
  8717. this.$backdrop = null;
  8718. },
  8719. backdrop: function (callback) {
  8720. var me = this;
  8721. if (me.data("isShown") && me.data("options").backdrop) {
  8722. me.$backdrop = $('<div class="edui-modal-backdrop" />').click(
  8723. me.data("options").backdrop == 'static' ?
  8724. $.proxy(me.root()[0].focus, me.root()[0])
  8725. : $.proxy(me.hide, me)
  8726. )
  8727. }
  8728. me.trigger('afterbackdrop');
  8729. callback && callback();
  8730. },
  8731. attachTo: function ($obj) {
  8732. var me = this
  8733. if (!$obj.data('$mergeObj')) {
  8734. $obj.data('$mergeObj', me.root());
  8735. $obj.on('click', function () {
  8736. me.toggle($obj)
  8737. });
  8738. me.data('$mergeObj', $obj)
  8739. }
  8740. },
  8741. ok: function () {
  8742. var me = this;
  8743. me.trigger('beforeok');
  8744. if (me.trigger("ok", me) === false) {
  8745. return;
  8746. }
  8747. me.hide();
  8748. },
  8749. getBodyContainer: function () {
  8750. return this.root().find('.edui-modal-body')
  8751. }
  8752. });
  8753. /*tooltip 类*/
  8754. UM.ui.define('tooltip', {
  8755. tpl: '<div class="edui-tooltip" unselectable="on" onmousedown="return false">' +
  8756. '<div class="edui-tooltip-arrow" unselectable="on" onmousedown="return false"></div>' +
  8757. '<div class="edui-tooltip-inner" unselectable="on" onmousedown="return false"></div>' +
  8758. '</div>',
  8759. init: function (options) {
  8760. var me = this;
  8761. me.root($($.parseTmpl(me.tpl, options || {})));
  8762. },
  8763. content: function (e) {
  8764. var me = this,
  8765. title = $(e.currentTarget).attr("data-original-title");
  8766. me.root().find('.edui-tooltip-inner')['text'](title);
  8767. },
  8768. position: function (e) {
  8769. var me = this,
  8770. $obj = $(e.currentTarget);
  8771. me.root().css($.extend({display: 'block'}, $obj ? {
  8772. top: $obj.outerHeight(),
  8773. left: (($obj.outerWidth() - me.root().outerWidth()) / 2)
  8774. } : {}))
  8775. },
  8776. show: function (e) {
  8777. if ($(e.currentTarget).hasClass('edui-disabled')) return;
  8778. var me = this;
  8779. me.content(e);
  8780. me.root().appendTo($(e.currentTarget));
  8781. me.position(e);
  8782. me.root().css('display', 'block');
  8783. },
  8784. hide: function () {
  8785. var me = this;
  8786. me.root().css('display', 'none')
  8787. },
  8788. attachTo: function ($obj) {
  8789. var me = this;
  8790. function tmp($obj) {
  8791. var me = this;
  8792. if (!$.contains(document.body, me.root()[0])) {
  8793. me.root().appendTo($obj);
  8794. }
  8795. me.data('tooltip', me.root());
  8796. $obj.each(function () {
  8797. if ($(this).attr("data-original-title")) {
  8798. $(this).on('mouseenter', $.proxy(me.show, me))
  8799. .on('mouseleave click', $.proxy(me.hide, me))
  8800. }
  8801. });
  8802. }
  8803. if ($.type($obj) === "undefined") {
  8804. $("[data-original-title]").each(function (i, el) {
  8805. tmp.call(me, $(el));
  8806. })
  8807. } else {
  8808. if (!$obj.data('tooltip')) {
  8809. tmp.call(me, $obj);
  8810. }
  8811. }
  8812. }
  8813. });
  8814. /*tab 类*/
  8815. UM.ui.define('tab', {
  8816. init: function (options) {
  8817. var me = this,
  8818. slr = options.selector;
  8819. if ($.type(slr)) {
  8820. me.root($(slr, options.context));
  8821. me.data("context", options.context);
  8822. $(slr, me.data("context")).on('click', function (e) {
  8823. me.show(e);
  8824. });
  8825. }
  8826. },
  8827. show: function (e) {
  8828. var me = this,
  8829. $cur = $(e.target),
  8830. $ul = $cur.closest('ul'),
  8831. selector,
  8832. previous,
  8833. $target,
  8834. e;
  8835. selector = $cur.attr('data-context');
  8836. selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '');
  8837. var $tmp = $cur.parent('li');
  8838. if (!$tmp.length || $tmp.hasClass('edui-active')) return;
  8839. previous = $ul.find('.edui-active:last a')[0];
  8840. e = $.Event('beforeshow', {
  8841. target: $cur[0],
  8842. relatedTarget: previous
  8843. });
  8844. me.trigger(e);
  8845. if (e.isDefaultPrevented()) return;
  8846. $target = $(selector, me.data("context"));
  8847. me.activate($cur.parent('li'), $ul);
  8848. me.activate($target, $target.parent(), function () {
  8849. me.trigger({
  8850. type: 'aftershow', relatedTarget: previous
  8851. })
  8852. });
  8853. },
  8854. activate: function (element, container, callback) {
  8855. if (element === undefined) {
  8856. return $(".edui-tab-item.edui-active",this.root()).index();
  8857. }
  8858. var $active = container.find('> .edui-active');
  8859. $active.removeClass('edui-active');
  8860. element.addClass('edui-active');
  8861. callback && callback();
  8862. }
  8863. });
  8864. //button 类
  8865. UM.ui.define('separator', {
  8866. tpl: '<div class="edui-separator" unselectable="on" onmousedown="return false" ></div>',
  8867. init: function (options) {
  8868. var me = this;
  8869. me.root($($.parseTmpl(me.tpl, options)));
  8870. return me;
  8871. }
  8872. });
  8873. /**
  8874. * @file adapter.js
  8875. * @desc adapt ui to editor
  8876. * @import core/Editor.js, core/utils.js
  8877. */
  8878. (function () {
  8879. var _editorUI = {},
  8880. _editors = {},
  8881. _readyFn = [],
  8882. _activeWidget = null,
  8883. _widgetData = {},
  8884. _widgetCallBack = {},
  8885. _cacheUI = {},
  8886. _maxZIndex = null;
  8887. utils.extend(UM, {
  8888. defaultWidth : 500,
  8889. defaultHeight : 500,
  8890. registerUI: function (name, fn) {
  8891. utils.each(name.split(/\s+/), function (uiname) {
  8892. _editorUI[uiname] = fn;
  8893. })
  8894. },
  8895. setEditor : function(editor){
  8896. !_editors[editor.id] && (_editors[editor.id] = editor);
  8897. },
  8898. registerWidget : function(name,pro,cb){
  8899. _widgetData[name] = $.extend2(pro,{
  8900. $root : '',
  8901. _preventDefault:false,
  8902. root:function($el){
  8903. return this.$root || (this.$root = $el);
  8904. },
  8905. preventDefault:function(){
  8906. this._preventDefault = true;
  8907. },
  8908. clear:false
  8909. });
  8910. if(cb){
  8911. _widgetCallBack[name] = cb;
  8912. }
  8913. },
  8914. getWidgetData : function(name){
  8915. return _widgetData[name]
  8916. },
  8917. setWidgetBody : function(name,$widget,editor){
  8918. if(!editor._widgetData){
  8919. utils.extend(editor,{
  8920. _widgetData : {},
  8921. getWidgetData : function(name){
  8922. return this._widgetData[name];
  8923. },
  8924. getWidgetCallback : function(widgetName){
  8925. var me = this;
  8926. return function(){
  8927. return _widgetCallBack[widgetName].apply(me,[me,$widget].concat(Array.prototype.slice.call(arguments,0)))
  8928. }
  8929. }
  8930. })
  8931. }
  8932. var pro = _widgetData[name];
  8933. if(!pro){
  8934. return null;
  8935. }
  8936. pro = editor._widgetData[name];
  8937. if(!pro){
  8938. pro = _widgetData[name];
  8939. pro = editor._widgetData[name] = $.type(pro) == 'function' ? pro : utils.clone(pro);
  8940. }
  8941. pro.root($widget.edui().getBodyContainer());
  8942. pro.initContent(editor,$widget);
  8943. if(!pro._preventDefault){
  8944. pro.initEvent(editor,$widget);
  8945. }
  8946. pro.width && $widget.width(pro.width);
  8947. },
  8948. setActiveWidget : function($widget){
  8949. _activeWidget = $widget;
  8950. },
  8951. getEditor: function (id, options) {
  8952. var editor = _editors[id] || (_editors[id] = this.createEditor(id, options));
  8953. _maxZIndex = _maxZIndex ? Math.max(editor.getOpt('zIndex'), _maxZIndex):editor.getOpt('zIndex');
  8954. return editor;
  8955. },
  8956. setTopEditor: function(editor){
  8957. $.each(_editors, function(i, o){
  8958. if(editor == o) {
  8959. editor.$container && editor.$container.css('zIndex', _maxZIndex + 1);
  8960. } else {
  8961. o.$container && o.$container.css('zIndex', o.getOpt('zIndex'));
  8962. }
  8963. });
  8964. },
  8965. clearCache : function(id){
  8966. if ( _editors[id]) {
  8967. delete _editors[id]
  8968. }
  8969. },
  8970. delEditor: function (id) {
  8971. var editor;
  8972. if (editor = _editors[id]) {
  8973. editor.destroy();
  8974. }
  8975. },
  8976. ready: function( fn ){
  8977. _readyFn.push( fn );
  8978. },
  8979. createEditor: function (id, opt) {
  8980. var editor = new UM.Editor(opt);
  8981. var T = this;
  8982. editor.langIsReady ? $.proxy(renderUI,T)() : editor.addListener("langReady", $.proxy(renderUI,T));
  8983. function renderUI(){
  8984. var $container = this.createUI('#' + id, editor);
  8985. editor.key=id;
  8986. editor.ready(function(){
  8987. $.each( _readyFn, function( index, fn ){
  8988. $.proxy( fn, editor )();
  8989. } );
  8990. });
  8991. var options = editor.options;
  8992. if(options.initialFrameWidth){
  8993. options.minFrameWidth = options.initialFrameWidth
  8994. }else{
  8995. options.minFrameWidth = options.initialFrameWidth = editor.$body.width() || UM.defaultWidth;
  8996. }
  8997. $container.css({
  8998. width: options.initialFrameWidth,
  8999. zIndex:editor.getOpt('zIndex')
  9000. });
  9001. //ie6下缓存图片
  9002. UM.browser.ie && UM.browser.version === 6 && document.execCommand("BackgroundImageCache", false, true);
  9003. editor.render(id);
  9004. //添加tooltip;
  9005. $.eduitooltip && $.eduitooltip('attachTo', $("[data-original-title]",$container)).css('z-index',editor.getOpt('zIndex')+1);
  9006. $container.find('a').click(function(evt){
  9007. evt.preventDefault()
  9008. });
  9009. editor.fireEvent("afteruiready");
  9010. }
  9011. return editor;
  9012. },
  9013. createUI: function (id, editor) {
  9014. var $editorCont = $(id),
  9015. $container = $('<div class="edui-container"><div class="edui-editor-body"></div></div>').insertBefore($editorCont);
  9016. editor.$container = $container;
  9017. editor.container = $container[0];
  9018. editor.$body = $editorCont;
  9019. //修正在ie9+以上的版本中,自动长高收起时的,残影问题
  9020. if(browser.ie && browser.ie9above){
  9021. var $span = $('<span style="padding:0;margin:0;height:0;width:0"></span>');
  9022. $span.insertAfter($container);
  9023. }
  9024. //初始化注册的ui组件
  9025. $.each(_editorUI,function(n,v){
  9026. var widget = v.call(editor,n);
  9027. if(widget){
  9028. _cacheUI[n] = widget;
  9029. }
  9030. });
  9031. $container.find('.edui-editor-body').append($editorCont).before(this.createToolbar(editor.options, editor));
  9032. $container.find('.edui-toolbar').append($('<div class="edui-dialog-container"></div>'));
  9033. return $container;
  9034. },
  9035. createToolbar: function (options, editor) {
  9036. var $toolbar = $.eduitoolbar(), toolbar = $toolbar.edui();
  9037. //创建下来菜单列表
  9038. if (options.toolbar && options.toolbar.length) {
  9039. var btns = [];
  9040. $.each(options.toolbar,function(i,uiNames){
  9041. $.each(uiNames.split(/\s+/),function(index,name){
  9042. if(name == '|'){
  9043. $.eduiseparator && btns.push($.eduiseparator());
  9044. }else{
  9045. var ui = _cacheUI[name];
  9046. if(name=="fullscreen"){
  9047. ui&&btns.unshift(ui);
  9048. }else{
  9049. ui && btns.push(ui);
  9050. }
  9051. }
  9052. });
  9053. btns.length && toolbar.appendToBtnmenu(btns);
  9054. });
  9055. } else {
  9056. $toolbar.find('.edui-btn-toolbar').remove()
  9057. }
  9058. return $toolbar;
  9059. }
  9060. })
  9061. })();
  9062. UM.registerUI('bold italic redo undo underline strikethrough superscript subscript insertorderedlist insertunorderedlist ' +
  9063. 'cleardoc selectall link unlink print preview justifyleft justifycenter justifyright justifyfull removeformat horizontal drafts',
  9064. function(name) {
  9065. var me = this;
  9066. var $btn = $.eduibutton({
  9067. icon : name,
  9068. click : function(){
  9069. me.execCommand(name);
  9070. },
  9071. title: this.getLang('labelMap')[name] || ''
  9072. });
  9073. this.addListener('selectionchange',function(){
  9074. var state = this.queryCommandState(name);
  9075. $btn.edui().disabled(state == -1).active(state == 1)
  9076. });
  9077. return $btn;
  9078. }
  9079. );
  9080. /**
  9081. * 全屏组件
  9082. */
  9083. (function(){
  9084. //状态缓存
  9085. var STATUS_CACHE = {},
  9086. //状态值列表
  9087. STATUS_LIST = [ 'width', 'height', 'position', 'top', 'left', 'margin', 'padding', 'overflowX', 'overflowY' ],
  9088. CONTENT_AREA_STATUS = {},
  9089. //页面状态
  9090. DOCUMENT_STATUS = {},
  9091. DOCUMENT_ELEMENT_STATUS = {},
  9092. FULLSCREENS = {};
  9093. UM.registerUI('fullscreen', function( name ){
  9094. var me = this,
  9095. $button = $.eduibutton({
  9096. 'icon': 'fullscreen',
  9097. 'title': (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9098. 'click': function(){
  9099. //切换
  9100. me.execCommand( name );
  9101. UM.setTopEditor(me);
  9102. }
  9103. });
  9104. me.addListener( "selectionchange", function () {
  9105. var state = this.queryCommandState( name );
  9106. $button.edui().disabled( state == -1 ).active( state == 1 );
  9107. } );
  9108. //切换至全屏
  9109. me.addListener('ready', function(){
  9110. me.options.fullscreen && Fullscreen.getInstance( me ).toggle();
  9111. });
  9112. return $button;
  9113. });
  9114. UM.commands[ 'fullscreen' ] = {
  9115. execCommand: function (cmdName) {
  9116. Fullscreen.getInstance( this ).toggle();
  9117. },
  9118. queryCommandState: function (cmdName) {
  9119. return this._edui_fullscreen_status;
  9120. },
  9121. notNeedUndo: 1
  9122. };
  9123. function Fullscreen( editor ) {
  9124. var me = this;
  9125. if( !editor ) {
  9126. throw new Error('invalid params, notfound editor');
  9127. }
  9128. me.editor = editor;
  9129. //记录初始化的全屏组件
  9130. FULLSCREENS[ editor.uid ] = this;
  9131. editor.addListener('destroy', function(){
  9132. delete FULLSCREENS[ editor.uid ];
  9133. me.editor = null;
  9134. });
  9135. }
  9136. Fullscreen.prototype = {
  9137. /**
  9138. * 全屏状态切换
  9139. */
  9140. toggle: function(){
  9141. var editor = this.editor,
  9142. //当前编辑器的缩放状态
  9143. _edui_fullscreen_status = this.isFullState();
  9144. editor.fireEvent('beforefullscreenchange', !_edui_fullscreen_status );
  9145. //更新状态
  9146. this.update( !_edui_fullscreen_status );
  9147. !_edui_fullscreen_status ? this.enlarge() : this.revert();
  9148. editor.fireEvent('afterfullscreenchange', !_edui_fullscreen_status );
  9149. if(editor.body.contentEditable === 'true'){
  9150. editor.fireEvent( 'fullscreenchanged', !_edui_fullscreen_status );
  9151. }
  9152. editor.fireEvent( 'selectionchange' );
  9153. },
  9154. /**
  9155. * 执行放大
  9156. */
  9157. enlarge: function(){
  9158. this.saveSataus();
  9159. this.setDocumentStatus();
  9160. this.resize();
  9161. },
  9162. /**
  9163. * 全屏还原
  9164. */
  9165. revert: function(){
  9166. //还原CSS表达式
  9167. var options = this.editor.options,
  9168. height = /%$/.test(options.initialFrameHeight) ? '100%' : (options.initialFrameHeight - this.getStyleValue("padding-top")- this.getStyleValue("padding-bottom") - this.getStyleValue('border-width'));
  9169. $.IE6 && this.getEditorHolder().style.setExpression('height', 'this.scrollHeight <= ' + height + ' ? "' + height + 'px" : "auto"');
  9170. //还原容器状态
  9171. this.revertContainerStatus();
  9172. this.revertContentAreaStatus();
  9173. this.revertDocumentStatus();
  9174. },
  9175. /**
  9176. * 更新状态
  9177. * @param isFull 当前状态是否是全屏状态
  9178. */
  9179. update: function( isFull ) {
  9180. this.editor._edui_fullscreen_status = isFull;
  9181. },
  9182. /**
  9183. * 调整当前编辑器的大小, 如果当前编辑器不处于全屏状态, 则不做调整
  9184. */
  9185. resize: function(){
  9186. var $win = null,
  9187. height = 0,
  9188. width = 0,
  9189. borderWidth = 0,
  9190. paddingWidth = 0,
  9191. editor = this.editor,
  9192. me = this,
  9193. bound = null,
  9194. editorBody = null;
  9195. if( !this.isFullState() ) {
  9196. return;
  9197. }
  9198. $win = $( window );
  9199. width = $win.width();
  9200. height = $win.height();
  9201. editorBody = this.getEditorHolder();
  9202. //文本编辑区border宽度
  9203. borderWidth = parseInt( domUtils.getComputedStyle( editorBody, 'border-width' ), 10 ) || 0;
  9204. //容器border宽度
  9205. borderWidth += parseInt( domUtils.getComputedStyle( editor.container, 'border-width' ), 10 ) || 0;
  9206. //容器padding
  9207. paddingWidth += parseInt( domUtils.getComputedStyle( editorBody, 'padding-left' ), 10 ) + parseInt( domUtils.getComputedStyle( editorBody, 'padding-right' ), 10 ) || 0;
  9208. //干掉css表达式
  9209. $.IE6 && editorBody.style.setExpression( 'height', null );
  9210. bound = this.getBound();
  9211. $( editor.container ).css( {
  9212. width: width + 'px',
  9213. height: height + 'px',
  9214. position: !$.IE6 ? 'fixed' : 'absolute',
  9215. top: bound.top,
  9216. left: bound.left,
  9217. margin: 0,
  9218. padding: 0,
  9219. overflowX: 'hidden',
  9220. overflowY: 'hidden'
  9221. } );
  9222. $( editorBody ).css({
  9223. width: width - 2*borderWidth - paddingWidth + 'px',
  9224. height: height - 2*borderWidth - ( editor.options.withoutToolbar ? 0 : $( '.edui-toolbar', editor.container ).outerHeight() ) - $( '.edui-bottombar', editor.container).outerHeight() + 'px',
  9225. overflowX: 'hidden',
  9226. overflowY: 'auto'
  9227. });
  9228. },
  9229. /**
  9230. * 保存状态
  9231. */
  9232. saveSataus: function(){
  9233. var styles = this.editor.container.style,
  9234. tmp = null,
  9235. cache = {};
  9236. for( var i= 0, len = STATUS_LIST.length; i<len; i++ ) {
  9237. tmp = STATUS_LIST[ i ];
  9238. cache[ tmp ] = styles[ tmp ];
  9239. }
  9240. STATUS_CACHE[ this.editor.uid ] = cache;
  9241. this.saveContentAreaStatus();
  9242. this.saveDocumentStatus();
  9243. },
  9244. saveContentAreaStatus: function(){
  9245. var $holder = $(this.getEditorHolder());
  9246. CONTENT_AREA_STATUS[ this.editor.uid ] = {
  9247. width: $holder.css("width"),
  9248. overflowX: $holder.css("overflowX"),
  9249. overflowY: $holder.css("overflowY"),
  9250. height: $holder.css("height")
  9251. };
  9252. },
  9253. /**
  9254. * 保存与指定editor相关的页面的状态
  9255. */
  9256. saveDocumentStatus: function(){
  9257. var $doc = $( this.getEditorDocumentBody() );
  9258. DOCUMENT_STATUS[ this.editor.uid ] = {
  9259. overflowX: $doc.css( 'overflowX' ),
  9260. overflowY: $doc.css( 'overflowY' )
  9261. };
  9262. DOCUMENT_ELEMENT_STATUS[ this.editor.uid ] = {
  9263. overflowX: $( this.getEditorDocumentElement() ).css( 'overflowX'),
  9264. overflowY: $( this.getEditorDocumentElement() ).css( 'overflowY' )
  9265. };
  9266. },
  9267. /**
  9268. * 恢复容器状态
  9269. */
  9270. revertContainerStatus: function(){
  9271. $( this.editor.container ).css( this.getEditorStatus() );
  9272. },
  9273. /**
  9274. * 恢复编辑区状态
  9275. */
  9276. revertContentAreaStatus: function(){
  9277. var holder = this.getEditorHolder(),
  9278. state = this.getContentAreaStatus();
  9279. if ( this.supportMin() ) {
  9280. delete state.height;
  9281. holder.style.height = null;
  9282. }
  9283. $( holder ).css( state );
  9284. },
  9285. /**
  9286. * 恢复页面状态
  9287. */
  9288. revertDocumentStatus: function() {
  9289. var status = this.getDocumentStatus();
  9290. $( this.getEditorDocumentBody() ).css( 'overflowX', status.body.overflowX );
  9291. $( this.getEditorDocumentElement() ).css( 'overflowY', status.html.overflowY );
  9292. },
  9293. setDocumentStatus: function(){
  9294. $(this.getEditorDocumentBody()).css( {
  9295. overflowX: 'hidden',
  9296. overflowY: 'hidden'
  9297. } );
  9298. $(this.getEditorDocumentElement()).css( {
  9299. overflowX: 'hidden',
  9300. overflowY: 'hidden'
  9301. } );
  9302. },
  9303. /**
  9304. * 检测当前编辑器是否处于全屏状态全屏状态
  9305. * @returns {boolean} 是否处于全屏状态
  9306. */
  9307. isFullState: function(){
  9308. return !!this.editor._edui_fullscreen_status;
  9309. },
  9310. /**
  9311. * 获取编辑器状态
  9312. */
  9313. getEditorStatus: function(){
  9314. return STATUS_CACHE[ this.editor.uid ];
  9315. },
  9316. getContentAreaStatus: function(){
  9317. return CONTENT_AREA_STATUS[ this.editor.uid ];
  9318. },
  9319. getEditorDocumentElement: function(){
  9320. return this.editor.container.ownerDocument.documentElement;
  9321. },
  9322. getEditorDocumentBody: function(){
  9323. return this.editor.container.ownerDocument.body;
  9324. },
  9325. /**
  9326. * 获取编辑区包裹对象
  9327. */
  9328. getEditorHolder: function(){
  9329. return this.editor.body;
  9330. },
  9331. /**
  9332. * 获取编辑器状态
  9333. * @returns {*}
  9334. */
  9335. getDocumentStatus: function(){
  9336. return {
  9337. 'body': DOCUMENT_STATUS[ this.editor.uid ],
  9338. 'html': DOCUMENT_ELEMENT_STATUS[ this.editor.uid ]
  9339. };
  9340. },
  9341. supportMin: function () {
  9342. var node = null;
  9343. if ( !this._support ) {
  9344. node = document.createElement("div");
  9345. this._support = "minWidth" in node.style;
  9346. node = null;
  9347. }
  9348. return this._support;
  9349. },
  9350. getBound: function () {
  9351. var tags = {
  9352. html: true,
  9353. body: true
  9354. },
  9355. result = {
  9356. top: 0,
  9357. left: 0
  9358. },
  9359. offsetParent = null;
  9360. if ( !$.IE6 ) {
  9361. return result;
  9362. }
  9363. offsetParent = this.editor.container.offsetParent;
  9364. if( offsetParent && !tags[ offsetParent.nodeName.toLowerCase() ] ) {
  9365. tags = offsetParent.getBoundingClientRect();
  9366. result.top = -tags.top;
  9367. result.left = -tags.left;
  9368. }
  9369. return result;
  9370. },
  9371. getStyleValue: function (attr) {
  9372. return parseInt(domUtils.getComputedStyle( this.getEditorHolder() ,attr));
  9373. }
  9374. };
  9375. $.extend( Fullscreen, {
  9376. /**
  9377. * 监听resize
  9378. */
  9379. listen: function(){
  9380. var timer = null;
  9381. if( Fullscreen._hasFullscreenListener ) {
  9382. return;
  9383. }
  9384. Fullscreen._hasFullscreenListener = true;
  9385. $( window ).on( 'resize', function(){
  9386. if( timer !== null ) {
  9387. window.clearTimeout( timer );
  9388. timer = null;
  9389. }
  9390. timer = window.setTimeout(function(){
  9391. for( var key in FULLSCREENS ) {
  9392. FULLSCREENS[ key ].resize();
  9393. }
  9394. timer = null;
  9395. }, 50);
  9396. } );
  9397. },
  9398. getInstance: function ( editor ) {
  9399. if ( !FULLSCREENS[editor.uid ] ) {
  9400. new Fullscreen( editor );
  9401. }
  9402. return FULLSCREENS[editor.uid ];
  9403. }
  9404. });
  9405. //开始监听
  9406. Fullscreen.listen();
  9407. })();
  9408. UM.registerUI('link image video map formula',function(name){
  9409. var me = this, currentRange, $dialog,
  9410. opt = {
  9411. title: (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9412. url: me.options.UMEDITOR_HOME_URL + 'dialogs/' + name + '/' + name + '.js'
  9413. };
  9414. var $btn = $.eduibutton({
  9415. icon: name,
  9416. title: this.getLang('labelMap')[name] || ''
  9417. });
  9418. //加载模版数据
  9419. utils.loadFile(document,{
  9420. src: opt.url,
  9421. tag: "script",
  9422. type: "text/javascript",
  9423. defer: "defer"
  9424. },function(){
  9425. //调整数据
  9426. var data = UM.getWidgetData(name);
  9427. if(!data) return;
  9428. if(data.buttons){
  9429. var ok = data.buttons.ok;
  9430. if(ok){
  9431. opt.oklabel = ok.label || me.getLang('ok');
  9432. if(ok.exec){
  9433. opt.okFn = function(){
  9434. return $.proxy(ok.exec,null,me,$dialog)()
  9435. }
  9436. }
  9437. }
  9438. var cancel = data.buttons.cancel;
  9439. if(cancel){
  9440. opt.cancellabel = cancel.label || me.getLang('cancel');
  9441. if(cancel.exec){
  9442. opt.cancelFn = function(){
  9443. return $.proxy(cancel.exec,null,me,$dialog)()
  9444. }
  9445. }
  9446. }
  9447. }
  9448. data.width && (opt.width = data.width);
  9449. data.height && (opt.height = data.height);
  9450. $dialog = $.eduimodal(opt);
  9451. $dialog.attr('id', 'edui-dialog-' + name).addClass('edui-dialog-' + name)
  9452. .find('.edui-modal-body').addClass('edui-dialog-' + name + '-body');
  9453. $dialog.edui().on('beforehide',function () {
  9454. var rng = me.selection.getRange();
  9455. if (rng.equals(currentRange)) {
  9456. rng.select()
  9457. }
  9458. }).on('beforeshow', function () {
  9459. var $root = this.root(),
  9460. win = null,
  9461. offset = null;
  9462. currentRange = me.selection.getRange();
  9463. if (!$root.parent()[0]) {
  9464. me.$container.find('.edui-dialog-container').append($root);
  9465. }
  9466. //IE6下 特殊处理, 通过计算进行定位
  9467. if( $.IE6 ) {
  9468. win = {
  9469. width: $( window ).width(),
  9470. height: $( window ).height()
  9471. };
  9472. offset = $root.parents(".edui-toolbar")[0].getBoundingClientRect();
  9473. $root.css({
  9474. position: 'absolute',
  9475. margin: 0,
  9476. left: ( win.width - $root.width() ) / 2 - offset.left,
  9477. top: 100 - offset.top
  9478. });
  9479. }
  9480. UM.setWidgetBody(name,$dialog,me);
  9481. UM.setTopEditor(me);
  9482. }).on('afterbackdrop',function(){
  9483. this.$backdrop.css('zIndex',me.getOpt('zIndex')+1).appendTo(me.$container.find('.edui-dialog-container'))
  9484. $dialog.css('zIndex',me.getOpt('zIndex')+2)
  9485. }).on('beforeok',function(){
  9486. try{
  9487. currentRange.select()
  9488. }catch(e){}
  9489. }).attachTo($btn)
  9490. });
  9491. me.addListener('selectionchange', function () {
  9492. var state = this.queryCommandState(name);
  9493. $btn.edui().disabled(state == -1).active(state == 1)
  9494. });
  9495. return $btn;
  9496. });
  9497. UM.registerUI( 'emotion formula', function( name ){
  9498. var me = this,
  9499. url = me.options.UMEDITOR_HOME_URL + 'dialogs/' +name+ '/'+name+'.js';
  9500. var $btn = $.eduibutton({
  9501. icon: name,
  9502. title: this.getLang('labelMap')[name] || ''
  9503. });
  9504. //加载模版数据
  9505. utils.loadFile(document,{
  9506. src: url,
  9507. tag: "script",
  9508. type: "text/javascript",
  9509. defer: "defer"
  9510. },function(){
  9511. var opt = {
  9512. url : url
  9513. };
  9514. //调整数据
  9515. var data = UM.getWidgetData(name);
  9516. data.width && (opt.width = data.width);
  9517. data.height && (opt.height = data.height);
  9518. $.eduipopup(opt).css('zIndex',me.options.zIndex + 1)
  9519. .addClass('edui-popup-' + name)
  9520. .edui()
  9521. .on('beforeshow',function(){
  9522. var $root = this.root();
  9523. if(!$root.parent().length){
  9524. me.$container.find('.edui-dialog-container').append($root);
  9525. }
  9526. UM.setWidgetBody(name,$root,me);
  9527. UM.setTopEditor(me);
  9528. }).attachTo($btn,{
  9529. offsetTop:-5,
  9530. offsetLeft:10,
  9531. caretLeft:11,
  9532. caretTop:-8
  9533. });
  9534. me.addListener('selectionchange', function () {
  9535. var state = this.queryCommandState(name);
  9536. $btn.edui().disabled(state == -1).active(state == 1);
  9537. });
  9538. });
  9539. return $btn;
  9540. } );
  9541. UM.registerUI('imagescale',function () {
  9542. var me = this,
  9543. $imagescale;
  9544. me.setOpt('imageScaleEnabled', true);
  9545. if (browser.webkit && me.getOpt('imageScaleEnabled')) {
  9546. me.addListener('click', function (type, e) {
  9547. var range = me.selection.getRange(),
  9548. img = range.getClosedNode(),
  9549. target = e.target;
  9550. /* 点击第一个图片的后面,八个角不消失 fix:3652 */
  9551. if (img && img.tagName == 'IMG' && target == img) {
  9552. if (!$imagescale) {
  9553. $imagescale = $.eduiscale({'$wrap':me.$container}).css('zIndex', me.options.zIndex);
  9554. me.$container.append($imagescale);
  9555. var _keyDownHandler = function () {
  9556. $imagescale.edui().hide();
  9557. }, _mouseDownHandler = function (e) {
  9558. var ele = e.target || e.srcElement;
  9559. if (ele && ele.className.indexOf('edui-scale') == -1) {
  9560. _keyDownHandler(e);
  9561. }
  9562. }, timer;
  9563. $imagescale.edui()
  9564. .on('aftershow', function () {
  9565. $(document).bind('keydown', _keyDownHandler);
  9566. $(document).bind('mousedown', _mouseDownHandler);
  9567. me.selection.getNative().removeAllRanges();
  9568. })
  9569. .on('afterhide', function () {
  9570. $(document).unbind('keydown', _keyDownHandler);
  9571. $(document).unbind('mousedown', _mouseDownHandler);
  9572. var target = $imagescale.edui().getScaleTarget();
  9573. if (target.parentNode) {
  9574. me.selection.getRange().selectNode(target).select();
  9575. }
  9576. })
  9577. .on('mousedown', function (e) {
  9578. me.selection.getNative().removeAllRanges();
  9579. var ele = e.target || e.srcElement;
  9580. if (ele && ele.className.indexOf('edui-scale-hand') == -1) {
  9581. timer = setTimeout(function() {
  9582. $imagescale.edui().hide();
  9583. }, 200);
  9584. }
  9585. })
  9586. .on('mouseup', function (e) {
  9587. var ele = e.target || e.srcElement;
  9588. if (ele && ele.className.indexOf('edui-scale-hand') == -1) {
  9589. clearTimeout(timer);
  9590. }
  9591. });
  9592. }
  9593. $imagescale.edui().show($(img));
  9594. } else {
  9595. if ($imagescale && $imagescale.css('display') != 'none') $imagescale.edui().hide();
  9596. }
  9597. });
  9598. me.addListener('click', function (type, e) {
  9599. if (e.target.tagName == 'IMG') {
  9600. var range = new dom.Range(me.document, me.body);
  9601. range.selectNode(e.target).select();
  9602. }
  9603. });
  9604. }
  9605. });
  9606. UM.registerUI('autofloat',function(){
  9607. var me = this,
  9608. lang = me.getLang();
  9609. me.setOpt({
  9610. autoFloatEnabled: true,
  9611. topOffset: 0
  9612. });
  9613. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  9614. topOffset = me.options.topOffset;
  9615. //如果不固定toolbar的位置,则直接退出
  9616. if(!optsAutoFloatEnabled){
  9617. return;
  9618. }
  9619. me.ready(function(){
  9620. var LteIE6 = browser.ie && browser.version <= 6,
  9621. quirks = browser.quirks;
  9622. function checkHasUI(){
  9623. if(!UM.ui){
  9624. alert(lang.autofloatMsg);
  9625. return 0;
  9626. }
  9627. return 1;
  9628. }
  9629. function fixIE6FixedPos(){
  9630. var docStyle = document.body.style;
  9631. docStyle.backgroundImage = 'url("about:blank")';
  9632. docStyle.backgroundAttachment = 'fixed';
  9633. }
  9634. var bakCssText,
  9635. placeHolder = document.createElement('div'),
  9636. toolbarBox,orgTop,
  9637. getPosition=function(element){
  9638. var bcr;
  9639. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  9640. try{
  9641. bcr = element.getBoundingClientRect();
  9642. }catch(e){
  9643. bcr={left:0,top:0,height:0,width:0}
  9644. }
  9645. var rect = {
  9646. left: Math.round(bcr.left),
  9647. top: Math.round(bcr.top),
  9648. height: Math.round(bcr.bottom - bcr.top),
  9649. width: Math.round(bcr.right - bcr.left)
  9650. };
  9651. var doc;
  9652. while ((doc = element.ownerDocument) !== document &&
  9653. (element = domUtils.getWindow(doc).frameElement)) {
  9654. bcr = element.getBoundingClientRect();
  9655. rect.left += bcr.left;
  9656. rect.top += bcr.top;
  9657. }
  9658. rect.bottom = rect.top + rect.height;
  9659. rect.right = rect.left + rect.width;
  9660. return rect;
  9661. };
  9662. var isFullScreening = false;
  9663. function setFloating(){
  9664. if(isFullScreening){
  9665. return;
  9666. }
  9667. var toobarBoxPos = domUtils.getXY(toolbarBox),
  9668. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  9669. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  9670. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  9671. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  9672. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  9673. if (LteIE6 || (quirks && browser.ie)) {
  9674. if(toolbarBox.style.position != 'absolute'){
  9675. toolbarBox.style.position = 'absolute';
  9676. }
  9677. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  9678. } else {
  9679. if(toolbarBox.style.position != 'fixed'){
  9680. toolbarBox.style.position = 'fixed';
  9681. toolbarBox.style.top = topOffset +"px";
  9682. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  9683. }
  9684. }
  9685. }
  9686. function unsetFloating(){
  9687. if(placeHolder.parentNode){
  9688. placeHolder.parentNode.removeChild(placeHolder);
  9689. }
  9690. toolbarBox.style.cssText = bakCssText;
  9691. }
  9692. function updateFloating(){
  9693. var rect3 = getPosition(me.container);
  9694. var offset=me.options.toolbarTopOffset||0;
  9695. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  9696. setFloating();
  9697. }else{
  9698. unsetFloating();
  9699. }
  9700. }
  9701. var defer_updateFloating = utils.defer(function(){
  9702. updateFloating();
  9703. },browser.ie ? 200 : 100,true);
  9704. me.addListener('destroy',function(){
  9705. $(window).off('scroll resize',updateFloating);
  9706. me.removeListener('keydown', defer_updateFloating);
  9707. });
  9708. if(checkHasUI(me)){
  9709. toolbarBox = $('.edui-toolbar',me.container)[0];
  9710. me.addListener("afteruiready",function(){
  9711. setTimeout(function(){
  9712. orgTop = $(toolbarBox).offset().top;
  9713. },100);
  9714. });
  9715. bakCssText = toolbarBox.style.cssText;
  9716. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  9717. if(LteIE6){
  9718. fixIE6FixedPos();
  9719. }
  9720. $(window).on('scroll resize',updateFloating);
  9721. me.addListener('keydown', defer_updateFloating);
  9722. me.addListener('resize', function(){
  9723. unsetFloating();
  9724. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  9725. updateFloating();
  9726. });
  9727. me.addListener('beforefullscreenchange', function (t, enabled){
  9728. if (enabled) {
  9729. unsetFloating();
  9730. isFullScreening = enabled;
  9731. }
  9732. });
  9733. me.addListener('fullscreenchanged', function (t, enabled){
  9734. if (!enabled) {
  9735. updateFloating();
  9736. }
  9737. isFullScreening = enabled;
  9738. });
  9739. me.addListener('sourcemodechanged', function (t, enabled){
  9740. setTimeout(function (){
  9741. updateFloating();
  9742. },0);
  9743. });
  9744. me.addListener("clearDoc",function(){
  9745. setTimeout(function(){
  9746. updateFloating();
  9747. },0);
  9748. })
  9749. }
  9750. })
  9751. });
  9752. UM.registerUI('source',function(name){
  9753. var me = this;
  9754. me.addListener('fullscreenchanged',function(){
  9755. me.$container.find('textarea').width(me.$body.width() - 10).height(me.$body.height())
  9756. });
  9757. var $btn = $.eduibutton({
  9758. icon : name,
  9759. click : function(){
  9760. me.execCommand(name);
  9761. UM.setTopEditor(me);
  9762. },
  9763. title: this.getLang('labelMap')[name] || ''
  9764. });
  9765. this.addListener('selectionchange',function(){
  9766. var state = this.queryCommandState(name);
  9767. $btn.edui().disabled(state == -1).active(state == 1)
  9768. });
  9769. return $btn;
  9770. });
  9771. UM.registerUI('paragraph fontfamily fontsize', function( name ) {
  9772. var me = this,
  9773. label = (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9774. options = {
  9775. label: label,
  9776. title: label,
  9777. comboboxName: name,
  9778. items: me.options[ name ] || [],
  9779. itemStyles: [],
  9780. value: [],
  9781. autowidthitem: []
  9782. },
  9783. $combox = null,
  9784. comboboxWidget = null;
  9785. if(options.items.length == 0){
  9786. return null;
  9787. }
  9788. switch ( name ) {
  9789. case 'paragraph':
  9790. options = transForParagraph( options );
  9791. break;
  9792. case 'fontfamily':
  9793. options = transForFontfamily( options );
  9794. break;
  9795. case 'fontsize':
  9796. options = transForFontsize( options );
  9797. break;
  9798. }
  9799. //实例化
  9800. $combox = $.eduibuttoncombobox(options).css('zIndex',me.getOpt('zIndex') + 1);
  9801. comboboxWidget = $combox.edui();
  9802. comboboxWidget.on('comboboxselect', function( evt, res ){
  9803. me.execCommand( name, res.value );
  9804. }).on("beforeshow", function(){
  9805. if( $combox.parent().length === 0 ) {
  9806. $combox.appendTo( me.$container.find('.edui-dialog-container') );
  9807. }
  9808. UM.setTopEditor(me);
  9809. });
  9810. //状态反射
  9811. this.addListener('selectionchange',function( evt ){
  9812. var state = this.queryCommandState( name ),
  9813. value = this.queryCommandValue( name );
  9814. //设置按钮状态
  9815. comboboxWidget.button().edui().disabled( state == -1 ).active( state == 1 );
  9816. if(value){
  9817. //设置label
  9818. value = value.replace(/['"]/g, '').toLowerCase().split(/['|"]?\s*,\s*[\1]?/);
  9819. comboboxWidget.selectItemByLabel( value );
  9820. }
  9821. });
  9822. return comboboxWidget.button().addClass('edui-combobox');
  9823. /**
  9824. * 宽度自适应工具函数
  9825. * @param word 单词内容
  9826. * @param hasSuffix 是否含有后缀
  9827. */
  9828. function wordCountAdaptive ( word, hasSuffix ) {
  9829. var $tmpNode = $('<span>' ).html( word ).css( {
  9830. display: 'inline',
  9831. position: 'absolute',
  9832. top: -10000000,
  9833. left: -100000
  9834. } ).appendTo( document.body),
  9835. width = $tmpNode.width();
  9836. $tmpNode.remove();
  9837. $tmpNode = null;
  9838. if( width < 50 ) {
  9839. return word;
  9840. } else {
  9841. word = word.slice( 0, hasSuffix ? -4 : -1 );
  9842. if( !word.length ) {
  9843. return '...';
  9844. }
  9845. return wordCountAdaptive( word + '...', true );
  9846. }
  9847. }
  9848. //段落参数转换
  9849. function transForParagraph ( options ) {
  9850. var tempItems = [];
  9851. for( var key in options.items ) {
  9852. options.value.push( key );
  9853. tempItems.push( key );
  9854. options.autowidthitem.push( wordCountAdaptive( key ) );
  9855. }
  9856. options.items = tempItems;
  9857. options.autoRecord = false;
  9858. return options;
  9859. }
  9860. //字体参数转换
  9861. function transForFontfamily ( options ) {
  9862. var temp = null,
  9863. tempItems = [];
  9864. for( var i = 0, len = options.items.length; i < len; i++ ) {
  9865. temp = options.items[ i ].val;
  9866. tempItems.push( temp.split(/\s*,\s*/)[0] );
  9867. options.itemStyles.push('font-family: ' + temp);
  9868. options.value.push( temp );
  9869. options.autowidthitem.push( wordCountAdaptive( tempItems[ i ] ) );
  9870. }
  9871. options.items = tempItems;
  9872. return options;
  9873. }
  9874. //字体大小参数转换
  9875. function transForFontsize ( options ) {
  9876. var temp = null,
  9877. tempItems = [];
  9878. options.itemStyles = [];
  9879. options.value = [];
  9880. for( var i = 0, len = options.items.length; i < len; i++ ) {
  9881. temp = options.items[ i ];
  9882. tempItems.push( temp );
  9883. options.itemStyles.push('font-size: ' + temp +'px');
  9884. }
  9885. options.value = options.items;
  9886. options.items = tempItems;
  9887. options.autoRecord = false;
  9888. return options;
  9889. }
  9890. });
  9891. UM.registerUI('forecolor backcolor', function( name ) {
  9892. function getCurrentColor() {
  9893. return domUtils.getComputedStyle( $colorLabel[0], 'background-color' );
  9894. }
  9895. var me = this,
  9896. $colorPickerWidget = null,
  9897. $colorLabel = null,
  9898. $btn = null;
  9899. //querycommand
  9900. this.addListener('selectionchange', function(){
  9901. var state = this.queryCommandState( name );
  9902. $btn.edui().disabled( state == -1 ).active( state == 1 );
  9903. });
  9904. $btn = $.eduicolorsplitbutton({
  9905. icon: name,
  9906. caret: true,
  9907. name: name,
  9908. title: me.getLang("labelMap")[name],
  9909. click: function() {
  9910. me.execCommand( name, getCurrentColor() );
  9911. }
  9912. });
  9913. $colorLabel = $btn.edui().colorLabel();
  9914. $colorPickerWidget = $.eduicolorpicker({
  9915. name: name,
  9916. lang_clearColor: me.getLang('clearColor') || '',
  9917. lang_themeColor: me.getLang('themeColor') || '',
  9918. lang_standardColor: me.getLang('standardColor') || ''
  9919. })
  9920. .on('pickcolor', function( evt, color ){
  9921. window.setTimeout( function(){
  9922. $colorLabel.css("backgroundColor", color);
  9923. me.execCommand( name, color );
  9924. }, 0 );
  9925. })
  9926. .on('show',function(){
  9927. UM.setActiveWidget( colorPickerWidget.root() );
  9928. }).css('zIndex',me.getOpt('zIndex') + 1);
  9929. $btn.edui().on('arrowclick',function(){
  9930. if(!$colorPickerWidget.parent().length){
  9931. me.$container.find('.edui-dialog-container').append($colorPickerWidget);
  9932. }
  9933. $colorPickerWidget.edui().show($btn,{
  9934. caretDir:"down",
  9935. offsetTop:-5,
  9936. offsetLeft:8,
  9937. caretLeft:11,
  9938. caretTop:-8
  9939. });
  9940. UM.setTopEditor(me);
  9941. }).register('click', $btn, function () {
  9942. $colorPickerWidget.edui().hide()
  9943. });
  9944. return $btn;
  9945. });
  9946. })(jQuery)