umeditor.js 380 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937
  1. /*!
  2. * UEditor Mini版本
  3. * version: 1.2.2
  4. * build: Wed Mar 19 2014 17:08:14 GMT+0800 (中国标准时间)
  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. isFillChar: function (node, isInStart) {
  1764. return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length
  1765. },
  1766. isEmptyBlock: function (node, reg) {
  1767. if (node.nodeType != 1)
  1768. return 0;
  1769. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  1770. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  1771. return 0;
  1772. }
  1773. for (var n in dtd.$isNotEmpty) {
  1774. if (node.getElementsByTagName(n).length) {
  1775. return 0;
  1776. }
  1777. }
  1778. return 1;
  1779. },
  1780. //判断是否是编辑器自定义的参数
  1781. isCustomeNode: function (node) {
  1782. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  1783. },
  1784. fillNode: function (doc, node) {
  1785. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  1786. node.innerHTML = '';
  1787. node.appendChild(tmpNode);
  1788. },
  1789. isBoundaryNode: function (node, dir) {
  1790. var tmp;
  1791. while (!domUtils.isBody(node)) {
  1792. tmp = node;
  1793. node = node.parentNode;
  1794. if (tmp !== node[dir]) {
  1795. return false;
  1796. }
  1797. }
  1798. return true;
  1799. },
  1800. isFillChar: function (node, isInStart) {
  1801. return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length
  1802. },
  1803. isBody: function(node){
  1804. return $(node).hasClass('edui-body-container');
  1805. }
  1806. };
  1807. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  1808. ///import editor.js
  1809. ///import core/utils.js
  1810. ///import core/browser.js
  1811. ///import core/dom/dom.js
  1812. ///import core/dom/dtd.js
  1813. ///import core/dom/domUtils.js
  1814. /**
  1815. * @file
  1816. * @name UM.dom.Range
  1817. * @anthor zhanyi
  1818. * @short Range
  1819. * @import editor.js,core/utils.js,core/browser.js,core/dom/domUtils.js,core/dom/dtd.js
  1820. * @desc Range范围实现类,本类是UEditor底层核心类,统一w3cRange和ieRange之间的差异,包括接口和属性
  1821. */
  1822. (function () {
  1823. var guid = 0,
  1824. fillChar = domUtils.fillChar,
  1825. fillData;
  1826. /**
  1827. * 更新range的collapse状态
  1828. * @param {Range} range range对象
  1829. */
  1830. function updateCollapse(range) {
  1831. range.collapsed =
  1832. range.startContainer && range.endContainer &&
  1833. range.startContainer === range.endContainer &&
  1834. range.startOffset == range.endOffset;
  1835. }
  1836. function selectOneNode(rng){
  1837. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  1838. }
  1839. function setEndPoint(toStart, node, offset, range) {
  1840. //如果node是自闭合标签要处理
  1841. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  1842. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  1843. node = node.parentNode;
  1844. }
  1845. if (toStart) {
  1846. range.startContainer = node;
  1847. range.startOffset = offset;
  1848. if (!range.endContainer) {
  1849. range.collapse(true);
  1850. }
  1851. } else {
  1852. range.endContainer = node;
  1853. range.endOffset = offset;
  1854. if (!range.startContainer) {
  1855. range.collapse(false);
  1856. }
  1857. }
  1858. updateCollapse(range);
  1859. return range;
  1860. }
  1861. /**
  1862. * @name Range
  1863. * @grammar new UM.dom.Range(document) => Range 实例
  1864. * @desc 创建一个跟document绑定的空的Range实例
  1865. * - ***startContainer*** 开始边界的容器节点,可以是elementNode或者是textNode
  1866. * - ***startOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  1867. * - ***endContainer*** 结束边界的容器节点,可以是elementNode或者是textNode
  1868. * - ***endOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符
  1869. * - ***document*** 跟range关联的document对象
  1870. * - ***collapsed*** 是否是闭合状态
  1871. */
  1872. var Range = dom.Range = function (document,body) {
  1873. var me = this;
  1874. me.startContainer =
  1875. me.startOffset =
  1876. me.endContainer =
  1877. me.endOffset = null;
  1878. me.document = document;
  1879. me.collapsed = true;
  1880. me.body = body;
  1881. };
  1882. /**
  1883. * 删除fillData
  1884. * @param doc
  1885. * @param excludeNode
  1886. */
  1887. function removeFillData(doc, excludeNode) {
  1888. try {
  1889. if (fillData && domUtils.inDoc(fillData, doc)) {
  1890. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  1891. var tmpNode = fillData.parentNode;
  1892. domUtils.remove(fillData);
  1893. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  1894. //safari的contains有bug
  1895. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  1896. ) {
  1897. fillData = tmpNode.parentNode;
  1898. domUtils.remove(tmpNode);
  1899. tmpNode = fillData;
  1900. }
  1901. } else {
  1902. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  1903. }
  1904. }
  1905. } catch (e) {
  1906. }
  1907. }
  1908. /**
  1909. *
  1910. * @param node
  1911. * @param dir
  1912. */
  1913. function mergeSibling(node, dir) {
  1914. var tmpNode;
  1915. node = node[dir];
  1916. while (node && domUtils.isFillChar(node)) {
  1917. tmpNode = node[dir];
  1918. domUtils.remove(node);
  1919. node = tmpNode;
  1920. }
  1921. }
  1922. function execContentsAction(range, action) {
  1923. //调整边界
  1924. //range.includeBookmark();
  1925. var start = range.startContainer,
  1926. end = range.endContainer,
  1927. startOffset = range.startOffset,
  1928. endOffset = range.endOffset,
  1929. doc = range.document,
  1930. frag = doc.createDocumentFragment(),
  1931. tmpStart, tmpEnd;
  1932. if (start.nodeType == 1) {
  1933. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  1934. }
  1935. if (end.nodeType == 1) {
  1936. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  1937. }
  1938. if (start === end && start.nodeType == 3) {
  1939. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  1940. //is not clone
  1941. if (action) {
  1942. start.deleteData(startOffset, endOffset - startOffset);
  1943. range.collapse(true);
  1944. }
  1945. return frag;
  1946. }
  1947. var current, currentLevel, clone = frag,
  1948. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  1949. for (var i = 0; startParents[i] == endParents[i];) {
  1950. i++;
  1951. }
  1952. for (var j = i, si; si = startParents[j]; j++) {
  1953. current = si.nextSibling;
  1954. if (si == start) {
  1955. if (!tmpStart) {
  1956. if (range.startContainer.nodeType == 3) {
  1957. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  1958. //is not clone
  1959. if (action) {
  1960. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  1961. }
  1962. } else {
  1963. clone.appendChild(!action ? start.cloneNode(true) : start);
  1964. }
  1965. }
  1966. } else {
  1967. currentLevel = si.cloneNode(false);
  1968. clone.appendChild(currentLevel);
  1969. }
  1970. while (current) {
  1971. if (current === end || current === endParents[j]) {
  1972. break;
  1973. }
  1974. si = current.nextSibling;
  1975. clone.appendChild(!action ? current.cloneNode(true) : current);
  1976. current = si;
  1977. }
  1978. clone = currentLevel;
  1979. }
  1980. clone = frag;
  1981. if (!startParents[i]) {
  1982. clone.appendChild(startParents[i - 1].cloneNode(false));
  1983. clone = clone.firstChild;
  1984. }
  1985. for (var j = i, ei; ei = endParents[j]; j++) {
  1986. current = ei.previousSibling;
  1987. if (ei == end) {
  1988. if (!tmpEnd && range.endContainer.nodeType == 3) {
  1989. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  1990. //is not clone
  1991. if (action) {
  1992. end.deleteData(0, endOffset);
  1993. }
  1994. }
  1995. } else {
  1996. currentLevel = ei.cloneNode(false);
  1997. clone.appendChild(currentLevel);
  1998. }
  1999. //如果两端同级,右边第一次已经被开始做了
  2000. if (j != i || !startParents[i]) {
  2001. while (current) {
  2002. if (current === start) {
  2003. break;
  2004. }
  2005. ei = current.previousSibling;
  2006. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  2007. current = ei;
  2008. }
  2009. }
  2010. clone = currentLevel;
  2011. }
  2012. if (action) {
  2013. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  2014. }
  2015. tmpStart && domUtils.remove(tmpStart);
  2016. tmpEnd && domUtils.remove(tmpEnd);
  2017. return frag;
  2018. }
  2019. Range.prototype = {
  2020. /**
  2021. * @name deleteContents
  2022. * @grammar range.deleteContents() => Range
  2023. * @desc 删除当前选区范围中的所有内容并返回range实例,这时的range已经变成了闭合状态
  2024. * @example
  2025. * DOM Element :
  2026. * <b>x<i>x[x<i>xx]x</b>
  2027. * //执行方法后
  2028. * <b>x<i>x<i>|x</b>
  2029. * 注意range改变了
  2030. * range.startContainer => b
  2031. * range.startOffset => 2
  2032. * range.endContainer => b
  2033. * range.endOffset => 2
  2034. * range.collapsed => true
  2035. */
  2036. deleteContents:function () {
  2037. var txt;
  2038. if (!this.collapsed) {
  2039. execContentsAction(this, 1);
  2040. }
  2041. if (browser.webkit) {
  2042. txt = this.startContainer;
  2043. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  2044. this.setStartBefore(txt).collapse(true);
  2045. domUtils.remove(txt);
  2046. }
  2047. }
  2048. return this;
  2049. },
  2050. inFillChar : function(){
  2051. var start = this.startContainer;
  2052. if(this.collapsed && start.nodeType == 3
  2053. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  2054. ){
  2055. return true;
  2056. }
  2057. return false;
  2058. },
  2059. /**
  2060. * @name setStart
  2061. * @grammar range.setStart(node,offset) => Range
  2062. * @desc 设置range的开始位置位于node节点内,偏移量为offset
  2063. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2064. */
  2065. setStart:function (node, offset) {
  2066. return setEndPoint(true, node, offset, this);
  2067. },
  2068. /**
  2069. * 设置range的结束位置位于node节点,偏移量为offset
  2070. * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符
  2071. * @name setEnd
  2072. * @grammar range.setEnd(node,offset) => Range
  2073. */
  2074. setEnd:function (node, offset) {
  2075. return setEndPoint(false, node, offset, this);
  2076. },
  2077. /**
  2078. * 将Range开始位置设置到node节点之后
  2079. * @name setStartAfter
  2080. * @grammar range.setStartAfter(node) => Range
  2081. * @example
  2082. * <b>xx<i>x|x</i>x</b>
  2083. * 执行setStartAfter(i)后
  2084. * range.startContainer =>b
  2085. * range.startOffset =>2
  2086. */
  2087. setStartAfter:function (node) {
  2088. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2089. },
  2090. /**
  2091. * 将Range开始位置设置到node节点之前
  2092. * @name setStartBefore
  2093. * @grammar range.setStartBefore(node) => Range
  2094. * @example
  2095. * <b>xx<i>x|x</i>x</b>
  2096. * 执行setStartBefore(i)后
  2097. * range.startContainer =>b
  2098. * range.startOffset =>1
  2099. */
  2100. setStartBefore:function (node) {
  2101. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  2102. },
  2103. /**
  2104. * 将Range结束位置设置到node节点之后
  2105. * @name setEndAfter
  2106. * @grammar range.setEndAfter(node) => Range
  2107. * @example
  2108. * <b>xx<i>x|x</i>x</b>
  2109. * setEndAfter(i)后
  2110. * range.endContainer =>b
  2111. * range.endtOffset =>2
  2112. */
  2113. setEndAfter:function (node) {
  2114. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  2115. },
  2116. /**
  2117. * 将Range结束位置设置到node节点之前
  2118. * @name setEndBefore
  2119. * @grammar range.setEndBefore(node) => Range
  2120. * @example
  2121. * <b>xx<i>x|x</i>x</b>
  2122. * 执行setEndBefore(i)后
  2123. * range.endContainer =>b
  2124. * range.endtOffset =>1
  2125. */
  2126. setEndBefore:function (node) {
  2127. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  2128. },
  2129. /**
  2130. * 将Range开始位置设置到node节点内的开始位置
  2131. * @name setStartAtFirst
  2132. * @grammar range.setStartAtFirst(node) => Range
  2133. */
  2134. setStartAtFirst:function (node) {
  2135. return this.setStart(node, 0);
  2136. },
  2137. /**
  2138. * 将Range开始位置设置到node节点内的结束位置
  2139. * @name setStartAtLast
  2140. * @grammar range.setStartAtLast(node) => Range
  2141. */
  2142. setStartAtLast:function (node) {
  2143. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2144. },
  2145. /**
  2146. * 将Range结束位置设置到node节点内的开始位置
  2147. * @name setEndAtFirst
  2148. * @grammar range.setEndAtFirst(node) => Range
  2149. */
  2150. setEndAtFirst:function (node) {
  2151. return this.setEnd(node, 0);
  2152. },
  2153. /**
  2154. * 将Range结束位置设置到node节点内的结束位置
  2155. * @name setEndAtLast
  2156. * @grammar range.setEndAtLast(node) => Range
  2157. */
  2158. setEndAtLast:function (node) {
  2159. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  2160. },
  2161. /**
  2162. * 选中完整的指定节点,并返回包含该节点的range
  2163. * @name selectNode
  2164. * @grammar range.selectNode(node) => Range
  2165. */
  2166. selectNode:function (node) {
  2167. return this.setStartBefore(node).setEndAfter(node);
  2168. },
  2169. /**
  2170. * 选中node内部的所有节点,并返回对应的range
  2171. * @name selectNodeContents
  2172. * @grammar range.selectNodeContents(node) => Range
  2173. * @example
  2174. * <b>xx[x<i>xxx</i>]xxx</b>
  2175. * 执行后
  2176. * <b>[xxx<i>xxx</i>xxx]</b>
  2177. * range.startContainer =>b
  2178. * range.startOffset =>0
  2179. * range.endContainer =>b
  2180. * range.endOffset =>3
  2181. */
  2182. selectNodeContents:function (node) {
  2183. return this.setStart(node, 0).setEndAtLast(node);
  2184. },
  2185. /**
  2186. * 克隆一个新的range对象
  2187. * @name cloneRange
  2188. * @grammar range.cloneRange() => Range
  2189. */
  2190. cloneRange:function () {
  2191. var me = this;
  2192. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  2193. },
  2194. /**
  2195. * 让选区闭合到尾部,若toStart为真,则闭合到头部
  2196. * @name collapse
  2197. * @grammar range.collapse() => Range
  2198. * @grammar range.collapse(true) => Range //闭合选区到头部
  2199. */
  2200. collapse:function (toStart) {
  2201. var me = this;
  2202. if (toStart) {
  2203. me.endContainer = me.startContainer;
  2204. me.endOffset = me.startOffset;
  2205. } else {
  2206. me.startContainer = me.endContainer;
  2207. me.startOffset = me.endOffset;
  2208. }
  2209. me.collapsed = true;
  2210. return me;
  2211. },
  2212. /**
  2213. * 调整range的边界,使其"收缩"到最小的位置
  2214. * @name shrinkBoundary
  2215. * @grammar range.shrinkBoundary() => Range //range开始位置和结束位置都调整,参见<code><a href="#adjustmentboundary">adjustmentBoundary</a></code>
  2216. * @grammar range.shrinkBoundary(true) => Range //仅调整开始位置,忽略结束位置
  2217. * @example
  2218. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  2219. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx]</b><i>xxx</i>
  2220. * [<b><i>xxxx</i>xxxxxxx</b>] ==> <b><i>[xxxx</i>xxxxxxx]</b>
  2221. */
  2222. shrinkBoundary:function (ignoreEnd) {
  2223. var me = this, child,
  2224. collapsed = me.collapsed;
  2225. function check(node){
  2226. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  2227. }
  2228. while (me.startContainer.nodeType == 1 //是element
  2229. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  2230. && check(child)) {
  2231. me.setStart(child, 0);
  2232. }
  2233. if (collapsed) {
  2234. return me.collapse(true);
  2235. }
  2236. if (!ignoreEnd) {
  2237. while (me.endContainer.nodeType == 1//是element
  2238. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  2239. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  2240. && check(child)) {
  2241. me.setEnd(child, child.childNodes.length);
  2242. }
  2243. }
  2244. return me;
  2245. },
  2246. /**
  2247. * 调整边界容器,如果是textNode,就调整到elementNode上
  2248. * @name trimBoundary
  2249. * @grammar range.trimBoundary([ignoreEnd]) => Range //true忽略结束边界
  2250. * @example
  2251. * DOM Element :
  2252. * <b>|xxx</b>
  2253. * startContainer = xxx; startOffset = 0
  2254. * //执行后本方法后
  2255. * startContainer = <b>; startOffset = 0
  2256. * @example
  2257. * Dom Element :
  2258. * <b>xx|x</b>
  2259. * startContainer = xxx; startOffset = 2
  2260. * //执行本方法后,xxx被实实在在地切分成两个TextNode
  2261. * startContainer = <b>; startOffset = 1
  2262. */
  2263. trimBoundary:function (ignoreEnd) {
  2264. this.txtToElmBoundary();
  2265. var start = this.startContainer,
  2266. offset = this.startOffset,
  2267. collapsed = this.collapsed,
  2268. end = this.endContainer;
  2269. if (start.nodeType == 3) {
  2270. if (offset == 0) {
  2271. this.setStartBefore(start);
  2272. } else {
  2273. if (offset >= start.nodeValue.length) {
  2274. this.setStartAfter(start);
  2275. } else {
  2276. var textNode = domUtils.split(start, offset);
  2277. //跟新结束边界
  2278. if (start === end) {
  2279. this.setEnd(textNode, this.endOffset - offset);
  2280. } else if (start.parentNode === end) {
  2281. this.endOffset += 1;
  2282. }
  2283. this.setStartBefore(textNode);
  2284. }
  2285. }
  2286. if (collapsed) {
  2287. return this.collapse(true);
  2288. }
  2289. }
  2290. if (!ignoreEnd) {
  2291. offset = this.endOffset;
  2292. end = this.endContainer;
  2293. if (end.nodeType == 3) {
  2294. if (offset == 0) {
  2295. this.setEndBefore(end);
  2296. } else {
  2297. offset < end.nodeValue.length && domUtils.split(end, offset);
  2298. this.setEndAfter(end);
  2299. }
  2300. }
  2301. }
  2302. return this;
  2303. },
  2304. /**
  2305. * 如果选区在文本的边界上,就扩展选区到文本的父节点上
  2306. * @name txtToElmBoundary
  2307. * @example
  2308. * Dom Element :
  2309. * <b> |xxx</b>
  2310. * startContainer = xxx; startOffset = 0
  2311. * //本方法执行后
  2312. * startContainer = <b>; startOffset = 0
  2313. * @example
  2314. * Dom Element :
  2315. * <b> xxx| </b>
  2316. * startContainer = xxx; startOffset = 3
  2317. * //本方法执行后
  2318. * startContainer = <b>; startOffset = 1
  2319. */
  2320. txtToElmBoundary:function (ignoreCollapsed) {
  2321. function adjust(r, c) {
  2322. var container = r[c + 'Container'],
  2323. offset = r[c + 'Offset'];
  2324. if (container.nodeType == 3) {
  2325. if (!offset) {
  2326. r['set' + c.replace(/(\w)/, function (a) {
  2327. return a.toUpperCase();
  2328. }) + 'Before'](container);
  2329. } else if (offset >= container.nodeValue.length) {
  2330. r['set' + c.replace(/(\w)/, function (a) {
  2331. return a.toUpperCase();
  2332. }) + 'After' ](container);
  2333. }
  2334. }
  2335. }
  2336. if (ignoreCollapsed || !this.collapsed) {
  2337. adjust(this, 'start');
  2338. adjust(this, 'end');
  2339. }
  2340. return this;
  2341. },
  2342. /**
  2343. * 在当前选区的开始位置前插入一个节点或者fragment,range的开始位置会在插入节点的前边
  2344. * @name insertNode
  2345. * @grammar range.insertNode(node) => Range //node可以是textNode,elementNode,fragment
  2346. * @example
  2347. * Range :
  2348. * xxx[x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2349. * 待插入Node :
  2350. * <p>ssss</p>
  2351. * 执行本方法后的Range :
  2352. * xxx[<p>ssss</p>x<p>xxxx</p>xxxx]x<p>sdfsdf</p>
  2353. */
  2354. insertNode:function (node) {
  2355. var first = node, length = 1;
  2356. if (node.nodeType == 11) {
  2357. first = node.firstChild;
  2358. length = node.childNodes.length;
  2359. }
  2360. this.trimBoundary(true);
  2361. var start = this.startContainer,
  2362. offset = this.startOffset;
  2363. var nextNode = start.childNodes[ offset ];
  2364. if (nextNode) {
  2365. start.insertBefore(node, nextNode);
  2366. } else {
  2367. start.appendChild(node);
  2368. }
  2369. if (first.parentNode === this.endContainer) {
  2370. this.endOffset = this.endOffset + length;
  2371. }
  2372. return this.setStartBefore(first);
  2373. },
  2374. /**
  2375. * 设置光标闭合位置,toEnd设置为true时光标将闭合到选区的结尾
  2376. * @name setCursor
  2377. * @grammar range.setCursor([toEnd]) => Range //toEnd为true时,光标闭合到选区的末尾
  2378. */
  2379. setCursor:function (toEnd, noFillData) {
  2380. return this.collapse(!toEnd).select(noFillData);
  2381. },
  2382. /**
  2383. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  2384. * @name createBookmark
  2385. * @grammar range.createBookmark([serialize]) => Object //{start:开始标记,end:结束标记,id:serialize} serialize为真时,开始结束标记是插入节点的id,否则是插入节点的引用
  2386. */
  2387. createBookmark:function (serialize, same) {
  2388. var endNode,
  2389. startNode = this.document.createElement('span');
  2390. startNode.style.cssText = 'display:none;line-height:0px;';
  2391. startNode.appendChild(this.document.createTextNode('\u200D'));
  2392. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  2393. if (!this.collapsed) {
  2394. endNode = startNode.cloneNode(true);
  2395. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  2396. }
  2397. this.insertNode(startNode);
  2398. if (endNode) {
  2399. this.collapse().insertNode(endNode).setEndBefore(endNode);
  2400. }
  2401. this.setStartAfter(startNode);
  2402. return {
  2403. start:serialize ? startNode.id : startNode,
  2404. end:endNode ? serialize ? endNode.id : endNode : null,
  2405. id:serialize
  2406. }
  2407. },
  2408. /**
  2409. * 移动边界到书签位置,并删除插入的书签节点
  2410. * @name moveToBookmark
  2411. * @grammar range.moveToBookmark(bookmark) => Range //让当前的range选到给定bookmark的位置,bookmark对象是由range.createBookmark创建的
  2412. */
  2413. moveToBookmark:function (bookmark) {
  2414. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  2415. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  2416. this.setStartBefore(start);
  2417. domUtils.remove(start);
  2418. if (end) {
  2419. this.setEndBefore(end);
  2420. domUtils.remove(end);
  2421. } else {
  2422. this.collapse(true);
  2423. }
  2424. return this;
  2425. },
  2426. /**
  2427. * 调整Range的边界,使其"缩小"到最合适的位置
  2428. * @name adjustmentBoundary
  2429. * @grammar range.adjustmentBoundary() => Range //参见<code><a href="#shrinkboundary">shrinkBoundary</a></code>
  2430. * @example
  2431. * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx]
  2432. * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx</b>]<i>xxx</i>
  2433. */
  2434. adjustmentBoundary:function () {
  2435. if (!this.collapsed) {
  2436. while (!domUtils.isBody(this.startContainer) &&
  2437. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  2438. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  2439. ) {
  2440. this.setStartAfter(this.startContainer);
  2441. }
  2442. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  2443. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  2444. ) {
  2445. this.setEndBefore(this.endContainer);
  2446. }
  2447. }
  2448. return this;
  2449. },
  2450. /**
  2451. * 得到一个自闭合的节点,常用于获取自闭和的节点,例如图片节点
  2452. * @name getClosedNode
  2453. * @grammar range.getClosedNode() => node|null
  2454. * @example
  2455. * <b>xxxx[<img />]xxx</b>
  2456. */
  2457. getClosedNode:function () {
  2458. var node;
  2459. if (!this.collapsed) {
  2460. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  2461. if (selectOneNode(range)) {
  2462. var child = range.startContainer.childNodes[range.startOffset];
  2463. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  2464. node = child;
  2465. }
  2466. }
  2467. }
  2468. return node;
  2469. },
  2470. /**
  2471. * 根据当前range选中内容节点(在页面上表现为反白显示)
  2472. * @name select
  2473. * @grammar range.select(); => Range
  2474. */
  2475. select:browser.ie ? function (noFillData, textRange) {
  2476. var nativeRange;
  2477. if (!this.collapsed)
  2478. this.shrinkBoundary();
  2479. var node = this.getClosedNode();
  2480. if (node && !textRange) {
  2481. try {
  2482. nativeRange = this.document.body.createControlRange();
  2483. nativeRange.addElement(node);
  2484. nativeRange.select();
  2485. } catch (e) {}
  2486. return this;
  2487. }
  2488. var bookmark = this.createBookmark(),
  2489. start = bookmark.start,
  2490. end;
  2491. nativeRange = this.document.body.createTextRange();
  2492. nativeRange.moveToElementText(start);
  2493. nativeRange.moveStart('character', 1);
  2494. if (!this.collapsed) {
  2495. var nativeRangeEnd = this.document.body.createTextRange();
  2496. end = bookmark.end;
  2497. nativeRangeEnd.moveToElementText(end);
  2498. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  2499. } else {
  2500. if (!noFillData && this.startContainer.nodeType != 3) {
  2501. //使用<span>|x<span>固定住光标
  2502. var tmpText = this.document.createTextNode(fillChar),
  2503. tmp = this.document.createElement('span');
  2504. tmp.appendChild(this.document.createTextNode(fillChar));
  2505. start.parentNode.insertBefore(tmp, start);
  2506. start.parentNode.insertBefore(tmpText, start);
  2507. //当点b,i,u时,不能清除i上边的b
  2508. removeFillData(this.document, tmpText);
  2509. fillData = tmpText;
  2510. mergeSibling(tmp, 'previousSibling');
  2511. mergeSibling(start, 'nextSibling');
  2512. nativeRange.moveStart('character', -1);
  2513. nativeRange.collapse(true);
  2514. }
  2515. }
  2516. this.moveToBookmark(bookmark);
  2517. tmp && domUtils.remove(tmp);
  2518. //IE在隐藏状态下不支持range操作,catch一下
  2519. try {
  2520. nativeRange.select();
  2521. } catch (e) {
  2522. }
  2523. return this;
  2524. } : function (notInsertFillData) {
  2525. function checkOffset(rng){
  2526. function check(node,offset,dir){
  2527. if(node.nodeType == 3 && node.nodeValue.length < offset){
  2528. rng[dir + 'Offset'] = node.nodeValue.length
  2529. }
  2530. }
  2531. check(rng.startContainer,rng.startOffset,'start');
  2532. check(rng.endContainer,rng.endOffset,'end');
  2533. }
  2534. var win = domUtils.getWindow(this.document),
  2535. sel = win.getSelection(),
  2536. txtNode;
  2537. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  2538. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  2539. browser.gecko ? this.body.focus() : win.focus();
  2540. if (sel) {
  2541. sel.removeAllRanges();
  2542. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  2543. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  2544. if (this.collapsed && !notInsertFillData) {
  2545. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  2546. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  2547. // var tmp = this.document.createTextNode('');
  2548. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  2549. // }
  2550. //
  2551. //处理光标落在文本节点的情况
  2552. //处理以下的情况
  2553. //<b>|xxxx</b>
  2554. //<b>xxxx</b>|xxxx
  2555. //xxxx<b>|</b>
  2556. var start = this.startContainer,child = start;
  2557. if(start.nodeType == 1){
  2558. child = start.childNodes[this.startOffset];
  2559. }
  2560. if( !(start.nodeType == 3 && this.startOffset) &&
  2561. (child ?
  2562. (!child.previousSibling || child.previousSibling.nodeType != 3)
  2563. :
  2564. (!start.lastChild || start.lastChild.nodeType != 3)
  2565. )
  2566. ){
  2567. txtNode = this.document.createTextNode(fillChar);
  2568. //跟着前边走
  2569. this.insertNode(txtNode);
  2570. removeFillData(this.document, txtNode);
  2571. mergeSibling(txtNode, 'previousSibling');
  2572. mergeSibling(txtNode, 'nextSibling');
  2573. fillData = txtNode;
  2574. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  2575. }
  2576. }
  2577. var nativeRange = this.document.createRange();
  2578. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  2579. var child = this.startContainer.childNodes[this.startOffset];
  2580. if(!child){
  2581. //往前靠拢
  2582. child = this.startContainer.lastChild;
  2583. if( child && domUtils.isBr(child)){
  2584. this.setStartBefore(child).collapse(true);
  2585. }
  2586. }else{
  2587. //向后靠拢
  2588. while(child && domUtils.isBlockElm(child)){
  2589. if(child.nodeType == 1 && child.childNodes[0]){
  2590. child = child.childNodes[0]
  2591. }else{
  2592. break;
  2593. }
  2594. }
  2595. child && this.setStartBefore(child).collapse(true)
  2596. }
  2597. }
  2598. //是createAddress最后一位算的不准,现在这里进行微调
  2599. checkOffset(this);
  2600. nativeRange.setStart(this.startContainer, this.startOffset);
  2601. nativeRange.setEnd(this.endContainer, this.endOffset);
  2602. sel.addRange(nativeRange);
  2603. }
  2604. return this;
  2605. },
  2606. createAddress : function(ignoreEnd,ignoreTxt){
  2607. var addr = {},me = this;
  2608. function getAddress(isStart){
  2609. var node = isStart ? me.startContainer : me.endContainer;
  2610. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  2611. addrs = [];
  2612. for(var i = 0,ci;ci = parents[i++];){
  2613. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  2614. }
  2615. var firstIndex = 0;
  2616. if(ignoreTxt){
  2617. if(node.nodeType == 3){
  2618. var tmpNode = node.previousSibling;
  2619. while(tmpNode && tmpNode.nodeType == 3){
  2620. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  2621. tmpNode = tmpNode.previousSibling;
  2622. }
  2623. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  2624. }else{
  2625. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  2626. if(node){
  2627. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  2628. }else{
  2629. node = isStart ? me.startContainer : me.endContainer;
  2630. var first = node.firstChild;
  2631. while(first){
  2632. if(domUtils.isFillChar(first)){
  2633. first = first.nextSibling;
  2634. continue;
  2635. }
  2636. firstIndex++;
  2637. if(first.nodeType == 3){
  2638. while( first && first.nodeType == 3){
  2639. first = first.nextSibling;
  2640. }
  2641. }else{
  2642. first = first.nextSibling;
  2643. }
  2644. }
  2645. }
  2646. }
  2647. }else{
  2648. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  2649. }
  2650. if(firstIndex < 0){
  2651. firstIndex = 0;
  2652. }
  2653. addrs.push(firstIndex);
  2654. return addrs;
  2655. }
  2656. addr.startAddress = getAddress(true);
  2657. if(!ignoreEnd){
  2658. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  2659. }
  2660. return addr;
  2661. },
  2662. moveToAddress : function(addr,ignoreEnd){
  2663. var me = this;
  2664. function getNode(address,isStart){
  2665. var tmpNode = me.body,
  2666. parentNode,offset;
  2667. for(var i= 0,ci,l=address.length;i<l;i++){
  2668. ci = address[i];
  2669. parentNode = tmpNode;
  2670. tmpNode = tmpNode.childNodes[ci];
  2671. if(!tmpNode){
  2672. offset = ci;
  2673. break;
  2674. }
  2675. }
  2676. if(isStart){
  2677. if(tmpNode){
  2678. me.setStartBefore(tmpNode)
  2679. }else{
  2680. me.setStart(parentNode,offset)
  2681. }
  2682. }else{
  2683. if(tmpNode){
  2684. me.setEndBefore(tmpNode)
  2685. }else{
  2686. me.setEnd(parentNode,offset)
  2687. }
  2688. }
  2689. }
  2690. getNode(addr.startAddress,true);
  2691. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  2692. return me;
  2693. },
  2694. equals : function(rng){
  2695. for(var p in this){
  2696. if(this.hasOwnProperty(p)){
  2697. if(this[p] !== rng[p])
  2698. return false
  2699. }
  2700. }
  2701. return true;
  2702. },
  2703. scrollIntoView : function(){
  2704. var $span = $('<span style="padding:0;margin:0;display:block;border:0">&nbsp;</span>');
  2705. this.cloneRange().insertNode($span.get(0));
  2706. var winScrollTop = $(window).scrollTop(),
  2707. winHeight = $(window).height(),
  2708. spanTop = $span.offset().top;
  2709. if(spanTop < winScrollTop-winHeight || spanTop > winScrollTop + winHeight ){
  2710. if(spanTop > winScrollTop + winHeight){
  2711. window.scrollTo(0,spanTop - winHeight + $span.height())
  2712. }else{
  2713. window.scrollTo(0,winScrollTop - spanTop)
  2714. }
  2715. }
  2716. $span.remove();
  2717. },
  2718. getOffset : function(){
  2719. var bk = this.createBookmark();
  2720. var offset = $(bk.start).css('display','inline-block').offset();
  2721. this.moveToBookmark(bk);
  2722. return offset
  2723. }
  2724. };
  2725. })();
  2726. ///import editor.js
  2727. ///import core/browser.js
  2728. ///import core/dom/dom.js
  2729. ///import core/dom/dtd.js
  2730. ///import core/dom/domUtils.js
  2731. ///import core/dom/Range.js
  2732. /**
  2733. * @class UM.dom.Selection Selection类
  2734. */
  2735. (function () {
  2736. function getBoundaryInformation( range, start ) {
  2737. var getIndex = domUtils.getNodeIndex;
  2738. range = range.duplicate();
  2739. range.collapse( start );
  2740. var parent = range.parentElement();
  2741. //如果节点里没有子节点,直接退出
  2742. if ( !parent.hasChildNodes() ) {
  2743. return {container:parent, offset:0};
  2744. }
  2745. var siblings = parent.children,
  2746. child,
  2747. testRange = range.duplicate(),
  2748. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  2749. distance;
  2750. while ( startIndex <= endIndex ) {
  2751. index = Math.floor( (startIndex + endIndex) / 2 );
  2752. child = siblings[index];
  2753. testRange.moveToElementText( child );
  2754. var position = testRange.compareEndPoints( 'StartToStart', range );
  2755. if ( position > 0 ) {
  2756. endIndex = index - 1;
  2757. } else if ( position < 0 ) {
  2758. startIndex = index + 1;
  2759. } else {
  2760. //trace:1043
  2761. return {container:parent, offset:getIndex( child )};
  2762. }
  2763. }
  2764. if ( index == -1 ) {
  2765. testRange.moveToElementText( parent );
  2766. testRange.setEndPoint( 'StartToStart', range );
  2767. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  2768. siblings = parent.childNodes;
  2769. if ( !distance ) {
  2770. child = siblings[siblings.length - 1];
  2771. return {container:child, offset:child.nodeValue.length};
  2772. }
  2773. var i = siblings.length;
  2774. while ( distance > 0 ){
  2775. distance -= siblings[ --i ].nodeValue.length;
  2776. }
  2777. return {container:siblings[i], offset:-distance};
  2778. }
  2779. testRange.collapse( position > 0 );
  2780. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  2781. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  2782. if ( !distance ) {
  2783. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  2784. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  2785. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  2786. }
  2787. while ( distance > 0 ) {
  2788. try {
  2789. var pre = child;
  2790. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  2791. distance -= child.nodeValue.length;
  2792. } catch ( e ) {
  2793. return {container:parent, offset:getIndex( pre )};
  2794. }
  2795. }
  2796. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  2797. }
  2798. /**
  2799. * 将ieRange转换为Range对象
  2800. * @param {Range} ieRange ieRange对象
  2801. * @param {Range} range Range对象
  2802. * @return {Range} range 返回转换后的Range对象
  2803. */
  2804. function transformIERangeToRange( ieRange, range ) {
  2805. if ( ieRange.item ) {
  2806. range.selectNode( ieRange.item( 0 ) );
  2807. } else {
  2808. var bi = getBoundaryInformation( ieRange, true );
  2809. range.setStart( bi.container, bi.offset );
  2810. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  2811. bi = getBoundaryInformation( ieRange, false );
  2812. range.setEnd( bi.container, bi.offset );
  2813. }
  2814. }
  2815. return range;
  2816. }
  2817. /**
  2818. * 获得ieRange
  2819. * @param {Selection} sel Selection对象
  2820. * @return {ieRange} 得到ieRange
  2821. */
  2822. function _getIERange( sel,txtRange ) {
  2823. var ieRange;
  2824. //ie下有可能报错
  2825. try {
  2826. ieRange = sel.getNative(txtRange).createRange();
  2827. } catch ( e ) {
  2828. return null;
  2829. }
  2830. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  2831. if ( ( el.ownerDocument || el ) === sel.document ) {
  2832. return ieRange;
  2833. }
  2834. return null;
  2835. }
  2836. var Selection = dom.Selection = function ( doc,body ) {
  2837. var me = this;
  2838. me.document = doc;
  2839. me.body = body;
  2840. if ( browser.ie9below ) {
  2841. $( body).on('beforedeactivate', function () {
  2842. me._bakIERange = me.getIERange();
  2843. } ).on('activate', function () {
  2844. try {
  2845. var ieNativRng = _getIERange( me );
  2846. if ( (!ieNativRng || !me.rangeInBody(ieNativRng)) && me._bakIERange ) {
  2847. me._bakIERange.select();
  2848. }
  2849. } catch ( ex ) {
  2850. }
  2851. me._bakIERange = null;
  2852. } );
  2853. }
  2854. };
  2855. Selection.prototype = {
  2856. hasNativeRange : function(){
  2857. var rng;
  2858. if(!browser.ie || browser.ie9above){
  2859. var nativeSel = this.getNative();
  2860. if(!nativeSel.rangeCount){
  2861. return false;
  2862. }
  2863. rng = nativeSel.getRangeAt(0);
  2864. }else{
  2865. rng = _getIERange(this);
  2866. }
  2867. return this.rangeInBody(rng);
  2868. },
  2869. /**
  2870. * 获取原生seleciton对象
  2871. * @public
  2872. * @function
  2873. * @name UM.dom.Selection.getNative
  2874. * @return {Selection} 获得selection对象
  2875. */
  2876. getNative:function (txtRange) {
  2877. var doc = this.document;
  2878. try {
  2879. return !doc ? null : browser.ie9below || txtRange? doc.selection : domUtils.getWindow( doc ).getSelection();
  2880. } catch ( e ) {
  2881. return null;
  2882. }
  2883. },
  2884. /**
  2885. * 获得ieRange
  2886. * @public
  2887. * @function
  2888. * @name UM.dom.Selection.getIERange
  2889. * @return {ieRange} 返回ie原生的Range
  2890. */
  2891. getIERange:function (txtRange) {
  2892. var ieRange = _getIERange( this,txtRange );
  2893. if ( !ieRange || !this.rangeInBody(ieRange,txtRange)) {
  2894. if ( this._bakIERange ) {
  2895. return this._bakIERange;
  2896. }
  2897. }
  2898. return ieRange;
  2899. },
  2900. rangeInBody : function(rng,txtRange){
  2901. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  2902. return node === this.body || domUtils.inDoc(node,this.body);
  2903. },
  2904. /**
  2905. * 缓存当前选区的range和选区的开始节点
  2906. * @public
  2907. * @function
  2908. * @name UM.dom.Selection.cache
  2909. */
  2910. cache:function () {
  2911. this.clear();
  2912. this._cachedRange = this.getRange();
  2913. this._cachedStartElement = this.getStart();
  2914. this._cachedStartElementPath = this.getStartElementPath();
  2915. },
  2916. getStartElementPath:function () {
  2917. if ( this._cachedStartElementPath ) {
  2918. return this._cachedStartElementPath;
  2919. }
  2920. var start = this.getStart();
  2921. if ( start ) {
  2922. return domUtils.findParents( start, true, null, true )
  2923. }
  2924. return [];
  2925. },
  2926. /**
  2927. * 清空缓存
  2928. * @public
  2929. * @function
  2930. * @name UM.dom.Selection.clear
  2931. */
  2932. clear:function () {
  2933. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  2934. },
  2935. /**
  2936. * 编辑器是否得到了选区
  2937. */
  2938. isFocus:function () {
  2939. return this.hasNativeRange()
  2940. },
  2941. /**
  2942. * 获取选区对应的Range
  2943. * @public
  2944. * @function
  2945. * @name UM.dom.Selection.getRange
  2946. * @returns {UM.dom.Range} 得到Range对象
  2947. */
  2948. getRange:function () {
  2949. var me = this;
  2950. function optimze( range ) {
  2951. var child = me.body.firstChild,
  2952. collapsed = range.collapsed;
  2953. while ( child && child.firstChild ) {
  2954. range.setStart( child, 0 );
  2955. child = child.firstChild;
  2956. }
  2957. if ( !range.startContainer ) {
  2958. range.setStart( me.body, 0 )
  2959. }
  2960. if ( collapsed ) {
  2961. range.collapse( true );
  2962. }
  2963. }
  2964. if ( me._cachedRange != null ) {
  2965. return this._cachedRange;
  2966. }
  2967. var range = new dom.Range( me.document,me.body );
  2968. if ( browser.ie9below ) {
  2969. var nativeRange = me.getIERange();
  2970. if ( nativeRange && this.rangeInBody(nativeRange)) {
  2971. try{
  2972. transformIERangeToRange( nativeRange, range );
  2973. }catch(e){
  2974. optimze( range );
  2975. }
  2976. } else {
  2977. optimze( range );
  2978. }
  2979. } else {
  2980. var sel = me.getNative();
  2981. if ( sel && sel.rangeCount && me.rangeInBody(sel.getRangeAt( 0 ))) {
  2982. var firstRange = sel.getRangeAt( 0 );
  2983. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  2984. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  2985. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  2986. optimze( range );
  2987. }
  2988. } else {
  2989. //trace:1734 有可能已经不在dom树上了,标识的节点
  2990. if ( this._bakRange && (this._bakRange.startContainer === this.body || domUtils.inDoc( this._bakRange.startContainer, this.body )) ){
  2991. return this._bakRange;
  2992. }
  2993. optimze( range );
  2994. }
  2995. }
  2996. return this._bakRange = range;
  2997. },
  2998. /**
  2999. * 获取开始元素,用于状态反射
  3000. * @public
  3001. * @function
  3002. * @name UM.dom.Selection.getStart
  3003. * @return {Element} 获得开始元素
  3004. */
  3005. getStart:function () {
  3006. if ( this._cachedStartElement ) {
  3007. return this._cachedStartElement;
  3008. }
  3009. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  3010. tmpRange,
  3011. start, tmp, parent;
  3012. if ( browser.ie9below ) {
  3013. if ( !range ) {
  3014. //todo 给第一个值可能会有问题
  3015. return this.document.body.firstChild;
  3016. }
  3017. //control元素
  3018. if ( range.item ){
  3019. return range.item( 0 );
  3020. }
  3021. tmpRange = range.duplicate();
  3022. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  3023. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  3024. tmpRange.collapse( 1 );
  3025. start = tmpRange.parentElement();
  3026. parent = tmp = range.parentElement();
  3027. while ( tmp = tmp.parentNode ) {
  3028. if ( tmp == start ) {
  3029. start = parent;
  3030. break;
  3031. }
  3032. }
  3033. } else {
  3034. start = range.startContainer;
  3035. if ( start.nodeType == 1 && start.hasChildNodes() ){
  3036. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  3037. }
  3038. if ( start.nodeType == 3 ){
  3039. return start.parentNode;
  3040. }
  3041. }
  3042. return start;
  3043. },
  3044. /**
  3045. * 得到选区中的文本
  3046. * @public
  3047. * @function
  3048. * @name UM.dom.Selection.getText
  3049. * @return {String} 选区中包含的文本
  3050. */
  3051. getText:function () {
  3052. var nativeSel, nativeRange;
  3053. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  3054. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  3055. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  3056. }
  3057. return '';
  3058. }
  3059. };
  3060. })();
  3061. /**
  3062. * @file
  3063. * @name UM.Editor
  3064. * @short Editor
  3065. * @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
  3066. * @desc 编辑器主类,包含编辑器提供的大部分公用接口
  3067. */
  3068. (function () {
  3069. var uid = 0, _selectionChangeTimer;
  3070. /**
  3071. * @private
  3072. * @ignore
  3073. * @param form 编辑器所在的form元素
  3074. * @param editor 编辑器实例对象
  3075. */
  3076. function setValue(form, editor) {
  3077. var textarea;
  3078. if (editor.textarea) {
  3079. if (utils.isString(editor.textarea)) {
  3080. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  3081. if (ti.id == 'umeditor_textarea_' + editor.options.textarea) {
  3082. textarea = ti;
  3083. break;
  3084. }
  3085. }
  3086. } else {
  3087. textarea = editor.textarea;
  3088. }
  3089. }
  3090. if (!textarea) {
  3091. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  3092. 'name': editor.options.textarea,
  3093. 'id': 'umeditor_textarea_' + editor.options.textarea,
  3094. 'style': "display:none"
  3095. }));
  3096. //不要产生多个textarea
  3097. editor.textarea = textarea;
  3098. }
  3099. textarea.value = editor.hasContents() ?
  3100. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  3101. ''
  3102. }
  3103. function loadPlugins(me){
  3104. //初始化插件
  3105. for (var pi in UM.plugins) {
  3106. if(me.options.excludePlugins.indexOf(pi) == -1){
  3107. UM.plugins[pi].call(me);
  3108. me.plugins[pi] = 1;
  3109. }
  3110. }
  3111. me.langIsReady = true;
  3112. me.fireEvent("langReady");
  3113. }
  3114. function checkCurLang(I18N){
  3115. for(var lang in I18N){
  3116. return lang
  3117. }
  3118. }
  3119. /**
  3120. * UEditor编辑器类
  3121. * @name Editor
  3122. * @desc 创建一个跟编辑器实例
  3123. * - ***container*** 编辑器容器对象
  3124. * - ***iframe*** 编辑区域所在的iframe对象
  3125. * - ***window*** 编辑区域所在的window
  3126. * - ***document*** 编辑区域所在的document对象
  3127. * - ***body*** 编辑区域所在的body对象
  3128. * - ***selection*** 编辑区域的选区对象
  3129. */
  3130. var Editor = UM.Editor = function (options) {
  3131. var me = this;
  3132. me.uid = uid++;
  3133. EventBase.call(me);
  3134. me.commands = {};
  3135. me.options = utils.extend(utils.clone(options || {}), UMEDITOR_CONFIG, true);
  3136. me.shortcutkeys = {};
  3137. me.inputRules = [];
  3138. me.outputRules = [];
  3139. //设置默认的常用属性
  3140. me.setOpt({
  3141. isShow: true,
  3142. initialContent: '',
  3143. initialStyle:'',
  3144. autoClearinitialContent: false,
  3145. textarea: 'editorValue',
  3146. focus: false,
  3147. focusInEnd: true,
  3148. autoClearEmptyNode: true,
  3149. fullscreen: false,
  3150. readonly: false,
  3151. zIndex: 999,
  3152. enterTag: 'p',
  3153. lang: 'zh-cn',
  3154. langPath: me.options.UMEDITOR_HOME_URL + 'lang/',
  3155. theme: 'default',
  3156. themePath: me.options.UMEDITOR_HOME_URL + 'themes/',
  3157. allHtmlEnabled: false,
  3158. autoSyncData : true,
  3159. autoHeightEnabled : true,
  3160. excludePlugins:''
  3161. });
  3162. me.plugins = {};
  3163. if(!utils.isEmptyObject(UM.I18N)){
  3164. //修改默认的语言类型
  3165. me.options.lang = checkCurLang(UM.I18N);
  3166. loadPlugins(me)
  3167. }else{
  3168. utils.loadFile(document, {
  3169. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  3170. tag: "script",
  3171. type: "text/javascript",
  3172. defer: "defer"
  3173. }, function () {
  3174. loadPlugins(me)
  3175. });
  3176. }
  3177. };
  3178. Editor.prototype = {
  3179. /**
  3180. * 当编辑器ready后执行传入的fn,如果编辑器已经完成ready,就马上执行fn,fn的中的this是编辑器实例。
  3181. * 大部分的实例接口都需要放在该方法内部执行,否则在IE下可能会报错。
  3182. * @name ready
  3183. * @grammar editor.ready(fn) fn是当编辑器渲染好后执行的function
  3184. * @example
  3185. * var editor = new UM.ui.Editor();
  3186. * editor.render("myEditor");
  3187. * editor.ready(function(){
  3188. * editor.setContent("欢迎使用UEditor!");
  3189. * })
  3190. */
  3191. ready: function (fn) {
  3192. var me = this;
  3193. if (fn) {
  3194. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  3195. }
  3196. },
  3197. /**
  3198. * 为编辑器设置默认参数值。若用户配置为空,则以默认配置为准
  3199. * @grammar editor.setOpt(key,value); //传入一个键、值对
  3200. * @grammar editor.setOpt({ key:value}); //传入一个json对象
  3201. */
  3202. setOpt: function (key, val) {
  3203. var obj = {};
  3204. if (utils.isString(key)) {
  3205. obj[key] = val
  3206. } else {
  3207. obj = key;
  3208. }
  3209. utils.extend(this.options, obj, true);
  3210. },
  3211. getOpt:function(key){
  3212. return this.options[key] || ''
  3213. },
  3214. /**
  3215. * 销毁编辑器实例对象
  3216. * @name destroy
  3217. * @grammar editor.destroy();
  3218. */
  3219. destroy: function () {
  3220. var me = this;
  3221. me.fireEvent('destroy');
  3222. var container = me.container.parentNode;
  3223. if(container === document.body){
  3224. container = me.container;
  3225. }
  3226. var textarea = me.textarea;
  3227. if (!textarea) {
  3228. textarea = document.createElement('textarea');
  3229. container.parentNode.insertBefore(textarea, container);
  3230. } else {
  3231. textarea.style.display = ''
  3232. }
  3233. textarea.style.width = me.body.offsetWidth + 'px';
  3234. textarea.style.height = me.body.offsetHeight + 'px';
  3235. textarea.value = me.getContent();
  3236. textarea.id = me.key;
  3237. if(container.contains(textarea)){
  3238. $(textarea).insertBefore(container);
  3239. }
  3240. container.innerHTML = '';
  3241. domUtils.remove(container);
  3242. UM.clearCache(me.id);
  3243. //trace:2004
  3244. for (var p in me) {
  3245. if (me.hasOwnProperty(p)) {
  3246. delete this[p];
  3247. }
  3248. }
  3249. },
  3250. initialCont : function(holder){
  3251. if(holder){
  3252. holder.getAttribute('name') && ( this.options.textarea = holder.getAttribute('name'));
  3253. if (holder && /script|textarea/ig.test(holder.tagName)) {
  3254. var newDiv = document.createElement('div');
  3255. holder.parentNode.insertBefore(newDiv, holder);
  3256. this.options.initialContent = UM.htmlparser(holder.value || holder.innerHTML|| this.options.initialContent).toHtml();
  3257. holder.className && (newDiv.className = holder.className);
  3258. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  3259. if (/textarea/i.test(holder.tagName)) {
  3260. this.textarea = holder;
  3261. this.textarea.style.display = 'none';
  3262. } else {
  3263. holder.parentNode.removeChild(holder);
  3264. holder.id && (newDiv.id = holder.id);
  3265. }
  3266. holder = newDiv;
  3267. holder.innerHTML = '';
  3268. }
  3269. return holder;
  3270. }else{
  3271. return null;
  3272. }
  3273. },
  3274. /**
  3275. * 渲染编辑器的DOM到指定容器,必须且只能调用一次
  3276. * @name render
  3277. * @grammar editor.render(containerId); //可以指定一个容器ID
  3278. * @grammar editor.render(containerDom); //也可以直接指定容器对象
  3279. */
  3280. render: function (container) {
  3281. var me = this,
  3282. options = me.options,
  3283. getStyleValue=function(attr){
  3284. return parseInt($(container).css(attr));
  3285. };
  3286. if (utils.isString(container)) {
  3287. container = document.getElementById(container);
  3288. }
  3289. if (container) {
  3290. this.id = container.getAttribute('id');
  3291. UM.setEditor(this);
  3292. utils.cssRule('edui-style-body',me.options.initialStyle,document);
  3293. container = this.initialCont(container);
  3294. container.className += ' edui-body-container';
  3295. if(options.initialFrameWidth){
  3296. options.minFrameWidth = options.initialFrameWidth
  3297. }else{
  3298. //都没给值,先写死了
  3299. options.minFrameWidth = options.initialFrameWidth = $(container).width() || UM.defaultWidth;
  3300. }
  3301. if(options.initialFrameHeight){
  3302. options.minFrameHeight = options.initialFrameHeight
  3303. }else{
  3304. options.initialFrameHeight = options.minFrameHeight = $(container).height() || UM.defaultHeight;
  3305. }
  3306. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth -
  3307. getStyleValue("padding-left")-
  3308. getStyleValue("padding-right") +'px';
  3309. var height = /%$/.test(options.initialFrameHeight) ? '100%' : (options.initialFrameHeight - getStyleValue("padding-top")- getStyleValue("padding-bottom") );
  3310. if(this.options.autoHeightEnabled){
  3311. container.style.minHeight = height +'px';
  3312. container.style.height = '';
  3313. if(browser.ie && browser.version <= 6){
  3314. container.style.height = height ;
  3315. container.style.setExpression('height', 'this.scrollHeight <= ' + height + ' ? "' + height + 'px" : "auto"');
  3316. }
  3317. }else{
  3318. $(container).height(height)
  3319. }
  3320. container.style.zIndex = options.zIndex;
  3321. this._setup(container);
  3322. }
  3323. },
  3324. /**
  3325. * 编辑器初始化
  3326. * @private
  3327. * @ignore
  3328. * @param {Element} doc 编辑器Iframe中的文档对象
  3329. */
  3330. _setup: function (cont) {
  3331. var me = this,
  3332. options = me.options;
  3333. cont.contentEditable = true;
  3334. document.body.spellcheck = false;
  3335. me.document = document;
  3336. me.window = document.defaultView || document.parentWindow;
  3337. me.body = cont;
  3338. me.$body = $(cont);
  3339. me.selection = new dom.Selection(document,me.body);
  3340. me._isEnabled = false;
  3341. //gecko初始化就能得到range,无法判断isFocus了
  3342. var geckoSel;
  3343. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  3344. geckoSel.removeAllRanges();
  3345. }
  3346. this._initEvents();
  3347. //为form提交提供一个隐藏的textarea
  3348. for (var form = cont.parentNode; form && !domUtils.isBody(form); form = form.parentNode) {
  3349. if (form.tagName == 'FORM') {
  3350. me.form = form;
  3351. if(me.options.autoSyncData){
  3352. $(cont).on('blur',function(){
  3353. setValue(form,me);
  3354. })
  3355. }else{
  3356. $(form).on('submit', function () {
  3357. setValue(this, me);
  3358. })
  3359. }
  3360. break;
  3361. }
  3362. }
  3363. if (options.initialContent) {
  3364. if (options.autoClearinitialContent) {
  3365. var oldExecCommand = me.execCommand;
  3366. me.execCommand = function () {
  3367. me.fireEvent('firstBeforeExecCommand');
  3368. return oldExecCommand.apply(me, arguments);
  3369. };
  3370. this._setDefaultContent(options.initialContent);
  3371. } else
  3372. this.setContent(options.initialContent, false, true);
  3373. }
  3374. //编辑器不能为空内容
  3375. if (domUtils.isEmptyNode(me.body)) {
  3376. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  3377. }
  3378. //如果要求focus, 就把光标定位到内容开始
  3379. if (options.focus) {
  3380. setTimeout(function () {
  3381. me.focus(me.options.focusInEnd);
  3382. //如果自动清除开着,就不需要做selectionchange;
  3383. !me.options.autoClearinitialContent && me._selectionChange();
  3384. }, 0);
  3385. }
  3386. if (!me.container) {
  3387. me.container = cont.parentNode;
  3388. }
  3389. me._bindshortcutKeys();
  3390. me.isReady = 1;
  3391. me.fireEvent('ready');
  3392. options.onready && options.onready.call(me);
  3393. if(!browser.ie || browser.ie9above){
  3394. $(me.body).on( 'blur focus', function (e) {
  3395. var nSel = me.selection.getNative();
  3396. //chrome下会出现alt+tab切换时,导致选区位置不对
  3397. if (e.type == 'blur') {
  3398. if(nSel.rangeCount > 0 ){
  3399. me._bakRange = nSel.getRangeAt(0);
  3400. }
  3401. } else {
  3402. try {
  3403. me._bakRange && nSel.addRange(me._bakRange)
  3404. } catch (e) {
  3405. }
  3406. me._bakRange = null;
  3407. }
  3408. });
  3409. }
  3410. !options.isShow && me.setHide();
  3411. options.readonly && me.setDisabled();
  3412. },
  3413. /**
  3414. * 同步编辑器的数据,为提交数据做准备,主要用于你是手动提交的情况
  3415. * @name sync
  3416. * @grammar editor.sync(); //从编辑器的容器向上查找,如果找到就同步数据
  3417. * @grammar editor.sync(formID); //formID制定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  3418. * @desc
  3419. * 后台取得数据得键值使用你容器上得''name''属性,如果没有就使用参数传入的''textarea''
  3420. * @example
  3421. * editor.sync();
  3422. * form.sumbit(); //form变量已经指向了form元素
  3423. *
  3424. */
  3425. sync: function (formId) {
  3426. var me = this,
  3427. form = formId ? document.getElementById(formId) :
  3428. domUtils.findParent(me.body.parentNode, function (node) {
  3429. return node.tagName == 'FORM'
  3430. }, true);
  3431. form && setValue(form, me);
  3432. },
  3433. /**
  3434. * 设置编辑器高度
  3435. * @name setHeight
  3436. * @grammar editor.setHeight(number); //纯数值,不带单位
  3437. */
  3438. setHeight: function (height,notSetHeight) {
  3439. !notSetHeight && (this.options.initialFrameHeight = height);
  3440. if(this.options.autoHeightEnabled){
  3441. $(this.body).css({
  3442. 'min-height':height + 'px'
  3443. });
  3444. if(browser.ie && browser.version <= 6 && this.container){
  3445. this.container.style.height = height ;
  3446. this.container.style.setExpression('height', 'this.scrollHeight <= ' + height + ' ? "' + height + 'px" : "auto"');
  3447. }
  3448. }else{
  3449. $(this.body).height(height)
  3450. }
  3451. this.fireEvent('resize');
  3452. },
  3453. /**
  3454. * 设置编辑器宽度
  3455. * @name setWidth
  3456. * @grammar editor.setWidth(number); //纯数值,不带单位
  3457. */
  3458. setWidth:function(width){
  3459. this.$container && this.$container.width(width);
  3460. $(this.body).width(width - $(this.body).css('padding-left').replace('px','') * 1 - $(this.body).css('padding-right').replace('px','') * 1);
  3461. this.fireEvent('resize');
  3462. },
  3463. addshortcutkey: function (cmd, keys) {
  3464. var obj = {};
  3465. if (keys) {
  3466. obj[cmd] = keys
  3467. } else {
  3468. obj = cmd;
  3469. }
  3470. utils.extend(this.shortcutkeys, obj)
  3471. },
  3472. _bindshortcutKeys: function () {
  3473. var me = this, shortcutkeys = this.shortcutkeys;
  3474. me.addListener('keydown', function (type, e) {
  3475. var keyCode = e.keyCode || e.which;
  3476. for (var i in shortcutkeys) {
  3477. var tmp = shortcutkeys[i].split(',');
  3478. for (var t = 0, ti; ti = tmp[t++];) {
  3479. ti = ti.split(':');
  3480. var key = ti[0], param = ti[1];
  3481. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  3482. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  3483. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  3484. && keyCode == RegExp.$3
  3485. ) ||
  3486. keyCode == RegExp.$1
  3487. ) {
  3488. if (me.queryCommandState(i,param) != -1)
  3489. me.execCommand(i, param);
  3490. domUtils.preventDefault(e);
  3491. }
  3492. }
  3493. }
  3494. }
  3495. });
  3496. },
  3497. /**
  3498. * 获取编辑器内容
  3499. * @name getContent
  3500. * @grammar editor.getContent() => String //若编辑器中只包含字符"&lt;p&gt;&lt;br /&gt;&lt;/p/&gt;"会返回空。
  3501. * @grammar editor.getContent(fn) => String
  3502. * @example
  3503. * getContent默认是会现调用hasContents来判断编辑器是否为空,如果是,就直接返回空字符串
  3504. * 你也可以传入一个fn来接替hasContents的工作,定制判断的规则
  3505. * editor.getContent(function(){
  3506. * return false //编辑器没有内容 ,getContent直接返回空
  3507. * })
  3508. */
  3509. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  3510. var me = this;
  3511. if (cmd && utils.isFunction(cmd)) {
  3512. fn = cmd;
  3513. cmd = '';
  3514. }
  3515. if (fn ? !fn() : !this.hasContents()) {
  3516. return '';
  3517. }
  3518. me.fireEvent('beforegetcontent');
  3519. var root = UM.htmlparser(me.body.innerHTML,ignoreBlank);
  3520. me.filterOutputRule(root);
  3521. me.fireEvent('aftergetcontent',root);
  3522. return root.toHtml(formatter);
  3523. },
  3524. /**
  3525. * 取得完整的html代码,可以直接显示成完整的html文档
  3526. * @name getAllHtml
  3527. * @grammar editor.getAllHtml() => String
  3528. */
  3529. getAllHtml: function () {
  3530. var me = this,
  3531. headHtml = [],
  3532. html = '';
  3533. me.fireEvent('getAllHtml', headHtml);
  3534. if (browser.ie && browser.version > 8) {
  3535. var headHtmlForIE9 = '';
  3536. utils.each(me.document.styleSheets, function (si) {
  3537. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  3538. });
  3539. utils.each(me.document.getElementsByTagName('script'), function (si) {
  3540. headHtmlForIE9 += si.outerHTML;
  3541. });
  3542. }
  3543. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  3544. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  3545. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  3546. },
  3547. /**
  3548. * 得到编辑器的纯文本内容,但会保留段落格式
  3549. * @name getPlainTxt
  3550. * @grammar editor.getPlainTxt() => String
  3551. */
  3552. getPlainTxt: function () {
  3553. var reg = new RegExp(domUtils.fillChar, 'g'),
  3554. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  3555. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  3556. .replace(/<br\/?>/gi, '\n')
  3557. .replace(/<[^>/]+>/g, '')
  3558. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  3559. return dtd.$block[c] ? '\n' : b ? b : '';
  3560. });
  3561. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  3562. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  3563. },
  3564. /**
  3565. * 获取编辑器中的纯文本内容,没有段落格式
  3566. * @name getContentTxt
  3567. * @grammar editor.getContentTxt() => String
  3568. */
  3569. getContentTxt: function () {
  3570. var reg = new RegExp(domUtils.fillChar, 'g');
  3571. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  3572. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  3573. },
  3574. /**
  3575. * 将html设置到编辑器中, 如果是用于初始化时给编辑器赋初值,则必须放在ready方法内部执行
  3576. * @name setContent
  3577. * @grammar editor.setContent(html)
  3578. * @example
  3579. * var editor = new UM.ui.Editor()
  3580. * editor.ready(function(){
  3581. * //需要ready后执行,否则可能报错
  3582. * editor.setContent("欢迎使用UEditor!");
  3583. * })
  3584. */
  3585. setContent: function (html, isAppendTo, notFireSelectionchange) {
  3586. var me = this;
  3587. me.fireEvent('beforesetcontent', html);
  3588. var root = UM.htmlparser(html);
  3589. me.filterInputRule(root);
  3590. html = root.toHtml();
  3591. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  3592. function isCdataDiv(node){
  3593. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  3594. }
  3595. //给文本或者inline节点套p标签
  3596. if (me.options.enterTag == 'p') {
  3597. var child = this.body.firstChild, tmpNode;
  3598. if (!child || child.nodeType == 1 &&
  3599. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  3600. domUtils.isCustomeNode(child)
  3601. )
  3602. && child === this.body.lastChild) {
  3603. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  3604. } else {
  3605. var p = me.document.createElement('p');
  3606. while (child) {
  3607. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  3608. tmpNode = child.nextSibling;
  3609. p.appendChild(child);
  3610. child = tmpNode;
  3611. }
  3612. if (p.firstChild) {
  3613. if (!child) {
  3614. me.body.appendChild(p);
  3615. break;
  3616. } else {
  3617. child.parentNode.insertBefore(p, child);
  3618. p = me.document.createElement('p');
  3619. }
  3620. }
  3621. child = child.nextSibling;
  3622. }
  3623. }
  3624. }
  3625. me.fireEvent('aftersetcontent');
  3626. me.fireEvent('contentchange');
  3627. !notFireSelectionchange && me._selectionChange();
  3628. //清除保存的选区
  3629. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  3630. //trace:1742 setContent后gecko能得到焦点问题
  3631. var geckoSel;
  3632. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  3633. geckoSel.removeAllRanges();
  3634. }
  3635. if(me.options.autoSyncData){
  3636. me.form && setValue(me.form,me);
  3637. }
  3638. },
  3639. /**
  3640. * 让编辑器获得焦点,toEnd确定focus位置
  3641. * @name focus
  3642. * @grammar editor.focus([toEnd]) //默认focus到编辑器头部,toEnd为true时focus到内容尾部
  3643. */
  3644. focus: function (toEnd) {
  3645. try {
  3646. var me = this,
  3647. rng = me.selection.getRange();
  3648. if (toEnd) {
  3649. rng.setStartAtLast(me.body.lastChild).setCursor(false, true);
  3650. } else {
  3651. rng.select(true);
  3652. }
  3653. this.fireEvent('focus');
  3654. } catch (e) {
  3655. }
  3656. },
  3657. /**
  3658. * 使编辑区域失去焦点
  3659. */
  3660. blur:function(){
  3661. var sel = this.selection.getNative();
  3662. sel.empty ? sel.empty() : sel.removeAllRanges();
  3663. this.fireEvent('blur')
  3664. },
  3665. /**
  3666. * 判断编辑器当前是否获得了焦点
  3667. */
  3668. isFocus : function(){
  3669. if(this.fireEvent('isfocus')===true){
  3670. return true;
  3671. }
  3672. return this.selection.isFocus();
  3673. },
  3674. /**
  3675. * 初始化UE事件及部分事件代理
  3676. * @private
  3677. * @ignore
  3678. */
  3679. _initEvents: function () {
  3680. var me = this,
  3681. cont = me.body,
  3682. _proxyDomEvent = function(){
  3683. me._proxyDomEvent.apply(me, arguments);
  3684. };
  3685. $(cont)
  3686. .on( 'click contextmenu mousedown keydown keyup keypress mouseup mouseover mouseout selectstart', _proxyDomEvent)
  3687. .on( 'focus blur', _proxyDomEvent)
  3688. .on('mouseup keydown', function (evt) {
  3689. //特殊键不触发selectionchange
  3690. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  3691. return;
  3692. }
  3693. if (evt.button == 2)return;
  3694. me._selectionChange(250, evt);
  3695. });
  3696. },
  3697. /**
  3698. * 触发事件代理
  3699. * @private
  3700. * @ignore
  3701. */
  3702. _proxyDomEvent: function (evt) {
  3703. return this.fireEvent(evt.type.replace(/^on/, ''), evt);
  3704. },
  3705. /**
  3706. * 变化选区
  3707. * @private
  3708. * @ignore
  3709. */
  3710. _selectionChange: function (delay, evt) {
  3711. var me = this;
  3712. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  3713. // if ( !me.selection.isFocus() ){
  3714. // return;
  3715. // }
  3716. var hackForMouseUp = false;
  3717. var mouseX, mouseY;
  3718. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  3719. var range = this.selection.getRange();
  3720. if (!range.collapsed) {
  3721. hackForMouseUp = true;
  3722. mouseX = evt.clientX;
  3723. mouseY = evt.clientY;
  3724. }
  3725. }
  3726. clearTimeout(_selectionChangeTimer);
  3727. _selectionChangeTimer = setTimeout(function () {
  3728. if (!me.selection.getNative()) {
  3729. return;
  3730. }
  3731. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  3732. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  3733. var ieRange;
  3734. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  3735. ieRange = me.document.body.createTextRange();
  3736. try {
  3737. ieRange.moveToPoint(mouseX, mouseY);
  3738. } catch (ex) {
  3739. ieRange = null;
  3740. }
  3741. }
  3742. var bakGetIERange;
  3743. if (ieRange) {
  3744. bakGetIERange = me.selection.getIERange;
  3745. me.selection.getIERange = function () {
  3746. return ieRange;
  3747. };
  3748. }
  3749. me.selection.cache();
  3750. if (bakGetIERange) {
  3751. me.selection.getIERange = bakGetIERange;
  3752. }
  3753. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  3754. me.fireEvent('beforeselectionchange');
  3755. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  3756. me.fireEvent('selectionchange', !!evt);
  3757. me.fireEvent('afterselectionchange');
  3758. me.selection.clear();
  3759. }
  3760. }, delay || 50);
  3761. },
  3762. _callCmdFn: function (fnName, args) {
  3763. args = Array.prototype.slice.call(args,0);
  3764. var cmdName = args.shift().toLowerCase(),
  3765. cmd, cmdFn;
  3766. cmd = this.commands[cmdName] || UM.commands[cmdName];
  3767. cmdFn = cmd && cmd[fnName];
  3768. //没有querycommandstate或者没有command的都默认返回0
  3769. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  3770. return 0;
  3771. } else if (cmdFn) {
  3772. return cmdFn.apply(this, [cmdName].concat(args));
  3773. }
  3774. },
  3775. /**
  3776. * 执行编辑命令cmdName,完成富文本编辑效果
  3777. * @name execCommand
  3778. * @grammar editor.execCommand(cmdName) => {*}
  3779. */
  3780. execCommand: function (cmdName) {
  3781. if(!this.isFocus()){
  3782. var bakRange = this.selection._bakRange;
  3783. if(bakRange){
  3784. bakRange.select()
  3785. }else{
  3786. this.focus(true)
  3787. }
  3788. }
  3789. cmdName = cmdName.toLowerCase();
  3790. var me = this,
  3791. result,
  3792. cmd = me.commands[cmdName] || UM.commands[cmdName];
  3793. if (!cmd || !cmd.execCommand) {
  3794. return null;
  3795. }
  3796. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  3797. me.__hasEnterExecCommand = true;
  3798. if (me.queryCommandState.apply(me,arguments) != -1) {
  3799. me.fireEvent('saveScene');
  3800. me.fireEvent('beforeexeccommand', cmdName);
  3801. result = this._callCmdFn('execCommand', arguments);
  3802. (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  3803. me.fireEvent('afterexeccommand', cmdName);
  3804. me.fireEvent('saveScene');
  3805. }
  3806. me.__hasEnterExecCommand = false;
  3807. } else {
  3808. result = this._callCmdFn('execCommand', arguments);
  3809. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  3810. }
  3811. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  3812. return result;
  3813. },
  3814. /**
  3815. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  3816. * @name queryCommandState
  3817. * @grammar editor.queryCommandState(cmdName) => (-1|0|1)
  3818. * @desc
  3819. * * ''-1'' 当前命令不可用
  3820. * * ''0'' 当前命令可用
  3821. * * ''1'' 当前命令已经执行过了
  3822. */
  3823. queryCommandState: function (cmdName) {
  3824. try{
  3825. return this._callCmdFn('queryCommandState', arguments);
  3826. }catch(e){
  3827. return 0
  3828. }
  3829. },
  3830. /**
  3831. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  3832. * @name queryCommandValue
  3833. * @grammar editor.queryCommandValue(cmdName) => {*}
  3834. */
  3835. queryCommandValue: function (cmdName) {
  3836. try{
  3837. return this._callCmdFn('queryCommandValue', arguments);
  3838. }catch(e){
  3839. return null
  3840. }
  3841. },
  3842. /**
  3843. * 检查编辑区域中是否有内容,若包含tags中的节点类型,直接返回true
  3844. * @name hasContents
  3845. * @desc
  3846. * 默认有文本内容,或者有以下节点都不认为是空
  3847. * <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>
  3848. * @grammar editor.hasContents() => (true|false)
  3849. * @grammar editor.hasContents(tags) => (true|false) //若文档中包含tags数组里对应的tag,直接返回true
  3850. * @example
  3851. * editor.hasContents(['span']) //如果编辑器里有这些,不认为是空
  3852. */
  3853. hasContents: function (tags) {
  3854. if (tags) {
  3855. for (var i = 0, ci; ci = tags[i++];) {
  3856. if (this.body.getElementsByTagName(ci).length > 0) {
  3857. return true;
  3858. }
  3859. }
  3860. }
  3861. if (!domUtils.isEmptyBlock(this.body)) {
  3862. return true
  3863. }
  3864. //随时添加,定义的特殊标签如果存在,不能认为是空
  3865. tags = ['div'];
  3866. for (i = 0; ci = tags[i++];) {
  3867. var nodes = domUtils.getElementsByTagName(this.body, ci);
  3868. for (var n = 0, cn; cn = nodes[n++];) {
  3869. if (domUtils.isCustomeNode(cn)) {
  3870. return true;
  3871. }
  3872. }
  3873. }
  3874. return false;
  3875. },
  3876. /**
  3877. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  3878. * @name reset
  3879. * @desc
  3880. * * 清空编辑器内容
  3881. * * 清空回退列表
  3882. * @grammar editor.reset()
  3883. */
  3884. reset: function () {
  3885. this.fireEvent('reset');
  3886. },
  3887. isEnabled: function(){
  3888. return this._isEnabled != true;
  3889. },
  3890. setEnabled: function () {
  3891. var me = this, range;
  3892. me.body.contentEditable = true;
  3893. /* 恢复选区 */
  3894. if (me.lastBk) {
  3895. range = me.selection.getRange();
  3896. try {
  3897. range.moveToBookmark(me.lastBk);
  3898. delete me.lastBk
  3899. } catch (e) {
  3900. range.setStartAtFirst(me.body).collapse(true)
  3901. }
  3902. range.select(true);
  3903. }
  3904. /* 恢复query函数 */
  3905. if (me.bkqueryCommandState) {
  3906. me.queryCommandState = me.bkqueryCommandState;
  3907. delete me.bkqueryCommandState;
  3908. }
  3909. /* 恢复原生事件 */
  3910. if (me._bkproxyDomEvent) {
  3911. me._proxyDomEvent = me._bkproxyDomEvent;
  3912. delete me._bkproxyDomEvent;
  3913. }
  3914. /* 触发事件 */
  3915. me.fireEvent('setEnabled');
  3916. },
  3917. /**
  3918. * 设置当前编辑区域可以编辑
  3919. * @name enable
  3920. * @grammar editor.enable()
  3921. */
  3922. enable: function () {
  3923. return this.setEnabled();
  3924. },
  3925. setDisabled: function (except, keepDomEvent) {
  3926. var me = this;
  3927. me.body.contentEditable = false;
  3928. me._except = except ? utils.isArray(except) ? except : [except] : [];
  3929. /* 备份最后的选区 */
  3930. if (!me.lastBk) {
  3931. me.lastBk = me.selection.getRange().createBookmark(true);
  3932. }
  3933. /* 备份并重置query函数 */
  3934. if(!me.bkqueryCommandState) {
  3935. me.bkqueryCommandState = me.queryCommandState;
  3936. me.queryCommandState = function (type) {
  3937. if (utils.indexOf(me._except, type) != -1) {
  3938. return me.bkqueryCommandState.apply(me, arguments);
  3939. }
  3940. return -1;
  3941. };
  3942. }
  3943. /* 备份并墙原生事件 */
  3944. if(!keepDomEvent && !me._bkproxyDomEvent) {
  3945. me._bkproxyDomEvent = me._proxyDomEvent;
  3946. me._proxyDomEvent = function () {
  3947. return false;
  3948. };
  3949. }
  3950. /* 触发事件 */
  3951. me.fireEvent('selectionchange');
  3952. me.fireEvent('setDisabled', me._except);
  3953. },
  3954. /** 设置当前编辑区域不可编辑,except中的命令除外
  3955. * @name disable
  3956. * @grammar editor.disable()
  3957. * @grammar editor.disable(except) //例外的命令,也即即使设置了disable,此处配置的命令仍然可以执行
  3958. * @example
  3959. * //禁用工具栏中除加粗和插入图片之外的所有功能
  3960. * editor.disable(['bold','insertimage']);//可以是单一的String,也可以是Array
  3961. */
  3962. disable: function (except) {
  3963. return this.setDisabled(except);
  3964. },
  3965. /**
  3966. * 设置默认内容
  3967. * @ignore
  3968. * @private
  3969. * @param {String} cont 要存入的内容
  3970. */
  3971. _setDefaultContent: function () {
  3972. function clear() {
  3973. var me = this;
  3974. if (me.document.getElementById('initContent')) {
  3975. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  3976. me.removeListener('firstBeforeExecCommand focus', clear);
  3977. setTimeout(function () {
  3978. me.focus();
  3979. me._selectionChange();
  3980. }, 0)
  3981. }
  3982. }
  3983. return function (cont) {
  3984. var me = this;
  3985. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  3986. me.addListener('firstBeforeExecCommand focus', clear);
  3987. }
  3988. }(),
  3989. /**
  3990. * show方法的兼容版本
  3991. * @private
  3992. * @ignore
  3993. */
  3994. setShow: function () {
  3995. var me = this, range = me.selection.getRange();
  3996. if (me.container.style.display == 'none') {
  3997. //有可能内容丢失了
  3998. try {
  3999. range.moveToBookmark(me.lastBk);
  4000. delete me.lastBk
  4001. } catch (e) {
  4002. range.setStartAtFirst(me.body).collapse(true)
  4003. }
  4004. //ie下focus实效,所以做了个延迟
  4005. setTimeout(function () {
  4006. range.select(true);
  4007. }, 100);
  4008. me.container.style.display = '';
  4009. }
  4010. },
  4011. /**
  4012. * 显示编辑器
  4013. * @name show
  4014. * @grammar editor.show()
  4015. */
  4016. show: function () {
  4017. return this.setShow();
  4018. },
  4019. /**
  4020. * hide方法的兼容版本
  4021. * @private
  4022. * @ignore
  4023. */
  4024. setHide: function () {
  4025. var me = this;
  4026. if (!me.lastBk) {
  4027. me.lastBk = me.selection.getRange().createBookmark(true);
  4028. }
  4029. me.container.style.display = 'none'
  4030. },
  4031. /**
  4032. * 隐藏编辑器
  4033. * @name hide
  4034. * @grammar editor.hide()
  4035. */
  4036. hide: function () {
  4037. return this.setHide();
  4038. },
  4039. /**
  4040. * 根据制定的路径,获取对应的语言资源
  4041. * @name getLang
  4042. * @grammar editor.getLang(path) => (JSON|String) 路径根据的是lang目录下的语言文件的路径结构
  4043. * @example
  4044. * editor.getLang('contextMenu.delete') //如果当前是中文,那返回是的是删除
  4045. */
  4046. getLang: function (path) {
  4047. var lang = UM.I18N[this.options.lang];
  4048. if (!lang) {
  4049. throw Error("not import language file");
  4050. }
  4051. path = (path || "").split(".");
  4052. for (var i = 0, ci; ci = path[i++];) {
  4053. lang = lang[ci];
  4054. if (!lang)break;
  4055. }
  4056. return lang;
  4057. },
  4058. /**
  4059. * 计算编辑器当前内容的长度
  4060. * @name getContentLength
  4061. * @grammar editor.getContentLength(ingoneHtml,tagNames) =>
  4062. * @example
  4063. * editor.getLang(true)
  4064. */
  4065. getContentLength: function (ingoneHtml, tagNames) {
  4066. var count = this.getContent(false,false,true).length;
  4067. if (ingoneHtml) {
  4068. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  4069. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  4070. for (var i = 0, ci; ci = tagNames[i++];) {
  4071. count += this.body.getElementsByTagName(ci).length;
  4072. }
  4073. }
  4074. return count;
  4075. },
  4076. addInputRule: function (rule,ignoreUndo) {
  4077. rule.ignoreUndo = ignoreUndo;
  4078. this.inputRules.push(rule);
  4079. },
  4080. filterInputRule: function (root,isUndoLoad) {
  4081. for (var i = 0, ci; ci = this.inputRules[i++];) {
  4082. if(isUndoLoad && ci.ignoreUndo){
  4083. continue;
  4084. }
  4085. ci.call(this, root)
  4086. }
  4087. },
  4088. addOutputRule: function (rule,ignoreUndo) {
  4089. rule.ignoreUndo = ignoreUndo;
  4090. this.outputRules.push(rule)
  4091. },
  4092. filterOutputRule: function (root,isUndoLoad) {
  4093. for (var i = 0, ci; ci = this.outputRules[i++];) {
  4094. if(isUndoLoad && ci.ignoreUndo){
  4095. continue;
  4096. }
  4097. ci.call(this, root)
  4098. }
  4099. }
  4100. };
  4101. utils.inherits(Editor, EventBase);
  4102. })();
  4103. /**
  4104. * @file
  4105. * @name UM.filterWord
  4106. * @short filterWord
  4107. * @desc 用来过滤word粘贴过来的字符串
  4108. * @import editor.js,core/utils.js
  4109. * @anthor zhanyi
  4110. */
  4111. var filterWord = UM.filterWord = function () {
  4112. //是否是word过来的内容
  4113. function isWordDocument( str ) {
  4114. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  4115. }
  4116. //去掉小数
  4117. function transUnit( v ) {
  4118. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  4119. return utils.transUnitToPx(m);
  4120. } );
  4121. return v;
  4122. }
  4123. function filterPasteWord( str ) {
  4124. return str.replace(/[\t\r\n]+/g,' ')
  4125. .replace( /<!--[\s\S]*?-->/ig, "" )
  4126. //转换图片
  4127. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  4128. //opera能自己解析出image所这里直接返回空
  4129. if(browser.opera){
  4130. return '';
  4131. }
  4132. try{
  4133. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  4134. if(/Bitmap/i.test(str)){
  4135. return '';
  4136. }
  4137. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  4138. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  4139. src = str.match(/src=\s*"([^"]*)"/i)[1];
  4140. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  4141. } catch(e){
  4142. return '';
  4143. }
  4144. })
  4145. //针对wps添加的多余标签处理
  4146. .replace(/<\/?div[^>]*>/g,'')
  4147. //去掉多余的属性
  4148. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  4149. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  4150. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  4151. //去掉多余的属性
  4152. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  4153. //保留list的标示
  4154. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  4155. })
  4156. //清除多余的font/span不能匹配&nbsp;有可能是空格
  4157. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  4158. return c.replace(/[\t\r\n ]+/g,' ')
  4159. })
  4160. //处理style的问题
  4161. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  4162. var n = [],
  4163. s = style.replace( /^\s+|\s+$/, '' )
  4164. .replace(/&#39;/g,'\'')
  4165. .replace( /&quot;/gi, "'" )
  4166. .split( /;\s*/g );
  4167. for ( var i = 0,v; v = s[i];i++ ) {
  4168. var name, value,
  4169. parts = v.split( ":" );
  4170. if ( parts.length == 2 ) {
  4171. name = parts[0].toLowerCase();
  4172. value = parts[1].toLowerCase();
  4173. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  4174. ||
  4175. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  4176. ){
  4177. continue;
  4178. }
  4179. switch ( name ) {
  4180. case "mso-padding-alt":
  4181. case "mso-padding-top-alt":
  4182. case "mso-padding-right-alt":
  4183. case "mso-padding-bottom-alt":
  4184. case "mso-padding-left-alt":
  4185. case "mso-margin-alt":
  4186. case "mso-margin-top-alt":
  4187. case "mso-margin-right-alt":
  4188. case "mso-margin-bottom-alt":
  4189. case "mso-margin-left-alt":
  4190. //ie下会出现挤到一起的情况
  4191. //case "mso-table-layout-alt":
  4192. case "mso-height":
  4193. case "mso-width":
  4194. case "mso-vertical-align-alt":
  4195. //trace:1819 ff下会解析出padding在table上
  4196. if(!/<table/.test(tag))
  4197. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  4198. continue;
  4199. case "horiz-align":
  4200. n[i] = "text-align:" + value;
  4201. continue;
  4202. case "vert-align":
  4203. n[i] = "vertical-align:" + value;
  4204. continue;
  4205. case "font-color":
  4206. case "mso-foreground":
  4207. n[i] = "color:" + value;
  4208. continue;
  4209. case "mso-background":
  4210. case "mso-highlight":
  4211. n[i] = "background:" + value;
  4212. continue;
  4213. case "mso-default-height":
  4214. n[i] = "min-height:" + transUnit( value );
  4215. continue;
  4216. case "mso-default-width":
  4217. n[i] = "min-width:" + transUnit( value );
  4218. continue;
  4219. case "mso-padding-between-alt":
  4220. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  4221. continue;
  4222. case "text-line-through":
  4223. if ( (value == "single") || (value == "double") ) {
  4224. n[i] = "text-decoration:line-through";
  4225. }
  4226. continue;
  4227. case "mso-zero-height":
  4228. if ( value == "yes" ) {
  4229. n[i] = "display:none";
  4230. }
  4231. continue;
  4232. // case 'background':
  4233. // break;
  4234. case 'margin':
  4235. if ( !/[1-9]/.test( value ) ) {
  4236. continue;
  4237. }
  4238. }
  4239. 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 )
  4240. ||
  4241. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  4242. ) {
  4243. continue;
  4244. }
  4245. n[i] = name + ":" + parts[1];
  4246. }
  4247. }
  4248. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  4249. })
  4250. .replace(/[\d.]+(cm|pt)/g,function(str){
  4251. return utils.transUnitToPx(str)
  4252. })
  4253. }
  4254. return function ( html ) {
  4255. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  4256. };
  4257. }();
  4258. ///import editor.js
  4259. ///import core/utils.js
  4260. ///import core/dom/dom.js
  4261. ///import core/dom/dtd.js
  4262. ///import core/htmlparser.js
  4263. //模拟的节点类
  4264. //by zhanyi
  4265. (function () {
  4266. var uNode = UM.uNode = function (obj) {
  4267. this.type = obj.type;
  4268. this.data = obj.data;
  4269. this.tagName = obj.tagName;
  4270. this.parentNode = obj.parentNode;
  4271. this.attrs = obj.attrs || {};
  4272. this.children = obj.children;
  4273. };
  4274. var notTransAttrs = {
  4275. 'href':1,
  4276. 'src':1,
  4277. '_src':1,
  4278. '_href':1,
  4279. 'cdata_data':1
  4280. };
  4281. var notTransTagName = {
  4282. style:1,
  4283. script:1
  4284. };
  4285. var indentChar = ' ',
  4286. breakChar = '\n';
  4287. function insertLine(arr, current, begin) {
  4288. arr.push(breakChar);
  4289. return current + (begin ? 1 : -1);
  4290. }
  4291. function insertIndent(arr, current) {
  4292. //插入缩进
  4293. for (var i = 0; i < current; i++) {
  4294. arr.push(indentChar);
  4295. }
  4296. }
  4297. //创建uNode的静态方法
  4298. //支持标签和html
  4299. uNode.createElement = function (html) {
  4300. if (/[<>]/.test(html)) {
  4301. return UM.htmlparser(html).children[0]
  4302. } else {
  4303. return new uNode({
  4304. type:'element',
  4305. children:[],
  4306. tagName:html
  4307. })
  4308. }
  4309. };
  4310. uNode.createText = function (data,noTrans) {
  4311. return new UM.uNode({
  4312. type:'text',
  4313. 'data':noTrans ? data : utils.unhtml(data || '')
  4314. })
  4315. };
  4316. function nodeToHtml(node, arr, formatter, current) {
  4317. switch (node.type) {
  4318. case 'root':
  4319. for (var i = 0, ci; ci = node.children[i++];) {
  4320. //插入新行
  4321. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  4322. insertLine(arr, current, true);
  4323. insertIndent(arr, current)
  4324. }
  4325. nodeToHtml(ci, arr, formatter, current)
  4326. }
  4327. break;
  4328. case 'text':
  4329. isText(node, arr);
  4330. break;
  4331. case 'element':
  4332. isElement(node, arr, formatter, current);
  4333. break;
  4334. case 'comment':
  4335. isComment(node, arr, formatter);
  4336. }
  4337. return arr;
  4338. }
  4339. function isText(node, arr) {
  4340. if(node.parentNode.tagName == 'pre'){
  4341. //源码模式下输入html标签,不能做转换处理,直接输出
  4342. arr.push(node.data)
  4343. }else{
  4344. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  4345. }
  4346. }
  4347. function isElement(node, arr, formatter, current) {
  4348. var attrhtml = '';
  4349. if (node.attrs) {
  4350. attrhtml = [];
  4351. var attrs = node.attrs;
  4352. for (var a in attrs) {
  4353. //这里就针对
  4354. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  4355. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  4356. //有可能做的不够
  4357. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  4358. return '&quot;'
  4359. }) : utils.unhtml(attrs[a])) + '"' : ''))
  4360. }
  4361. attrhtml = attrhtml.join(' ');
  4362. }
  4363. arr.push('<' + node.tagName +
  4364. (attrhtml ? ' ' + attrhtml : '') +
  4365. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  4366. );
  4367. //插入新行
  4368. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  4369. if(node.children && node.children.length){
  4370. current = insertLine(arr, current, true);
  4371. insertIndent(arr, current)
  4372. }
  4373. }
  4374. if (node.children && node.children.length) {
  4375. for (var i = 0, ci; ci = node.children[i++];) {
  4376. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  4377. insertLine(arr, current);
  4378. insertIndent(arr, current)
  4379. }
  4380. nodeToHtml(ci, arr, formatter, current)
  4381. }
  4382. }
  4383. if (!dtd.$empty[node.tagName]) {
  4384. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  4385. if(node.children && node.children.length){
  4386. current = insertLine(arr, current);
  4387. insertIndent(arr, current)
  4388. }
  4389. }
  4390. arr.push('<\/' + node.tagName + '>');
  4391. }
  4392. }
  4393. function isComment(node, arr) {
  4394. arr.push('<!--' + node.data + '-->');
  4395. }
  4396. function getNodeById(root, id) {
  4397. var node;
  4398. if (root.type == 'element' && root.getAttr('id') == id) {
  4399. return root;
  4400. }
  4401. if (root.children && root.children.length) {
  4402. for (var i = 0, ci; ci = root.children[i++];) {
  4403. if (node = getNodeById(ci, id)) {
  4404. return node;
  4405. }
  4406. }
  4407. }
  4408. }
  4409. function getNodesByTagName(node, tagName, arr) {
  4410. if (node.type == 'element' && node.tagName == tagName) {
  4411. arr.push(node);
  4412. }
  4413. if (node.children && node.children.length) {
  4414. for (var i = 0, ci; ci = node.children[i++];) {
  4415. getNodesByTagName(ci, tagName, arr)
  4416. }
  4417. }
  4418. }
  4419. function nodeTraversal(root,fn){
  4420. if(root.children && root.children.length){
  4421. for(var i= 0,ci;ci=root.children[i];){
  4422. nodeTraversal(ci,fn);
  4423. //ci被替换的情况,这里就不再走 fn了
  4424. if(ci.parentNode ){
  4425. if(ci.children && ci.children.length){
  4426. fn(ci)
  4427. }
  4428. if(ci.parentNode) i++
  4429. }
  4430. }
  4431. }else{
  4432. fn(root)
  4433. }
  4434. }
  4435. uNode.prototype = {
  4436. /**
  4437. * 当前节点对象,转换成html文本
  4438. * @method toHtml
  4439. * @return { String } 返回转换后的html字符串
  4440. * @example
  4441. * ```javascript
  4442. * node.toHtml();
  4443. * ```
  4444. */
  4445. /**
  4446. * 当前节点对象,转换成html文本
  4447. * @method toHtml
  4448. * @param { Boolean } formatter 是否格式化返回值
  4449. * @return { String } 返回转换后的html字符串
  4450. * @example
  4451. * ```javascript
  4452. * node.toHtml( true );
  4453. * ```
  4454. */
  4455. toHtml:function (formatter) {
  4456. var arr = [];
  4457. nodeToHtml(this, arr, formatter, 0);
  4458. return arr.join('')
  4459. },
  4460. /**
  4461. * 获取节点的html内容
  4462. * @method innerHTML
  4463. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4464. * @return { String } 返回节点的html内容
  4465. * @example
  4466. * ```javascript
  4467. * var htmlstr = node.innerHTML();
  4468. * ```
  4469. */
  4470. /**
  4471. * 设置节点的html内容
  4472. * @method innerHTML
  4473. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4474. * @param { String } htmlstr 传入要设置的html内容
  4475. * @return { UM.uNode } 返回节点本身
  4476. * @example
  4477. * ```javascript
  4478. * node.innerHTML('<span>text</span>');
  4479. * ```
  4480. */
  4481. innerHTML:function (htmlstr) {
  4482. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  4483. return this;
  4484. }
  4485. if (utils.isString(htmlstr)) {
  4486. if(this.children){
  4487. for (var i = 0, ci; ci = this.children[i++];) {
  4488. ci.parentNode = null;
  4489. }
  4490. }
  4491. this.children = [];
  4492. var tmpRoot = UM.htmlparser(htmlstr);
  4493. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  4494. this.children.push(ci);
  4495. ci.parentNode = this;
  4496. }
  4497. return this;
  4498. } else {
  4499. var tmpRoot = new UM.uNode({
  4500. type:'root',
  4501. children:this.children
  4502. });
  4503. return tmpRoot.toHtml();
  4504. }
  4505. },
  4506. /**
  4507. * 获取节点的纯文本内容
  4508. * @method innerText
  4509. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4510. * @return { String } 返回节点的存文本内容
  4511. * @example
  4512. * ```javascript
  4513. * var textStr = node.innerText();
  4514. * ```
  4515. */
  4516. /**
  4517. * 设置节点的纯文本内容
  4518. * @method innerText
  4519. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  4520. * @param { String } textStr 传入要设置的文本内容
  4521. * @return { UM.uNode } 返回节点本身
  4522. * @example
  4523. * ```javascript
  4524. * node.innerText('<span>text</span>');
  4525. * ```
  4526. */
  4527. innerText:function (textStr,noTrans) {
  4528. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  4529. return this;
  4530. }
  4531. if (textStr) {
  4532. if(this.children){
  4533. for (var i = 0, ci; ci = this.children[i++];) {
  4534. ci.parentNode = null;
  4535. }
  4536. }
  4537. this.children = [];
  4538. this.appendChild(uNode.createText(textStr,noTrans));
  4539. return this;
  4540. } else {
  4541. return this.toHtml().replace(/<[^>]+>/g, '');
  4542. }
  4543. },
  4544. /**
  4545. * 获取当前对象的data属性
  4546. * @method getData
  4547. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  4548. * @example
  4549. * ```javascript
  4550. * node.getData();
  4551. * ```
  4552. */
  4553. getData:function () {
  4554. if (this.type == 'element')
  4555. return '';
  4556. return this.data
  4557. },
  4558. /**
  4559. * 获取当前节点下的第一个子节点
  4560. * @method firstChild
  4561. * @return { UM.uNode } 返回第一个子节点
  4562. * @example
  4563. * ```javascript
  4564. * node.firstChild(); //返回第一个子节点
  4565. * ```
  4566. */
  4567. firstChild:function () {
  4568. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  4569. // return this;
  4570. // }
  4571. return this.children ? this.children[0] : null;
  4572. },
  4573. /**
  4574. * 获取当前节点下的最后一个子节点
  4575. * @method lastChild
  4576. * @return { UM.uNode } 返回最后一个子节点
  4577. * @example
  4578. * ```javascript
  4579. * node.lastChild(); //返回最后一个子节点
  4580. * ```
  4581. */
  4582. lastChild:function () {
  4583. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  4584. // return this;
  4585. // }
  4586. return this.children ? this.children[this.children.length - 1] : null;
  4587. },
  4588. /**
  4589. * 获取和当前节点有相同父亲节点的前一个节点
  4590. * @method previousSibling
  4591. * @return { UM.uNode } 返回前一个节点
  4592. * @example
  4593. * ```javascript
  4594. * node.children[2].previousSibling(); //返回子节点node.children[1]
  4595. * ```
  4596. */
  4597. previousSibling : function(){
  4598. var parent = this.parentNode;
  4599. for (var i = 0, ci; ci = parent.children[i]; i++) {
  4600. if (ci === this) {
  4601. return i == 0 ? null : parent.children[i-1];
  4602. }
  4603. }
  4604. },
  4605. /**
  4606. * 获取和当前节点有相同父亲节点的后一个节点
  4607. * @method nextSibling
  4608. * @return { UM.uNode } 返回后一个节点,找不到返回null
  4609. * @example
  4610. * ```javascript
  4611. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  4612. * ```
  4613. */
  4614. nextSibling : function(){
  4615. var parent = this.parentNode;
  4616. for (var i = 0, ci; ci = parent.children[i++];) {
  4617. if (ci === this) {
  4618. return parent.children[i];
  4619. }
  4620. }
  4621. },
  4622. /**
  4623. * 用新的节点替换当前节点
  4624. * @method replaceChild
  4625. * @param { UM.uNode } target 要替换成该节点参数
  4626. * @param { UM.uNode } source 要被替换掉的节点
  4627. * @return { UM.uNode } 返回替换之后的节点对象
  4628. * @example
  4629. * ```javascript
  4630. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  4631. * ```
  4632. */
  4633. replaceChild:function (target, source) {
  4634. if (this.children) {
  4635. if(target.parentNode){
  4636. target.parentNode.removeChild(target);
  4637. }
  4638. for (var i = 0, ci; ci = this.children[i]; i++) {
  4639. if (ci === source) {
  4640. this.children.splice(i, 1, target);
  4641. source.parentNode = null;
  4642. target.parentNode = this;
  4643. return target;
  4644. }
  4645. }
  4646. }
  4647. },
  4648. /**
  4649. * 在节点的子节点列表最后位置插入一个节点
  4650. * @method appendChild
  4651. * @param { UM.uNode } node 要插入的节点
  4652. * @return { UM.uNode } 返回刚插入的子节点
  4653. * @example
  4654. * ```javascript
  4655. * node.appendChild( newNode ); //在node内插入子节点newNode
  4656. * ```
  4657. */
  4658. appendChild:function (node) {
  4659. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  4660. if (!this.children) {
  4661. this.children = []
  4662. }
  4663. if(node.parentNode){
  4664. node.parentNode.removeChild(node);
  4665. }
  4666. for (var i = 0, ci; ci = this.children[i]; i++) {
  4667. if (ci === node) {
  4668. this.children.splice(i, 1);
  4669. break;
  4670. }
  4671. }
  4672. this.children.push(node);
  4673. node.parentNode = this;
  4674. return node;
  4675. }
  4676. },
  4677. /**
  4678. * 在传入节点的前面插入一个节点
  4679. * @method insertBefore
  4680. * @param { UM.uNode } target 要插入的节点
  4681. * @param { UM.uNode } source 在该参数节点前面插入
  4682. * @return { UM.uNode } 返回刚插入的子节点
  4683. * @example
  4684. * ```javascript
  4685. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  4686. * ```
  4687. */
  4688. insertBefore:function (target, source) {
  4689. if (this.children) {
  4690. if(target.parentNode){
  4691. target.parentNode.removeChild(target);
  4692. }
  4693. for (var i = 0, ci; ci = this.children[i]; i++) {
  4694. if (ci === source) {
  4695. this.children.splice(i, 0, target);
  4696. target.parentNode = this;
  4697. return target;
  4698. }
  4699. }
  4700. }
  4701. },
  4702. /**
  4703. * 在传入节点的后面插入一个节点
  4704. * @method insertAfter
  4705. * @param { UM.uNode } target 要插入的节点
  4706. * @param { UM.uNode } source 在该参数节点后面插入
  4707. * @return { UM.uNode } 返回刚插入的子节点
  4708. * @example
  4709. * ```javascript
  4710. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  4711. * ```
  4712. */
  4713. insertAfter:function (target, source) {
  4714. if (this.children) {
  4715. if(target.parentNode){
  4716. target.parentNode.removeChild(target);
  4717. }
  4718. for (var i = 0, ci; ci = this.children[i]; i++) {
  4719. if (ci === source) {
  4720. this.children.splice(i + 1, 0, target);
  4721. target.parentNode = this;
  4722. return target;
  4723. }
  4724. }
  4725. }
  4726. },
  4727. /**
  4728. * 从当前节点的子节点列表中,移除节点
  4729. * @method removeChild
  4730. * @param { UM.uNode } node 要移除的节点引用
  4731. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  4732. * @return { * } 返回刚移除的子节点
  4733. * @example
  4734. * ```javascript
  4735. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  4736. * ```
  4737. */
  4738. removeChild:function (node,keepChildren) {
  4739. if (this.children) {
  4740. for (var i = 0, ci; ci = this.children[i]; i++) {
  4741. if (ci === node) {
  4742. this.children.splice(i, 1);
  4743. ci.parentNode = null;
  4744. if(keepChildren && ci.children && ci.children.length){
  4745. for(var j= 0,cj;cj=ci.children[j];j++){
  4746. this.children.splice(i+j,0,cj);
  4747. cj.parentNode = this;
  4748. }
  4749. }
  4750. return ci;
  4751. }
  4752. }
  4753. }
  4754. },
  4755. /**
  4756. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  4757. * @method getAttr
  4758. * @param { String } attrName 要获取的属性名称
  4759. * @return { * } 返回attrs对象下的属性值
  4760. * @example
  4761. * ```javascript
  4762. * node.getAttr('title');
  4763. * ```
  4764. */
  4765. getAttr:function (attrName) {
  4766. return this.attrs && this.attrs[attrName.toLowerCase()]
  4767. },
  4768. /**
  4769. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  4770. * @method setAttr
  4771. * @param { String } attrName 要设置的属性名称
  4772. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  4773. * @return { * } 返回attrs对象下的属性值
  4774. * @example
  4775. * ```javascript
  4776. * node.setAttr('title','标题');
  4777. * ```
  4778. */
  4779. setAttr:function (attrName, attrVal) {
  4780. if (!attrName) {
  4781. delete this.attrs;
  4782. return;
  4783. }
  4784. if(!this.attrs){
  4785. this.attrs = {};
  4786. }
  4787. if (utils.isObject(attrName)) {
  4788. for (var a in attrName) {
  4789. if (!attrName[a]) {
  4790. delete this.attrs[a]
  4791. } else {
  4792. this.attrs[a.toLowerCase()] = attrName[a];
  4793. }
  4794. }
  4795. } else {
  4796. if (!attrVal) {
  4797. delete this.attrs[attrName]
  4798. } else {
  4799. this.attrs[attrName.toLowerCase()] = attrVal;
  4800. }
  4801. }
  4802. },
  4803. hasAttr: function( attrName ){
  4804. var attrVal = this.getAttr( attrName );
  4805. return ( attrVal !== null ) && ( attrVal !== undefined );
  4806. },
  4807. /**
  4808. * 获取当前节点在父节点下的位置索引
  4809. * @method getIndex
  4810. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  4811. * @example
  4812. * ```javascript
  4813. * node.getIndex();
  4814. * ```
  4815. */
  4816. getIndex:function(){
  4817. var parent = this.parentNode;
  4818. for(var i= 0,ci;ci=parent.children[i];i++){
  4819. if(ci === this){
  4820. return i;
  4821. }
  4822. }
  4823. return -1;
  4824. },
  4825. /**
  4826. * 在当前节点下,根据id查找节点
  4827. * @method getNodeById
  4828. * @param { String } id 要查找的id
  4829. * @return { UM.uNode } 返回找到的节点
  4830. * @example
  4831. * ```javascript
  4832. * node.getNodeById('textId');
  4833. * ```
  4834. */
  4835. getNodeById:function (id) {
  4836. var node;
  4837. if (this.children && this.children.length) {
  4838. for (var i = 0, ci; ci = this.children[i++];) {
  4839. if (node = getNodeById(ci, id)) {
  4840. return node;
  4841. }
  4842. }
  4843. }
  4844. },
  4845. /**
  4846. * 在当前节点下,根据元素名称查找节点列表
  4847. * @method getNodesByTagName
  4848. * @param { String } tagNames 要查找的元素名称
  4849. * @return { Array } 返回找到的节点列表
  4850. * @example
  4851. * ```javascript
  4852. * node.getNodesByTagName('span');
  4853. * ```
  4854. */
  4855. getNodesByTagName:function (tagNames) {
  4856. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  4857. var arr = [], me = this;
  4858. utils.each(tagNames, function (tagName) {
  4859. if (me.children && me.children.length) {
  4860. for (var i = 0, ci; ci = me.children[i++];) {
  4861. getNodesByTagName(ci, tagName, arr)
  4862. }
  4863. }
  4864. });
  4865. return arr;
  4866. },
  4867. /**
  4868. * 根据样式名称,获取节点的样式值
  4869. * @method getStyle
  4870. * @param { String } name 要获取的样式名称
  4871. * @return { String } 返回样式值
  4872. * @example
  4873. * ```javascript
  4874. * node.getStyle('font-size');
  4875. * ```
  4876. */
  4877. getStyle:function (name) {
  4878. var cssStyle = this.getAttr('style');
  4879. if (!cssStyle) {
  4880. return ''
  4881. }
  4882. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  4883. var match = cssStyle.match(reg);
  4884. if (match && match[0]) {
  4885. return match[2]
  4886. }
  4887. return '';
  4888. },
  4889. /**
  4890. * 给节点设置样式
  4891. * @method setStyle
  4892. * @param { String } name 要设置的的样式名称
  4893. * @param { String } val 要设置的的样值
  4894. * @example
  4895. * ```javascript
  4896. * node.setStyle('font-size', '12px');
  4897. * ```
  4898. */
  4899. setStyle:function (name, val) {
  4900. function exec(name, val) {
  4901. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  4902. cssStyle = cssStyle.replace(reg, '$1');
  4903. if (val) {
  4904. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  4905. }
  4906. }
  4907. var cssStyle = this.getAttr('style');
  4908. if (!cssStyle) {
  4909. cssStyle = '';
  4910. }
  4911. if (utils.isObject(name)) {
  4912. for (var a in name) {
  4913. exec(a, name[a])
  4914. }
  4915. } else {
  4916. exec(name, val)
  4917. }
  4918. this.setAttr('style', utils.trim(cssStyle))
  4919. },
  4920. hasClass: function( className ){
  4921. if( this.hasAttr('class') ) {
  4922. var classNames = this.getAttr('class').split(/\s+/),
  4923. hasClass = false;
  4924. $.each(classNames, function(key, item){
  4925. if( item === className ) {
  4926. hasClass = true;
  4927. }
  4928. });
  4929. return hasClass;
  4930. } else {
  4931. return false;
  4932. }
  4933. },
  4934. addClass: function( className ){
  4935. var classes = null,
  4936. hasClass = false;
  4937. if( this.hasAttr('class') ) {
  4938. classes = this.getAttr('class');
  4939. classes = classes.split(/\s+/);
  4940. classes.forEach( function( item ){
  4941. if( item===className ) {
  4942. hasClass = true;
  4943. return;
  4944. }
  4945. } );
  4946. !hasClass && classes.push( className );
  4947. this.setAttr('class', classes.join(" "));
  4948. } else {
  4949. this.setAttr('class', className);
  4950. }
  4951. },
  4952. removeClass: function( className ){
  4953. if( this.hasAttr('class') ) {
  4954. var cl = this.getAttr('class');
  4955. cl = cl.replace(new RegExp('\\b' + className + '\\b', 'g'),'');
  4956. this.setAttr('class', utils.trim(cl).replace(/[ ]{2,}/g,' '));
  4957. }
  4958. },
  4959. /**
  4960. * 传入一个函数,递归遍历当前节点下的所有节点
  4961. * @method traversal
  4962. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  4963. * @example
  4964. * ```javascript
  4965. * traversal(node, function(){
  4966. * console.log(node.type);
  4967. * });
  4968. * ```
  4969. */
  4970. traversal:function(fn){
  4971. if(this.children && this.children.length){
  4972. nodeTraversal(this,fn);
  4973. }
  4974. return this;
  4975. }
  4976. }
  4977. })();
  4978. //html字符串转换成uNode节点
  4979. //by zhanyi
  4980. var htmlparser = UM.htmlparser = function (htmlstr,ignoreBlank) {
  4981. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  4982. //先去掉了,加上的原因忘了,这里先记录
  4983. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  4984. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  4985. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  4986. var allowEmptyTags = {
  4987. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  4988. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  4989. };
  4990. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  4991. if(!ignoreBlank){
  4992. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  4993. //br暂时单独处理
  4994. if(b && allowEmptyTags[b.toLowerCase()]){
  4995. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  4996. }
  4997. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  4998. });
  4999. }
  5000. var notTransAttrs = {
  5001. 'href':1,
  5002. 'src':1
  5003. };
  5004. var uNode = UM.uNode,
  5005. needParentNode = {
  5006. 'td':'tr',
  5007. 'tr':['tbody','thead','tfoot'],
  5008. 'tbody':'table',
  5009. 'th':'tr',
  5010. 'thead':'table',
  5011. 'tfoot':'table',
  5012. 'caption':'table',
  5013. 'li':['ul', 'ol'],
  5014. 'dt':'dl',
  5015. 'dd':'dl',
  5016. 'option':'select'
  5017. },
  5018. needChild = {
  5019. 'ol':'li',
  5020. 'ul':'li'
  5021. };
  5022. function text(parent, data) {
  5023. if(needChild[parent.tagName]){
  5024. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  5025. parent.appendChild(tmpNode);
  5026. tmpNode.appendChild(uNode.createText(data));
  5027. parent = tmpNode;
  5028. }else{
  5029. parent.appendChild(uNode.createText(data));
  5030. }
  5031. }
  5032. function element(parent, tagName, htmlattr) {
  5033. var needParentTag;
  5034. if (needParentTag = needParentNode[tagName]) {
  5035. var tmpParent = parent,hasParent;
  5036. while(tmpParent.type != 'root'){
  5037. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  5038. parent = tmpParent;
  5039. hasParent = true;
  5040. break;
  5041. }
  5042. tmpParent = tmpParent.parentNode;
  5043. }
  5044. if(!hasParent){
  5045. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  5046. }
  5047. }
  5048. //按dtd处理嵌套
  5049. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  5050. // parent = parent.parentNode;
  5051. var elm = new uNode({
  5052. parentNode:parent,
  5053. type:'element',
  5054. tagName:tagName.toLowerCase(),
  5055. //是自闭合的处理一下
  5056. children:dtd.$empty[tagName] ? null : []
  5057. });
  5058. //如果属性存在,处理属性
  5059. if (htmlattr) {
  5060. var attrs = {}, match;
  5061. while (match = re_attr.exec(htmlattr)) {
  5062. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  5063. }
  5064. elm.attrs = attrs;
  5065. }
  5066. parent.children.push(elm);
  5067. //如果是自闭合节点返回父亲节点
  5068. return dtd.$empty[tagName] ? parent : elm
  5069. }
  5070. function comment(parent, data) {
  5071. parent.children.push(new uNode({
  5072. type:'comment',
  5073. data:data,
  5074. parentNode:parent
  5075. }));
  5076. }
  5077. var match, currentIndex = 0, nextIndex = 0;
  5078. //设置根节点
  5079. var root = new uNode({
  5080. type:'root',
  5081. children:[]
  5082. });
  5083. var currentParent = root;
  5084. while (match = re_tag.exec(htmlstr)) {
  5085. currentIndex = match.index;
  5086. try{
  5087. if (currentIndex > nextIndex) {
  5088. //text node
  5089. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  5090. }
  5091. if (match[3]) {
  5092. if(dtd.$cdata[currentParent.tagName]){
  5093. text(currentParent, match[0]);
  5094. }else{
  5095. //start tag
  5096. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  5097. }
  5098. } else if (match[1]) {
  5099. if(currentParent.type != 'root'){
  5100. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  5101. text(currentParent, match[0]);
  5102. }else{
  5103. var tmpParent = currentParent;
  5104. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  5105. currentParent = currentParent.parentNode;
  5106. if(currentParent.type == 'root'){
  5107. currentParent = tmpParent;
  5108. throw 'break'
  5109. }
  5110. }
  5111. //end tag
  5112. currentParent = currentParent.parentNode;
  5113. }
  5114. }
  5115. } else if (match[2]) {
  5116. //comment
  5117. comment(currentParent, match[2])
  5118. }
  5119. }catch(e){}
  5120. nextIndex = re_tag.lastIndex;
  5121. }
  5122. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  5123. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  5124. if (nextIndex < htmlstr.length) {
  5125. text(currentParent, htmlstr.slice(nextIndex));
  5126. }
  5127. return root;
  5128. };
  5129. /**
  5130. * @file
  5131. * @name UM.filterNode
  5132. * @short filterNode
  5133. * @desc 根据给定的规则过滤节点
  5134. * @import editor.js,core/utils.js
  5135. * @anthor zhanyi
  5136. */
  5137. var filterNode = UM.filterNode = function () {
  5138. function filterNode(node,rules){
  5139. switch (node.type) {
  5140. case 'text':
  5141. break;
  5142. case 'element':
  5143. var val;
  5144. if(val = rules[node.tagName]){
  5145. if(val === '-'){
  5146. node.parentNode.removeChild(node)
  5147. }else if(utils.isFunction(val)){
  5148. var parentNode = node.parentNode,
  5149. index = node.getIndex();
  5150. val(node);
  5151. if(node.parentNode){
  5152. if(node.children){
  5153. for(var i = 0,ci;ci=node.children[i];){
  5154. filterNode(ci,rules);
  5155. if(ci.parentNode){
  5156. i++;
  5157. }
  5158. }
  5159. }
  5160. }else{
  5161. for(var i = index,ci;ci=parentNode.children[i];){
  5162. filterNode(ci,rules);
  5163. if(ci.parentNode){
  5164. i++;
  5165. }
  5166. }
  5167. }
  5168. }else{
  5169. var attrs = val['$'];
  5170. if(attrs && node.attrs){
  5171. var tmpAttrs = {},tmpVal;
  5172. for(var a in attrs){
  5173. tmpVal = node.getAttr(a);
  5174. //todo 只先对style单独处理
  5175. if(a == 'style' && utils.isArray(attrs[a])){
  5176. var tmpCssStyle = [];
  5177. utils.each(attrs[a],function(v){
  5178. var tmp;
  5179. if(tmp = node.getStyle(v)){
  5180. tmpCssStyle.push(v + ':' + tmp);
  5181. }
  5182. });
  5183. tmpVal = tmpCssStyle.join(';')
  5184. }
  5185. if(tmpVal){
  5186. tmpAttrs[a] = tmpVal;
  5187. }
  5188. }
  5189. node.attrs = tmpAttrs;
  5190. }
  5191. if(node.children){
  5192. for(var i = 0,ci;ci=node.children[i];){
  5193. filterNode(ci,rules);
  5194. if(ci.parentNode){
  5195. i++;
  5196. }
  5197. }
  5198. }
  5199. }
  5200. }else{
  5201. //如果不在名单里扣出子节点并删除该节点,cdata除外
  5202. if(dtd.$cdata[node.tagName]){
  5203. node.parentNode.removeChild(node)
  5204. }else{
  5205. var parentNode = node.parentNode,
  5206. index = node.getIndex();
  5207. node.parentNode.removeChild(node,true);
  5208. for(var i = index,ci;ci=parentNode.children[i];){
  5209. filterNode(ci,rules);
  5210. if(ci.parentNode){
  5211. i++;
  5212. }
  5213. }
  5214. }
  5215. }
  5216. break;
  5217. case 'comment':
  5218. node.parentNode.removeChild(node)
  5219. }
  5220. }
  5221. return function(root,rules){
  5222. if(utils.isEmptyObject(rules)){
  5223. return root;
  5224. }
  5225. var val;
  5226. if(val = rules['-']){
  5227. utils.each(val.split(' '),function(k){
  5228. rules[k] = '-'
  5229. })
  5230. }
  5231. for(var i= 0,ci;ci=root.children[i];){
  5232. filterNode(ci,rules);
  5233. if(ci.parentNode){
  5234. i++;
  5235. }
  5236. }
  5237. return root;
  5238. }
  5239. }();
  5240. ///import core
  5241. /**
  5242. * @description 插入内容
  5243. * @name baidu.editor.execCommand
  5244. * @param {String} cmdName inserthtml插入内容的命令
  5245. * @param {String} html 要插入的内容
  5246. * @author zhanyi
  5247. */
  5248. UM.commands['inserthtml'] = {
  5249. execCommand: function (command,html,notNeedFilter){
  5250. var me = this,
  5251. range,
  5252. div;
  5253. if(!html){
  5254. return;
  5255. }
  5256. if(me.fireEvent('beforeinserthtml',html) === true){
  5257. return;
  5258. }
  5259. range = me.selection.getRange();
  5260. div = range.document.createElement( 'div' );
  5261. div.style.display = 'inline';
  5262. if (!notNeedFilter) {
  5263. var root = UM.htmlparser(html);
  5264. //如果给了过滤规则就先进行过滤
  5265. if(me.options.filterRules){
  5266. UM.filterNode(root,me.options.filterRules);
  5267. }
  5268. //执行默认的处理
  5269. me.filterInputRule(root);
  5270. html = root.toHtml()
  5271. }
  5272. div.innerHTML = utils.trim( html );
  5273. if ( !range.collapsed ) {
  5274. var tmpNode = range.startContainer;
  5275. if(domUtils.isFillChar(tmpNode)){
  5276. range.setStartBefore(tmpNode)
  5277. }
  5278. tmpNode = range.endContainer;
  5279. if(domUtils.isFillChar(tmpNode)){
  5280. range.setEndAfter(tmpNode)
  5281. }
  5282. range.txtToElmBoundary();
  5283. //结束边界可能放到了br的前边,要把br包含进来
  5284. // x[xxx]<br/>
  5285. if(range.endContainer && range.endContainer.nodeType == 1){
  5286. tmpNode = range.endContainer.childNodes[range.endOffset];
  5287. if(tmpNode && domUtils.isBr(tmpNode)){
  5288. range.setEndAfter(tmpNode);
  5289. }
  5290. }
  5291. if(range.startOffset == 0){
  5292. tmpNode = range.startContainer;
  5293. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  5294. tmpNode = range.endContainer;
  5295. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  5296. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  5297. range.setStart(me.body.firstChild,0).collapse(true)
  5298. }
  5299. }
  5300. }
  5301. !range.collapsed && range.deleteContents();
  5302. if(range.startContainer.nodeType == 1){
  5303. var child = range.startContainer.childNodes[range.startOffset],pre;
  5304. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  5305. range.setEnd(pre,pre.childNodes.length).collapse();
  5306. while(child.firstChild){
  5307. pre.appendChild(child.firstChild);
  5308. }
  5309. domUtils.remove(child);
  5310. }
  5311. }
  5312. }
  5313. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  5314. //如果当前位置选中了fillchar要干掉,要不会产生空行
  5315. if(range.inFillChar()){
  5316. child = range.startContainer;
  5317. if(domUtils.isFillChar(child)){
  5318. range.setStartBefore(child).collapse(true);
  5319. domUtils.remove(child);
  5320. }else if(domUtils.isFillChar(child,true)){
  5321. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  5322. range.startOffset--;
  5323. range.collapsed && range.collapse(true)
  5324. }
  5325. }
  5326. while ( child = div.firstChild ) {
  5327. if(hadBreak){
  5328. var p = me.document.createElement('p');
  5329. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  5330. nextNode = child.nextSibling;
  5331. p.appendChild(child);
  5332. child = nextNode;
  5333. }
  5334. if(p.firstChild){
  5335. child = p
  5336. }
  5337. }
  5338. range.insertNode( child );
  5339. nextNode = child.nextSibling;
  5340. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  5341. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  5342. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  5343. if(!dtd[parent.tagName][child.nodeName]){
  5344. pre = parent;
  5345. }else{
  5346. tmp = child.parentNode;
  5347. while (tmp !== parent){
  5348. pre = tmp;
  5349. tmp = tmp.parentNode;
  5350. }
  5351. }
  5352. domUtils.breakParent( child, pre || tmp );
  5353. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  5354. var pre = child.previousSibling;
  5355. domUtils.trimWhiteTextNode(pre);
  5356. if(!pre.childNodes.length){
  5357. domUtils.remove(pre);
  5358. }
  5359. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  5360. if(!browser.ie &&
  5361. (next = child.nextSibling) &&
  5362. domUtils.isBlockElm(next) &&
  5363. next.lastChild &&
  5364. !domUtils.isBr(next.lastChild)){
  5365. next.appendChild(me.document.createElement('br'));
  5366. }
  5367. hadBreak = 1;
  5368. }
  5369. }
  5370. var next = child.nextSibling;
  5371. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  5372. range.setStart(next,0).collapse(true);
  5373. break;
  5374. }
  5375. range.setEndAfter( child ).collapse();
  5376. }
  5377. child = range.startContainer;
  5378. if(nextNode && domUtils.isBr(nextNode)){
  5379. domUtils.remove(nextNode)
  5380. }
  5381. //用chrome可能有空白展位符
  5382. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  5383. if(nextNode = child.nextSibling){
  5384. domUtils.remove(child);
  5385. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  5386. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  5387. }
  5388. }else{
  5389. try{
  5390. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  5391. }catch(e){
  5392. range.setStartBefore(child);
  5393. domUtils.remove(child)
  5394. }
  5395. }
  5396. }
  5397. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  5398. try{
  5399. if(browser.ie9below && range.startContainer.nodeType == 1 && !range.startContainer.childNodes[range.startOffset]){
  5400. var start = range.startContainer,pre = start.childNodes[range.startOffset-1];
  5401. if(pre && pre.nodeType == 1 && dtd.$empty[pre.tagName]){
  5402. var txt = this.document.createTextNode(domUtils.fillChar);
  5403. range.insertNode(txt).setStart(txt,0).collapse(true);
  5404. }
  5405. }
  5406. setTimeout(function(){
  5407. range.select(true);
  5408. })
  5409. }catch(e){}
  5410. setTimeout(function(){
  5411. range = me.selection.getRange();
  5412. range.scrollIntoView();
  5413. me.fireEvent('afterinserthtml');
  5414. },200);
  5415. }
  5416. };
  5417. ///import core
  5418. ///import plugins\inserthtml.js
  5419. ///commands 插入图片,操作图片的对齐方式
  5420. ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter
  5421. ///commandsTitle 图片,默认,居左,居右,居中
  5422. ///commandsDialog dialogs\image
  5423. /**
  5424. * Created by .
  5425. * User: zhanyi
  5426. * for image
  5427. */
  5428. UM.commands['insertimage'] = {
  5429. execCommand:function (cmd, opt) {
  5430. opt = utils.isArray(opt) ? opt : [opt];
  5431. if (!opt.length) {
  5432. return;
  5433. }
  5434. var me = this;
  5435. var html = [], str = '', ci;
  5436. ci = opt[0];
  5437. if (opt.length == 1) {
  5438. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  5439. (ci.width ? 'width="' + ci.width + '" ' : '') +
  5440. (ci.height ? ' height="' + ci.height + '" ' : '') +
  5441. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  5442. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  5443. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  5444. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  5445. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  5446. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  5447. if (ci['floatStyle'] == 'center') {
  5448. str = '<p style="text-align: center">' + str + '</p>';
  5449. }
  5450. html.push(str);
  5451. } else {
  5452. for (var i = 0; ci = opt[i++];) {
  5453. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  5454. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  5455. (ci.height ? ' height="' + ci.height + '" ' : '') +
  5456. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  5457. (ci.border || '') + '" ' +
  5458. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  5459. html.push(str);
  5460. }
  5461. }
  5462. me.execCommand('insertHtml', html.join(''), true);
  5463. }
  5464. };
  5465. ///import core
  5466. ///commands 段落格式,居左,居右,居中,两端对齐
  5467. ///commandsName JustifyLeft,JustifyCenter,JustifyRight,JustifyJustify
  5468. ///commandsTitle 居左对齐,居中对齐,居右对齐,两端对齐
  5469. /**
  5470. * @description 居左右中
  5471. * @name UM.execCommand
  5472. * @param {String} cmdName justify执行对齐方式的命令
  5473. * @param {String} align 对齐方式:left居左,right居右,center居中,justify两端对齐
  5474. * @author zhanyi
  5475. */
  5476. UM.plugins['justify']=function(){
  5477. var me = this;
  5478. $.each('justifyleft justifyright justifycenter justifyfull'.split(' '),function(i,cmdName){
  5479. me.commands[cmdName] = {
  5480. execCommand:function (cmdName) {
  5481. return this.document.execCommand(cmdName);
  5482. },
  5483. queryCommandValue: function (cmdName) {
  5484. var val = this.document.queryCommandValue(cmdName);
  5485. return val === true || val === 'true' ? cmdName.replace(/justify/,'') : '';
  5486. },
  5487. queryCommandState: function (cmdName) {
  5488. return this.document.queryCommandState(cmdName) ? 1 : 0
  5489. }
  5490. };
  5491. })
  5492. };
  5493. ///import core
  5494. ///import plugins\removeformat.js
  5495. ///commands 字体颜色,背景色,字号,字体,下划线,删除线
  5496. ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough
  5497. ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线
  5498. /**
  5499. * @description 字体
  5500. * @name UM.execCommand
  5501. * @param {String} cmdName 执行的功能名称
  5502. * @param {String} value 传入的值
  5503. */
  5504. UM.plugins['font'] = function () {
  5505. var me = this,
  5506. fonts = {
  5507. 'forecolor': 'forecolor',
  5508. 'backcolor': 'backcolor',
  5509. 'fontsize': 'fontsize',
  5510. 'fontfamily': 'fontname'
  5511. },
  5512. cmdNameToStyle = {
  5513. 'forecolor': 'color',
  5514. 'backcolor': 'background-color',
  5515. 'fontsize': 'font-size',
  5516. 'fontfamily': 'font-family'
  5517. },
  5518. cmdNameToAttr = {
  5519. 'forecolor': 'color',
  5520. 'fontsize': 'size',
  5521. 'fontfamily': 'face'
  5522. };
  5523. me.setOpt({
  5524. 'fontfamily': [
  5525. { name: 'songti', val: '宋体,SimSun'},
  5526. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  5527. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  5528. { name: 'heiti', val: '黑体, SimHei'},
  5529. { name: 'lishu', val: '隶书, SimLi'},
  5530. { name: 'andaleMono', val: 'andale mono'},
  5531. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  5532. { name: 'arialBlack', val: 'arial black,avant garde'},
  5533. { name: 'comicSansMs', val: 'comic sans ms'},
  5534. { name: 'impact', val: 'impact,chicago'},
  5535. { name: 'timesNewRoman', val: 'times new roman'},
  5536. { name: 'sans-serif',val:'sans-serif'}
  5537. ],
  5538. 'fontsize': [10, 12, 16, 18,24, 32,48]
  5539. });
  5540. me.addOutputRule(function (root) {
  5541. utils.each(root.getNodesByTagName('font'), function (node) {
  5542. if (node.tagName == 'font') {
  5543. var cssStyle = [];
  5544. for (var p in node.attrs) {
  5545. switch (p) {
  5546. case 'size':
  5547. var val = node.attrs[p];
  5548. $.each({
  5549. '10':'1',
  5550. '12':'2',
  5551. '16':'3',
  5552. '18':'4',
  5553. '24':'5',
  5554. '32':'6',
  5555. '48':'7'
  5556. },function(k,v){
  5557. if(v == val){
  5558. val = k;
  5559. return false;
  5560. }
  5561. });
  5562. cssStyle.push('font-size:' + val + 'px');
  5563. break;
  5564. case 'color':
  5565. cssStyle.push('color:' + node.attrs[p]);
  5566. break;
  5567. case 'face':
  5568. cssStyle.push('font-family:' + node.attrs[p]);
  5569. break;
  5570. case 'style':
  5571. cssStyle.push(node.attrs[p]);
  5572. }
  5573. }
  5574. node.attrs = {
  5575. 'style': cssStyle.join(';')
  5576. };
  5577. }
  5578. node.tagName = 'span';
  5579. if(node.parentNode.tagName == 'span' && node.parentNode.children.length == 1){
  5580. $.each(node.attrs,function(k,v){
  5581. node.parentNode.attrs[k] = k == 'style' ? node.parentNode.attrs[k] + v : v;
  5582. })
  5583. node.parentNode.removeChild(node,true);
  5584. }
  5585. });
  5586. });
  5587. for(var p in fonts){
  5588. (function (cmd) {
  5589. me.commands[cmd] = {
  5590. execCommand: function (cmdName,value) {
  5591. if(value == 'transparent'){
  5592. return;
  5593. }
  5594. var rng = this.selection.getRange();
  5595. if(rng.collapsed){
  5596. var span = $('<span></span>').css(cmdNameToStyle[cmdName],value)[0];
  5597. rng.insertNode(span).setStart(span,0).setCursor();
  5598. }else{
  5599. if(cmdName == 'fontsize'){
  5600. value = {
  5601. '10':'1',
  5602. '12':'2',
  5603. '16':'3',
  5604. '18':'4',
  5605. '24':'5',
  5606. '32':'6',
  5607. '48':'7'
  5608. }[(value+"").replace(/px/,'')]
  5609. }
  5610. this.document.execCommand(fonts[cmdName],false, value);
  5611. if(browser.gecko){
  5612. $.each(this.$body.find('a'),function(i,a){
  5613. var parent = a.parentNode;
  5614. if(parent.lastChild === parent.firstChild && /FONT|SPAN/.test(parent.tagName)){
  5615. var cloneNode = parent.cloneNode(false);
  5616. cloneNode.innerHTML = a.innerHTML;
  5617. $(a).html('').append(cloneNode).insertBefore(parent);
  5618. $(parent).remove();
  5619. }
  5620. });
  5621. }
  5622. if(!browser.ie){
  5623. var nativeRange = this.selection.getNative().getRangeAt(0);
  5624. var common = nativeRange.commonAncestorContainer;
  5625. var rng = this.selection.getRange(),
  5626. bk = rng.createBookmark(true);
  5627. $(common).find('a').each(function(i,n){
  5628. var parent = n.parentNode;
  5629. if(parent.nodeName == 'FONT'){
  5630. var font = parent.cloneNode(false);
  5631. font.innerHTML = n.innerHTML;
  5632. $(n).html('').append(font);
  5633. }
  5634. });
  5635. rng.moveToBookmark(bk).select()
  5636. }
  5637. return true
  5638. }
  5639. },
  5640. queryCommandValue: function (cmdName) {
  5641. var start = me.selection.getStart();
  5642. var val = $(start).css(cmdNameToStyle[cmdName]);
  5643. if(val === undefined){
  5644. val = $(start).attr(cmdNameToAttr[cmdName])
  5645. }
  5646. return val ? utils.fixColor(cmdName,val).replace(/px/,'') : '';
  5647. },
  5648. queryCommandState: function (cmdName) {
  5649. return this.queryCommandValue(cmdName)
  5650. }
  5651. };
  5652. })(p);
  5653. }
  5654. };
  5655. ///import core
  5656. ///commands 超链接,取消链接
  5657. ///commandsName Link,Unlink
  5658. ///commandsTitle 超链接,取消链接
  5659. ///commandsDialog dialogs\link
  5660. /**
  5661. * 超链接
  5662. * @function
  5663. * @name UM.execCommand
  5664. * @param {String} cmdName link插入超链接
  5665. * @param {Object} options url地址,title标题,target是否打开新页
  5666. * @author zhanyi
  5667. */
  5668. /**
  5669. * 取消链接
  5670. * @function
  5671. * @name UM.execCommand
  5672. * @param {String} cmdName unlink取消链接
  5673. * @author zhanyi
  5674. */
  5675. UM.plugins['link'] = function(){
  5676. var me = this;
  5677. me.setOpt('autourldetectinie',false);
  5678. //在ie下禁用autolink
  5679. if(browser.ie && this.options.autourldetectinie === false){
  5680. this.addListener('keyup',function(cmd,evt){
  5681. var me = this,keyCode = evt.keyCode;
  5682. if(keyCode == 13 || keyCode == 32){
  5683. var rng = me.selection.getRange();
  5684. var start = rng.startContainer;
  5685. if(keyCode == 13){
  5686. if(start.nodeName == 'P'){
  5687. var pre = start.previousSibling;
  5688. if(pre && pre.nodeType == 1){
  5689. var pre = pre.lastChild;
  5690. if(pre && pre.nodeName == 'A' && !pre.getAttribute('_href')){
  5691. domUtils.remove(pre,true);
  5692. }
  5693. }
  5694. }
  5695. }else if(keyCode == 32){
  5696. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  5697. start = start.previousSibling;
  5698. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  5699. domUtils.remove(start,true);
  5700. }
  5701. }
  5702. }
  5703. }
  5704. });
  5705. }
  5706. this.addOutputRule(function(root){
  5707. $.each(root.getNodesByTagName('a'),function(i,a){
  5708. var _href = utils.html(a.getAttr('_href'));
  5709. if(!/^(ftp|https?|\/|file)/.test(_href)){
  5710. _href = 'http://' + _href;
  5711. }
  5712. a.setAttr('href', _href);
  5713. a.setAttr('_href')
  5714. if(a.getAttr('title')==''){
  5715. a.setAttr('title')
  5716. }
  5717. })
  5718. });
  5719. this.addInputRule(function(root){
  5720. $.each(root.getNodesByTagName('a'),function(i,a){
  5721. a.setAttr('_href', utils.html(a.getAttr('href')));
  5722. })
  5723. });
  5724. me.commands['link'] = {
  5725. execCommand : function( cmdName, opt ) {
  5726. var me = this;
  5727. var rng = me.selection.getRange();
  5728. if(rng.collapsed){
  5729. var start = rng.startContainer;
  5730. if(start = domUtils.findParentByTagName(start,'a',true)){
  5731. $(start).attr(opt);
  5732. rng.selectNode(start).select()
  5733. }else{
  5734. rng.insertNode($('<a>' +opt.href+'</a>').attr(opt)[0]).select()
  5735. }
  5736. }else{
  5737. me.document.execCommand('createlink',false,'_umeditor_link');
  5738. utils.each(domUtils.getElementsByTagName(me.body,'a',function(n){
  5739. return n.getAttribute('href') == '_umeditor_link'
  5740. }),function(l){
  5741. if($(l).text() == '_umeditor_link'){
  5742. $(l).text(opt.href);
  5743. }
  5744. domUtils.setAttributes(l,opt);
  5745. rng.selectNode(l).select()
  5746. })
  5747. }
  5748. },
  5749. queryCommandState:function(){
  5750. return this.queryCommandValue('link') ? 1 : 0;
  5751. },
  5752. queryCommandValue:function(){
  5753. var path = this.selection.getStartElementPath();
  5754. var result;
  5755. $.each(path,function(i,n){
  5756. if(n.nodeName == "A"){
  5757. result = n;
  5758. return false;
  5759. }
  5760. })
  5761. return result;
  5762. }
  5763. };
  5764. me.commands['unlink'] = {
  5765. execCommand : function() {
  5766. this.document.execCommand('unlink');
  5767. }
  5768. };
  5769. };
  5770. ///import core
  5771. ///commands 打印
  5772. ///commandsName Print
  5773. ///commandsTitle 打印
  5774. /**
  5775. * @description 打印
  5776. * @name baidu.editor.execCommand
  5777. * @param {String} cmdName print打印编辑器内容
  5778. * @author zhanyi
  5779. */
  5780. UM.commands['print'] = {
  5781. execCommand : function(){
  5782. var me = this,
  5783. id = 'editor_print_' + +new Date();
  5784. $('<iframe src="" id="' + id + '" name="' + id + '" frameborder="0"></iframe>').attr('id', id)
  5785. .css({
  5786. width:'0px',
  5787. height:'0px',
  5788. 'overflow':'hidden',
  5789. 'float':'left',
  5790. 'position':'absolute',
  5791. top:'-10000px',
  5792. left:'-10000px'
  5793. })
  5794. .appendTo(me.$container.find('.edui-dialog-container'));
  5795. var w = window.open('', id, ''),
  5796. d = w.document;
  5797. d.open();
  5798. d.write('<html><head></head><body><div>'+this.getContent(null,null,true)+'</div><script>' +
  5799. "setTimeout(function(){" +
  5800. "window.print();" +
  5801. "setTimeout(function(){" +
  5802. "window.parent.$('#" + id + "').remove();" +
  5803. "},100);" +
  5804. "},200);" +
  5805. '</script></body></html>');
  5806. d.close();
  5807. },
  5808. notNeedUndo : 1
  5809. };
  5810. ///import core
  5811. ///commands 格式
  5812. ///commandsName Paragraph
  5813. ///commandsTitle 段落格式
  5814. /**
  5815. * 段落样式
  5816. * @function
  5817. * @name UM.execCommand
  5818. * @param {String} cmdName paragraph插入段落执行命令
  5819. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  5820. * @param {String} attrs 标签的属性
  5821. * @author zhanyi
  5822. */
  5823. UM.plugins['paragraph'] = function() {
  5824. var me = this;
  5825. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  5826. me.commands['paragraph'] = {
  5827. execCommand : function( cmdName, style ) {
  5828. return this.document.execCommand('formatBlock',false,'<' + style + '>');
  5829. },
  5830. queryCommandValue : function() {
  5831. try{
  5832. var val = this.document.queryCommandValue('formatBlock')
  5833. }catch(e){
  5834. }
  5835. return val ;
  5836. }
  5837. };
  5838. };
  5839. ///import core
  5840. ///import plugins\inserthtml.js
  5841. ///commands 分割线
  5842. ///commandsName Horizontal
  5843. ///commandsTitle 分隔线
  5844. /**
  5845. * 分割线
  5846. * @function
  5847. * @name UM.execCommand
  5848. * @param {String} cmdName horizontal插入分割线
  5849. */
  5850. UM.plugins['horizontal'] = function(){
  5851. var me = this;
  5852. me.commands['horizontal'] = {
  5853. execCommand : function( ) {
  5854. this.document.execCommand('insertHorizontalRule');
  5855. var rng = me.selection.getRange().txtToElmBoundary(true),
  5856. start = rng.startContainer;
  5857. if(domUtils.isBody(rng.startContainer)){
  5858. var next = rng.startContainer.childNodes[rng.startOffset];
  5859. if(!next){
  5860. next = $('<p></p>').appendTo(rng.startContainer).html(browser.ie ? '&nbsp;' : '<br/>')[0]
  5861. }
  5862. rng.setStart(next,0).setCursor()
  5863. }else{
  5864. while(dtd.$inline[start.tagName] && start.lastChild === start.firstChild){
  5865. var parent = start.parentNode;
  5866. parent.appendChild(start.firstChild);
  5867. parent.removeChild(start);
  5868. start = parent;
  5869. }
  5870. while(dtd.$inline[start.tagName]){
  5871. start = start.parentNode;
  5872. }
  5873. if(start.childNodes.length == 1 && start.lastChild.nodeName == 'HR'){
  5874. var hr = start.lastChild;
  5875. $(hr).insertBefore(start);
  5876. rng.setStart(start,0).setCursor();
  5877. }else{
  5878. hr = $('hr',start)[0];
  5879. domUtils.breakParent(hr,start);
  5880. var pre = hr.previousSibling;
  5881. if(pre && domUtils.isEmptyBlock(pre)){
  5882. $(pre).remove()
  5883. }
  5884. rng.setStart(hr.nextSibling,0).setCursor();
  5885. }
  5886. }
  5887. }
  5888. };
  5889. };
  5890. ///import core
  5891. ///commands 清空文档
  5892. ///commandsName ClearDoc
  5893. ///commandsTitle 清空文档
  5894. /**
  5895. *
  5896. * 清空文档
  5897. * @function
  5898. * @name UM.execCommand
  5899. * @param {String} cmdName cleardoc清空文档
  5900. */
  5901. UM.commands['cleardoc'] = {
  5902. execCommand : function() {
  5903. var me = this,
  5904. range = me.selection.getRange();
  5905. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  5906. range.setStart(me.body.firstChild,0).setCursor(false,true);
  5907. setTimeout(function(){
  5908. me.fireEvent("clearDoc");
  5909. },0);
  5910. }
  5911. };
  5912. ///import core
  5913. ///commands 撤销和重做
  5914. ///commandsName Undo,Redo
  5915. ///commandsTitle 撤销,重做
  5916. /**
  5917. * @description 回退
  5918. * @author zhanyi
  5919. */
  5920. UM.plugins['undo'] = function () {
  5921. var saveSceneTimer;
  5922. var me = this,
  5923. maxUndoCount = me.options.maxUndoCount || 20,
  5924. maxInputCount = me.options.maxInputCount || 20,
  5925. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  5926. var noNeedFillCharTags = {
  5927. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  5928. };
  5929. var orgState = me.options.autoClearEmptyNode;
  5930. function compareAddr(indexA, indexB) {
  5931. if (indexA.length != indexB.length)
  5932. return 0;
  5933. for (var i = 0, l = indexA.length; i < l; i++) {
  5934. if (indexA[i] != indexB[i])
  5935. return 0
  5936. }
  5937. return 1;
  5938. }
  5939. function compareRangeAddress(rngAddrA, rngAddrB) {
  5940. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  5941. return 0;
  5942. }
  5943. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  5944. return 0;
  5945. }
  5946. return 1;
  5947. }
  5948. function UndoManager() {
  5949. this.list = [];
  5950. this.index = 0;
  5951. this.hasUndo = false;
  5952. this.hasRedo = false;
  5953. this.undo = function () {
  5954. if (this.hasUndo) {
  5955. if (!this.list[this.index - 1] && this.list.length == 1) {
  5956. this.reset();
  5957. return;
  5958. }
  5959. while (this.list[this.index].content == this.list[this.index - 1].content) {
  5960. this.index--;
  5961. if (this.index == 0) {
  5962. return this.restore(0);
  5963. }
  5964. }
  5965. this.restore(--this.index);
  5966. }
  5967. };
  5968. this.redo = function () {
  5969. if (this.hasRedo) {
  5970. while (this.list[this.index].content == this.list[this.index + 1].content) {
  5971. this.index++;
  5972. if (this.index == this.list.length - 1) {
  5973. return this.restore(this.index);
  5974. }
  5975. }
  5976. this.restore(++this.index);
  5977. }
  5978. };
  5979. this.restore = function () {
  5980. var me = this.editor;
  5981. var scene = this.list[this.index];
  5982. var root = UM.htmlparser(scene.content.replace(fillchar, ''));
  5983. me.options.autoClearEmptyNode = false;
  5984. me.filterInputRule(root,true);
  5985. me.options.autoClearEmptyNode = orgState;
  5986. //trace:873
  5987. //去掉展位符
  5988. me.body.innerHTML = root.toHtml();
  5989. me.fireEvent('afterscencerestore');
  5990. //处理undo后空格不展位的问题
  5991. if (browser.ie) {
  5992. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  5993. if(domUtils.isEmptyNode(node)){
  5994. domUtils.fillNode(me.document, node);
  5995. }
  5996. })
  5997. }
  5998. try{
  5999. var rng = new dom.Range(me.document,me.body).moveToAddress(scene.address);
  6000. if(browser.ie && rng.collapsed && rng.startContainer.nodeType == 1){
  6001. var tmpNode = rng.startContainer.childNodes[rng.startOffset];
  6002. if( !tmpNode || tmpNode.nodeType == 1 && dtd.$empty[tmpNode]){
  6003. rng.insertNode(me.document.createTextNode(' ')).collapse(true);
  6004. }
  6005. }
  6006. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  6007. }catch(e){}
  6008. this.update();
  6009. this.clearKey();
  6010. //不能把自己reset了
  6011. me.fireEvent('reset', true);
  6012. };
  6013. this.getScene = function () {
  6014. var me = this.editor;
  6015. var rng = me.selection.getRange(),
  6016. rngAddress = rng.createAddress(false,true);
  6017. me.fireEvent('beforegetscene');
  6018. var root = UM.htmlparser(me.body.innerHTML,true);
  6019. me.options.autoClearEmptyNode = false;
  6020. me.filterOutputRule(root,true);
  6021. me.options.autoClearEmptyNode = orgState;
  6022. var cont = root.toHtml();
  6023. browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  6024. me.fireEvent('aftergetscene');
  6025. return {
  6026. address:rngAddress,
  6027. content:cont
  6028. }
  6029. };
  6030. this.save = function (notCompareRange,notSetCursor) {
  6031. clearTimeout(saveSceneTimer);
  6032. var currentScene = this.getScene(notSetCursor),
  6033. lastScene = this.list[this.index];
  6034. //内容相同位置相同不存
  6035. if (lastScene && lastScene.content == currentScene.content &&
  6036. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  6037. ) {
  6038. return;
  6039. }
  6040. this.list = this.list.slice(0, this.index + 1);
  6041. this.list.push(currentScene);
  6042. //如果大于最大数量了,就把最前的剔除
  6043. if (this.list.length > maxUndoCount) {
  6044. this.list.shift();
  6045. }
  6046. this.index = this.list.length - 1;
  6047. this.clearKey();
  6048. //跟新undo/redo状态
  6049. this.update();
  6050. };
  6051. this.update = function () {
  6052. this.hasRedo = !!this.list[this.index + 1];
  6053. this.hasUndo = !!this.list[this.index - 1];
  6054. };
  6055. this.reset = function () {
  6056. this.list = [];
  6057. this.index = 0;
  6058. this.hasUndo = false;
  6059. this.hasRedo = false;
  6060. this.clearKey();
  6061. };
  6062. this.clearKey = function () {
  6063. keycont = 0;
  6064. lastKeyCode = null;
  6065. };
  6066. }
  6067. me.undoManger = new UndoManager();
  6068. me.undoManger.editor = me;
  6069. function saveScene() {
  6070. this.undoManger.save();
  6071. }
  6072. me.addListener('saveScene', function () {
  6073. var args = Array.prototype.splice.call(arguments,1);
  6074. this.undoManger.save.apply(this.undoManger,args);
  6075. });
  6076. me.addListener('beforeexeccommand', saveScene);
  6077. me.addListener('afterexeccommand', saveScene);
  6078. me.addListener('reset', function (type, exclude) {
  6079. if (!exclude) {
  6080. this.undoManger.reset();
  6081. }
  6082. });
  6083. me.commands['redo'] = me.commands['undo'] = {
  6084. execCommand:function (cmdName) {
  6085. this.undoManger[cmdName]();
  6086. },
  6087. queryCommandState:function (cmdName) {
  6088. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  6089. },
  6090. notNeedUndo:1
  6091. };
  6092. var keys = {
  6093. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  6094. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  6095. 37:1, 38:1, 39:1, 40:1
  6096. },
  6097. keycont = 0,
  6098. lastKeyCode;
  6099. //输入法状态下不计算字符数
  6100. var inputType = false;
  6101. me.addListener('ready', function () {
  6102. $(this.body).on('compositionstart', function () {
  6103. inputType = true;
  6104. }).on('compositionend', function () {
  6105. inputType = false;
  6106. })
  6107. });
  6108. //快捷键
  6109. me.addshortcutkey({
  6110. "Undo":"ctrl+90", //undo
  6111. "Redo":"ctrl+89,shift+ctrl+z" //redo
  6112. });
  6113. var isCollapsed = true;
  6114. me.addListener('keydown', function (type, evt) {
  6115. var me = this;
  6116. var keyCode = evt.keyCode || evt.which;
  6117. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  6118. if (inputType)
  6119. return;
  6120. if(!me.selection.getRange().collapsed){
  6121. me.undoManger.save(false,true);
  6122. isCollapsed = false;
  6123. return;
  6124. }
  6125. if (me.undoManger.list.length == 0) {
  6126. me.undoManger.save(true);
  6127. }
  6128. clearTimeout(saveSceneTimer);
  6129. function save(cont){
  6130. if (cont.selection.getRange().collapsed)
  6131. cont.fireEvent('contentchange');
  6132. cont.undoManger.save(false,true);
  6133. cont.fireEvent('selectionchange');
  6134. }
  6135. saveSceneTimer = setTimeout(function(){
  6136. if(inputType){
  6137. var interalTimer = setInterval(function(){
  6138. if(!inputType){
  6139. save(me);
  6140. clearInterval(interalTimer)
  6141. }
  6142. },300)
  6143. return;
  6144. }
  6145. save(me);
  6146. },200);
  6147. lastKeyCode = keyCode;
  6148. keycont++;
  6149. if (keycont >= maxInputCount ) {
  6150. save(me)
  6151. }
  6152. }
  6153. });
  6154. me.addListener('keyup', function (type, evt) {
  6155. var keyCode = evt.keyCode || evt.which;
  6156. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  6157. if (inputType)
  6158. return;
  6159. if(!isCollapsed){
  6160. this.undoManger.save(false,true);
  6161. isCollapsed = true;
  6162. }
  6163. }
  6164. });
  6165. };
  6166. ///import core
  6167. ///import plugins/inserthtml.js
  6168. ///import plugins/undo.js
  6169. ///import plugins/serialize.js
  6170. ///commands 粘贴
  6171. ///commandsName PastePlain
  6172. ///commandsTitle 纯文本粘贴模式
  6173. /**
  6174. * @description 粘贴
  6175. * @author zhanyi
  6176. */
  6177. UM.plugins['paste'] = function () {
  6178. function getClipboardData(callback) {
  6179. var doc = this.document;
  6180. if (doc.getElementById('baidu_pastebin')) {
  6181. return;
  6182. }
  6183. var range = this.selection.getRange(),
  6184. bk = range.createBookmark(),
  6185. //创建剪贴的容器div
  6186. pastebin = doc.createElement('div');
  6187. pastebin.id = 'baidu_pastebin';
  6188. // Safari 要求div必须有内容,才能粘贴内容进来
  6189. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  6190. this.body.appendChild(pastebin);
  6191. //trace:717 隐藏的span不能得到top
  6192. //bk.start.innerHTML = '&nbsp;';
  6193. bk.start.style.display = '';
  6194. // pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  6195. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;top:" +
  6196. //要在现在光标平行的位置加入,否则会出现跳动的问题
  6197. $(bk.start).position().top + 'px';
  6198. range.selectNodeContents(pastebin).select(true);
  6199. setTimeout(function () {
  6200. if (browser.webkit) {
  6201. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  6202. if (domUtils.isEmptyNode(pi)) {
  6203. domUtils.remove(pi);
  6204. } else {
  6205. pastebin = pi;
  6206. break;
  6207. }
  6208. }
  6209. }
  6210. try {
  6211. pastebin.parentNode.removeChild(pastebin);
  6212. } catch (e) {
  6213. }
  6214. range.moveToBookmark(bk).select(true);
  6215. callback(pastebin);
  6216. }, 0);
  6217. }
  6218. var me = this;
  6219. function filter(div) {
  6220. var html;
  6221. if (div.firstChild) {
  6222. //去掉cut中添加的边界值
  6223. var nodes = domUtils.getElementsByTagName(div, 'span');
  6224. for (var i = 0, ni; ni = nodes[i++];) {
  6225. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  6226. domUtils.remove(ni);
  6227. }
  6228. }
  6229. if (browser.webkit) {
  6230. var brs = div.querySelectorAll('div br');
  6231. for (var i = 0, bi; bi = brs[i++];) {
  6232. var pN = bi.parentNode;
  6233. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  6234. pN.innerHTML = '<p><br/></p>';
  6235. domUtils.remove(pN);
  6236. }
  6237. }
  6238. var divs = div.querySelectorAll('#baidu_pastebin');
  6239. for (var i = 0, di; di = divs[i++];) {
  6240. var tmpP = me.document.createElement('p');
  6241. di.parentNode.insertBefore(tmpP, di);
  6242. while (di.firstChild) {
  6243. tmpP.appendChild(di.firstChild);
  6244. }
  6245. domUtils.remove(di);
  6246. }
  6247. var metas = div.querySelectorAll('meta');
  6248. for (var i = 0, ci; ci = metas[i++];) {
  6249. domUtils.remove(ci);
  6250. }
  6251. var brs = div.querySelectorAll('br');
  6252. for (i = 0; ci = brs[i++];) {
  6253. if (/^apple-/i.test(ci.className)) {
  6254. domUtils.remove(ci);
  6255. }
  6256. }
  6257. }
  6258. if (browser.gecko) {
  6259. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  6260. for (i = 0; ci = dirtyNodes[i++];) {
  6261. ci.removeAttribute('_moz_dirty');
  6262. }
  6263. }
  6264. if (!browser.ie) {
  6265. var spans = div.querySelectorAll('span.Apple-style-span');
  6266. for (var i = 0, ci; ci = spans[i++];) {
  6267. domUtils.remove(ci, true);
  6268. }
  6269. }
  6270. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  6271. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  6272. //过滤word粘贴过来的冗余属性
  6273. html = UM.filterWord(html);
  6274. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  6275. var root = UM.htmlparser(html);
  6276. //如果给了过滤规则就先进行过滤
  6277. if (me.options.filterRules) {
  6278. UM.filterNode(root, me.options.filterRules);
  6279. }
  6280. //执行默认的处理
  6281. me.filterInputRule(root);
  6282. //针对chrome的处理
  6283. if (browser.webkit) {
  6284. var br = root.lastChild();
  6285. if (br && br.type == 'element' && br.tagName == 'br') {
  6286. root.removeChild(br)
  6287. }
  6288. utils.each(me.body.querySelectorAll('div'), function (node) {
  6289. if (domUtils.isEmptyBlock(node)) {
  6290. domUtils.remove(node)
  6291. }
  6292. })
  6293. }
  6294. html = {'html': root.toHtml()};
  6295. me.fireEvent('beforepaste', html, root);
  6296. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  6297. if(!html.html){
  6298. return;
  6299. }
  6300. me.execCommand('insertHtml', html.html, true);
  6301. me.fireEvent("afterpaste", html);
  6302. }
  6303. }
  6304. me.addListener('ready', function () {
  6305. $(me.body).on( 'cut', function () {
  6306. var range = me.selection.getRange();
  6307. if (!range.collapsed && me.undoManger) {
  6308. me.undoManger.save();
  6309. }
  6310. }).on(browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  6311. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  6312. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  6313. return;
  6314. }
  6315. getClipboardData.call(me, function (div) {
  6316. filter(div);
  6317. });
  6318. });
  6319. });
  6320. };
  6321. ///import core
  6322. ///commands 有序列表,无序列表
  6323. ///commandsName InsertOrderedList,InsertUnorderedList
  6324. ///commandsTitle 有序列表,无序列表
  6325. /**
  6326. * 有序列表
  6327. * @function
  6328. * @name UM.execCommand
  6329. * @param {String} cmdName insertorderlist插入有序列表
  6330. * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman
  6331. * @author zhanyi
  6332. */
  6333. /**
  6334. * 无序链接
  6335. * @function
  6336. * @name UM.execCommand
  6337. * @param {String} cmdName insertunorderlist插入无序列表
  6338. * * @param {String} style 值为:circle,disc,square
  6339. * @author zhanyi
  6340. */
  6341. UM.plugins['list'] = function () {
  6342. var me = this;
  6343. me.setOpt( {
  6344. 'insertorderedlist':{
  6345. 'decimal':'',
  6346. 'lower-alpha':'',
  6347. 'lower-roman':'',
  6348. 'upper-alpha':'',
  6349. 'upper-roman':''
  6350. },
  6351. 'insertunorderedlist':{
  6352. 'circle':'',
  6353. 'disc':'',
  6354. 'square':''
  6355. }
  6356. } );
  6357. this.addInputRule(function(root){
  6358. utils.each(root.getNodesByTagName('li'), function (node) {
  6359. if(node.children.length == 0){
  6360. node.parentNode.removeChild(node);
  6361. }
  6362. })
  6363. });
  6364. me.commands['insertorderedlist'] =
  6365. me.commands['insertunorderedlist'] = {
  6366. execCommand:function (cmdName) {
  6367. this.document.execCommand(cmdName);
  6368. var rng = this.selection.getRange(),
  6369. bk = rng.createBookmark(true);
  6370. this.$body.find('ol,ul').each(function(i,n){
  6371. var parent = n.parentNode;
  6372. if(parent.tagName == 'P' && parent.lastChild === parent.firstChild){
  6373. $(n).children().each(function(j,li){
  6374. var p = parent.cloneNode(false);
  6375. $(p).append(li.innerHTML);
  6376. $(li).html('').append(p);
  6377. });
  6378. $(n).insertBefore(parent);
  6379. $(parent).remove();
  6380. }
  6381. if(dtd.$inline[parent.tagName]){
  6382. if(parent.tagName == 'SPAN'){
  6383. $(n).children().each(function(k,li){
  6384. var span = parent.cloneNode(false);
  6385. if(li.firstChild.nodeName != 'P'){
  6386. while(li.firstChild){
  6387. span.appendChild(li.firstChild)
  6388. };
  6389. $('<p></p>').appendTo(li).append(span);
  6390. }else{
  6391. while(li.firstChild){
  6392. span.appendChild(li.firstChild)
  6393. };
  6394. $(li.firstChild).append(span);
  6395. }
  6396. })
  6397. }
  6398. domUtils.remove(parent,true)
  6399. }
  6400. });
  6401. rng.moveToBookmark(bk).select();
  6402. return true;
  6403. },
  6404. queryCommandState:function (cmdName) {
  6405. return this.document.queryCommandState(cmdName);
  6406. }
  6407. };
  6408. };
  6409. ///import core
  6410. ///import plugins/serialize.js
  6411. ///import plugins/undo.js
  6412. ///commands 查看源码
  6413. ///commandsName Source
  6414. ///commandsTitle 查看源码
  6415. (function (){
  6416. var sourceEditors = {
  6417. textarea: function (editor, holder){
  6418. var textarea = holder.ownerDocument.createElement('textarea');
  6419. textarea.style.cssText = 'resize:none;border:0;padding:0;margin:0;overflow-y:auto;outline:0';
  6420. // todo: IE下只有onresize属性可用... 很纠结
  6421. if (browser.ie && browser.version < 8) {
  6422. textarea.style.width = holder.offsetWidth + 'px';
  6423. textarea.style.height = holder.offsetHeight + 'px';
  6424. holder.onresize = function (){
  6425. textarea.style.width = holder.offsetWidth + 'px';
  6426. textarea.style.height = holder.offsetHeight + 'px';
  6427. };
  6428. }
  6429. holder.appendChild(textarea);
  6430. return {
  6431. container : textarea,
  6432. setContent: function (content){
  6433. textarea.value = content;
  6434. },
  6435. getContent: function (){
  6436. return textarea.value;
  6437. },
  6438. select: function (){
  6439. var range;
  6440. if (browser.ie) {
  6441. range = textarea.createTextRange();
  6442. range.collapse(true);
  6443. range.select();
  6444. } else {
  6445. //todo: chrome下无法设置焦点
  6446. textarea.setSelectionRange(0, 0);
  6447. textarea.focus();
  6448. }
  6449. },
  6450. dispose: function (){
  6451. holder.removeChild(textarea);
  6452. // todo
  6453. holder.onresize = null;
  6454. textarea = null;
  6455. holder = null;
  6456. }
  6457. };
  6458. }
  6459. };
  6460. UM.plugins['source'] = function (){
  6461. var me = this;
  6462. var opt = this.options;
  6463. var sourceMode = false;
  6464. var sourceEditor;
  6465. opt.sourceEditor = 'textarea';
  6466. me.setOpt({
  6467. sourceEditorFirst:false
  6468. });
  6469. function createSourceEditor(holder){
  6470. return sourceEditors.textarea(me, holder);
  6471. }
  6472. var bakCssText;
  6473. //解决在源码模式下getContent不能得到最新的内容问题
  6474. var oldGetContent = me.getContent,
  6475. bakAddress;
  6476. me.commands['source'] = {
  6477. execCommand: function (){
  6478. sourceMode = !sourceMode;
  6479. if (sourceMode) {
  6480. bakAddress = me.selection.getRange().createAddress(false,true);
  6481. me.undoManger && me.undoManger.save(true);
  6482. if(browser.gecko){
  6483. me.body.contentEditable = false;
  6484. }
  6485. // bakCssText = me.body.style.cssText;
  6486. me.body.style.cssText += ';position:absolute;left:-32768px;top:-32768px;';
  6487. me.fireEvent('beforegetcontent');
  6488. var root = UM.htmlparser(me.body.innerHTML);
  6489. me.filterOutputRule(root);
  6490. root.traversal(function (node) {
  6491. if (node.type == 'element') {
  6492. switch (node.tagName) {
  6493. case 'td':
  6494. case 'th':
  6495. case 'caption':
  6496. if(node.children && node.children.length == 1){
  6497. if(node.firstChild().tagName == 'br' ){
  6498. node.removeChild(node.firstChild())
  6499. }
  6500. };
  6501. break;
  6502. case 'pre':
  6503. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  6504. }
  6505. }
  6506. });
  6507. me.fireEvent('aftergetcontent');
  6508. var content = root.toHtml(true);
  6509. sourceEditor = createSourceEditor(me.body.parentNode);
  6510. sourceEditor.setContent(content);
  6511. var getStyleValue=function(attr){
  6512. return parseInt($(me.body).css(attr));
  6513. };
  6514. $(sourceEditor.container).width($(me.body).width()+getStyleValue("padding-left")+getStyleValue("padding-right"))
  6515. .height($(me.body).height());
  6516. setTimeout(function (){
  6517. sourceEditor.select();
  6518. });
  6519. //重置getContent,源码模式下取值也能是最新的数据
  6520. me.getContent = function (){
  6521. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  6522. };
  6523. } else {
  6524. me.$body.css({
  6525. 'position':'',
  6526. 'left':'',
  6527. 'top':''
  6528. });
  6529. // me.body.style.cssText = bakCssText;
  6530. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  6531. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  6532. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  6533. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  6534. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  6535. }
  6536. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  6537. });
  6538. me.setContent(cont);
  6539. sourceEditor.dispose();
  6540. sourceEditor = null;
  6541. //还原getContent方法
  6542. me.getContent = oldGetContent;
  6543. var first = me.body.firstChild;
  6544. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  6545. if(!first){
  6546. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  6547. }
  6548. //要在ifm为显示时ff才能取到selection,否则报错
  6549. //这里不能比较位置了
  6550. me.undoManger && me.undoManger.save(true);
  6551. if(browser.gecko){
  6552. me.body.contentEditable = true;
  6553. }
  6554. try{
  6555. me.selection.getRange().moveToAddress(bakAddress).select();
  6556. }catch(e){}
  6557. }
  6558. this.fireEvent('sourcemodechanged', sourceMode);
  6559. },
  6560. queryCommandState: function (){
  6561. return sourceMode|0;
  6562. },
  6563. notNeedUndo : 1
  6564. };
  6565. var oldQueryCommandState = me.queryCommandState;
  6566. me.queryCommandState = function (cmdName){
  6567. cmdName = cmdName.toLowerCase();
  6568. if (sourceMode) {
  6569. //源码模式下可以开启的命令
  6570. return cmdName in {
  6571. 'source' : 1,
  6572. 'fullscreen' : 1
  6573. } ? oldQueryCommandState.apply(this, arguments) : -1
  6574. }
  6575. return oldQueryCommandState.apply(this, arguments);
  6576. };
  6577. };
  6578. })();
  6579. ///import core
  6580. ///import plugins/undo.js
  6581. ///commands 设置回车标签p或br
  6582. ///commandsName EnterKey
  6583. ///commandsTitle 设置回车标签p或br
  6584. /**
  6585. * @description 处理回车
  6586. * @author zhanyi
  6587. */
  6588. UM.plugins['enterkey'] = function() {
  6589. var hTag,
  6590. me = this,
  6591. tag = me.options.enterTag;
  6592. me.addListener('keyup', function(type, evt) {
  6593. var keyCode = evt.keyCode || evt.which;
  6594. if (keyCode == 13) {
  6595. var range = me.selection.getRange(),
  6596. start = range.startContainer,
  6597. doSave;
  6598. //修正在h1-h6里边回车后不能嵌套p的问题
  6599. if (!browser.ie) {
  6600. if (/h\d/i.test(hTag)) {
  6601. if (browser.gecko) {
  6602. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  6603. if (!h) {
  6604. me.document.execCommand('formatBlock', false, '<p>');
  6605. doSave = 1;
  6606. }
  6607. } else {
  6608. //chrome remove div
  6609. if (start.nodeType == 1) {
  6610. var tmp = me.document.createTextNode(''),div;
  6611. range.insertNode(tmp);
  6612. div = domUtils.findParentByTagName(tmp, 'div', true);
  6613. if (div) {
  6614. var p = me.document.createElement('p');
  6615. while (div.firstChild) {
  6616. p.appendChild(div.firstChild);
  6617. }
  6618. div.parentNode.insertBefore(p, div);
  6619. domUtils.remove(div);
  6620. range.setStartBefore(tmp).setCursor();
  6621. doSave = 1;
  6622. }
  6623. domUtils.remove(tmp);
  6624. }
  6625. }
  6626. if (me.undoManger && doSave) {
  6627. me.undoManger.save();
  6628. }
  6629. }
  6630. //没有站位符,会出现多行的问题
  6631. browser.opera && range.select();
  6632. }else{
  6633. me.fireEvent('saveScene',true,true)
  6634. }
  6635. }
  6636. });
  6637. me.addListener('keydown', function(type, evt) {
  6638. var keyCode = evt.keyCode || evt.which;
  6639. if (keyCode == 13) {//回车
  6640. if(me.fireEvent('beforeenterkeydown')){
  6641. domUtils.preventDefault(evt);
  6642. return;
  6643. }
  6644. me.fireEvent('saveScene',true,true);
  6645. hTag = '';
  6646. var range = me.selection.getRange();
  6647. if (!range.collapsed) {
  6648. //跨td不能删
  6649. var start = range.startContainer,
  6650. end = range.endContainer,
  6651. startTd = domUtils.findParentByTagName(start, 'td', true),
  6652. endTd = domUtils.findParentByTagName(end, 'td', true);
  6653. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  6654. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  6655. return;
  6656. }
  6657. }
  6658. if (tag == 'p') {
  6659. if (!browser.ie) {
  6660. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  6661. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  6662. //trace:2431
  6663. if (!start && !browser.opera) {
  6664. me.document.execCommand('formatBlock', false, '<p>');
  6665. if (browser.gecko) {
  6666. range = me.selection.getRange();
  6667. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  6668. start && domUtils.removeDirtyAttr(start);
  6669. }
  6670. } else {
  6671. hTag = start.tagName;
  6672. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  6673. }
  6674. }
  6675. }
  6676. }
  6677. });
  6678. browser.ie && me.addListener('setDisabled',function(){
  6679. $(me.body).find('p').each(function(i,p){
  6680. if(domUtils.isEmptyBlock(p)){
  6681. p.innerHTML = '&nbsp;'
  6682. }
  6683. })
  6684. })
  6685. };
  6686. ///import core
  6687. ///commands 预览
  6688. ///commandsName Preview
  6689. ///commandsTitle 预览
  6690. /**
  6691. * 预览
  6692. * @function
  6693. * @name UM.execCommand
  6694. * @param {String} cmdName preview预览编辑器内容
  6695. */
  6696. UM.commands['preview'] = {
  6697. execCommand : function(){
  6698. var w = window.open('', '_blank', ''),
  6699. d = w.document,
  6700. c = this.getContent(null,null,true),
  6701. path = this.getOpt('UMEDITOR_HOME_URL'),
  6702. formula = c.indexOf('mathquill-embedded-latex')!=-1 ?
  6703. '<link rel="stylesheet" href="' + path + 'third-party/mathquill/mathquill.css"/>' +
  6704. '<script src="' + path + 'third-party/jquery.min.js"></script>' +
  6705. '<script src="' + path + 'third-party/mathquill/mathquill.min.js"></script>':'';
  6706. d.open();
  6707. d.write('<html><head>' + formula + '</head><body><div>'+c+'</div></body></html>');
  6708. d.close();
  6709. },
  6710. notNeedUndo : 1
  6711. };
  6712. ///import core
  6713. ///commands 加粗,斜体,上标,下标
  6714. ///commandsName Bold,Italic,Subscript,Superscript
  6715. ///commandsTitle 加粗,加斜,下标,上标
  6716. /**
  6717. * b u i等基础功能实现
  6718. * @function
  6719. * @name UM.execCommands
  6720. * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。
  6721. */
  6722. UM.plugins['basestyle'] = function(){
  6723. var basestyles = ['bold','underline','superscript','subscript','italic','strikethrough'],
  6724. me = this;
  6725. //添加快捷键
  6726. me.addshortcutkey({
  6727. "Bold" : "ctrl+66",//^B
  6728. "Italic" : "ctrl+73", //^I
  6729. "Underline" : "ctrl+shift+85",//^U
  6730. "strikeThrough" : 'ctrl+shift+83' //^s
  6731. });
  6732. //过滤最后的产出数据
  6733. me.addOutputRule(function(root){
  6734. $.each(root.getNodesByTagName('b i u strike s'),function(i,node){
  6735. switch (node.tagName){
  6736. case 'b':
  6737. node.tagName = 'strong';
  6738. break;
  6739. case 'i':
  6740. node.tagName = 'em';
  6741. break;
  6742. case 'u':
  6743. node.tagName = 'span';
  6744. node.setStyle('text-decoration','underline');
  6745. break;
  6746. case 's':
  6747. case 'strike':
  6748. node.tagName = 'span';
  6749. node.setStyle('text-decoration','line-through')
  6750. }
  6751. });
  6752. });
  6753. $.each(basestyles,function(i,cmd){
  6754. me.commands[cmd] = {
  6755. execCommand : function( cmdName ) {
  6756. var rng = this.selection.getRange();
  6757. if(rng.collapsed && this.queryCommandState(cmdName) != 1){
  6758. var node = this.document.createElement({
  6759. 'bold':'strong',
  6760. 'underline':'u',
  6761. 'superscript':'sup',
  6762. 'subscript':'sub',
  6763. 'italic':'em',
  6764. 'strikethrough':'strike'
  6765. }[cmdName]);
  6766. rng.insertNode(node).setStart(node,0).setCursor(false);
  6767. return true;
  6768. }else{
  6769. return this.document.execCommand(cmdName)
  6770. }
  6771. },
  6772. queryCommandState : function(cmdName) {
  6773. if(browser.gecko){
  6774. return this.document.queryCommandState(cmdName)
  6775. }
  6776. var path = this.selection.getStartElementPath(),result = false;
  6777. $.each(path,function(i,n){
  6778. switch (cmdName){
  6779. case 'bold':
  6780. if(n.nodeName == 'STRONG' || n.nodeName == 'B'){
  6781. result = 1;
  6782. return false;
  6783. }
  6784. break;
  6785. case 'underline':
  6786. if(n.nodeName == 'U' || n.nodeName == 'SPAN' && $(n).css('text-decoration') == 'underline'){
  6787. result = 1;
  6788. return false;
  6789. }
  6790. break;
  6791. case 'superscript':
  6792. if(n.nodeName == 'SUP'){
  6793. result = 1;
  6794. return false;
  6795. }
  6796. break;
  6797. case 'subscript':
  6798. if(n.nodeName == 'SUB'){
  6799. result = 1;
  6800. return false;
  6801. }
  6802. break;
  6803. case 'italic':
  6804. if(n.nodeName == 'EM' || n.nodeName == 'I'){
  6805. result = 1;
  6806. return false;
  6807. }
  6808. break;
  6809. case 'strikethrough':
  6810. if(n.nodeName == 'S' || n.nodeName == 'STRIKE' || n.nodeName == 'SPAN' && $(n).css('text-decoration') == 'line-through'){
  6811. result = 1;
  6812. return false;
  6813. }
  6814. break;
  6815. }
  6816. })
  6817. return result
  6818. }
  6819. };
  6820. })
  6821. };
  6822. ///import core
  6823. ///import plugins/inserthtml.js
  6824. ///commands 视频
  6825. ///commandsName InsertVideo
  6826. ///commandsTitle 插入视频
  6827. ///commandsDialog dialogs\video
  6828. UM.plugins['video'] = function (){
  6829. var me =this,
  6830. div;
  6831. /**
  6832. * 创建插入视频字符窜
  6833. * @param url 视频地址
  6834. * @param width 视频宽度
  6835. * @param height 视频高度
  6836. * @param align 视频对齐
  6837. * @param toEmbed 是否以flash代替显示
  6838. * @param addParagraph 是否需要添加P 标签
  6839. */
  6840. function creatInsertStr(url,width,height,id,align,toEmbed){
  6841. return !toEmbed ?
  6842. '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-video"' +
  6843. ' 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 + ';': '')+'" />'
  6844. :
  6845. '<embed type="application/x-shockwave-flash" class="edui-faked-video" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  6846. ' src="' + url + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  6847. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  6848. }
  6849. function switchImgAndEmbed(root,img2embed){
  6850. utils.each(root.getNodesByTagName(img2embed ? 'img' : 'embed'),function(node){
  6851. if(node.getAttr('class') == 'edui-faked-video'){
  6852. var html = creatInsertStr( img2embed ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',img2embed);
  6853. node.parentNode.replaceChild(UM.uNode.createElement(html),node)
  6854. }
  6855. })
  6856. }
  6857. me.addOutputRule(function(root){
  6858. switchImgAndEmbed(root,true)
  6859. });
  6860. me.addInputRule(function(root){
  6861. switchImgAndEmbed(root)
  6862. });
  6863. me.commands["insertvideo"] = {
  6864. execCommand: function (cmd, videoObjs){
  6865. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  6866. var html = [],id = 'tmpVedio';
  6867. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  6868. vi = videoObjs[i];
  6869. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i,vi.align,false));
  6870. }
  6871. me.execCommand("inserthtml",html.join(""),true);
  6872. },
  6873. queryCommandState : function(){
  6874. var img = me.selection.getRange().getClosedNode(),
  6875. flag = img && (img.className == "edui-faked-video");
  6876. return flag ? 1 : 0;
  6877. }
  6878. };
  6879. };
  6880. ///import core
  6881. ///commands 全选
  6882. ///commandsName SelectAll
  6883. ///commandsTitle 全选
  6884. /**
  6885. * 选中所有
  6886. * @function
  6887. * @name UM.execCommand
  6888. * @param {String} cmdName selectall选中编辑器里的所有内容
  6889. * @author zhanyi
  6890. */
  6891. UM.plugins['selectall'] = function(){
  6892. var me = this;
  6893. me.commands['selectall'] = {
  6894. execCommand : function(){
  6895. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  6896. var me = this,body = me.body,
  6897. range = me.selection.getRange();
  6898. range.selectNodeContents(body);
  6899. if(domUtils.isEmptyBlock(body)){
  6900. //opera不能自动合并到元素的里边,要手动处理一下
  6901. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  6902. range.setStartAtFirst(body.firstChild);
  6903. }
  6904. range.collapse(true);
  6905. }
  6906. range.select(true);
  6907. },
  6908. notNeedUndo : 1
  6909. };
  6910. //快捷键
  6911. me.addshortcutkey({
  6912. "selectAll" : "ctrl+65"
  6913. });
  6914. };
  6915. //UM.plugins['removeformat'] = function () {
  6916. // var me = this;
  6917. // me.commands['removeformat'] = {
  6918. // execCommand: function () {
  6919. // me.document.execCommand('removeformat');
  6920. //
  6921. // /* 处理ie8和firefox选区有链接时,清除格式的bug */
  6922. // if (browser.gecko || browser.ie8 || browser.webkit) {
  6923. // var nativeRange = this.selection.getNative().getRangeAt(0),
  6924. // common = nativeRange.commonAncestorContainer,
  6925. // rng = me.selection.getRange(),
  6926. // bk = rng.createBookmark();
  6927. //
  6928. // function isEleInBookmark(node, bk){
  6929. // if ( (domUtils.getPosition(node, bk.start) & domUtils.POSITION_FOLLOWING) &&
  6930. // (domUtils.getPosition(bk.end, node) & domUtils.POSITION_FOLLOWING) ) {
  6931. // return true;
  6932. // } else if ( (domUtils.getPosition(node, bk.start) & domUtils.POSITION_CONTAINS) ||
  6933. // (domUtils.getPosition(node, bk.end) & domUtils.POSITION_CONTAINS) ) {
  6934. // return true;
  6935. // }
  6936. // return false;
  6937. // }
  6938. //
  6939. // $(common).find('a').each(function (k, a) {
  6940. // if ( isEleInBookmark(a, bk) ) {
  6941. // a.removeAttribute('style');
  6942. // }
  6943. // });
  6944. //
  6945. // }
  6946. // }
  6947. // };
  6948. //
  6949. //};
  6950. //
  6951. UM.plugins['removeformat'] = function(){
  6952. var me = this;
  6953. me.setOpt({
  6954. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  6955. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  6956. });
  6957. me.commands['removeformat'] = {
  6958. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  6959. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  6960. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  6961. range = new dom.Range( this.document ),
  6962. bookmark,node,parent,
  6963. filter = function( node ) {
  6964. return node.nodeType == 1;
  6965. };
  6966. function isRedundantSpan (node) {
  6967. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  6968. return 0;
  6969. }
  6970. if (browser.ie) {
  6971. //ie 下判断实效,所以只能简单用style来判断
  6972. //return node.style.cssText == '' ? 1 : 0;
  6973. var attrs = node.attributes;
  6974. if ( attrs.length ) {
  6975. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  6976. if ( attrs[i].specified ) {
  6977. return 0;
  6978. }
  6979. }
  6980. return 1;
  6981. }
  6982. }
  6983. return !node.attributes.length;
  6984. }
  6985. function doRemove( range ) {
  6986. var bookmark1 = range.createBookmark();
  6987. if ( range.collapsed ) {
  6988. range.enlarge( true );
  6989. }
  6990. //不能把a标签切了
  6991. if(!notIncludeA){
  6992. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  6993. if(aNode){
  6994. range.setStartBefore(aNode);
  6995. }
  6996. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  6997. if(aNode){
  6998. range.setEndAfter(aNode);
  6999. }
  7000. }
  7001. bookmark = range.createBookmark();
  7002. node = bookmark.start;
  7003. //切开始
  7004. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7005. domUtils.breakParent( node, parent );
  7006. domUtils.clearEmptySibling( node );
  7007. }
  7008. if ( bookmark.end ) {
  7009. //切结束
  7010. node = bookmark.end;
  7011. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7012. domUtils.breakParent( node, parent );
  7013. domUtils.clearEmptySibling( node );
  7014. }
  7015. //开始去除样式
  7016. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  7017. next;
  7018. while ( current ) {
  7019. if ( current == bookmark.end ) {
  7020. break;
  7021. }
  7022. next = domUtils.getNextDomNode( current, true, filter );
  7023. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  7024. if ( tagReg.test( current.tagName ) ) {
  7025. if ( style ) {
  7026. domUtils.removeStyle( current, style );
  7027. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  7028. domUtils.remove( current, true );
  7029. }
  7030. } else {
  7031. domUtils.remove( current, true );
  7032. }
  7033. } else {
  7034. //trace:939 不能把list上的样式去掉
  7035. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  7036. domUtils.removeAttributes( current, removeFormatAttributes );
  7037. if ( isRedundantSpan( current ) ){
  7038. domUtils.remove( current, true );
  7039. }
  7040. }
  7041. }
  7042. }
  7043. current = next;
  7044. }
  7045. }
  7046. //trace:1035
  7047. //trace:1096 不能把td上的样式去掉,比如边框
  7048. var pN = bookmark.start.parentNode;
  7049. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  7050. domUtils.removeAttributes( pN,removeFormatAttributes );
  7051. }
  7052. pN = bookmark.end.parentNode;
  7053. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  7054. domUtils.removeAttributes( pN,removeFormatAttributes );
  7055. }
  7056. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  7057. //清除冗余的代码 <b><bookmark></b>
  7058. var node = range.startContainer,
  7059. tmp,
  7060. collapsed = range.collapsed;
  7061. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7062. tmp = node.parentNode;
  7063. range.setStartBefore(node);
  7064. //trace:937
  7065. //更新结束边界
  7066. if(range.startContainer === range.endContainer){
  7067. range.endOffset--;
  7068. }
  7069. domUtils.remove(node);
  7070. node = tmp;
  7071. }
  7072. if(!collapsed){
  7073. node = range.endContainer;
  7074. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7075. tmp = node.parentNode;
  7076. range.setEndBefore(node);
  7077. domUtils.remove(node);
  7078. node = tmp;
  7079. }
  7080. }
  7081. }
  7082. range = this.selection.getRange();
  7083. if(!range.collapsed) {
  7084. doRemove( range );
  7085. range.select();
  7086. }
  7087. }
  7088. };
  7089. };
  7090. /*
  7091. * 处理特殊键的兼容性问题
  7092. */
  7093. UM.plugins['keystrokes'] = function() {
  7094. var me = this;
  7095. var collapsed = true;
  7096. me.addListener('keydown', function(type, evt) {
  7097. var keyCode = evt.keyCode || evt.which,
  7098. rng = me.selection.getRange();
  7099. //处理全选的情况
  7100. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  7101. || keyCode >= 48 && keyCode <= 57 ||
  7102. keyCode >= 96 && keyCode <= 111 || {
  7103. 13:1,
  7104. 8:1,
  7105. 46:1
  7106. }[keyCode])
  7107. ){
  7108. var tmpNode = rng.startContainer;
  7109. if(domUtils.isFillChar(tmpNode)){
  7110. rng.setStartBefore(tmpNode)
  7111. }
  7112. tmpNode = rng.endContainer;
  7113. if(domUtils.isFillChar(tmpNode)){
  7114. rng.setEndAfter(tmpNode)
  7115. }
  7116. rng.txtToElmBoundary();
  7117. //结束边界可能放到了br的前边,要把br包含进来
  7118. // x[xxx]<br/>
  7119. if(rng.endContainer && rng.endContainer.nodeType == 1){
  7120. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  7121. if(tmpNode && domUtils.isBr(tmpNode)){
  7122. rng.setEndAfter(tmpNode);
  7123. }
  7124. }
  7125. if(rng.startOffset == 0){
  7126. tmpNode = rng.startContainer;
  7127. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  7128. tmpNode = rng.endContainer;
  7129. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  7130. me.fireEvent('saveScene');
  7131. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  7132. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  7133. me._selectionChange();
  7134. return;
  7135. }
  7136. }
  7137. }
  7138. }
  7139. //处理backspace
  7140. if (keyCode == 8) {
  7141. rng = me.selection.getRange();
  7142. collapsed = rng.collapsed;
  7143. if(me.fireEvent('delkeydown',evt)){
  7144. return;
  7145. }
  7146. var start,end;
  7147. //避免按两次删除才能生效的问题
  7148. if(rng.collapsed && rng.inFillChar()){
  7149. start = rng.startContainer;
  7150. if(domUtils.isFillChar(start)){
  7151. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  7152. domUtils.remove(start)
  7153. }else{
  7154. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  7155. rng.startOffset--;
  7156. rng.collapse(true).select(true)
  7157. }
  7158. }
  7159. //解决选中control元素不能删除的问题
  7160. if (start = rng.getClosedNode()) {
  7161. me.fireEvent('saveScene');
  7162. rng.setStartBefore(start);
  7163. domUtils.remove(start);
  7164. rng.setCursor();
  7165. me.fireEvent('saveScene');
  7166. domUtils.preventDefault(evt);
  7167. return;
  7168. }
  7169. //阻止在table上的删除
  7170. if (!browser.ie) {
  7171. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  7172. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  7173. if (start && !end || !start && end || start !== end) {
  7174. evt.preventDefault();
  7175. return;
  7176. }
  7177. }
  7178. start = rng.startContainer;
  7179. if(rng.collapsed && start.nodeType == 1){
  7180. var currentNode = start.childNodes[rng.startOffset-1];
  7181. if(currentNode && currentNode.nodeType == 1 && currentNode.tagName == 'BR'){
  7182. me.fireEvent('saveScene');
  7183. rng.setStartBefore(currentNode).collapse(true);
  7184. domUtils.remove(currentNode);
  7185. rng.select();
  7186. me.fireEvent('saveScene');
  7187. }
  7188. }
  7189. //trace:3613
  7190. if(browser.chrome){
  7191. if(rng.collapsed){
  7192. while(rng.startOffset == 0 && !domUtils.isEmptyBlock(rng.startContainer)){
  7193. rng.setStartBefore(rng.startContainer)
  7194. }
  7195. var pre = rng.startContainer.childNodes[rng.startOffset-1];
  7196. if(pre && pre.nodeName == 'BR'){
  7197. rng.setStartBefore(pre);
  7198. me.fireEvent('saveScene');
  7199. $(pre).remove();
  7200. rng.setCursor();
  7201. me.fireEvent('saveScene');
  7202. }
  7203. }
  7204. }
  7205. }
  7206. //trace:1634
  7207. //ff的del键在容器空的时候,也会删除
  7208. if(browser.gecko && keyCode == 46){
  7209. var range = me.selection.getRange();
  7210. if(range.collapsed){
  7211. start = range.startContainer;
  7212. if(domUtils.isEmptyBlock(start)){
  7213. var parent = start.parentNode;
  7214. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  7215. start = parent;
  7216. parent = parent.parentNode;
  7217. }
  7218. if(start === parent.lastChild)
  7219. evt.preventDefault();
  7220. return;
  7221. }
  7222. }
  7223. }
  7224. });
  7225. me.addListener('keyup', function(type, evt) {
  7226. var keyCode = evt.keyCode || evt.which,
  7227. rng,me = this;
  7228. if(keyCode == 8){
  7229. if(me.fireEvent('delkeyup')){
  7230. return;
  7231. }
  7232. rng = me.selection.getRange();
  7233. if(rng.collapsed){
  7234. var tmpNode,
  7235. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  7236. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  7237. if(domUtils.isEmptyBlock(tmpNode)){
  7238. var pre = tmpNode.previousSibling;
  7239. if(pre && pre.nodeName != 'TABLE'){
  7240. domUtils.remove(tmpNode);
  7241. rng.setStartAtLast(pre).setCursor(false,true);
  7242. return;
  7243. }else{
  7244. var next = tmpNode.nextSibling;
  7245. if(next && next.nodeName != 'TABLE'){
  7246. domUtils.remove(tmpNode);
  7247. rng.setStartAtFirst(next).setCursor(false,true);
  7248. return;
  7249. }
  7250. }
  7251. }
  7252. }
  7253. //处理当删除到body时,要重新给p标签展位
  7254. if(domUtils.isBody(rng.startContainer)){
  7255. var tmpNode = domUtils.createElement(me.document,'p',{
  7256. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  7257. });
  7258. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  7259. }
  7260. }
  7261. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  7262. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  7263. if(browser.ie){
  7264. var span = rng.document.createElement('span');
  7265. rng.insertNode(span).setStartBefore(span).collapse(true);
  7266. rng.select();
  7267. domUtils.remove(span)
  7268. }else{
  7269. rng.select()
  7270. }
  7271. }
  7272. }
  7273. })
  7274. };
  7275. /**
  7276. * 自动保存草稿
  7277. */
  7278. UM.plugins['autosave'] = function() {
  7279. var me = this,
  7280. //无限循环保护
  7281. lastSaveTime = new Date(),
  7282. //最小保存间隔时间
  7283. MIN_TIME = 20,
  7284. //auto save key
  7285. saveKey = null;
  7286. //默认间隔时间
  7287. me.setOpt('saveInterval', 500);
  7288. //存储媒介封装
  7289. var LocalStorage = UM.LocalStorage = ( function () {
  7290. var storage = window.localStorage || getUserData() || null,
  7291. LOCAL_FILE = "localStorage";
  7292. return {
  7293. saveLocalData: function ( key, data ) {
  7294. if ( storage && data) {
  7295. storage.setItem( key, data );
  7296. return true;
  7297. }
  7298. return false;
  7299. },
  7300. getLocalData: function ( key ) {
  7301. if ( storage ) {
  7302. return storage.getItem( key );
  7303. }
  7304. return null;
  7305. },
  7306. removeItem: function ( key ) {
  7307. storage && storage.removeItem( key );
  7308. }
  7309. };
  7310. function getUserData () {
  7311. var container = document.createElement( "div" );
  7312. container.style.display = "none";
  7313. if( !container.addBehavior ) {
  7314. return null;
  7315. }
  7316. container.addBehavior("#default#userdata");
  7317. return {
  7318. getItem: function ( key ) {
  7319. var result = null;
  7320. try {
  7321. document.body.appendChild( container );
  7322. container.load( LOCAL_FILE );
  7323. result = container.getAttribute( key );
  7324. document.body.removeChild( container );
  7325. } catch ( e ) {
  7326. }
  7327. return result;
  7328. },
  7329. setItem: function ( key, value ) {
  7330. document.body.appendChild( container );
  7331. container.setAttribute( key, value );
  7332. container.save( LOCAL_FILE );
  7333. document.body.removeChild( container );
  7334. },
  7335. // 暂时没有用到
  7336. // clear: function () {
  7337. //
  7338. // var expiresTime = new Date();
  7339. // expiresTime.setFullYear( expiresTime.getFullYear() - 1 );
  7340. // document.body.appendChild( container );
  7341. // container.expires = expiresTime.toUTCString();
  7342. // container.save( LOCAL_FILE );
  7343. // document.body.removeChild( container );
  7344. //
  7345. // },
  7346. removeItem: function ( key ) {
  7347. document.body.appendChild( container );
  7348. container.removeAttribute( key );
  7349. container.save( LOCAL_FILE );
  7350. document.body.removeChild( container );
  7351. }
  7352. };
  7353. }
  7354. } )();
  7355. function save ( editor ) {
  7356. var saveData = null;
  7357. if ( new Date() - lastSaveTime < MIN_TIME ) {
  7358. return;
  7359. }
  7360. if ( !editor.hasContents() ) {
  7361. //这里不能调用命令来删除, 会造成事件死循环
  7362. saveKey && LocalStorage.removeItem( saveKey );
  7363. return;
  7364. }
  7365. lastSaveTime = new Date();
  7366. editor._saveFlag = null;
  7367. saveData = me.body.innerHTML;
  7368. if ( editor.fireEvent( "beforeautosave", {
  7369. content: saveData
  7370. } ) === false ) {
  7371. return;
  7372. }
  7373. LocalStorage.saveLocalData( saveKey, saveData );
  7374. editor.fireEvent( "afterautosave", {
  7375. content: saveData
  7376. } );
  7377. }
  7378. me.addListener('ready', function(){
  7379. var _suffix = "-drafts-data",
  7380. key = null;
  7381. if ( me.key ) {
  7382. key = me.key + _suffix;
  7383. } else {
  7384. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  7385. }
  7386. //页面地址+编辑器ID 保持唯一
  7387. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  7388. });
  7389. me.addListener('contentchange', function(){
  7390. if ( !saveKey ) {
  7391. return;
  7392. }
  7393. if ( me._saveFlag ) {
  7394. window.clearTimeout( me._saveFlag );
  7395. }
  7396. if ( me.options.saveInterval > 0 ) {
  7397. me._saveFlag = window.setTimeout( function () {
  7398. save( me );
  7399. }, me.options.saveInterval );
  7400. } else {
  7401. save(me);
  7402. }
  7403. })
  7404. me.commands['clearlocaldata'] = {
  7405. execCommand:function (cmd, name) {
  7406. if ( saveKey && LocalStorage.getLocalData( saveKey ) ) {
  7407. LocalStorage.removeItem( saveKey )
  7408. }
  7409. },
  7410. notNeedUndo: true,
  7411. ignoreContentChange:true
  7412. };
  7413. me.commands['getlocaldata'] = {
  7414. execCommand:function (cmd, name) {
  7415. return saveKey ? LocalStorage.getLocalData( saveKey ) || '' : '';
  7416. },
  7417. notNeedUndo: true,
  7418. ignoreContentChange:true
  7419. };
  7420. me.commands['drafts'] = {
  7421. execCommand:function (cmd, name) {
  7422. if ( saveKey ) {
  7423. me.body.innerHTML = LocalStorage.getLocalData( saveKey ) || '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>';
  7424. me.focus(true);
  7425. }
  7426. },
  7427. queryCommandState: function () {
  7428. return saveKey ? ( LocalStorage.getLocalData( saveKey ) === null ? -1 : 0 ) : -1;
  7429. },
  7430. notNeedUndo: true,
  7431. ignoreContentChange:true
  7432. }
  7433. };
  7434. /**
  7435. * @description
  7436. * 1.拖放文件到编辑区域,自动上传并插入到选区
  7437. * 2.插入粘贴板的图片,自动上传并插入到选区
  7438. * @author Jinqn
  7439. * @date 2013-10-14
  7440. */
  7441. UM.plugins['autoupload'] = function () {
  7442. var me = this;
  7443. me.setOpt('pasteImageEnabled', true);
  7444. me.setOpt('dropFileEnabled', true);
  7445. var insertBase64Image = function (file, editor) {
  7446. var reader = new FileReader();
  7447. reader.onload = function (e) {
  7448. editor.execCommand('insertimage', {
  7449. src: this.result,
  7450. _src: this.result
  7451. });
  7452. };
  7453. reader.readAsDataURL(file);
  7454. };
  7455. var sendAndInsertImage = function (file, editor) {
  7456. //模拟数据
  7457. var fd = new FormData();
  7458. fd.append(editor.options.imageFieldName || 'upfile', file, file.name || ('blob.' + file.type.substr('image/'.length)));
  7459. fd.append('type', 'ajax');
  7460. var xhr = new XMLHttpRequest();
  7461. xhr.open("post", me.options.imageUrl, true);
  7462. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  7463. xhr.addEventListener('load', function (e) {
  7464. try {
  7465. var json = eval('('+e.target.response+')'),
  7466. link = json.url,
  7467. picLink = me.options.imagePath + link;
  7468. editor.execCommand('insertimage', {
  7469. src: picLink,
  7470. _src: picLink
  7471. });
  7472. } catch (er) {
  7473. }
  7474. });
  7475. xhr.send(fd);
  7476. };
  7477. function getPasteImage(e) {
  7478. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items : null;
  7479. }
  7480. function getDropImage(e) {
  7481. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : null;
  7482. }
  7483. me.addListener('ready', function () {
  7484. if (window.FormData && window.FileReader) {
  7485. var autoUploadHandler = function (e) {
  7486. var hasImg = false,
  7487. items;
  7488. //获取粘贴板文件列表或者拖放文件列表
  7489. items = e.type == 'paste' ? getPasteImage(e.originalEvent) : getDropImage(e.originalEvent);
  7490. if (items) {
  7491. var len = items.length,
  7492. file;
  7493. while (len--) {
  7494. file = items[len];
  7495. if (file.getAsFile) file = file.getAsFile();
  7496. if (file && file.size > 0 && /image\/\w+/i.test(file.type)) {
  7497. me.getOpt('convertImageToBase64Enable') ? insertBase64Image(file, me) : sendAndInsertImage(file, me);
  7498. hasImg = true;
  7499. }
  7500. }
  7501. if (hasImg) return false;
  7502. }
  7503. };
  7504. me.getOpt('pasteImageEnabled') && me.$body.on('paste', autoUploadHandler);
  7505. me.getOpt('dropFileEnabled') && me.$body.on('drop', autoUploadHandler);
  7506. //取消拖放图片时出现的文字光标位置提示
  7507. me.$body.on('dragover', function (e) {
  7508. if (e.originalEvent.dataTransfer.types[0] == 'Files') {
  7509. return false;
  7510. }
  7511. });
  7512. }
  7513. });
  7514. };
  7515. /**
  7516. * 公式插件
  7517. */
  7518. UM.plugins['formula'] = function () {
  7519. var me = this;
  7520. function getActiveIframe() {
  7521. return me.$body.find('iframe.edui-formula-active')[0] || null;
  7522. }
  7523. function blurActiveIframe(){
  7524. var iframe = getActiveIframe();
  7525. iframe && iframe.contentWindow.formula.blur();
  7526. }
  7527. me.addInputRule(function (root) {
  7528. $.each(root.getNodesByTagName('span'), function (i, node) {
  7529. if (node.hasClass('mathquill-embedded-latex')) {
  7530. var firstChild, latex = '';
  7531. while(firstChild = node.firstChild()){
  7532. latex += firstChild.data;
  7533. node.removeChild(firstChild);
  7534. }
  7535. node.tagName = 'iframe';
  7536. node.setAttr({
  7537. 'frameborder': '0',
  7538. 'src': me.getOpt('UMEDITOR_HOME_URL') + 'dialogs/formula/formula.html',
  7539. 'data-latex': utils.unhtml(latex)
  7540. });
  7541. }
  7542. });
  7543. });
  7544. me.addOutputRule(function (root) {
  7545. $.each(root.getNodesByTagName('iframe'), function (i, node) {
  7546. if (node.hasClass('mathquill-embedded-latex')) {
  7547. node.tagName = 'span';
  7548. node.appendChild(UM.uNode.createText(node.getAttr('data-latex')));
  7549. node.setAttr({
  7550. 'frameborder': '',
  7551. 'src': '',
  7552. 'data-latex': ''
  7553. });
  7554. }
  7555. });
  7556. });
  7557. me.addListener('click', function(){
  7558. blurActiveIframe();
  7559. });
  7560. me.addListener('afterexeccommand', function(type, cmd){
  7561. if(cmd != 'formula') {
  7562. blurActiveIframe();
  7563. }
  7564. });
  7565. me.commands['formula'] = {
  7566. execCommand: function (cmd, latex) {
  7567. var iframe = getActiveIframe();
  7568. if (iframe) {
  7569. iframe.contentWindow.formula.insertLatex(latex);
  7570. } else {
  7571. me.execCommand('inserthtml', '<span class="mathquill-embedded-latex">' + latex + '</span>');
  7572. browser.ie && browser.ie9below && setTimeout(function(){
  7573. var rng = me.selection.getRange(),
  7574. startContainer = rng.startContainer;
  7575. if(startContainer.nodeType == 1 && !startContainer.childNodes[rng.startOffset]){
  7576. rng.insertNode(me.document.createTextNode(' '));
  7577. rng.setCursor()
  7578. }
  7579. },100)
  7580. }
  7581. },
  7582. queryCommandState: function (cmd) {
  7583. return 0;
  7584. },
  7585. queryCommandValue: function (cmd) {
  7586. var iframe = getActiveIframe();
  7587. return iframe && iframe.contentWindow.formula.getLatex();
  7588. }
  7589. }
  7590. };
  7591. (function ($) {
  7592. //对jquery的扩展
  7593. $.parseTmpl = function parse(str, data) {
  7594. 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) {
  7595. return "'," + code.replace(/\\'/g, "'") + ",'";
  7596. }).replace(/<%([\s\S]+?)%>/g,function (match, code) {
  7597. return "');" + code.replace(/\\'/g, "'").replace(/[\r\n\t]/g, ' ') + "__p.push('";
  7598. }).replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + "');}return __p.join('');";
  7599. var func = new Function('obj', tmpl);
  7600. return data ? func(data) : func;
  7601. };
  7602. $.extend2 = function (t, s) {
  7603. var a = arguments,
  7604. notCover = $.type(a[a.length - 1]) == 'boolean' ? a[a.length - 1] : false,
  7605. len = $.type(a[a.length - 1]) == 'boolean' ? a.length - 1 : a.length;
  7606. for (var i = 1; i < len; i++) {
  7607. var x = a[i];
  7608. for (var k in x) {
  7609. if (!notCover || !t.hasOwnProperty(k)) {
  7610. t[k] = x[k];
  7611. }
  7612. }
  7613. }
  7614. return t;
  7615. };
  7616. $.IE6 = !!window.ActiveXObject && parseFloat(navigator.userAgent.match(/msie (\d+)/i)[1]) == 6;
  7617. //所有ui的基类
  7618. var _eventHandler = [];
  7619. var _widget = function () {
  7620. };
  7621. var _prefix = 'edui';
  7622. _widget.prototype = {
  7623. on: function (ev, cb) {
  7624. this.root().on(ev, $.proxy(cb, this));
  7625. return this;
  7626. },
  7627. off: function (ev, cb) {
  7628. this.root().off(ev, $.proxy(cb, this));
  7629. return this;
  7630. },
  7631. trigger: function (ev, data) {
  7632. return this.root().trigger(ev, data) === false ? false : this;
  7633. },
  7634. root: function ($el) {
  7635. return this._$el || (this._$el = $el);
  7636. },
  7637. destroy: function () {
  7638. },
  7639. data: function (key, val) {
  7640. if (val !== undefined) {
  7641. this.root().data(_prefix + key, val);
  7642. return this;
  7643. } else {
  7644. return this.root().data(_prefix + key)
  7645. }
  7646. },
  7647. register: function (eventName, $el, fn) {
  7648. _eventHandler.push({
  7649. 'evtname': eventName,
  7650. '$els': $.isArray($el) ? $el : [$el],
  7651. handler: $.proxy(fn, $el)
  7652. })
  7653. }
  7654. };
  7655. //从jq实例上拿到绑定的widget实例
  7656. $.fn.edui = function (obj) {
  7657. return obj ? this.data('eduiwidget', obj) : this.data('eduiwidget');
  7658. };
  7659. function _createClass(ClassObj, properties, supperClass) {
  7660. ClassObj.prototype = $.extend2(
  7661. $.extend({}, properties),
  7662. (UM.ui[supperClass] || _widget).prototype,
  7663. true
  7664. );
  7665. ClassObj.prototype.supper = (UM.ui[supperClass] || _widget).prototype;
  7666. //父class的defaultOpt 合并
  7667. if( UM.ui[supperClass] && UM.ui[supperClass].prototype.defaultOpt ) {
  7668. var parentDefaultOptions = UM.ui[supperClass].prototype.defaultOpt,
  7669. subDefaultOptions = ClassObj.prototype.defaultOpt;
  7670. ClassObj.prototype.defaultOpt = $.extend( {}, parentDefaultOptions, subDefaultOptions || {} );
  7671. }
  7672. return ClassObj
  7673. }
  7674. var _guid = 1;
  7675. function mergeToJQ(ClassObj, className) {
  7676. $[_prefix + className] = ClassObj;
  7677. $.fn[_prefix + className] = function (opt) {
  7678. var result, args = Array.prototype.slice.call(arguments, 1);
  7679. this.each(function (i, el) {
  7680. var $this = $(el);
  7681. var obj = $this.edui();
  7682. if (!obj) {
  7683. ClassObj(!opt || !$.isPlainObject(opt) ? {} : opt, $this);
  7684. $this.edui(obj)
  7685. }
  7686. if ($.type(opt) == 'string') {
  7687. if (opt == 'this') {
  7688. result = obj;
  7689. } else {
  7690. result = obj[opt].apply(obj, args);
  7691. if (result !== obj && result !== undefined) {
  7692. return false;
  7693. }
  7694. result = null;
  7695. }
  7696. }
  7697. });
  7698. return result !== null ? result : this;
  7699. }
  7700. }
  7701. UM.ui = {
  7702. define: function (className, properties, supperClass) {
  7703. var ClassObj = UM.ui[className] = _createClass(function (options, $el) {
  7704. var _obj = function () {
  7705. };
  7706. $.extend(_obj.prototype, ClassObj.prototype, {
  7707. guid: className + _guid++,
  7708. widgetName: className
  7709. }
  7710. );
  7711. var obj = new _obj;
  7712. if ($.type(options) == 'string') {
  7713. obj.init && obj.init({});
  7714. obj.root().edui(obj);
  7715. obj.root().find('a').click(function (evt) {
  7716. evt.preventDefault()
  7717. });
  7718. return obj.root()[_prefix + className].apply(obj.root(), arguments)
  7719. } else {
  7720. $el && obj.root($el);
  7721. obj.init && obj.init(!options || $.isPlainObject(options) ? $.extend2(options || {}, obj.defaultOpt || {}, true) : options);
  7722. try{
  7723. obj.root().find('a').click(function (evt) {
  7724. evt.preventDefault()
  7725. });
  7726. }catch(e){
  7727. }
  7728. return obj.root().edui(obj);
  7729. }
  7730. },properties, supperClass);
  7731. mergeToJQ(ClassObj, className);
  7732. }
  7733. };
  7734. $(function () {
  7735. $(document).on('click mouseup mousedown dblclick mouseover', function (evt) {
  7736. $.each(_eventHandler, function (i, obj) {
  7737. if (obj.evtname == evt.type) {
  7738. $.each(obj.$els, function (i, $el) {
  7739. if ($el[0] !== evt.target && !$.contains($el[0], evt.target)) {
  7740. obj.handler(evt);
  7741. }
  7742. })
  7743. }
  7744. })
  7745. })
  7746. })
  7747. })(jQuery);
  7748. //button 类
  7749. UM.ui.define('button', {
  7750. 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%>" <%};%>> ' +
  7751. '<% 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><%}%>' +
  7752. '<%if(caret && text){%><span class="edui-button-spacing"></span><%}%>' +
  7753. '<% if(caret) {%><span unselectable="on" onmousedown="return false" class="edui-caret"></span><% };%></<%if(!texttype){%>div<%}else{%>a<%}%>>',
  7754. defaultOpt: {
  7755. text: '',
  7756. title: '',
  7757. icon: '',
  7758. width: '',
  7759. caret: false,
  7760. texttype: false,
  7761. click: function () {
  7762. }
  7763. },
  7764. init: function (options) {
  7765. var me = this;
  7766. me.root($($.parseTmpl(me.tpl, options)))
  7767. .click(function (evt) {
  7768. me.wrapclick(options.click, evt)
  7769. });
  7770. me.root().hover(function () {
  7771. if(!me.root().hasClass("edui-disabled")){
  7772. me.root().toggleClass('edui-hover')
  7773. }
  7774. })
  7775. return me;
  7776. },
  7777. wrapclick: function (fn, evt) {
  7778. if (!this.disabled()) {
  7779. this.root().trigger('wrapclick');
  7780. $.proxy(fn, this, evt)()
  7781. }
  7782. return this;
  7783. },
  7784. label: function (text) {
  7785. if (text === undefined) {
  7786. return this.root().find('.edui-button-label').text();
  7787. } else {
  7788. this.root().find('.edui-button-label').text(text);
  7789. return this;
  7790. }
  7791. },
  7792. disabled: function (state) {
  7793. if (state === undefined) {
  7794. return this.root().hasClass('edui-disabled')
  7795. }
  7796. this.root().toggleClass('edui-disabled', state);
  7797. if(this.root().hasClass('edui-disabled')){
  7798. this.root().removeClass('edui-hover')
  7799. }
  7800. return this;
  7801. },
  7802. active: function (state) {
  7803. if (state === undefined) {
  7804. return this.root().hasClass('edui-active')
  7805. }
  7806. this.root().toggleClass('edui-active', state)
  7807. return this;
  7808. },
  7809. mergeWith: function ($obj) {
  7810. var me = this;
  7811. me.data('$mergeObj', $obj);
  7812. $obj.edui().data('$mergeObj', me.root());
  7813. if (!$.contains(document.body, $obj[0])) {
  7814. $obj.appendTo(me.root());
  7815. }
  7816. me.on('click',function () {
  7817. me.wrapclick(function () {
  7818. $obj.edui().show();
  7819. })
  7820. }).register('click', me.root(), function (evt) {
  7821. $obj.hide()
  7822. });
  7823. }
  7824. });
  7825. //toolbar 类
  7826. (function () {
  7827. UM.ui.define('toolbar', {
  7828. tpl: '<div class="edui-toolbar" ><div class="edui-btn-toolbar" unselectable="on" onmousedown="return false" ></div></div>'
  7829. ,
  7830. init: function () {
  7831. var $root = this.root($(this.tpl));
  7832. this.data('$btnToolbar', $root.find('.edui-btn-toolbar'))
  7833. },
  7834. appendToBtnmenu : function(data){
  7835. var $cont = this.data('$btnToolbar');
  7836. data = $.isArray(data) ? data : [data];
  7837. $.each(data,function(i,$item){
  7838. $cont.append($item)
  7839. })
  7840. }
  7841. });
  7842. })();
  7843. //menu 类
  7844. UM.ui.define('menu',{
  7845. show : function($obj,dir,fnname,topOffset,leftOffset){
  7846. fnname = fnname || 'position';
  7847. if(this.trigger('beforeshow') === false){
  7848. return;
  7849. }else{
  7850. this.root().css($.extend({display:'block'},$obj ? {
  7851. top : $obj[fnname]().top + ( dir == 'right' ? 0 : $obj.outerHeight()) - (topOffset || 0),
  7852. left : $obj[fnname]().left + (dir == 'right' ? $obj.outerWidth() : 0) - (leftOffset || 0)
  7853. }:{}))
  7854. this.trigger('aftershow');
  7855. }
  7856. },
  7857. hide : function(all){
  7858. var $parentmenu;
  7859. if(this.trigger('beforehide') === false){
  7860. return;
  7861. } else {
  7862. if($parentmenu = this.root().data('parentmenu')){
  7863. if($parentmenu.data('parentmenu')|| all)
  7864. $parentmenu.edui().hide();
  7865. }
  7866. this.root().css('display','none');
  7867. this.trigger('afterhide');
  7868. }
  7869. },
  7870. attachTo : function($obj){
  7871. var me = this;
  7872. if(!$obj.data('$mergeObj')){
  7873. $obj.data('$mergeObj',me.root());
  7874. $obj.on('wrapclick',function(evt){
  7875. me.show()
  7876. });
  7877. me.register('click',$obj,function(evt){
  7878. me.hide()
  7879. });
  7880. me.data('$mergeObj',$obj)
  7881. }
  7882. }
  7883. });
  7884. //dropmenu 类
  7885. UM.ui.define('dropmenu', {
  7886. tmpl: '<ul class="edui-dropdown-menu" aria-labelledby="dropdownMenu" >' +
  7887. '<%for(var i=0,ci;ci=data[i++];){%>' +
  7888. '<%if(ci.divider){%><li class="edui-divider"></li><%}else{%>' +
  7889. '<li <%if(ci.active||ci.disabled){%>class="<%= ci.active|| \'\' %> <%=ci.disabled||\'\' %>" <%}%> data-value="<%= ci.value%>">' +
  7890. '<a href="#" tabindex="-1"><em class="edui-dropmenu-checkbox"><i class="edui-icon-ok"></i></em><%= ci.label%></a>' +
  7891. '</li><%}%>' +
  7892. '<%}%>' +
  7893. '</ul>',
  7894. defaultOpt: {
  7895. data: [],
  7896. click: function () {
  7897. }
  7898. },
  7899. init: function (options) {
  7900. var me = this;
  7901. var eventName = {
  7902. click: 1,
  7903. mouseover: 1,
  7904. mouseout: 1
  7905. };
  7906. this.root($($.parseTmpl(this.tmpl, options))).on('click', 'li[class!="edui-disabled edui-divider edui-dropdown-submenu"]',function (evt) {
  7907. $.proxy(options.click, me, evt, $(this).data('value'), $(this))()
  7908. }).find('li').each(function (i, el) {
  7909. var $this = $(this);
  7910. if (!$this.hasClass("edui-disabled edui-divider edui-dropdown-submenu")) {
  7911. var data = options.data[i];
  7912. $.each(eventName, function (k) {
  7913. data[k] && $this[k](function (evt) {
  7914. $.proxy(data[k], el)(evt, data, me.root)
  7915. })
  7916. })
  7917. }
  7918. })
  7919. },
  7920. disabled: function (cb) {
  7921. $('li[class!=edui-divider]', this.root()).each(function () {
  7922. var $el = $(this);
  7923. if (cb === true) {
  7924. $el.addClass('edui-disabled')
  7925. } else if ($.isFunction(cb)) {
  7926. $el.toggleClass('edui-disabled', cb(li))
  7927. } else {
  7928. $el.removeClass('edui-disabled')
  7929. }
  7930. });
  7931. },
  7932. val: function (val) {
  7933. var currentVal;
  7934. $('li[class!="edui-divider edui-disabled edui-dropdown-submenu"]', this.root()).each(function () {
  7935. var $el = $(this);
  7936. if (val === undefined) {
  7937. if ($el.find('em.edui-dropmenu-checked').length) {
  7938. currentVal = $el.data('value');
  7939. return false
  7940. }
  7941. } else {
  7942. $el.find('em').toggleClass('edui-dropmenu-checked', $el.data('value') == val)
  7943. }
  7944. });
  7945. if (val === undefined) {
  7946. return currentVal
  7947. }
  7948. },
  7949. addSubmenu: function (label, menu, index) {
  7950. index = index || 0;
  7951. var $list = $('li[class!=edui-divider]', this.root());
  7952. var $node = $('<li class="edui-dropdown-submenu"><a tabindex="-1" href="#">' + label + '</a></li>').append(menu);
  7953. if (index >= 0 && index < $list.length) {
  7954. $node.insertBefore($list[index]);
  7955. } else if (index < 0) {
  7956. $node.insertBefore($list[0]);
  7957. } else if (index >= $list.length) {
  7958. $node.appendTo($list);
  7959. }
  7960. }
  7961. }, 'menu');
  7962. //splitbutton 类
  7963. ///import button
  7964. UM.ui.define('splitbutton',{
  7965. 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>'+
  7966. '<div unselectable="on" class="edui-btn edui-dropdown-toggle" >'+
  7967. '<div unselectable="on" class="edui-caret"><\/div>'+
  7968. '</div>'+
  7969. '</div>',
  7970. defaultOpt:{
  7971. text:'',
  7972. title:'',
  7973. click:function(){}
  7974. },
  7975. init : function(options){
  7976. var me = this;
  7977. me.root( $($.parseTmpl(me.tpl,options)));
  7978. me.root().find('.edui-btn:first').click(function(evt){
  7979. if(!me.disabled()){
  7980. $.proxy(options.click,me)();
  7981. }
  7982. });
  7983. me.root().find('.edui-dropdown-toggle').click(function(){
  7984. if(!me.disabled()){
  7985. me.trigger('arrowclick')
  7986. }
  7987. });
  7988. me.root().hover(function () {
  7989. if(!me.root().hasClass("edui-disabled")){
  7990. me.root().toggleClass('edui-hover')
  7991. }
  7992. });
  7993. return me;
  7994. },
  7995. wrapclick:function(fn,evt){
  7996. if(!this.disabled()){
  7997. $.proxy(fn,this,evt)()
  7998. }
  7999. return this;
  8000. },
  8001. disabled : function(state){
  8002. if(state === undefined){
  8003. return this.root().hasClass('edui-disabled')
  8004. }
  8005. this.root().toggleClass('edui-disabled',state).find('.edui-btn').toggleClass('edui-disabled',state);
  8006. return this;
  8007. },
  8008. active:function(state){
  8009. if(state === undefined){
  8010. return this.root().hasClass('edui-active')
  8011. }
  8012. this.root().toggleClass('edui-active',state).find('.edui-btn:first').toggleClass('edui-active',state);
  8013. return this;
  8014. },
  8015. mergeWith:function($obj){
  8016. var me = this;
  8017. me.data('$mergeObj',$obj);
  8018. $obj.edui().data('$mergeObj',me.root());
  8019. if(!$.contains(document.body,$obj[0])){
  8020. $obj.appendTo(me.root());
  8021. }
  8022. me.root().delegate('.edui-dropdown-toggle','click',function(){
  8023. me.wrapclick(function(){
  8024. $obj.edui().show();
  8025. })
  8026. });
  8027. me.register('click',me.root().find('.edui-dropdown-toggle'),function(evt){
  8028. $obj.hide()
  8029. });
  8030. }
  8031. });
  8032. /**
  8033. * Created with JetBrains PhpStorm.
  8034. * User: hn
  8035. * Date: 13-7-10
  8036. * Time: 下午3:07
  8037. * To change this template use File | Settings | File Templates.
  8038. */
  8039. UM.ui.define('colorsplitbutton',{
  8040. 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>'+
  8041. '<div unselectable="on" class="edui-btn edui-dropdown-toggle" >'+
  8042. '<div unselectable="on" class="edui-caret"><\/div>'+
  8043. '</div>'+
  8044. '</div>',
  8045. defaultOpt: {
  8046. color: ''
  8047. },
  8048. init: function( options ){
  8049. var me = this;
  8050. me.supper.init.call( me, options );
  8051. },
  8052. colorLabel: function(){
  8053. return this.root().find('.edui-splitbutton-color-label');
  8054. }
  8055. }, 'splitbutton');
  8056. //popup 类
  8057. UM.ui.define('popup', {
  8058. tpl: '<div class="edui-dropdown-menu edui-popup"'+
  8059. '<%if(!<%=stopprop%>){%>onmousedown="return false"<%}%>'+
  8060. '><div class="edui-popup-body" unselectable="on" onmousedown="return false"><%=subtpl%></div>' +
  8061. '<div class="edui-popup-caret"></div>' +
  8062. '</div>',
  8063. defaultOpt: {
  8064. stopprop:false,
  8065. subtpl: '',
  8066. width: '',
  8067. height: ''
  8068. },
  8069. init: function (options) {
  8070. this.root($($.parseTmpl(this.tpl, options)));
  8071. return this;
  8072. },
  8073. mergeTpl: function (data) {
  8074. return $.parseTmpl(this.tpl, {subtpl: data});
  8075. },
  8076. show: function ($obj, posObj) {
  8077. if (!posObj) posObj = {};
  8078. var fnname = posObj.fnname || 'position';
  8079. if (this.trigger('beforeshow') === false) {
  8080. return;
  8081. } else {
  8082. this.root().css($.extend({display: 'block'}, $obj ? {
  8083. top: $obj[fnname]().top + ( posObj.dir == 'right' ? 0 : $obj.outerHeight()) - (posObj.offsetTop || 0),
  8084. left: $obj[fnname]().left + (posObj.dir == 'right' ? $obj.outerWidth() : 0) - (posObj.offsetLeft || 0),
  8085. position: 'absolute'
  8086. } : {}));
  8087. this.root().find('.edui-popup-caret').css({
  8088. top: posObj.caretTop || 0,
  8089. left: posObj.caretLeft || 0,
  8090. position: 'absolute'
  8091. }).addClass(posObj.caretDir || "up")
  8092. }
  8093. this.trigger("aftershow");
  8094. },
  8095. hide: function () {
  8096. this.root().css('display', 'none');
  8097. this.trigger('afterhide')
  8098. },
  8099. attachTo: function ($obj, posObj) {
  8100. var me = this
  8101. if (!$obj.data('$mergeObj')) {
  8102. $obj.data('$mergeObj', me.root());
  8103. $obj.on('wrapclick', function (evt) {
  8104. me.show($obj, posObj)
  8105. });
  8106. me.register('click', $obj, function (evt) {
  8107. me.hide()
  8108. });
  8109. me.data('$mergeObj', $obj)
  8110. }
  8111. },
  8112. getBodyContainer: function () {
  8113. return this.root().find(".edui-popup-body");
  8114. }
  8115. });
  8116. //scale 类
  8117. UM.ui.define('scale', {
  8118. tpl: '<div class="edui-scale" unselectable="on">' +
  8119. '<span class="edui-scale-hand0"></span>' +
  8120. '<span class="edui-scale-hand1"></span>' +
  8121. '<span class="edui-scale-hand2"></span>' +
  8122. '<span class="edui-scale-hand3"></span>' +
  8123. '<span class="edui-scale-hand4"></span>' +
  8124. '<span class="edui-scale-hand5"></span>' +
  8125. '<span class="edui-scale-hand6"></span>' +
  8126. '<span class="edui-scale-hand7"></span>' +
  8127. '</div>',
  8128. defaultOpt: {
  8129. $doc: $(document),
  8130. $wrap: $(document)
  8131. },
  8132. init: function (options) {
  8133. if(options.$doc) this.defaultOpt.$doc = options.$doc;
  8134. if(options.$wrap) this.defaultOpt.$wrap = options.$wrap;
  8135. this.root($($.parseTmpl(this.tpl, options)));
  8136. this.initStyle();
  8137. this.startPos = this.prePos = {x: 0, y: 0};
  8138. this.dragId = -1;
  8139. return this;
  8140. },
  8141. initStyle: function () {
  8142. utils.cssRule('edui-style-scale', '.edui-scale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;}' +
  8143. '.edui-scale span{position:absolute;left:0;top:0;width:7px;height:7px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  8144. + '.edui-scale .edui-scale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  8145. + '.edui-scale .edui-scale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  8146. + '.edui-scale .edui-scale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  8147. + '.edui-scale .edui-scale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  8148. + '.edui-scale .edui-scale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  8149. + '.edui-scale .edui-scale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  8150. + '.edui-scale .edui-scale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  8151. + '.edui-scale .edui-scale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  8152. },
  8153. _eventHandler: function (e) {
  8154. var me = this,
  8155. $doc = me.defaultOpt.$doc;
  8156. switch (e.type) {
  8157. case 'mousedown':
  8158. var hand = e.target || e.srcElement, hand;
  8159. if (hand.className.indexOf('edui-scale-hand') != -1) {
  8160. me.dragId = hand.className.slice(-1);
  8161. me.startPos.x = me.prePos.x = e.clientX;
  8162. me.startPos.y = me.prePos.y = e.clientY;
  8163. $doc.bind('mousemove', $.proxy(me._eventHandler, me));
  8164. }
  8165. break;
  8166. case 'mousemove':
  8167. if (me.dragId != -1) {
  8168. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  8169. me.prePos.x = e.clientX;
  8170. me.prePos.y = e.clientY;
  8171. me.updateTargetElement();
  8172. }
  8173. break;
  8174. case 'mouseup':
  8175. if (me.dragId != -1) {
  8176. me.dragId = -1;
  8177. me.updateTargetElement();
  8178. var $target = me.data('$scaleTarget');
  8179. if ($target.parent()) me.attachTo(me.data('$scaleTarget'));
  8180. }
  8181. $doc.unbind('mousemove', $.proxy(me._eventHandler, me));
  8182. break;
  8183. default:
  8184. break;
  8185. }
  8186. },
  8187. updateTargetElement: function () {
  8188. var me = this,
  8189. $root = me.root(),
  8190. $target = me.data('$scaleTarget');
  8191. $target.css({width: $root.width(), height: $root.height()});
  8192. me.attachTo($target);
  8193. },
  8194. updateContainerStyle: function (dir, offset) {
  8195. var me = this,
  8196. $dom = me.root(),
  8197. tmp,
  8198. rect = [
  8199. //[left, top, width, height]
  8200. [0, 0, -1, -1],
  8201. [0, 0, 0, -1],
  8202. [0, 0, 1, -1],
  8203. [0, 0, -1, 0],
  8204. [0, 0, 1, 0],
  8205. [0, 0, -1, 1],
  8206. [0, 0, 0, 1],
  8207. [0, 0, 1, 1]
  8208. ];
  8209. if (rect[dir][0] != 0) {
  8210. tmp = parseInt($dom.offset().left) + offset.x;
  8211. $dom.css('left', me._validScaledProp('left', tmp));
  8212. }
  8213. if (rect[dir][1] != 0) {
  8214. tmp = parseInt($dom.offset().top) + offset.y;
  8215. $dom.css('top', me._validScaledProp('top', tmp));
  8216. }
  8217. if (rect[dir][2] != 0) {
  8218. tmp = $dom.width() + rect[dir][2] * offset.x;
  8219. $dom.css('width', me._validScaledProp('width', tmp));
  8220. }
  8221. if (rect[dir][3] != 0) {
  8222. tmp = $dom.height() + rect[dir][3] * offset.y;
  8223. $dom.css('height', me._validScaledProp('height', tmp));
  8224. }
  8225. },
  8226. _validScaledProp: function (prop, value) {
  8227. var $ele = this.root(),
  8228. $wrap = this.defaultOpt.$doc,
  8229. calc = function(val, a, b){
  8230. return (val + a) > b ? b - a : value;
  8231. };
  8232. value = isNaN(value) ? 0 : value;
  8233. switch (prop) {
  8234. case 'left':
  8235. return value < 0 ? 0 : calc(value, $ele.width(), $wrap.width());
  8236. case 'top':
  8237. return value < 0 ? 0 : calc(value, $ele.height(),$wrap.height());
  8238. case 'width':
  8239. return value <= 0 ? 1 : calc(value, $ele.offset().left, $wrap.width());
  8240. case 'height':
  8241. return value <= 0 ? 1 : calc(value, $ele.offset().top, $wrap.height());
  8242. }
  8243. },
  8244. show: function ($obj) {
  8245. var me = this;
  8246. if ($obj) me.attachTo($obj);
  8247. me.root().bind('mousedown', $.proxy(me._eventHandler, me));
  8248. me.defaultOpt.$doc.bind('mouseup', $.proxy(me._eventHandler, me));
  8249. me.root().show();
  8250. me.trigger("aftershow");
  8251. },
  8252. hide: function () {
  8253. var me = this;
  8254. me.root().unbind('mousedown', $.proxy(me._eventHandler, me));
  8255. me.defaultOpt.$doc.unbind('mouseup', $.proxy(me._eventHandler, me));
  8256. me.root().hide();
  8257. me.trigger('afterhide')
  8258. },
  8259. attachTo: function ($obj) {
  8260. var me = this,
  8261. imgPos = $obj.offset(),
  8262. $root = me.root(),
  8263. $wrap = me.defaultOpt.$wrap,
  8264. posObj = $wrap.offset();
  8265. me.data('$scaleTarget', $obj);
  8266. me.root().css({
  8267. position: 'absolute',
  8268. width: $obj.width(),
  8269. height: $obj.height(),
  8270. left: imgPos.left - posObj.left - parseInt($wrap.css('border-left-width')) - parseInt($root.css('border-left-width')),
  8271. top: imgPos.top - posObj.top - parseInt($wrap.css('border-top-width')) - parseInt($root.css('border-top-width'))
  8272. });
  8273. },
  8274. getScaleTarget: function () {
  8275. return this.data('$scaleTarget')[0];
  8276. }
  8277. });
  8278. //colorpicker 类
  8279. UM.ui.define('colorpicker', {
  8280. tpl: function (opt) {
  8281. var COLORS = (
  8282. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  8283. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  8284. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  8285. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  8286. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  8287. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  8288. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  8289. var html = '<div unselectable="on" onmousedown="return false" class="edui-colorpicker<%if (name){%> edui-colorpicker-<%=name%><%}%>" >' +
  8290. '<table unselectable="on" onmousedown="return false">' +
  8291. '<tr><td colspan="10">'+opt.lang_themeColor+'</td> </tr>' +
  8292. '<tr class="edui-colorpicker-firstrow" >';
  8293. for (var i = 0; i < COLORS.length; i++) {
  8294. if (i && i % 10 === 0) {
  8295. html += '</tr>' + (i == 60 ? '<tr><td colspan="10">'+opt.lang_standardColor+'</td></tr>' : '') + '<tr' + (i == 60 ? ' class="edui-colorpicker-firstrow"' : '') + '>';
  8296. }
  8297. html += i < 70 ? '<td><a unselectable="on" onmousedown="return false" title="' + COLORS[i] + '" class="edui-colorpicker-colorcell"' +
  8298. ' data-color="#' + COLORS[i] + '"' +
  8299. ' style="background-color:#' + COLORS[i] + ';border:solid #ccc;' +
  8300. (i < 10 || i >= 60 ? 'border-width:1px;' :
  8301. i >= 10 && i < 20 ? 'border-width:1px 1px 0 1px;' :
  8302. 'border-width:0 1px 0 1px;') +
  8303. '"' +
  8304. '></a></td>' : '';
  8305. }
  8306. html += '</tr></table></div>';
  8307. return html;
  8308. },
  8309. init: function (options) {
  8310. var me = this;
  8311. me.root($($.parseTmpl(me.supper.mergeTpl(me.tpl(options)),options)));
  8312. me.root().on("click",function (e) {
  8313. me.trigger('pickcolor', $(e.target).data('color'));
  8314. });
  8315. }
  8316. }, 'popup');
  8317. /**
  8318. * Created with JetBrains PhpStorm.
  8319. * User: hn
  8320. * Date: 13-5-29
  8321. * Time: 下午8:01
  8322. * To change this template use File | Settings | File Templates.
  8323. */
  8324. (function(){
  8325. var widgetName = 'combobox',
  8326. itemClassName = 'edui-combobox-item',
  8327. HOVER_CLASS = 'edui-combobox-item-hover',
  8328. ICON_CLASS = 'edui-combobox-checked-icon',
  8329. labelClassName = 'edui-combobox-item-label';
  8330. UM.ui.define( widgetName, ( function(){
  8331. return {
  8332. tpl: "<ul class=\"dropdown-menu edui-combobox-menu<%if (comboboxName!=='') {%> edui-combobox-<%=comboboxName%><%}%>\" unselectable=\"on\" onmousedown=\"return false\" role=\"menu\" aria-labelledby=\"dropdownMenu\">" +
  8333. "<%if(autoRecord) {%>" +
  8334. "<%for( var i=0, len = recordStack.length; i<len; i++ ) {%>" +
  8335. "<%var index = recordStack[i];%>" +
  8336. "<li class=\"<%=itemClassName%><%if( selected == index ) {%> edui-combobox-checked<%}%>\" data-item-index=\"<%=index%>\" unselectable=\"on\" onmousedown=\"return false\">" +
  8337. "<span class=\"edui-combobox-icon\" unselectable=\"on\" onmousedown=\"return false\"></span>" +
  8338. "<label class=\"<%=labelClassName%>\" style=\"<%=itemStyles[ index ]%>\" unselectable=\"on\" onmousedown=\"return false\"><%=items[index]%></label>" +
  8339. "</li>" +
  8340. "<%}%>" +
  8341. "<%if( i ) {%>" +
  8342. "<li class=\"edui-combobox-item-separator\"></li>" +
  8343. "<%}%>" +
  8344. "<%}%>" +
  8345. "<%for( var i=0, label; label = items[i]; i++ ) {%>" +
  8346. "<li class=\"<%=itemClassName%><%if( selected == i ) {%> edui-combobox-checked<%}%> edui-combobox-item-<%=i%>\" data-item-index=\"<%=i%>\" unselectable=\"on\" onmousedown=\"return false\">" +
  8347. "<span class=\"edui-combobox-icon\" unselectable=\"on\" onmousedown=\"return false\"></span>" +
  8348. "<label class=\"<%=labelClassName%>\" style=\"<%=itemStyles[ i ]%>\" unselectable=\"on\" onmousedown=\"return false\"><%=label%></label>" +
  8349. "</li>" +
  8350. "<%}%>" +
  8351. "</ul>",
  8352. defaultOpt: {
  8353. //记录栈初始列表
  8354. recordStack: [],
  8355. //可用项列表
  8356. items: [],
  8357. //item对应的值列表
  8358. value: [],
  8359. comboboxName: '',
  8360. selected: '',
  8361. //自动记录
  8362. autoRecord: true,
  8363. //最多记录条数
  8364. recordCount: 5
  8365. },
  8366. init: function( options ){
  8367. var me = this;
  8368. $.extend( me._optionAdaptation( options ), me._createItemMapping( options.recordStack, options.items ), {
  8369. itemClassName: itemClassName,
  8370. iconClass: ICON_CLASS,
  8371. labelClassName: labelClassName
  8372. } );
  8373. this._transStack( options );
  8374. me.root( $( $.parseTmpl( me.tpl, options ) ) );
  8375. this.data( 'options', options ).initEvent();
  8376. },
  8377. initEvent: function(){
  8378. var me = this;
  8379. me.initSelectItem();
  8380. this.initItemActive();
  8381. },
  8382. /**
  8383. * 初始化选择项
  8384. */
  8385. initSelectItem: function(){
  8386. var me = this,
  8387. labelClass = "."+labelClassName;
  8388. me.root().delegate('.' + itemClassName, 'click', function(){
  8389. var $li = $(this),
  8390. index = $li.attr('data-item-index');
  8391. me.trigger('comboboxselect', {
  8392. index: index,
  8393. label: $li.find(labelClass).text(),
  8394. value: me.data('options').value[ index ]
  8395. }).select( index );
  8396. me.hide();
  8397. return false;
  8398. });
  8399. },
  8400. initItemActive: function(){
  8401. var fn = {
  8402. mouseenter: 'addClass',
  8403. mouseleave: 'removeClass'
  8404. };
  8405. if ($.IE6) {
  8406. this.root().delegate( '.'+itemClassName, 'mouseenter mouseleave', function( evt ){
  8407. $(this)[ fn[ evt.type ] ]( HOVER_CLASS );
  8408. }).one('afterhide', function(){
  8409. });
  8410. }
  8411. },
  8412. /**
  8413. * 选择给定索引的项
  8414. * @param index 项索引
  8415. * @returns {*} 如果存在对应索引的项,则返回该项;否则返回null
  8416. */
  8417. select: function( index ){
  8418. var itemCount = this.data('options').itemCount,
  8419. items = this.data('options').autowidthitem;
  8420. if ( items && !items.length ) {
  8421. items = this.data('options').items;
  8422. }
  8423. if( itemCount == 0 ) {
  8424. return null;
  8425. }
  8426. if( index < 0 ) {
  8427. index = itemCount + index % itemCount;
  8428. } else if ( index >= itemCount ) {
  8429. index = itemCount-1;
  8430. }
  8431. this.trigger( 'changebefore', items[ index ] );
  8432. this._update( index );
  8433. this.trigger( 'changeafter', items[ index ] );
  8434. return null;
  8435. },
  8436. selectItemByLabel: function( label ){
  8437. var itemMapping = this.data('options').itemMapping,
  8438. me = this,
  8439. index = null;
  8440. !$.isArray( label ) && ( label = [ label ] );
  8441. $.each( label, function( i, item ){
  8442. index = itemMapping[ item ];
  8443. if( index !== undefined ) {
  8444. me.select( index );
  8445. return false;
  8446. }
  8447. } );
  8448. },
  8449. /**
  8450. * 转换记录栈
  8451. */
  8452. _transStack: function( options ) {
  8453. var temp = [],
  8454. itemIndex = -1,
  8455. selected = -1;
  8456. $.each( options.recordStack, function( index, item ){
  8457. itemIndex = options.itemMapping[ item ];
  8458. if( $.isNumeric( itemIndex ) ) {
  8459. temp.push( itemIndex );
  8460. //selected的合法性检测
  8461. if( item == options.selected ) {
  8462. selected = itemIndex;
  8463. }
  8464. }
  8465. } );
  8466. options.recordStack = temp;
  8467. options.selected = selected;
  8468. temp = null;
  8469. },
  8470. _optionAdaptation: function( options ) {
  8471. if( !( 'itemStyles' in options ) ) {
  8472. options.itemStyles = [];
  8473. for( var i = 0, len = options.items.length; i < len; i++ ) {
  8474. options.itemStyles.push('');
  8475. }
  8476. }
  8477. options.autowidthitem = options.autowidthitem || options.items;
  8478. options.itemCount = options.items.length;
  8479. return options;
  8480. },
  8481. _createItemMapping: function( stackItem, items ){
  8482. var temp = {},
  8483. result = {
  8484. recordStack: [],
  8485. mapping: {}
  8486. };
  8487. $.each( items, function( index, item ){
  8488. temp[ item ] = index;
  8489. } );
  8490. result.itemMapping = temp;
  8491. $.each( stackItem, function( index, item ){
  8492. if( temp[ item ] !== undefined ) {
  8493. result.recordStack.push( temp[ item ] );
  8494. result.mapping[ item ] = temp[ item ];
  8495. }
  8496. } );
  8497. return result;
  8498. },
  8499. _update: function ( index ) {
  8500. var options = this.data("options"),
  8501. newStack = [],
  8502. newChilds = null;
  8503. $.each( options.recordStack, function( i, item ){
  8504. if( item != index ) {
  8505. newStack.push( item );
  8506. }
  8507. } );
  8508. //压入最新的记录
  8509. newStack.unshift( index );
  8510. if( newStack.length > options.recordCount ) {
  8511. newStack.length = options.recordCount;
  8512. }
  8513. options.recordStack = newStack;
  8514. options.selected = index;
  8515. newChilds = $( $.parseTmpl( this.tpl, options ) );
  8516. //重新渲染
  8517. this.root().html( newChilds.html() );
  8518. newChilds = null;
  8519. newStack = null;
  8520. }
  8521. };
  8522. } )(), 'menu' );
  8523. })();
  8524. /**
  8525. * Combox 抽象基类
  8526. * User: hn
  8527. * Date: 13-5-29
  8528. * Time: 下午8:01
  8529. * To change this template use File | Settings | File Templates.
  8530. */
  8531. (function(){
  8532. var widgetName = 'buttoncombobox';
  8533. UM.ui.define( widgetName, ( function(){
  8534. return {
  8535. defaultOpt: {
  8536. //按钮初始文字
  8537. label: '',
  8538. title: ''
  8539. },
  8540. init: function( options ) {
  8541. var me = this;
  8542. var btnWidget = $.eduibutton({
  8543. caret: true,
  8544. name: options.comboboxName,
  8545. title: options.title,
  8546. text: options.label,
  8547. click: function(){
  8548. me.show( this.root() );
  8549. }
  8550. });
  8551. me.supper.init.call( me, options );
  8552. //监听change, 改变button显示内容
  8553. me.on('changebefore', function( e, label ){
  8554. btnWidget.eduibutton('label', label );
  8555. });
  8556. me.data( 'button', btnWidget );
  8557. me.attachTo(btnWidget)
  8558. },
  8559. button: function(){
  8560. return this.data( 'button' );
  8561. }
  8562. }
  8563. } )(), 'combobox' );
  8564. })();
  8565. /*modal 类*/
  8566. UM.ui.define('modal', {
  8567. tpl: '<div class="edui-modal" tabindex="-1" >' +
  8568. '<div class="edui-modal-header">' +
  8569. '<div class="edui-close" data-hide="modal"></div>' +
  8570. '<h3 class="edui-title"><%=title%></h3>' +
  8571. '</div>' +
  8572. '<div class="edui-modal-body" style="<%if(width){%>width:<%=width%>px;<%}%>' +
  8573. '<%if(height){%>height:<%=height%>px;<%}%>">' +
  8574. ' </div>' +
  8575. '<% if(cancellabel || oklabel) {%>' +
  8576. '<div class="edui-modal-footer">' +
  8577. '<div class="edui-modal-tip"></div>' +
  8578. '<%if(oklabel){%><div class="edui-btn edui-btn-primary" data-ok="modal"><%=oklabel%></div><%}%>' +
  8579. '<%if(cancellabel){%><div class="edui-btn" data-hide="modal"><%=cancellabel%></div><%}%>' +
  8580. '</div>' +
  8581. '<%}%></div>',
  8582. defaultOpt: {
  8583. title: "",
  8584. cancellabel: "",
  8585. oklabel: "",
  8586. width: '',
  8587. height: '',
  8588. backdrop: true,
  8589. keyboard: true
  8590. },
  8591. init: function (options) {
  8592. var me = this;
  8593. me.root($($.parseTmpl(me.tpl, options || {})));
  8594. me.data("options", options);
  8595. if (options.okFn) {
  8596. me.on('ok', $.proxy(options.okFn, me))
  8597. }
  8598. if (options.cancelFn) {
  8599. me.on('beforehide', $.proxy(options.cancelFn, me))
  8600. }
  8601. me.root().delegate('[data-hide="modal"]', 'click', $.proxy(me.hide, me))
  8602. .delegate('[data-ok="modal"]', 'click', $.proxy(me.ok, me));
  8603. $('[data-hide="modal"],[data-ok="modal"]',me.root()).hover(function(){
  8604. $(this).toggleClass('edui-hover')
  8605. });
  8606. },
  8607. toggle: function () {
  8608. var me = this;
  8609. return me[!me.data("isShown") ? 'show' : 'hide']();
  8610. },
  8611. show: function () {
  8612. var me = this;
  8613. me.trigger("beforeshow");
  8614. if (me.data("isShown")) return;
  8615. me.data("isShown", true);
  8616. me.escape();
  8617. me.backdrop(function () {
  8618. me.autoCenter();
  8619. me.root()
  8620. .show()
  8621. .focus()
  8622. .trigger('aftershow');
  8623. })
  8624. },
  8625. showTip: function ( text ) {
  8626. $( '.edui-modal-tip', this.root() ).html( text ).fadeIn();
  8627. },
  8628. hideTip: function ( text ) {
  8629. $( '.edui-modal-tip', this.root() ).fadeOut( function (){
  8630. $(this).html('');
  8631. } );
  8632. },
  8633. autoCenter: function () {
  8634. //ie6下不用处理了
  8635. !$.IE6 && this.root().css("margin-left", -(this.root().width() / 2));
  8636. },
  8637. hide: function () {
  8638. var me = this;
  8639. me.trigger("beforehide");
  8640. if (!me.data("isShown")) return;
  8641. me.data("isShown", false);
  8642. me.escape();
  8643. me.hideModal();
  8644. },
  8645. escape: function () {
  8646. var me = this;
  8647. if (me.data("isShown") && me.data("options").keyboard) {
  8648. me.root().on('keyup', function (e) {
  8649. e.which == 27 && me.hide();
  8650. })
  8651. }
  8652. else if (!me.data("isShown")) {
  8653. me.root().off('keyup');
  8654. }
  8655. },
  8656. hideModal: function () {
  8657. var me = this;
  8658. me.root().hide();
  8659. me.backdrop(function () {
  8660. me.removeBackdrop();
  8661. me.trigger('afterhide');
  8662. })
  8663. },
  8664. removeBackdrop: function () {
  8665. this.$backdrop && this.$backdrop.remove();
  8666. this.$backdrop = null;
  8667. },
  8668. backdrop: function (callback) {
  8669. var me = this;
  8670. if (me.data("isShown") && me.data("options").backdrop) {
  8671. me.$backdrop = $('<div class="edui-modal-backdrop" />').click(
  8672. me.data("options").backdrop == 'static' ?
  8673. $.proxy(me.root()[0].focus, me.root()[0])
  8674. : $.proxy(me.hide, me)
  8675. )
  8676. }
  8677. me.trigger('afterbackdrop');
  8678. callback && callback();
  8679. },
  8680. attachTo: function ($obj) {
  8681. var me = this
  8682. if (!$obj.data('$mergeObj')) {
  8683. $obj.data('$mergeObj', me.root());
  8684. $obj.on('click', function () {
  8685. me.toggle($obj)
  8686. });
  8687. me.data('$mergeObj', $obj)
  8688. }
  8689. },
  8690. ok: function () {
  8691. var me = this;
  8692. me.trigger('beforeok');
  8693. if (me.trigger("ok", me) === false) {
  8694. return;
  8695. }
  8696. me.hide();
  8697. },
  8698. getBodyContainer: function () {
  8699. return this.root().find('.edui-modal-body')
  8700. }
  8701. });
  8702. /*tooltip 类*/
  8703. UM.ui.define('tooltip', {
  8704. tpl: '<div class="edui-tooltip" unselectable="on" onmousedown="return false">' +
  8705. '<div class="edui-tooltip-arrow" unselectable="on" onmousedown="return false"></div>' +
  8706. '<div class="edui-tooltip-inner" unselectable="on" onmousedown="return false"></div>' +
  8707. '</div>',
  8708. init: function (options) {
  8709. var me = this;
  8710. me.root($($.parseTmpl(me.tpl, options || {})));
  8711. },
  8712. content: function (e) {
  8713. var me = this,
  8714. title = $(e.currentTarget).attr("data-original-title");
  8715. me.root().find('.edui-tooltip-inner')['text'](title);
  8716. },
  8717. position: function (e) {
  8718. var me = this,
  8719. $obj = $(e.currentTarget);
  8720. me.root().css($.extend({display: 'block'}, $obj ? {
  8721. top: $obj.outerHeight(),
  8722. left: (($obj.outerWidth() - me.root().outerWidth()) / 2)
  8723. } : {}))
  8724. },
  8725. show: function (e) {
  8726. if ($(e.currentTarget).hasClass('edui-disabled')) return;
  8727. var me = this;
  8728. me.content(e);
  8729. me.root().appendTo($(e.currentTarget));
  8730. me.position(e);
  8731. me.root().css('display', 'block');
  8732. },
  8733. hide: function () {
  8734. var me = this;
  8735. me.root().css('display', 'none')
  8736. },
  8737. attachTo: function ($obj) {
  8738. var me = this;
  8739. function tmp($obj) {
  8740. var me = this;
  8741. if (!$.contains(document.body, me.root()[0])) {
  8742. me.root().appendTo($obj);
  8743. }
  8744. me.data('tooltip', me.root());
  8745. $obj.each(function () {
  8746. if ($(this).attr("data-original-title")) {
  8747. $(this).on('mouseenter', $.proxy(me.show, me))
  8748. .on('mouseleave click', $.proxy(me.hide, me))
  8749. }
  8750. });
  8751. }
  8752. if ($.type($obj) === "undefined") {
  8753. $("[data-original-title]").each(function (i, el) {
  8754. tmp.call(me, $(el));
  8755. })
  8756. } else {
  8757. if (!$obj.data('tooltip')) {
  8758. tmp.call(me, $obj);
  8759. }
  8760. }
  8761. }
  8762. });
  8763. /*tab 类*/
  8764. UM.ui.define('tab', {
  8765. init: function (options) {
  8766. var me = this,
  8767. slr = options.selector;
  8768. if ($.type(slr)) {
  8769. me.root($(slr, options.context));
  8770. me.data("context", options.context);
  8771. $(slr, me.data("context")).on('click', function (e) {
  8772. me.show(e);
  8773. });
  8774. }
  8775. },
  8776. show: function (e) {
  8777. var me = this,
  8778. $cur = $(e.target),
  8779. $ul = $cur.closest('ul'),
  8780. selector,
  8781. previous,
  8782. $target,
  8783. e;
  8784. selector = $cur.attr('data-context');
  8785. selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '');
  8786. var $tmp = $cur.parent('li');
  8787. if (!$tmp.length || $tmp.hasClass('edui-active')) return;
  8788. previous = $ul.find('.edui-active:last a')[0];
  8789. e = $.Event('beforeshow', {
  8790. target: $cur[0],
  8791. relatedTarget: previous
  8792. });
  8793. me.trigger(e);
  8794. if (e.isDefaultPrevented()) return;
  8795. $target = $(selector, me.data("context"));
  8796. me.activate($cur.parent('li'), $ul);
  8797. me.activate($target, $target.parent(), function () {
  8798. me.trigger({
  8799. type: 'aftershow', relatedTarget: previous
  8800. })
  8801. });
  8802. },
  8803. activate: function (element, container, callback) {
  8804. if (element === undefined) {
  8805. return $(".edui-tab-item.edui-active",this.root()).index();
  8806. }
  8807. var $active = container.find('> .edui-active');
  8808. $active.removeClass('edui-active');
  8809. element.addClass('edui-active');
  8810. callback && callback();
  8811. }
  8812. });
  8813. //button 类
  8814. UM.ui.define('separator', {
  8815. tpl: '<div class="edui-separator" unselectable="on" onmousedown="return false" ></div>',
  8816. init: function (options) {
  8817. var me = this;
  8818. me.root($($.parseTmpl(me.tpl, options)));
  8819. return me;
  8820. }
  8821. });
  8822. /**
  8823. * @file adapter.js
  8824. * @desc adapt ui to editor
  8825. * @import core/Editor.js, core/utils.js
  8826. */
  8827. (function () {
  8828. var _editorUI = {},
  8829. _editors = {},
  8830. _readyFn = [],
  8831. _activeWidget = null,
  8832. _widgetData = {},
  8833. _widgetCallBack = {},
  8834. _cacheUI = {},
  8835. _maxZIndex = null;
  8836. utils.extend(UM, {
  8837. defaultWidth : 500,
  8838. defaultHeight : 500,
  8839. registerUI: function (name, fn) {
  8840. utils.each(name.split(/\s+/), function (uiname) {
  8841. _editorUI[uiname] = fn;
  8842. })
  8843. },
  8844. setEditor : function(editor){
  8845. !_editors[editor.id] && (_editors[editor.id] = editor);
  8846. },
  8847. registerWidget : function(name,pro,cb){
  8848. _widgetData[name] = $.extend2(pro,{
  8849. $root : '',
  8850. _preventDefault:false,
  8851. root:function($el){
  8852. return this.$root || (this.$root = $el);
  8853. },
  8854. preventDefault:function(){
  8855. this._preventDefault = true;
  8856. },
  8857. clear:false
  8858. });
  8859. if(cb){
  8860. _widgetCallBack[name] = cb;
  8861. }
  8862. },
  8863. getWidgetData : function(name){
  8864. return _widgetData[name]
  8865. },
  8866. setWidgetBody : function(name,$widget,editor){
  8867. if(!editor._widgetData){
  8868. utils.extend(editor,{
  8869. _widgetData : {},
  8870. getWidgetData : function(name){
  8871. return this._widgetData[name];
  8872. },
  8873. getWidgetCallback : function(widgetName){
  8874. var me = this;
  8875. return function(){
  8876. return _widgetCallBack[widgetName].apply(me,[me,$widget].concat(Array.prototype.slice.call(arguments,0)))
  8877. }
  8878. }
  8879. })
  8880. }
  8881. var pro = _widgetData[name];
  8882. if(!pro){
  8883. return null;
  8884. }
  8885. pro = editor._widgetData[name];
  8886. if(!pro){
  8887. pro = _widgetData[name];
  8888. pro = editor._widgetData[name] = $.type(pro) == 'function' ? pro : utils.clone(pro);
  8889. }
  8890. pro.root($widget.edui().getBodyContainer());
  8891. pro.initContent(editor,$widget);
  8892. if(!pro._preventDefault){
  8893. pro.initEvent(editor,$widget);
  8894. }
  8895. pro.width && $widget.width(pro.width);
  8896. },
  8897. setActiveWidget : function($widget){
  8898. _activeWidget = $widget;
  8899. },
  8900. getEditor: function (id, options) {
  8901. var editor = _editors[id] || (_editors[id] = this.createEditor(id, options));
  8902. _maxZIndex = _maxZIndex ? Math.max(editor.getOpt('zIndex'), _maxZIndex):editor.getOpt('zIndex');
  8903. return editor;
  8904. },
  8905. setTopEditor: function(editor){
  8906. $.each(_editors, function(i, o){
  8907. if(editor == o) {
  8908. editor.$container && editor.$container.css('zIndex', _maxZIndex + 1);
  8909. } else {
  8910. o.$container && o.$container.css('zIndex', o.getOpt('zIndex'));
  8911. }
  8912. });
  8913. },
  8914. clearCache : function(id){
  8915. if ( _editors[id]) {
  8916. delete _editors[id]
  8917. }
  8918. },
  8919. delEditor: function (id) {
  8920. var editor;
  8921. if (editor = _editors[id]) {
  8922. editor.destroy();
  8923. }
  8924. },
  8925. ready: function( fn ){
  8926. _readyFn.push( fn );
  8927. },
  8928. createEditor: function (id, opt) {
  8929. var editor = new UM.Editor(opt);
  8930. var T = this;
  8931. editor.langIsReady ? $.proxy(renderUI,T)() : editor.addListener("langReady", $.proxy(renderUI,T));
  8932. function renderUI(){
  8933. var $container = this.createUI('#' + id, editor);
  8934. editor.key=id;
  8935. editor.ready(function(){
  8936. $.each( _readyFn, function( index, fn ){
  8937. $.proxy( fn, editor )();
  8938. } );
  8939. });
  8940. var options = editor.options;
  8941. if(options.initialFrameWidth){
  8942. options.minFrameWidth = options.initialFrameWidth
  8943. }else{
  8944. options.minFrameWidth = options.initialFrameWidth = editor.$body.width() || UM.defaultWidth;
  8945. }
  8946. $container.css({
  8947. width: options.initialFrameWidth,
  8948. zIndex:editor.getOpt('zIndex')
  8949. });
  8950. //ie6下缓存图片
  8951. UM.browser.ie && UM.browser.version === 6 && document.execCommand("BackgroundImageCache", false, true);
  8952. editor.render(id);
  8953. //添加tooltip;
  8954. $.eduitooltip && $.eduitooltip('attachTo', $("[data-original-title]",$container)).css('z-index',editor.getOpt('zIndex')+1);
  8955. $container.find('a').click(function(evt){
  8956. evt.preventDefault()
  8957. });
  8958. editor.fireEvent("afteruiready");
  8959. }
  8960. return editor;
  8961. },
  8962. createUI: function (id, editor) {
  8963. var $editorCont = $(id),
  8964. $container = $('<div class="edui-container"><div class="edui-editor-body"></div></div>').insertBefore($editorCont);
  8965. editor.$container = $container;
  8966. editor.container = $container[0];
  8967. editor.$body = $editorCont;
  8968. //修正在ie9+以上的版本中,自动长高收起时的,残影问题
  8969. if(browser.ie && browser.ie9above){
  8970. var $span = $('<span style="padding:0;margin:0;height:0;width:0"></span>');
  8971. $span.insertAfter($container);
  8972. }
  8973. //初始化注册的ui组件
  8974. $.each(_editorUI,function(n,v){
  8975. var widget = v.call(editor,n);
  8976. if(widget){
  8977. _cacheUI[n] = widget;
  8978. }
  8979. });
  8980. $container.find('.edui-editor-body').append($editorCont).before(this.createToolbar(editor.options, editor));
  8981. $container.find('.edui-toolbar').append($('<div class="edui-dialog-container"></div>'));
  8982. return $container;
  8983. },
  8984. createToolbar: function (options, editor) {
  8985. var $toolbar = $.eduitoolbar(), toolbar = $toolbar.edui();
  8986. //创建下来菜单列表
  8987. if (options.toolbar && options.toolbar.length) {
  8988. var btns = [];
  8989. $.each(options.toolbar,function(i,uiNames){
  8990. $.each(uiNames.split(/\s+/),function(index,name){
  8991. if(name == '|'){
  8992. $.eduiseparator && btns.push($.eduiseparator());
  8993. }else{
  8994. var ui = _cacheUI[name];
  8995. if(name=="fullscreen"){
  8996. ui&&btns.unshift(ui);
  8997. }else{
  8998. ui && btns.push(ui);
  8999. }
  9000. }
  9001. });
  9002. btns.length && toolbar.appendToBtnmenu(btns);
  9003. });
  9004. } else {
  9005. $toolbar.find('.edui-btn-toolbar').remove()
  9006. }
  9007. return $toolbar;
  9008. }
  9009. })
  9010. })();
  9011. UM.registerUI('bold italic redo undo underline strikethrough superscript subscript insertorderedlist insertunorderedlist ' +
  9012. 'cleardoc selectall link unlink print preview justifyleft justifycenter justifyright justifyfull removeformat horizontal drafts',
  9013. function(name) {
  9014. var me = this;
  9015. var $btn = $.eduibutton({
  9016. icon : name,
  9017. click : function(){
  9018. me.execCommand(name);
  9019. },
  9020. title: this.getLang('labelMap')[name] || ''
  9021. });
  9022. this.addListener('selectionchange',function(){
  9023. var state = this.queryCommandState(name);
  9024. $btn.edui().disabled(state == -1).active(state == 1)
  9025. });
  9026. return $btn;
  9027. }
  9028. );
  9029. /**
  9030. * 全屏组件
  9031. */
  9032. (function(){
  9033. //状态缓存
  9034. var STATUS_CACHE = {},
  9035. //状态值列表
  9036. STATUS_LIST = [ 'width', 'height', 'position', 'top', 'left', 'margin', 'padding', 'overflowX', 'overflowY' ],
  9037. CONTENT_AREA_STATUS = {},
  9038. //页面状态
  9039. DOCUMENT_STATUS = {},
  9040. DOCUMENT_ELEMENT_STATUS = {},
  9041. FULLSCREENS = {};
  9042. UM.registerUI('fullscreen', function( name ){
  9043. var me = this,
  9044. $button = $.eduibutton({
  9045. 'icon': 'fullscreen',
  9046. 'title': (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9047. 'click': function(){
  9048. //切换
  9049. me.execCommand( name );
  9050. UM.setTopEditor(me);
  9051. }
  9052. });
  9053. me.addListener( "selectionchange", function () {
  9054. var state = this.queryCommandState( name );
  9055. $button.edui().disabled( state == -1 ).active( state == 1 );
  9056. } );
  9057. //切换至全屏
  9058. me.addListener('ready', function(){
  9059. me.options.fullscreen && Fullscreen.getInstance( me ).toggle();
  9060. });
  9061. return $button;
  9062. });
  9063. UM.commands[ 'fullscreen' ] = {
  9064. execCommand: function (cmdName) {
  9065. Fullscreen.getInstance( this ).toggle();
  9066. },
  9067. queryCommandState: function (cmdName) {
  9068. return this._edui_fullscreen_status;
  9069. },
  9070. notNeedUndo: 1
  9071. };
  9072. function Fullscreen( editor ) {
  9073. var me = this;
  9074. if( !editor ) {
  9075. throw new Error('invalid params, notfound editor');
  9076. }
  9077. me.editor = editor;
  9078. //记录初始化的全屏组件
  9079. FULLSCREENS[ editor.uid ] = this;
  9080. editor.addListener('destroy', function(){
  9081. delete FULLSCREENS[ editor.uid ];
  9082. me.editor = null;
  9083. });
  9084. }
  9085. Fullscreen.prototype = {
  9086. /**
  9087. * 全屏状态切换
  9088. */
  9089. toggle: function(){
  9090. var editor = this.editor,
  9091. //当前编辑器的缩放状态
  9092. _edui_fullscreen_status = this.isFullState();
  9093. editor.fireEvent('beforefullscreenchange', !_edui_fullscreen_status );
  9094. //更新状态
  9095. this.update( !_edui_fullscreen_status );
  9096. !_edui_fullscreen_status ? this.enlarge() : this.revert();
  9097. editor.fireEvent('afterfullscreenchange', !_edui_fullscreen_status );
  9098. if(editor.body.contentEditable === 'true'){
  9099. editor.fireEvent( 'fullscreenchanged', !_edui_fullscreen_status );
  9100. }
  9101. editor.fireEvent( 'selectionchange' );
  9102. },
  9103. /**
  9104. * 执行放大
  9105. */
  9106. enlarge: function(){
  9107. this.saveSataus();
  9108. this.setDocumentStatus();
  9109. this.resize();
  9110. },
  9111. /**
  9112. * 全屏还原
  9113. */
  9114. revert: function(){
  9115. //还原CSS表达式
  9116. var options = this.editor.options,
  9117. height = /%$/.test(options.initialFrameHeight) ? '100%' : (options.initialFrameHeight - this.getStyleValue("padding-top")- this.getStyleValue("padding-bottom") - this.getStyleValue('border-width'));
  9118. $.IE6 && this.getEditorHolder().style.setExpression('height', 'this.scrollHeight <= ' + height + ' ? "' + height + 'px" : "auto"');
  9119. //还原容器状态
  9120. this.revertContainerStatus();
  9121. this.revertContentAreaStatus();
  9122. this.revertDocumentStatus();
  9123. },
  9124. /**
  9125. * 更新状态
  9126. * @param isFull 当前状态是否是全屏状态
  9127. */
  9128. update: function( isFull ) {
  9129. this.editor._edui_fullscreen_status = isFull;
  9130. },
  9131. /**
  9132. * 调整当前编辑器的大小, 如果当前编辑器不处于全屏状态, 则不做调整
  9133. */
  9134. resize: function(){
  9135. var $win = null,
  9136. height = 0,
  9137. width = 0,
  9138. borderWidth = 0,
  9139. paddingWidth = 0,
  9140. editor = this.editor,
  9141. me = this,
  9142. bound = null,
  9143. editorBody = null;
  9144. if( !this.isFullState() ) {
  9145. return;
  9146. }
  9147. $win = $( window );
  9148. width = $win.width();
  9149. height = $win.height();
  9150. editorBody = this.getEditorHolder();
  9151. //文本编辑区border宽度
  9152. borderWidth = parseInt( domUtils.getComputedStyle( editorBody, 'border-width' ), 10 ) || 0;
  9153. //容器border宽度
  9154. borderWidth += parseInt( domUtils.getComputedStyle( editor.container, 'border-width' ), 10 ) || 0;
  9155. //容器padding
  9156. paddingWidth += parseInt( domUtils.getComputedStyle( editorBody, 'padding-left' ), 10 ) + parseInt( domUtils.getComputedStyle( editorBody, 'padding-right' ), 10 ) || 0;
  9157. //干掉css表达式
  9158. $.IE6 && editorBody.style.setExpression( 'height', null );
  9159. bound = this.getBound();
  9160. $( editor.container ).css( {
  9161. width: width + 'px',
  9162. height: height + 'px',
  9163. position: !$.IE6 ? 'fixed' : 'absolute',
  9164. top: bound.top,
  9165. left: bound.left,
  9166. margin: 0,
  9167. padding: 0,
  9168. overflowX: 'hidden',
  9169. overflowY: 'hidden'
  9170. } );
  9171. $( editorBody ).css({
  9172. width: width - 2*borderWidth - paddingWidth + 'px',
  9173. height: height - 2*borderWidth - ( editor.options.withoutToolbar ? 0 : $( '.edui-toolbar', editor.container ).outerHeight() ) - $( '.edui-bottombar', editor.container).outerHeight() + 'px',
  9174. overflowX: 'hidden',
  9175. overflowY: 'auto'
  9176. });
  9177. },
  9178. /**
  9179. * 保存状态
  9180. */
  9181. saveSataus: function(){
  9182. var styles = this.editor.container.style,
  9183. tmp = null,
  9184. cache = {};
  9185. for( var i= 0, len = STATUS_LIST.length; i<len; i++ ) {
  9186. tmp = STATUS_LIST[ i ];
  9187. cache[ tmp ] = styles[ tmp ];
  9188. }
  9189. STATUS_CACHE[ this.editor.uid ] = cache;
  9190. this.saveContentAreaStatus();
  9191. this.saveDocumentStatus();
  9192. },
  9193. saveContentAreaStatus: function(){
  9194. var $holder = $(this.getEditorHolder());
  9195. CONTENT_AREA_STATUS[ this.editor.uid ] = {
  9196. width: $holder.css("width"),
  9197. overflowX: $holder.css("overflowX"),
  9198. overflowY: $holder.css("overflowY"),
  9199. height: $holder.css("height")
  9200. };
  9201. },
  9202. /**
  9203. * 保存与指定editor相关的页面的状态
  9204. */
  9205. saveDocumentStatus: function(){
  9206. var $doc = $( this.getEditorDocumentBody() );
  9207. DOCUMENT_STATUS[ this.editor.uid ] = {
  9208. overflowX: $doc.css( 'overflowX' ),
  9209. overflowY: $doc.css( 'overflowY' )
  9210. };
  9211. DOCUMENT_ELEMENT_STATUS[ this.editor.uid ] = {
  9212. overflowX: $( this.getEditorDocumentElement() ).css( 'overflowX'),
  9213. overflowY: $( this.getEditorDocumentElement() ).css( 'overflowY' )
  9214. };
  9215. },
  9216. /**
  9217. * 恢复容器状态
  9218. */
  9219. revertContainerStatus: function(){
  9220. $( this.editor.container ).css( this.getEditorStatus() );
  9221. },
  9222. /**
  9223. * 恢复编辑区状态
  9224. */
  9225. revertContentAreaStatus: function(){
  9226. var holder = this.getEditorHolder(),
  9227. state = this.getContentAreaStatus();
  9228. if ( this.supportMin() ) {
  9229. delete state.height;
  9230. holder.style.height = null;
  9231. }
  9232. $( holder ).css( state );
  9233. },
  9234. /**
  9235. * 恢复页面状态
  9236. */
  9237. revertDocumentStatus: function() {
  9238. var status = this.getDocumentStatus();
  9239. $( this.getEditorDocumentBody() ).css( 'overflowX', status.body.overflowX );
  9240. $( this.getEditorDocumentElement() ).css( 'overflowY', status.html.overflowY );
  9241. },
  9242. setDocumentStatus: function(){
  9243. $(this.getEditorDocumentBody()).css( {
  9244. overflowX: 'hidden',
  9245. overflowY: 'hidden'
  9246. } );
  9247. $(this.getEditorDocumentElement()).css( {
  9248. overflowX: 'hidden',
  9249. overflowY: 'hidden'
  9250. } );
  9251. },
  9252. /**
  9253. * 检测当前编辑器是否处于全屏状态全屏状态
  9254. * @returns {boolean} 是否处于全屏状态
  9255. */
  9256. isFullState: function(){
  9257. return !!this.editor._edui_fullscreen_status;
  9258. },
  9259. /**
  9260. * 获取编辑器状态
  9261. */
  9262. getEditorStatus: function(){
  9263. return STATUS_CACHE[ this.editor.uid ];
  9264. },
  9265. getContentAreaStatus: function(){
  9266. return CONTENT_AREA_STATUS[ this.editor.uid ];
  9267. },
  9268. getEditorDocumentElement: function(){
  9269. return this.editor.container.ownerDocument.documentElement;
  9270. },
  9271. getEditorDocumentBody: function(){
  9272. return this.editor.container.ownerDocument.body;
  9273. },
  9274. /**
  9275. * 获取编辑区包裹对象
  9276. */
  9277. getEditorHolder: function(){
  9278. return this.editor.body;
  9279. },
  9280. /**
  9281. * 获取编辑器状态
  9282. * @returns {*}
  9283. */
  9284. getDocumentStatus: function(){
  9285. return {
  9286. 'body': DOCUMENT_STATUS[ this.editor.uid ],
  9287. 'html': DOCUMENT_ELEMENT_STATUS[ this.editor.uid ]
  9288. };
  9289. },
  9290. supportMin: function () {
  9291. var node = null;
  9292. if ( !this._support ) {
  9293. node = document.createElement("div");
  9294. this._support = "minWidth" in node.style;
  9295. node = null;
  9296. }
  9297. return this._support;
  9298. },
  9299. getBound: function () {
  9300. var tags = {
  9301. html: true,
  9302. body: true
  9303. },
  9304. result = {
  9305. top: 0,
  9306. left: 0
  9307. },
  9308. offsetParent = null;
  9309. if ( !$.IE6 ) {
  9310. return result;
  9311. }
  9312. offsetParent = this.editor.container.offsetParent;
  9313. if( offsetParent && !tags[ offsetParent.nodeName.toLowerCase() ] ) {
  9314. tags = offsetParent.getBoundingClientRect();
  9315. result.top = -tags.top;
  9316. result.left = -tags.left;
  9317. }
  9318. return result;
  9319. },
  9320. getStyleValue: function (attr) {
  9321. return parseInt(domUtils.getComputedStyle( this.getEditorHolder() ,attr));
  9322. }
  9323. };
  9324. $.extend( Fullscreen, {
  9325. /**
  9326. * 监听resize
  9327. */
  9328. listen: function(){
  9329. var timer = null;
  9330. if( Fullscreen._hasFullscreenListener ) {
  9331. return;
  9332. }
  9333. Fullscreen._hasFullscreenListener = true;
  9334. $( window ).on( 'resize', function(){
  9335. if( timer !== null ) {
  9336. window.clearTimeout( timer );
  9337. timer = null;
  9338. }
  9339. timer = window.setTimeout(function(){
  9340. for( var key in FULLSCREENS ) {
  9341. FULLSCREENS[ key ].resize();
  9342. }
  9343. timer = null;
  9344. }, 50);
  9345. } );
  9346. },
  9347. getInstance: function ( editor ) {
  9348. if ( !FULLSCREENS[editor.uid ] ) {
  9349. new Fullscreen( editor );
  9350. }
  9351. return FULLSCREENS[editor.uid ];
  9352. }
  9353. });
  9354. //开始监听
  9355. Fullscreen.listen();
  9356. })();
  9357. UM.registerUI('link image video map formula',function(name){
  9358. var me = this, currentRange, $dialog,
  9359. opt = {
  9360. title: (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9361. url: me.options.UMEDITOR_HOME_URL + 'dialogs/' + name + '/' + name + '.js'
  9362. };
  9363. var $btn = $.eduibutton({
  9364. icon: name,
  9365. title: this.getLang('labelMap')[name] || ''
  9366. });
  9367. //加载模版数据
  9368. utils.loadFile(document,{
  9369. src: opt.url,
  9370. tag: "script",
  9371. type: "text/javascript",
  9372. defer: "defer"
  9373. },function(){
  9374. //调整数据
  9375. var data = UM.getWidgetData(name);
  9376. if(!data) return;
  9377. if(data.buttons){
  9378. var ok = data.buttons.ok;
  9379. if(ok){
  9380. opt.oklabel = ok.label || me.getLang('ok');
  9381. if(ok.exec){
  9382. opt.okFn = function(){
  9383. return $.proxy(ok.exec,null,me,$dialog)()
  9384. }
  9385. }
  9386. }
  9387. var cancel = data.buttons.cancel;
  9388. if(cancel){
  9389. opt.cancellabel = cancel.label || me.getLang('cancel');
  9390. if(cancel.exec){
  9391. opt.cancelFn = function(){
  9392. return $.proxy(cancel.exec,null,me,$dialog)()
  9393. }
  9394. }
  9395. }
  9396. }
  9397. data.width && (opt.width = data.width);
  9398. data.height && (opt.height = data.height);
  9399. $dialog = $.eduimodal(opt);
  9400. $dialog.attr('id', 'edui-dialog-' + name).addClass('edui-dialog-' + name)
  9401. .find('.edui-modal-body').addClass('edui-dialog-' + name + '-body');
  9402. $dialog.edui().on('beforehide',function () {
  9403. var rng = me.selection.getRange();
  9404. if (rng.equals(currentRange)) {
  9405. rng.select()
  9406. }
  9407. }).on('beforeshow', function () {
  9408. var $root = this.root(),
  9409. win = null,
  9410. offset = null;
  9411. currentRange = me.selection.getRange();
  9412. if (!$root.parent()[0]) {
  9413. me.$container.find('.edui-dialog-container').append($root);
  9414. }
  9415. //IE6下 特殊处理, 通过计算进行定位
  9416. if( $.IE6 ) {
  9417. win = {
  9418. width: $( window ).width(),
  9419. height: $( window ).height()
  9420. };
  9421. offset = $root.parents(".edui-toolbar")[0].getBoundingClientRect();
  9422. $root.css({
  9423. position: 'absolute',
  9424. margin: 0,
  9425. left: ( win.width - $root.width() ) / 2 - offset.left,
  9426. top: 100 - offset.top
  9427. });
  9428. }
  9429. UM.setWidgetBody(name,$dialog,me);
  9430. UM.setTopEditor(me);
  9431. }).on('afterbackdrop',function(){
  9432. this.$backdrop.css('zIndex',me.getOpt('zIndex')+1).appendTo(me.$container.find('.edui-dialog-container'))
  9433. $dialog.css('zIndex',me.getOpt('zIndex')+2)
  9434. }).on('beforeok',function(){
  9435. try{
  9436. currentRange.select()
  9437. }catch(e){}
  9438. }).attachTo($btn)
  9439. });
  9440. me.addListener('selectionchange', function () {
  9441. var state = this.queryCommandState(name);
  9442. $btn.edui().disabled(state == -1).active(state == 1)
  9443. });
  9444. return $btn;
  9445. });
  9446. UM.registerUI( 'emotion formula', function( name ){
  9447. var me = this,
  9448. url = me.options.UMEDITOR_HOME_URL + 'dialogs/' +name+ '/'+name+'.js';
  9449. var $btn = $.eduibutton({
  9450. icon: name,
  9451. title: this.getLang('labelMap')[name] || ''
  9452. });
  9453. //加载模版数据
  9454. utils.loadFile(document,{
  9455. src: url,
  9456. tag: "script",
  9457. type: "text/javascript",
  9458. defer: "defer"
  9459. },function(){
  9460. var opt = {
  9461. url : url
  9462. };
  9463. //调整数据
  9464. var data = UM.getWidgetData(name);
  9465. data.width && (opt.width = data.width);
  9466. data.height && (opt.height = data.height);
  9467. $.eduipopup(opt).css('zIndex',me.options.zIndex + 1)
  9468. .addClass('edui-popup-' + name)
  9469. .edui()
  9470. .on('beforeshow',function(){
  9471. var $root = this.root();
  9472. if(!$root.parent().length){
  9473. me.$container.find('.edui-dialog-container').append($root);
  9474. }
  9475. UM.setWidgetBody(name,$root,me);
  9476. UM.setTopEditor(me);
  9477. }).attachTo($btn,{
  9478. offsetTop:-5,
  9479. offsetLeft:10,
  9480. caretLeft:11,
  9481. caretTop:-8
  9482. });
  9483. me.addListener('selectionchange', function () {
  9484. var state = this.queryCommandState(name);
  9485. $btn.edui().disabled(state == -1).active(state == 1);
  9486. });
  9487. });
  9488. return $btn;
  9489. } );
  9490. UM.registerUI('imagescale',function () {
  9491. var me = this,
  9492. $imagescale;
  9493. me.setOpt('imageScaleEnabled', true);
  9494. if (browser.webkit && me.getOpt('imageScaleEnabled')) {
  9495. me.addListener('click', function (type, e) {
  9496. var range = me.selection.getRange(),
  9497. img = range.getClosedNode(),
  9498. target = e.target;
  9499. /* 点击第一个图片的后面,八个角不消失 fix:3652 */
  9500. if (img && img.tagName == 'IMG' && target == img) {
  9501. if (!$imagescale) {
  9502. $imagescale = $.eduiscale({'$wrap':me.$container}).css('zIndex', me.options.zIndex);
  9503. me.$container.append($imagescale);
  9504. var _keyDownHandler = function () {
  9505. $imagescale.edui().hide();
  9506. }, _mouseDownHandler = function (e) {
  9507. var ele = e.target || e.srcElement;
  9508. if (ele && ele.className.indexOf('edui-scale') == -1) {
  9509. _keyDownHandler(e);
  9510. }
  9511. }, timer;
  9512. $imagescale.edui()
  9513. .on('aftershow', function () {
  9514. $(document).bind('keydown', _keyDownHandler);
  9515. $(document).bind('mousedown', _mouseDownHandler);
  9516. me.selection.getNative().removeAllRanges();
  9517. })
  9518. .on('afterhide', function () {
  9519. $(document).unbind('keydown', _keyDownHandler);
  9520. $(document).unbind('mousedown', _mouseDownHandler);
  9521. var target = $imagescale.edui().getScaleTarget();
  9522. if (target.parentNode) {
  9523. me.selection.getRange().selectNode(target).select();
  9524. }
  9525. })
  9526. .on('mousedown', function (e) {
  9527. me.selection.getNative().removeAllRanges();
  9528. var ele = e.target || e.srcElement;
  9529. if (ele && ele.className.indexOf('edui-scale-hand') == -1) {
  9530. timer = setTimeout(function() {
  9531. $imagescale.edui().hide();
  9532. }, 200);
  9533. }
  9534. })
  9535. .on('mouseup', function (e) {
  9536. var ele = e.target || e.srcElement;
  9537. if (ele && ele.className.indexOf('edui-scale-hand') == -1) {
  9538. clearTimeout(timer);
  9539. }
  9540. });
  9541. }
  9542. $imagescale.edui().show($(img));
  9543. } else {
  9544. if ($imagescale && $imagescale.css('display') != 'none') $imagescale.edui().hide();
  9545. }
  9546. });
  9547. me.addListener('click', function (type, e) {
  9548. if (e.target.tagName == 'IMG') {
  9549. var range = new dom.Range(me.document, me.body);
  9550. range.selectNode(e.target).select();
  9551. }
  9552. });
  9553. }
  9554. });
  9555. UM.registerUI('autofloat',function(){
  9556. var me = this,
  9557. lang = me.getLang();
  9558. me.setOpt({
  9559. autoFloatEnabled: true,
  9560. topOffset: 0
  9561. });
  9562. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  9563. topOffset = me.options.topOffset;
  9564. //如果不固定toolbar的位置,则直接退出
  9565. if(!optsAutoFloatEnabled){
  9566. return;
  9567. }
  9568. me.ready(function(){
  9569. var LteIE6 = browser.ie && browser.version <= 6,
  9570. quirks = browser.quirks;
  9571. function checkHasUI(){
  9572. if(!UM.ui){
  9573. alert(lang.autofloatMsg);
  9574. return 0;
  9575. }
  9576. return 1;
  9577. }
  9578. function fixIE6FixedPos(){
  9579. var docStyle = document.body.style;
  9580. docStyle.backgroundImage = 'url("about:blank")';
  9581. docStyle.backgroundAttachment = 'fixed';
  9582. }
  9583. var bakCssText,
  9584. placeHolder = document.createElement('div'),
  9585. toolbarBox,orgTop,
  9586. getPosition=function(element){
  9587. var bcr;
  9588. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  9589. try{
  9590. bcr = element.getBoundingClientRect();
  9591. }catch(e){
  9592. bcr={left:0,top:0,height:0,width:0}
  9593. }
  9594. var rect = {
  9595. left: Math.round(bcr.left),
  9596. top: Math.round(bcr.top),
  9597. height: Math.round(bcr.bottom - bcr.top),
  9598. width: Math.round(bcr.right - bcr.left)
  9599. };
  9600. var doc;
  9601. while ((doc = element.ownerDocument) !== document &&
  9602. (element = domUtils.getWindow(doc).frameElement)) {
  9603. bcr = element.getBoundingClientRect();
  9604. rect.left += bcr.left;
  9605. rect.top += bcr.top;
  9606. }
  9607. rect.bottom = rect.top + rect.height;
  9608. rect.right = rect.left + rect.width;
  9609. return rect;
  9610. };
  9611. var isFullScreening = false;
  9612. function setFloating(){
  9613. if(isFullScreening){
  9614. return;
  9615. }
  9616. var toobarBoxPos = domUtils.getXY(toolbarBox),
  9617. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  9618. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  9619. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  9620. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  9621. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  9622. if (LteIE6 || (quirks && browser.ie)) {
  9623. if(toolbarBox.style.position != 'absolute'){
  9624. toolbarBox.style.position = 'absolute';
  9625. }
  9626. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  9627. } else {
  9628. if(toolbarBox.style.position != 'fixed'){
  9629. toolbarBox.style.position = 'fixed';
  9630. toolbarBox.style.top = topOffset +"px";
  9631. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  9632. }
  9633. }
  9634. }
  9635. function unsetFloating(){
  9636. if(placeHolder.parentNode){
  9637. placeHolder.parentNode.removeChild(placeHolder);
  9638. }
  9639. toolbarBox.style.cssText = bakCssText;
  9640. }
  9641. function updateFloating(){
  9642. var rect3 = getPosition(me.container);
  9643. var offset=me.options.toolbarTopOffset||0;
  9644. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  9645. setFloating();
  9646. }else{
  9647. unsetFloating();
  9648. }
  9649. }
  9650. var defer_updateFloating = utils.defer(function(){
  9651. updateFloating();
  9652. },browser.ie ? 200 : 100,true);
  9653. me.addListener('destroy',function(){
  9654. $(window).off('scroll resize',updateFloating);
  9655. me.removeListener('keydown', defer_updateFloating);
  9656. });
  9657. if(checkHasUI(me)){
  9658. toolbarBox = $('.edui-toolbar',me.container)[0];
  9659. me.addListener("afteruiready",function(){
  9660. setTimeout(function(){
  9661. orgTop = $(toolbarBox).offset().top;
  9662. },100);
  9663. });
  9664. bakCssText = toolbarBox.style.cssText;
  9665. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  9666. if(LteIE6){
  9667. fixIE6FixedPos();
  9668. }
  9669. $(window).on('scroll resize',updateFloating);
  9670. me.addListener('keydown', defer_updateFloating);
  9671. me.addListener('resize', function(){
  9672. unsetFloating();
  9673. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  9674. updateFloating();
  9675. });
  9676. me.addListener('beforefullscreenchange', function (t, enabled){
  9677. if (enabled) {
  9678. unsetFloating();
  9679. isFullScreening = enabled;
  9680. }
  9681. });
  9682. me.addListener('fullscreenchanged', function (t, enabled){
  9683. if (!enabled) {
  9684. updateFloating();
  9685. }
  9686. isFullScreening = enabled;
  9687. });
  9688. me.addListener('sourcemodechanged', function (t, enabled){
  9689. setTimeout(function (){
  9690. updateFloating();
  9691. },0);
  9692. });
  9693. me.addListener("clearDoc",function(){
  9694. setTimeout(function(){
  9695. updateFloating();
  9696. },0);
  9697. })
  9698. }
  9699. })
  9700. });
  9701. UM.registerUI('source',function(name){
  9702. var me = this;
  9703. me.addListener('fullscreenchanged',function(){
  9704. me.$container.find('textarea').width(me.$body.width() - 10).height(me.$body.height())
  9705. });
  9706. var $btn = $.eduibutton({
  9707. icon : name,
  9708. click : function(){
  9709. me.execCommand(name);
  9710. UM.setTopEditor(me);
  9711. },
  9712. title: this.getLang('labelMap')[name] || ''
  9713. });
  9714. this.addListener('selectionchange',function(){
  9715. var state = this.queryCommandState(name);
  9716. $btn.edui().disabled(state == -1).active(state == 1)
  9717. });
  9718. return $btn;
  9719. });
  9720. UM.registerUI('paragraph fontfamily fontsize', function( name ) {
  9721. var me = this,
  9722. label = (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9723. options = {
  9724. label: label,
  9725. title: label,
  9726. comboboxName: name,
  9727. items: me.options[ name ] || [],
  9728. itemStyles: [],
  9729. value: [],
  9730. autowidthitem: []
  9731. },
  9732. $combox = null,
  9733. comboboxWidget = null;
  9734. if(options.items.length == 0){
  9735. return null;
  9736. }
  9737. switch ( name ) {
  9738. case 'paragraph':
  9739. options = transForParagraph( options );
  9740. break;
  9741. case 'fontfamily':
  9742. options = transForFontfamily( options );
  9743. break;
  9744. case 'fontsize':
  9745. options = transForFontsize( options );
  9746. break;
  9747. }
  9748. //实例化
  9749. $combox = $.eduibuttoncombobox(options).css('zIndex',me.getOpt('zIndex') + 1);
  9750. comboboxWidget = $combox.edui();
  9751. comboboxWidget.on('comboboxselect', function( evt, res ){
  9752. me.execCommand( name, res.value );
  9753. }).on("beforeshow", function(){
  9754. if( $combox.parent().length === 0 ) {
  9755. $combox.appendTo( me.$container.find('.edui-dialog-container') );
  9756. }
  9757. UM.setTopEditor(me);
  9758. });
  9759. //状态反射
  9760. this.addListener('selectionchange',function( evt ){
  9761. var state = this.queryCommandState( name ),
  9762. value = this.queryCommandValue( name );
  9763. //设置按钮状态
  9764. comboboxWidget.button().edui().disabled( state == -1 ).active( state == 1 );
  9765. if(value){
  9766. //设置label
  9767. value = value.replace(/['"]/g, '').toLowerCase().split(/['|"]?\s*,\s*[\1]?/);
  9768. comboboxWidget.selectItemByLabel( value );
  9769. }
  9770. });
  9771. return comboboxWidget.button().addClass('edui-combobox');
  9772. /**
  9773. * 宽度自适应工具函数
  9774. * @param word 单词内容
  9775. * @param hasSuffix 是否含有后缀
  9776. */
  9777. function wordCountAdaptive ( word, hasSuffix ) {
  9778. var $tmpNode = $('<span>' ).html( word ).css( {
  9779. display: 'inline',
  9780. position: 'absolute',
  9781. top: -10000000,
  9782. left: -100000
  9783. } ).appendTo( document.body),
  9784. width = $tmpNode.width();
  9785. $tmpNode.remove();
  9786. $tmpNode = null;
  9787. if( width < 50 ) {
  9788. return word;
  9789. } else {
  9790. word = word.slice( 0, hasSuffix ? -4 : -1 );
  9791. if( !word.length ) {
  9792. return '...';
  9793. }
  9794. return wordCountAdaptive( word + '...', true );
  9795. }
  9796. }
  9797. //段落参数转换
  9798. function transForParagraph ( options ) {
  9799. var tempItems = [];
  9800. for( var key in options.items ) {
  9801. options.value.push( key );
  9802. tempItems.push( key );
  9803. options.autowidthitem.push( wordCountAdaptive( key ) );
  9804. }
  9805. options.items = tempItems;
  9806. options.autoRecord = false;
  9807. return options;
  9808. }
  9809. //字体参数转换
  9810. function transForFontfamily ( options ) {
  9811. var temp = null,
  9812. tempItems = [];
  9813. for( var i = 0, len = options.items.length; i < len; i++ ) {
  9814. temp = options.items[ i ].val;
  9815. tempItems.push( temp.split(/\s*,\s*/)[0] );
  9816. options.itemStyles.push('font-family: ' + temp);
  9817. options.value.push( temp );
  9818. options.autowidthitem.push( wordCountAdaptive( tempItems[ i ] ) );
  9819. }
  9820. options.items = tempItems;
  9821. return options;
  9822. }
  9823. //字体大小参数转换
  9824. function transForFontsize ( options ) {
  9825. var temp = null,
  9826. tempItems = [];
  9827. options.itemStyles = [];
  9828. options.value = [];
  9829. for( var i = 0, len = options.items.length; i < len; i++ ) {
  9830. temp = options.items[ i ];
  9831. tempItems.push( temp );
  9832. options.itemStyles.push('font-size: ' + temp +'px');
  9833. }
  9834. options.value = options.items;
  9835. options.items = tempItems;
  9836. options.autoRecord = false;
  9837. return options;
  9838. }
  9839. });
  9840. UM.registerUI('forecolor backcolor', function( name ) {
  9841. function getCurrentColor() {
  9842. return domUtils.getComputedStyle( $colorLabel[0], 'background-color' );
  9843. }
  9844. var me = this,
  9845. $colorPickerWidget = null,
  9846. $colorLabel = null,
  9847. $btn = null;
  9848. //querycommand
  9849. this.addListener('selectionchange', function(){
  9850. var state = this.queryCommandState( name );
  9851. $btn.edui().disabled( state == -1 ).active( state == 1 );
  9852. });
  9853. $btn = $.eduicolorsplitbutton({
  9854. icon: name,
  9855. caret: true,
  9856. name: name,
  9857. title: me.getLang("labelMap")[name],
  9858. click: function() {
  9859. me.execCommand( name, getCurrentColor() );
  9860. }
  9861. });
  9862. $colorLabel = $btn.edui().colorLabel();
  9863. $colorPickerWidget = $.eduicolorpicker({
  9864. name: name,
  9865. lang_clearColor: me.getLang('clearColor') || '',
  9866. lang_themeColor: me.getLang('themeColor') || '',
  9867. lang_standardColor: me.getLang('standardColor') || ''
  9868. })
  9869. .on('pickcolor', function( evt, color ){
  9870. window.setTimeout( function(){
  9871. $colorLabel.css("backgroundColor", color);
  9872. me.execCommand( name, color );
  9873. }, 0 );
  9874. })
  9875. .on('show',function(){
  9876. UM.setActiveWidget( colorPickerWidget.root() );
  9877. }).css('zIndex',me.getOpt('zIndex') + 1);
  9878. $btn.edui().on('arrowclick',function(){
  9879. if(!$colorPickerWidget.parent().length){
  9880. me.$container.find('.edui-dialog-container').append($colorPickerWidget);
  9881. }
  9882. $colorPickerWidget.edui().show($btn,{
  9883. caretDir:"down",
  9884. offsetTop:-5,
  9885. offsetLeft:8,
  9886. caretLeft:11,
  9887. caretTop:-8
  9888. });
  9889. UM.setTopEditor(me);
  9890. }).register('click', $btn, function () {
  9891. $colorPickerWidget.edui().hide()
  9892. });
  9893. return $btn;
  9894. });
  9895. })(jQuery)