umeditor.js 417 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958
  1. /*!
  2. * UEditor Mini版本
  3. * version: 1.2.2
  4. * build: Wed Mar 19 2014 17:14: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,video: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 || 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;
  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,video: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 image
  5893. ///commandsTitle 图片选择
  5894. /**
  5895. *
  5896. * 图片选择
  5897. * @function
  5898. * @name UM.execCommand
  5899. * @param {String} cmdName image 图片选择
  5900. */
  5901. UM.commands['image'] = {
  5902. execCommand : function() {
  5903. var me = this;
  5904. $.fileLibrary({
  5905. type: 'image',
  5906. done: function (images) {
  5907. console.log(images);
  5908. var html = [];
  5909. images.forEach(function (item) {
  5910. html.push('<p><img src="' + item.file_path + '"></p>');
  5911. });
  5912. me.execCommand('insertHtml', html.join(''), true);
  5913. }
  5914. });
  5915. }
  5916. };
  5917. ///import core
  5918. ///commands 清空文档
  5919. ///commandsName ClearDoc
  5920. ///commandsTitle 清空文档
  5921. /**
  5922. *
  5923. * 清空文档
  5924. * @function
  5925. * @name UM.execCommand
  5926. * @param {String} cmdName cleardoc清空文档
  5927. */
  5928. UM.commands['cleardoc'] = {
  5929. execCommand : function() {
  5930. var me = this,
  5931. range = me.selection.getRange();
  5932. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  5933. range.setStart(me.body.firstChild,0).setCursor(false,true);
  5934. setTimeout(function(){
  5935. me.fireEvent("clearDoc");
  5936. },0);
  5937. }
  5938. };
  5939. ///import core
  5940. ///commands 撤销和重做
  5941. ///commandsName Undo,Redo
  5942. ///commandsTitle 撤销,重做
  5943. /**
  5944. * @description 回退
  5945. * @author zhanyi
  5946. */
  5947. UM.plugins['undo'] = function () {
  5948. var saveSceneTimer;
  5949. var me = this,
  5950. maxUndoCount = me.options.maxUndoCount || 20,
  5951. maxInputCount = me.options.maxInputCount || 20,
  5952. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  5953. var noNeedFillCharTags = {
  5954. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  5955. };
  5956. var orgState = me.options.autoClearEmptyNode;
  5957. function compareAddr(indexA, indexB) {
  5958. if (indexA.length != indexB.length)
  5959. return 0;
  5960. for (var i = 0, l = indexA.length; i < l; i++) {
  5961. if (indexA[i] != indexB[i])
  5962. return 0
  5963. }
  5964. return 1;
  5965. }
  5966. function compareRangeAddress(rngAddrA, rngAddrB) {
  5967. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  5968. return 0;
  5969. }
  5970. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  5971. return 0;
  5972. }
  5973. return 1;
  5974. }
  5975. function UndoManager() {
  5976. this.list = [];
  5977. this.index = 0;
  5978. this.hasUndo = false;
  5979. this.hasRedo = false;
  5980. this.undo = function () {
  5981. if (this.hasUndo) {
  5982. if (!this.list[this.index - 1] && this.list.length == 1) {
  5983. this.reset();
  5984. return;
  5985. }
  5986. while (this.list[this.index].content == this.list[this.index - 1].content) {
  5987. this.index--;
  5988. if (this.index == 0) {
  5989. return this.restore(0);
  5990. }
  5991. }
  5992. this.restore(--this.index);
  5993. }
  5994. };
  5995. this.redo = function () {
  5996. if (this.hasRedo) {
  5997. while (this.list[this.index].content == this.list[this.index + 1].content) {
  5998. this.index++;
  5999. if (this.index == this.list.length - 1) {
  6000. return this.restore(this.index);
  6001. }
  6002. }
  6003. this.restore(++this.index);
  6004. }
  6005. };
  6006. this.restore = function () {
  6007. var me = this.editor;
  6008. var scene = this.list[this.index];
  6009. var root = UM.htmlparser(scene.content.replace(fillchar, ''));
  6010. me.options.autoClearEmptyNode = false;
  6011. me.filterInputRule(root,true);
  6012. me.options.autoClearEmptyNode = orgState;
  6013. //trace:873
  6014. //去掉展位符
  6015. me.body.innerHTML = root.toHtml();
  6016. me.fireEvent('afterscencerestore');
  6017. //处理undo后空格不展位的问题
  6018. if (browser.ie) {
  6019. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  6020. if(domUtils.isEmptyNode(node)){
  6021. domUtils.fillNode(me.document, node);
  6022. }
  6023. })
  6024. }
  6025. try{
  6026. var rng = new dom.Range(me.document,me.body).moveToAddress(scene.address);
  6027. if(browser.ie && rng.collapsed && rng.startContainer.nodeType == 1){
  6028. var tmpNode = rng.startContainer.childNodes[rng.startOffset];
  6029. if( !tmpNode || tmpNode.nodeType == 1 && dtd.$empty[tmpNode]){
  6030. rng.insertNode(me.document.createTextNode(' ')).collapse(true);
  6031. }
  6032. }
  6033. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  6034. }catch(e){}
  6035. this.update();
  6036. this.clearKey();
  6037. //不能把自己reset了
  6038. me.fireEvent('reset', true);
  6039. };
  6040. this.getScene = function () {
  6041. var me = this.editor;
  6042. var rng = me.selection.getRange(),
  6043. rngAddress = rng.createAddress(false,true);
  6044. me.fireEvent('beforegetscene');
  6045. var root = UM.htmlparser(me.body.innerHTML,true);
  6046. me.options.autoClearEmptyNode = false;
  6047. me.filterOutputRule(root,true);
  6048. me.options.autoClearEmptyNode = orgState;
  6049. var cont = root.toHtml();
  6050. browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  6051. me.fireEvent('aftergetscene');
  6052. return {
  6053. address:rngAddress,
  6054. content:cont
  6055. }
  6056. };
  6057. this.save = function (notCompareRange,notSetCursor) {
  6058. clearTimeout(saveSceneTimer);
  6059. var currentScene = this.getScene(notSetCursor),
  6060. lastScene = this.list[this.index];
  6061. //内容相同位置相同不存
  6062. if (lastScene && lastScene.content == currentScene.content &&
  6063. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  6064. ) {
  6065. return;
  6066. }
  6067. this.list = this.list.slice(0, this.index + 1);
  6068. this.list.push(currentScene);
  6069. //如果大于最大数量了,就把最前的剔除
  6070. if (this.list.length > maxUndoCount) {
  6071. this.list.shift();
  6072. }
  6073. this.index = this.list.length - 1;
  6074. this.clearKey();
  6075. //跟新undo/redo状态
  6076. this.update();
  6077. };
  6078. this.update = function () {
  6079. this.hasRedo = !!this.list[this.index + 1];
  6080. this.hasUndo = !!this.list[this.index - 1];
  6081. };
  6082. this.reset = function () {
  6083. this.list = [];
  6084. this.index = 0;
  6085. this.hasUndo = false;
  6086. this.hasRedo = false;
  6087. this.clearKey();
  6088. };
  6089. this.clearKey = function () {
  6090. keycont = 0;
  6091. lastKeyCode = null;
  6092. };
  6093. }
  6094. me.undoManger = new UndoManager();
  6095. me.undoManger.editor = me;
  6096. function saveScene() {
  6097. this.undoManger.save();
  6098. }
  6099. me.addListener('saveScene', function () {
  6100. var args = Array.prototype.splice.call(arguments,1);
  6101. this.undoManger.save.apply(this.undoManger,args);
  6102. });
  6103. me.addListener('beforeexeccommand', saveScene);
  6104. me.addListener('afterexeccommand', saveScene);
  6105. me.addListener('reset', function (type, exclude) {
  6106. if (!exclude) {
  6107. this.undoManger.reset();
  6108. }
  6109. });
  6110. me.commands['redo'] = me.commands['undo'] = {
  6111. execCommand:function (cmdName) {
  6112. this.undoManger[cmdName]();
  6113. },
  6114. queryCommandState:function (cmdName) {
  6115. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  6116. },
  6117. notNeedUndo:1
  6118. };
  6119. var keys = {
  6120. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  6121. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  6122. 37:1, 38:1, 39:1, 40:1
  6123. },
  6124. keycont = 0,
  6125. lastKeyCode;
  6126. //输入法状态下不计算字符数
  6127. var inputType = false;
  6128. me.addListener('ready', function () {
  6129. $(this.body).on('compositionstart', function () {
  6130. inputType = true;
  6131. }).on('compositionend', function () {
  6132. inputType = false;
  6133. })
  6134. });
  6135. //快捷键
  6136. me.addshortcutkey({
  6137. "Undo":"ctrl+90", //undo
  6138. "Redo":"ctrl+89,shift+ctrl+z" //redo
  6139. });
  6140. var isCollapsed = true;
  6141. me.addListener('keydown', function (type, evt) {
  6142. var me = this;
  6143. var keyCode = evt.keyCode || evt.which;
  6144. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  6145. if (inputType)
  6146. return;
  6147. if(!me.selection.getRange().collapsed){
  6148. me.undoManger.save(false,true);
  6149. isCollapsed = false;
  6150. return;
  6151. }
  6152. if (me.undoManger.list.length == 0) {
  6153. me.undoManger.save(true);
  6154. }
  6155. clearTimeout(saveSceneTimer);
  6156. function save(cont){
  6157. if (cont.selection.getRange().collapsed)
  6158. cont.fireEvent('contentchange');
  6159. cont.undoManger.save(false,true);
  6160. cont.fireEvent('selectionchange');
  6161. }
  6162. saveSceneTimer = setTimeout(function(){
  6163. if(inputType){
  6164. var interalTimer = setInterval(function(){
  6165. if(!inputType){
  6166. save(me);
  6167. clearInterval(interalTimer)
  6168. }
  6169. },300)
  6170. return;
  6171. }
  6172. save(me);
  6173. },200);
  6174. lastKeyCode = keyCode;
  6175. keycont++;
  6176. if (keycont >= maxInputCount ) {
  6177. save(me)
  6178. }
  6179. }
  6180. });
  6181. me.addListener('keyup', function (type, evt) {
  6182. var keyCode = evt.keyCode || evt.which;
  6183. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  6184. if (inputType)
  6185. return;
  6186. if(!isCollapsed){
  6187. this.undoManger.save(false,true);
  6188. isCollapsed = true;
  6189. }
  6190. }
  6191. });
  6192. };
  6193. ///import core
  6194. ///import plugins/inserthtml.js
  6195. ///import plugins/undo.js
  6196. ///import plugins/serialize.js
  6197. ///commands 粘贴
  6198. ///commandsName PastePlain
  6199. ///commandsTitle 纯文本粘贴模式
  6200. /**
  6201. * @description 粘贴
  6202. * @author zhanyi
  6203. */
  6204. UM.plugins['paste'] = function () {
  6205. function getClipboardData(callback) {
  6206. var doc = this.document;
  6207. if (doc.getElementById('baidu_pastebin')) {
  6208. return;
  6209. }
  6210. var range = this.selection.getRange(),
  6211. bk = range.createBookmark(),
  6212. //创建剪贴的容器div
  6213. pastebin = doc.createElement('div');
  6214. pastebin.id = 'baidu_pastebin';
  6215. // Safari 要求div必须有内容,才能粘贴内容进来
  6216. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  6217. this.body.appendChild(pastebin);
  6218. //trace:717 隐藏的span不能得到top
  6219. //bk.start.innerHTML = '&nbsp;';
  6220. bk.start.style.display = '';
  6221. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  6222. //要在现在光标平行的位置加入,否则会出现跳动的问题
  6223. $(bk.start).position().top + 'px';
  6224. range.selectNodeContents(pastebin).select(true);
  6225. setTimeout(function () {
  6226. if (browser.webkit) {
  6227. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  6228. if (domUtils.isEmptyNode(pi)) {
  6229. domUtils.remove(pi);
  6230. } else {
  6231. pastebin = pi;
  6232. break;
  6233. }
  6234. }
  6235. }
  6236. try {
  6237. pastebin.parentNode.removeChild(pastebin);
  6238. } catch (e) {
  6239. }
  6240. range.moveToBookmark(bk).select(true);
  6241. callback(pastebin);
  6242. }, 0);
  6243. }
  6244. var me = this;
  6245. function filter(div) {
  6246. var html;
  6247. if (div.firstChild) {
  6248. //去掉cut中添加的边界值
  6249. var nodes = domUtils.getElementsByTagName(div, 'span');
  6250. for (var i = 0, ni; ni = nodes[i++];) {
  6251. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  6252. domUtils.remove(ni);
  6253. }
  6254. }
  6255. if (browser.webkit) {
  6256. var brs = div.querySelectorAll('div br');
  6257. for (var i = 0, bi; bi = brs[i++];) {
  6258. var pN = bi.parentNode;
  6259. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  6260. pN.innerHTML = '<p><br/></p>';
  6261. domUtils.remove(pN);
  6262. }
  6263. }
  6264. var divs = div.querySelectorAll('#baidu_pastebin');
  6265. for (var i = 0, di; di = divs[i++];) {
  6266. var tmpP = me.document.createElement('p');
  6267. di.parentNode.insertBefore(tmpP, di);
  6268. while (di.firstChild) {
  6269. tmpP.appendChild(di.firstChild);
  6270. }
  6271. domUtils.remove(di);
  6272. }
  6273. var metas = div.querySelectorAll('meta');
  6274. for (var i = 0, ci; ci = metas[i++];) {
  6275. domUtils.remove(ci);
  6276. }
  6277. var brs = div.querySelectorAll('br');
  6278. for (i = 0; ci = brs[i++];) {
  6279. if (/^apple-/i.test(ci.className)) {
  6280. domUtils.remove(ci);
  6281. }
  6282. }
  6283. }
  6284. if (browser.gecko) {
  6285. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  6286. for (i = 0; ci = dirtyNodes[i++];) {
  6287. ci.removeAttribute('_moz_dirty');
  6288. }
  6289. }
  6290. if (!browser.ie) {
  6291. var spans = div.querySelectorAll('span.Apple-style-span');
  6292. for (var i = 0, ci; ci = spans[i++];) {
  6293. domUtils.remove(ci, true);
  6294. }
  6295. }
  6296. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  6297. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  6298. //过滤word粘贴过来的冗余属性
  6299. html = UM.filterWord(html);
  6300. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  6301. var root = UM.htmlparser(html);
  6302. //如果给了过滤规则就先进行过滤
  6303. if (me.options.filterRules) {
  6304. UM.filterNode(root, me.options.filterRules);
  6305. }
  6306. //执行默认的处理
  6307. me.filterInputRule(root);
  6308. //针对chrome的处理
  6309. if (browser.webkit) {
  6310. var br = root.lastChild();
  6311. if (br && br.type == 'element' && br.tagName == 'br') {
  6312. root.removeChild(br)
  6313. }
  6314. utils.each(me.body.querySelectorAll('div'), function (node) {
  6315. if (domUtils.isEmptyBlock(node)) {
  6316. domUtils.remove(node)
  6317. }
  6318. })
  6319. }
  6320. html = {'html': root.toHtml()};
  6321. me.fireEvent('beforepaste', html, root);
  6322. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  6323. if(!html.html){
  6324. return;
  6325. }
  6326. me.execCommand('insertHtml', html.html, true);
  6327. me.fireEvent("afterpaste", html);
  6328. }
  6329. }
  6330. me.addListener('ready', function () {
  6331. $(me.body).on( 'cut', function () {
  6332. var range = me.selection.getRange();
  6333. if (!range.collapsed && me.undoManger) {
  6334. me.undoManger.save();
  6335. }
  6336. }).on(browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  6337. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  6338. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  6339. return;
  6340. }
  6341. getClipboardData.call(me, function (div) {
  6342. filter(div);
  6343. });
  6344. });
  6345. });
  6346. };
  6347. ///import core
  6348. ///commands 有序列表,无序列表
  6349. ///commandsName InsertOrderedList,InsertUnorderedList
  6350. ///commandsTitle 有序列表,无序列表
  6351. /**
  6352. * 有序列表
  6353. * @function
  6354. * @name UM.execCommand
  6355. * @param {String} cmdName insertorderlist插入有序列表
  6356. * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman
  6357. * @author zhanyi
  6358. */
  6359. /**
  6360. * 无序链接
  6361. * @function
  6362. * @name UM.execCommand
  6363. * @param {String} cmdName insertunorderlist插入无序列表
  6364. * * @param {String} style 值为:circle,disc,square
  6365. * @author zhanyi
  6366. */
  6367. UM.plugins['list'] = function () {
  6368. var me = this;
  6369. me.setOpt( {
  6370. 'insertorderedlist':{
  6371. 'decimal':'',
  6372. 'lower-alpha':'',
  6373. 'lower-roman':'',
  6374. 'upper-alpha':'',
  6375. 'upper-roman':''
  6376. },
  6377. 'insertunorderedlist':{
  6378. 'circle':'',
  6379. 'disc':'',
  6380. 'square':''
  6381. }
  6382. } );
  6383. this.addInputRule(function(root){
  6384. utils.each(root.getNodesByTagName('li'), function (node) {
  6385. if(node.children.length == 0){
  6386. node.parentNode.removeChild(node);
  6387. }
  6388. })
  6389. });
  6390. me.commands['insertorderedlist'] =
  6391. me.commands['insertunorderedlist'] = {
  6392. execCommand:function (cmdName) {
  6393. this.document.execCommand(cmdName);
  6394. var rng = this.selection.getRange(),
  6395. bk = rng.createBookmark(true);
  6396. this.$body.find('ol,ul').each(function(i,n){
  6397. var parent = n.parentNode;
  6398. if(parent.tagName == 'P' && parent.lastChild === parent.firstChild){
  6399. $(n).children().each(function(j,li){
  6400. var p = parent.cloneNode(false);
  6401. $(p).append(li.innerHTML);
  6402. $(li).html('').append(p);
  6403. });
  6404. $(n).insertBefore(parent);
  6405. $(parent).remove();
  6406. }
  6407. if(dtd.$inline[parent.tagName]){
  6408. if(parent.tagName == 'SPAN'){
  6409. $(n).children().each(function(k,li){
  6410. var span = parent.cloneNode(false);
  6411. if(li.firstChild.nodeName != 'P'){
  6412. while(li.firstChild){
  6413. span.appendChild(li.firstChild)
  6414. };
  6415. $('<p></p>').appendTo(li).append(span);
  6416. }else{
  6417. while(li.firstChild){
  6418. span.appendChild(li.firstChild)
  6419. };
  6420. $(li.firstChild).append(span);
  6421. }
  6422. })
  6423. }
  6424. domUtils.remove(parent,true)
  6425. }
  6426. });
  6427. rng.moveToBookmark(bk).select();
  6428. return true;
  6429. },
  6430. queryCommandState:function (cmdName) {
  6431. return this.document.queryCommandState(cmdName);
  6432. }
  6433. };
  6434. };
  6435. ///import core
  6436. ///import plugins/serialize.js
  6437. ///import plugins/undo.js
  6438. ///commands 查看源码
  6439. ///commandsName Source
  6440. ///commandsTitle 查看源码
  6441. (function (){
  6442. var sourceEditors = {
  6443. textarea: function (editor, holder){
  6444. var textarea = holder.ownerDocument.createElement('textarea');
  6445. textarea.style.cssText = 'resize:none;border:0;padding:0;margin:0;overflow-y:auto;outline:0';
  6446. // todo: IE下只有onresize属性可用... 很纠结
  6447. if (browser.ie && browser.version < 8) {
  6448. textarea.style.width = holder.offsetWidth + 'px';
  6449. textarea.style.height = holder.offsetHeight + 'px';
  6450. holder.onresize = function (){
  6451. textarea.style.width = holder.offsetWidth + 'px';
  6452. textarea.style.height = holder.offsetHeight + 'px';
  6453. };
  6454. }
  6455. holder.appendChild(textarea);
  6456. return {
  6457. container : textarea,
  6458. setContent: function (content){
  6459. textarea.value = content;
  6460. },
  6461. getContent: function (){
  6462. return textarea.value;
  6463. },
  6464. select: function (){
  6465. var range;
  6466. if (browser.ie) {
  6467. range = textarea.createTextRange();
  6468. range.collapse(true);
  6469. range.select();
  6470. } else {
  6471. //todo: chrome下无法设置焦点
  6472. textarea.setSelectionRange(0, 0);
  6473. textarea.focus();
  6474. }
  6475. },
  6476. dispose: function (){
  6477. holder.removeChild(textarea);
  6478. // todo
  6479. holder.onresize = null;
  6480. textarea = null;
  6481. holder = null;
  6482. }
  6483. };
  6484. }
  6485. };
  6486. UM.plugins['source'] = function (){
  6487. var me = this;
  6488. var opt = this.options;
  6489. var sourceMode = false;
  6490. var sourceEditor;
  6491. opt.sourceEditor = 'textarea';
  6492. me.setOpt({
  6493. sourceEditorFirst:false
  6494. });
  6495. function createSourceEditor(holder){
  6496. return sourceEditors.textarea(me, holder);
  6497. }
  6498. var bakCssText;
  6499. //解决在源码模式下getContent不能得到最新的内容问题
  6500. var oldGetContent = me.getContent,
  6501. bakAddress;
  6502. me.commands['source'] = {
  6503. execCommand: function (){
  6504. sourceMode = !sourceMode;
  6505. if (sourceMode) {
  6506. bakAddress = me.selection.getRange().createAddress(false,true);
  6507. me.undoManger && me.undoManger.save(true);
  6508. if(browser.gecko){
  6509. me.body.contentEditable = false;
  6510. }
  6511. // bakCssText = me.body.style.cssText;
  6512. me.body.style.cssText += ';position:absolute;left:-32768px;top:-32768px;';
  6513. me.fireEvent('beforegetcontent');
  6514. var root = UM.htmlparser(me.body.innerHTML);
  6515. me.filterOutputRule(root);
  6516. root.traversal(function (node) {
  6517. if (node.type == 'element') {
  6518. switch (node.tagName) {
  6519. case 'td':
  6520. case 'th':
  6521. case 'caption':
  6522. if(node.children && node.children.length == 1){
  6523. if(node.firstChild().tagName == 'br' ){
  6524. node.removeChild(node.firstChild())
  6525. }
  6526. };
  6527. break;
  6528. case 'pre':
  6529. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  6530. }
  6531. }
  6532. });
  6533. me.fireEvent('aftergetcontent');
  6534. var content = root.toHtml(true);
  6535. sourceEditor = createSourceEditor(me.body.parentNode);
  6536. sourceEditor.setContent(content);
  6537. var getStyleValue=function(attr){
  6538. return parseInt($(me.body).css(attr));
  6539. };
  6540. $(sourceEditor.container).width($(me.body).width()+getStyleValue("padding-left")+getStyleValue("padding-right"))
  6541. .height($(me.body).height());
  6542. setTimeout(function (){
  6543. sourceEditor.select();
  6544. });
  6545. //重置getContent,源码模式下取值也能是最新的数据
  6546. me.getContent = function (){
  6547. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  6548. };
  6549. } else {
  6550. me.$body.css({
  6551. 'position':'',
  6552. 'left':'',
  6553. 'top':''
  6554. });
  6555. // me.body.style.cssText = bakCssText;
  6556. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  6557. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  6558. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  6559. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  6560. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  6561. }
  6562. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  6563. });
  6564. me.setContent(cont);
  6565. sourceEditor.dispose();
  6566. sourceEditor = null;
  6567. //还原getContent方法
  6568. me.getContent = oldGetContent;
  6569. var first = me.body.firstChild;
  6570. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  6571. if(!first){
  6572. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  6573. }
  6574. //要在ifm为显示时ff才能取到selection,否则报错
  6575. //这里不能比较位置了
  6576. me.undoManger && me.undoManger.save(true);
  6577. if(browser.gecko){
  6578. me.body.contentEditable = true;
  6579. }
  6580. try{
  6581. me.selection.getRange().moveToAddress(bakAddress).select();
  6582. }catch(e){}
  6583. }
  6584. this.fireEvent('sourcemodechanged', sourceMode);
  6585. },
  6586. queryCommandState: function (){
  6587. return sourceMode|0;
  6588. },
  6589. notNeedUndo : 1
  6590. };
  6591. var oldQueryCommandState = me.queryCommandState;
  6592. me.queryCommandState = function (cmdName){
  6593. cmdName = cmdName.toLowerCase();
  6594. if (sourceMode) {
  6595. //源码模式下可以开启的命令
  6596. return cmdName in {
  6597. 'source' : 1,
  6598. 'fullscreen' : 1
  6599. } ? oldQueryCommandState.apply(this, arguments) : -1
  6600. }
  6601. return oldQueryCommandState.apply(this, arguments);
  6602. };
  6603. };
  6604. })();
  6605. ///import core
  6606. ///import plugins/undo.js
  6607. ///commands 设置回车标签p或br
  6608. ///commandsName EnterKey
  6609. ///commandsTitle 设置回车标签p或br
  6610. /**
  6611. * @description 处理回车
  6612. * @author zhanyi
  6613. */
  6614. UM.plugins['enterkey'] = function() {
  6615. var hTag,
  6616. me = this,
  6617. tag = me.options.enterTag;
  6618. me.addListener('keyup', function(type, evt) {
  6619. var keyCode = evt.keyCode || evt.which;
  6620. if (keyCode == 13) {
  6621. var range = me.selection.getRange(),
  6622. start = range.startContainer,
  6623. doSave;
  6624. //修正在h1-h6里边回车后不能嵌套p的问题
  6625. if (!browser.ie) {
  6626. if (/h\d/i.test(hTag)) {
  6627. if (browser.gecko) {
  6628. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  6629. if (!h) {
  6630. me.document.execCommand('formatBlock', false, '<p>');
  6631. doSave = 1;
  6632. }
  6633. } else {
  6634. //chrome remove div
  6635. if (start.nodeType == 1) {
  6636. var tmp = me.document.createTextNode(''),div;
  6637. range.insertNode(tmp);
  6638. div = domUtils.findParentByTagName(tmp, 'div', true);
  6639. if (div) {
  6640. var p = me.document.createElement('p');
  6641. while (div.firstChild) {
  6642. p.appendChild(div.firstChild);
  6643. }
  6644. div.parentNode.insertBefore(p, div);
  6645. domUtils.remove(div);
  6646. range.setStartBefore(tmp).setCursor();
  6647. doSave = 1;
  6648. }
  6649. domUtils.remove(tmp);
  6650. }
  6651. }
  6652. if (me.undoManger && doSave) {
  6653. me.undoManger.save();
  6654. }
  6655. }
  6656. //没有站位符,会出现多行的问题
  6657. browser.opera && range.select();
  6658. }else{
  6659. me.fireEvent('saveScene',true,true)
  6660. }
  6661. }
  6662. });
  6663. me.addListener('keydown', function(type, evt) {
  6664. var keyCode = evt.keyCode || evt.which;
  6665. if (keyCode == 13) {//回车
  6666. if(me.fireEvent('beforeenterkeydown')){
  6667. domUtils.preventDefault(evt);
  6668. return;
  6669. }
  6670. me.fireEvent('saveScene',true,true);
  6671. hTag = '';
  6672. var range = me.selection.getRange();
  6673. if (!range.collapsed) {
  6674. //跨td不能删
  6675. var start = range.startContainer,
  6676. end = range.endContainer,
  6677. startTd = domUtils.findParentByTagName(start, 'td', true),
  6678. endTd = domUtils.findParentByTagName(end, 'td', true);
  6679. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  6680. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  6681. return;
  6682. }
  6683. }
  6684. if (tag == 'p') {
  6685. if (!browser.ie) {
  6686. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  6687. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  6688. //trace:2431
  6689. if (!start && !browser.opera) {
  6690. me.document.execCommand('formatBlock', false, '<p>');
  6691. if (browser.gecko) {
  6692. range = me.selection.getRange();
  6693. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  6694. start && domUtils.removeDirtyAttr(start);
  6695. }
  6696. } else {
  6697. hTag = start.tagName;
  6698. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  6699. }
  6700. }
  6701. }
  6702. }
  6703. });
  6704. browser.ie && me.addListener('setDisabled',function(){
  6705. $(me.body).find('p').each(function(i,p){
  6706. if(domUtils.isEmptyBlock(p)){
  6707. p.innerHTML = '&nbsp;'
  6708. }
  6709. })
  6710. })
  6711. };
  6712. ///import core
  6713. ///commands 预览
  6714. ///commandsName Preview
  6715. ///commandsTitle 预览
  6716. /**
  6717. * 预览
  6718. * @function
  6719. * @name UM.execCommand
  6720. * @param {String} cmdName preview预览编辑器内容
  6721. */
  6722. UM.commands['preview'] = {
  6723. execCommand : function(){
  6724. var w = window.open('', '_blank', ''),
  6725. d = w.document,
  6726. c = this.getContent(null,null,true),
  6727. path = this.getOpt('UMEDITOR_HOME_URL'),
  6728. formula = c.indexOf('mathquill-embedded-latex')!=-1 ?
  6729. '<link rel="stylesheet" href="' + path + 'third-party/mathquill/mathquill.css"/>' +
  6730. '<script src="' + path + 'third-party/jquery.min.js"></script>' +
  6731. '<script src="' + path + 'third-party/mathquill/mathquill.min.js"></script>':'';
  6732. d.open();
  6733. d.write('<html><head>' + formula + '</head><body><div>'+c+'</div></body></html>');
  6734. d.close();
  6735. },
  6736. notNeedUndo : 1
  6737. };
  6738. ///import core
  6739. ///commands 加粗,斜体,上标,下标
  6740. ///commandsName Bold,Italic,Subscript,Superscript
  6741. ///commandsTitle 加粗,加斜,下标,上标
  6742. /**
  6743. * b u i等基础功能实现
  6744. * @function
  6745. * @name UM.execCommands
  6746. * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。
  6747. */
  6748. UM.plugins['basestyle'] = function(){
  6749. var basestyles = ['bold','underline','superscript','subscript','italic','strikethrough'],
  6750. me = this;
  6751. //添加快捷键
  6752. me.addshortcutkey({
  6753. "Bold" : "ctrl+66",//^B
  6754. "Italic" : "ctrl+73", //^I
  6755. "Underline" : "ctrl+shift+85",//^U
  6756. "strikeThrough" : 'ctrl+shift+83' //^s
  6757. });
  6758. //过滤最后的产出数据
  6759. me.addOutputRule(function(root){
  6760. $.each(root.getNodesByTagName('b i u strike s'),function(i,node){
  6761. switch (node.tagName){
  6762. case 'b':
  6763. node.tagName = 'strong';
  6764. break;
  6765. case 'i':
  6766. node.tagName = 'em';
  6767. break;
  6768. case 'u':
  6769. node.tagName = 'span';
  6770. node.setStyle('text-decoration','underline');
  6771. break;
  6772. case 's':
  6773. case 'strike':
  6774. node.tagName = 'span';
  6775. node.setStyle('text-decoration','line-through')
  6776. }
  6777. });
  6778. });
  6779. $.each(basestyles,function(i,cmd){
  6780. me.commands[cmd] = {
  6781. execCommand : function( cmdName ) {
  6782. var rng = this.selection.getRange();
  6783. if(rng.collapsed && this.queryCommandState(cmdName) != 1){
  6784. var node = this.document.createElement({
  6785. 'bold':'strong',
  6786. 'underline':'u',
  6787. 'superscript':'sup',
  6788. 'subscript':'sub',
  6789. 'italic':'em',
  6790. 'strikethrough':'strike'
  6791. }[cmdName]);
  6792. rng.insertNode(node).setStart(node,0).setCursor(false);
  6793. return true;
  6794. }else{
  6795. return this.document.execCommand(cmdName)
  6796. }
  6797. },
  6798. queryCommandState : function(cmdName) {
  6799. if(browser.gecko){
  6800. return this.document.queryCommandState(cmdName)
  6801. }
  6802. var path = this.selection.getStartElementPath(),result = false;
  6803. $.each(path,function(i,n){
  6804. switch (cmdName){
  6805. case 'bold':
  6806. if(n.nodeName == 'STRONG' || n.nodeName == 'B'){
  6807. result = 1;
  6808. return false;
  6809. }
  6810. break;
  6811. case 'underline':
  6812. if(n.nodeName == 'U' || n.nodeName == 'SPAN' && $(n).css('text-decoration') == 'underline'){
  6813. result = 1;
  6814. return false;
  6815. }
  6816. break;
  6817. case 'superscript':
  6818. if(n.nodeName == 'SUP'){
  6819. result = 1;
  6820. return false;
  6821. }
  6822. break;
  6823. case 'subscript':
  6824. if(n.nodeName == 'SUB'){
  6825. result = 1;
  6826. return false;
  6827. }
  6828. break;
  6829. case 'italic':
  6830. if(n.nodeName == 'EM' || n.nodeName == 'I'){
  6831. result = 1;
  6832. return false;
  6833. }
  6834. break;
  6835. case 'strikethrough':
  6836. if(n.nodeName == 'S' || n.nodeName == 'STRIKE' || n.nodeName == 'SPAN' && $(n).css('text-decoration') == 'line-through'){
  6837. result = 1;
  6838. return false;
  6839. }
  6840. break;
  6841. }
  6842. });
  6843. return result
  6844. }
  6845. };
  6846. })
  6847. };
  6848. ///import core
  6849. ///import plugins/inserthtml.js
  6850. ///commands 视频
  6851. ///commandsName InsertVideo
  6852. ///commandsTitle 插入视频
  6853. ///commandsDialog dialogs\video
  6854. UM.plugins['video'] = function (){
  6855. var me =this,
  6856. div;
  6857. /**
  6858. * 创建插入视频字符窜
  6859. * @param url 视频地址
  6860. * @param poster 封面图url
  6861. * @param width 视频宽度
  6862. * @param height 视频高度
  6863. * @param id 组件id
  6864. * @param align 视频对齐
  6865. * @param toEmbed 是否以flash代替显示
  6866. */
  6867. function creatInsertStr(url, poster, width, height, id, align, toEmbed){
  6868. var attr = {
  6869. src: url,
  6870. poster: poster,
  6871. style: {
  6872. height: height ? ('height: ' + height + 'px;') : '',
  6873. width: width ? ('width: ' + width + 'px;') : ''
  6874. }
  6875. };
  6876. return '<video src="' + attr.src + '" poster="' + attr.poster + '" style="' + attr.style.height + '" controls></video>';
  6877. }
  6878. function switchImgAndEmbed(root,img2embed){
  6879. utils.each(root.getNodesByTagName(img2embed ? 'img' : 'embed'),function(node){
  6880. if(node.getAttr('class') == 'edui-faked-video'){
  6881. var html = creatInsertStr( img2embed ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',img2embed);
  6882. node.parentNode.replaceChild(UM.uNode.createElement(html),node)
  6883. }
  6884. })
  6885. }
  6886. me.addOutputRule(function(root){
  6887. switchImgAndEmbed(root,true)
  6888. });
  6889. me.addInputRule(function(root){
  6890. switchImgAndEmbed(root)
  6891. });
  6892. me.commands["insertvideo"] = {
  6893. execCommand: function (cmd, videoObjs){
  6894. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  6895. var html = [],id = 'tmpVedio';
  6896. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  6897. vi = videoObjs[i];
  6898. html.push(creatInsertStr( vi.url, vi.poster, vi.width || 375, vi.height || 190, id + i,vi.align,false));
  6899. }
  6900. me.execCommand("inserthtml",html.join(""),true);
  6901. },
  6902. queryCommandState : function(){
  6903. var img = me.selection.getRange().getClosedNode(),
  6904. flag = img && (img.className == "edui-faked-video");
  6905. return flag ? 1 : 0;
  6906. }
  6907. };
  6908. };
  6909. ///import core
  6910. ///commands 全选
  6911. ///commandsName SelectAll
  6912. ///commandsTitle 全选
  6913. /**
  6914. * 选中所有
  6915. * @function
  6916. * @name UM.execCommand
  6917. * @param {String} cmdName selectall选中编辑器里的所有内容
  6918. * @author zhanyi
  6919. */
  6920. UM.plugins['selectall'] = function(){
  6921. var me = this;
  6922. me.commands['selectall'] = {
  6923. execCommand : function(){
  6924. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  6925. var me = this,body = me.body,
  6926. range = me.selection.getRange();
  6927. range.selectNodeContents(body);
  6928. if(domUtils.isEmptyBlock(body)){
  6929. //opera不能自动合并到元素的里边,要手动处理一下
  6930. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  6931. range.setStartAtFirst(body.firstChild);
  6932. }
  6933. range.collapse(true);
  6934. }
  6935. range.select(true);
  6936. },
  6937. notNeedUndo : 1
  6938. };
  6939. //快捷键
  6940. me.addshortcutkey({
  6941. "selectAll" : "ctrl+65"
  6942. });
  6943. };
  6944. //UM.plugins['removeformat'] = function () {
  6945. // var me = this;
  6946. // me.commands['removeformat'] = {
  6947. // execCommand: function () {
  6948. // me.document.execCommand('removeformat');
  6949. //
  6950. // /* 处理ie8和firefox选区有链接时,清除格式的bug */
  6951. // if (browser.gecko || browser.ie8 || browser.webkit) {
  6952. // var nativeRange = this.selection.getNative().getRangeAt(0),
  6953. // common = nativeRange.commonAncestorContainer,
  6954. // rng = me.selection.getRange(),
  6955. // bk = rng.createBookmark();
  6956. //
  6957. // function isEleInBookmark(node, bk){
  6958. // if ( (domUtils.getPosition(node, bk.start) & domUtils.POSITION_FOLLOWING) &&
  6959. // (domUtils.getPosition(bk.end, node) & domUtils.POSITION_FOLLOWING) ) {
  6960. // return true;
  6961. // } else if ( (domUtils.getPosition(node, bk.start) & domUtils.POSITION_CONTAINS) ||
  6962. // (domUtils.getPosition(node, bk.end) & domUtils.POSITION_CONTAINS) ) {
  6963. // return true;
  6964. // }
  6965. // return false;
  6966. // }
  6967. //
  6968. // $(common).find('a').each(function (k, a) {
  6969. // if ( isEleInBookmark(a, bk) ) {
  6970. // a.removeAttribute('style');
  6971. // }
  6972. // });
  6973. //
  6974. // }
  6975. // }
  6976. // };
  6977. //
  6978. //};
  6979. //
  6980. UM.plugins['removeformat'] = function(){
  6981. var me = this;
  6982. me.setOpt({
  6983. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  6984. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  6985. });
  6986. me.commands['removeformat'] = {
  6987. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  6988. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  6989. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  6990. range = new dom.Range( this.document ),
  6991. bookmark,node,parent,
  6992. filter = function( node ) {
  6993. return node.nodeType == 1;
  6994. };
  6995. function isRedundantSpan (node) {
  6996. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  6997. return 0;
  6998. }
  6999. if (browser.ie) {
  7000. //ie 下判断实效,所以只能简单用style来判断
  7001. //return node.style.cssText == '' ? 1 : 0;
  7002. var attrs = node.attributes;
  7003. if ( attrs.length ) {
  7004. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  7005. if ( attrs[i].specified ) {
  7006. return 0;
  7007. }
  7008. }
  7009. return 1;
  7010. }
  7011. }
  7012. return !node.attributes.length;
  7013. }
  7014. function doRemove( range ) {
  7015. var bookmark1 = range.createBookmark();
  7016. if ( range.collapsed ) {
  7017. range.enlarge( true );
  7018. }
  7019. //不能把a标签切了
  7020. if(!notIncludeA){
  7021. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  7022. if(aNode){
  7023. range.setStartBefore(aNode);
  7024. }
  7025. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  7026. if(aNode){
  7027. range.setEndAfter(aNode);
  7028. }
  7029. }
  7030. bookmark = range.createBookmark();
  7031. node = bookmark.start;
  7032. //切开始
  7033. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7034. domUtils.breakParent( node, parent );
  7035. domUtils.clearEmptySibling( node );
  7036. }
  7037. if ( bookmark.end ) {
  7038. //切结束
  7039. node = bookmark.end;
  7040. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  7041. domUtils.breakParent( node, parent );
  7042. domUtils.clearEmptySibling( node );
  7043. }
  7044. //开始去除样式
  7045. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  7046. next;
  7047. while ( current ) {
  7048. if ( current == bookmark.end ) {
  7049. break;
  7050. }
  7051. next = domUtils.getNextDomNode( current, true, filter );
  7052. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  7053. if ( tagReg.test( current.tagName ) ) {
  7054. if ( style ) {
  7055. domUtils.removeStyle( current, style );
  7056. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  7057. domUtils.remove( current, true );
  7058. }
  7059. } else {
  7060. domUtils.remove( current, true );
  7061. }
  7062. } else {
  7063. //trace:939 不能把list上的样式去掉
  7064. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  7065. domUtils.removeAttributes( current, removeFormatAttributes );
  7066. if ( isRedundantSpan( current ) ){
  7067. domUtils.remove( current, true );
  7068. }
  7069. }
  7070. }
  7071. }
  7072. current = next;
  7073. }
  7074. }
  7075. //trace:1035
  7076. //trace:1096 不能把td上的样式去掉,比如边框
  7077. var pN = bookmark.start.parentNode;
  7078. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  7079. domUtils.removeAttributes( pN,removeFormatAttributes );
  7080. }
  7081. pN = bookmark.end.parentNode;
  7082. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  7083. domUtils.removeAttributes( pN,removeFormatAttributes );
  7084. }
  7085. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  7086. //清除冗余的代码 <b><bookmark></b>
  7087. var node = range.startContainer,
  7088. tmp,
  7089. collapsed = range.collapsed;
  7090. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7091. tmp = node.parentNode;
  7092. range.setStartBefore(node);
  7093. //trace:937
  7094. //更新结束边界
  7095. if(range.startContainer === range.endContainer){
  7096. range.endOffset--;
  7097. }
  7098. domUtils.remove(node);
  7099. node = tmp;
  7100. }
  7101. if(!collapsed){
  7102. node = range.endContainer;
  7103. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  7104. tmp = node.parentNode;
  7105. range.setEndBefore(node);
  7106. domUtils.remove(node);
  7107. node = tmp;
  7108. }
  7109. }
  7110. }
  7111. range = this.selection.getRange();
  7112. if(!range.collapsed) {
  7113. doRemove( range );
  7114. range.select();
  7115. }
  7116. }
  7117. };
  7118. };
  7119. /*
  7120. * 处理特殊键的兼容性问题
  7121. */
  7122. UM.plugins['keystrokes'] = function() {
  7123. var me = this;
  7124. var collapsed = true;
  7125. me.addListener('keydown', function(type, evt) {
  7126. var keyCode = evt.keyCode || evt.which,
  7127. rng = me.selection.getRange();
  7128. //处理全选的情况
  7129. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  7130. || keyCode >= 48 && keyCode <= 57 ||
  7131. keyCode >= 96 && keyCode <= 111 || {
  7132. 13:1,
  7133. 8:1,
  7134. 46:1
  7135. }[keyCode])
  7136. ){
  7137. var tmpNode = rng.startContainer;
  7138. if(domUtils.isFillChar(tmpNode)){
  7139. rng.setStartBefore(tmpNode)
  7140. }
  7141. tmpNode = rng.endContainer;
  7142. if(domUtils.isFillChar(tmpNode)){
  7143. rng.setEndAfter(tmpNode)
  7144. }
  7145. rng.txtToElmBoundary();
  7146. //结束边界可能放到了br的前边,要把br包含进来
  7147. // x[xxx]<br/>
  7148. if(rng.endContainer && rng.endContainer.nodeType == 1){
  7149. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  7150. if(tmpNode && domUtils.isBr(tmpNode)){
  7151. rng.setEndAfter(tmpNode);
  7152. }
  7153. }
  7154. if(rng.startOffset == 0){
  7155. tmpNode = rng.startContainer;
  7156. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  7157. tmpNode = rng.endContainer;
  7158. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  7159. me.fireEvent('saveScene');
  7160. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  7161. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  7162. me._selectionChange();
  7163. return;
  7164. }
  7165. }
  7166. }
  7167. }
  7168. //处理backspace
  7169. if (keyCode == 8) {
  7170. rng = me.selection.getRange();
  7171. collapsed = rng.collapsed;
  7172. if(me.fireEvent('delkeydown',evt)){
  7173. return;
  7174. }
  7175. var start,end;
  7176. //避免按两次删除才能生效的问题
  7177. if(rng.collapsed && rng.inFillChar()){
  7178. start = rng.startContainer;
  7179. if(domUtils.isFillChar(start)){
  7180. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  7181. domUtils.remove(start)
  7182. }else{
  7183. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  7184. rng.startOffset--;
  7185. rng.collapse(true).select(true)
  7186. }
  7187. }
  7188. //解决选中control元素不能删除的问题
  7189. if (start = rng.getClosedNode()) {
  7190. me.fireEvent('saveScene');
  7191. rng.setStartBefore(start);
  7192. domUtils.remove(start);
  7193. rng.setCursor();
  7194. me.fireEvent('saveScene');
  7195. domUtils.preventDefault(evt);
  7196. return;
  7197. }
  7198. //阻止在table上的删除
  7199. if (!browser.ie) {
  7200. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  7201. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  7202. if (start && !end || !start && end || start !== end) {
  7203. evt.preventDefault();
  7204. return;
  7205. }
  7206. }
  7207. start = rng.startContainer;
  7208. if(rng.collapsed && start.nodeType == 1){
  7209. var currentNode = start.childNodes[rng.startOffset-1];
  7210. if(currentNode && currentNode.nodeType == 1 && currentNode.tagName == 'BR'){
  7211. me.fireEvent('saveScene');
  7212. rng.setStartBefore(currentNode).collapse(true);
  7213. domUtils.remove(currentNode);
  7214. rng.select();
  7215. me.fireEvent('saveScene');
  7216. }
  7217. }
  7218. //trace:3613
  7219. if(browser.chrome){
  7220. if(rng.collapsed){
  7221. while(rng.startOffset == 0 && !domUtils.isEmptyBlock(rng.startContainer)){
  7222. rng.setStartBefore(rng.startContainer)
  7223. }
  7224. var pre = rng.startContainer.childNodes[rng.startOffset-1];
  7225. if(pre && pre.nodeName == 'BR'){
  7226. rng.setStartBefore(pre);
  7227. me.fireEvent('saveScene');
  7228. $(pre).remove();
  7229. rng.setCursor();
  7230. me.fireEvent('saveScene');
  7231. }
  7232. }
  7233. }
  7234. }
  7235. //trace:1634
  7236. //ff的del键在容器空的时候,也会删除
  7237. if(browser.gecko && keyCode == 46){
  7238. var range = me.selection.getRange();
  7239. if(range.collapsed){
  7240. start = range.startContainer;
  7241. if(domUtils.isEmptyBlock(start)){
  7242. var parent = start.parentNode;
  7243. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  7244. start = parent;
  7245. parent = parent.parentNode;
  7246. }
  7247. if(start === parent.lastChild)
  7248. evt.preventDefault();
  7249. return;
  7250. }
  7251. }
  7252. }
  7253. });
  7254. me.addListener('keyup', function(type, evt) {
  7255. var keyCode = evt.keyCode || evt.which,
  7256. rng,me = this;
  7257. if(keyCode == 8){
  7258. if(me.fireEvent('delkeyup')){
  7259. return;
  7260. }
  7261. rng = me.selection.getRange();
  7262. if(rng.collapsed){
  7263. var tmpNode,
  7264. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  7265. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  7266. if(domUtils.isEmptyBlock(tmpNode)){
  7267. var pre = tmpNode.previousSibling;
  7268. if(pre && pre.nodeName != 'TABLE'){
  7269. domUtils.remove(tmpNode);
  7270. rng.setStartAtLast(pre).setCursor(false,true);
  7271. return;
  7272. }else{
  7273. var next = tmpNode.nextSibling;
  7274. if(next && next.nodeName != 'TABLE'){
  7275. domUtils.remove(tmpNode);
  7276. rng.setStartAtFirst(next).setCursor(false,true);
  7277. return;
  7278. }
  7279. }
  7280. }
  7281. }
  7282. //处理当删除到body时,要重新给p标签展位
  7283. if(domUtils.isBody(rng.startContainer)){
  7284. var tmpNode = domUtils.createElement(me.document,'p',{
  7285. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  7286. });
  7287. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  7288. }
  7289. }
  7290. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  7291. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  7292. if(browser.ie){
  7293. var span = rng.document.createElement('span');
  7294. rng.insertNode(span).setStartBefore(span).collapse(true);
  7295. rng.select();
  7296. domUtils.remove(span)
  7297. }else{
  7298. rng.select()
  7299. }
  7300. }
  7301. }
  7302. })
  7303. };
  7304. /**
  7305. * 自动保存草稿
  7306. */
  7307. UM.plugins['autosave'] = function() {
  7308. var me = this,
  7309. //无限循环保护
  7310. lastSaveTime = new Date(),
  7311. //最小保存间隔时间
  7312. MIN_TIME = 20,
  7313. //auto save key
  7314. saveKey = null;
  7315. //默认间隔时间
  7316. me.setOpt('saveInterval', 500);
  7317. //存储媒介封装
  7318. var LocalStorage = UM.LocalStorage = ( function () {
  7319. var storage = window.localStorage || getUserData() || null,
  7320. LOCAL_FILE = "localStorage";
  7321. return {
  7322. saveLocalData: function ( key, data ) {
  7323. if ( storage && data) {
  7324. storage.setItem( key, data );
  7325. return true;
  7326. }
  7327. return false;
  7328. },
  7329. getLocalData: function ( key ) {
  7330. if ( storage ) {
  7331. return storage.getItem( key );
  7332. }
  7333. return null;
  7334. },
  7335. removeItem: function ( key ) {
  7336. storage && storage.removeItem( key );
  7337. }
  7338. };
  7339. function getUserData () {
  7340. var container = document.createElement( "div" );
  7341. container.style.display = "none";
  7342. if( !container.addBehavior ) {
  7343. return null;
  7344. }
  7345. container.addBehavior("#default#userdata");
  7346. return {
  7347. getItem: function ( key ) {
  7348. var result = null;
  7349. try {
  7350. document.body.appendChild( container );
  7351. container.load( LOCAL_FILE );
  7352. result = container.getAttribute( key );
  7353. document.body.removeChild( container );
  7354. } catch ( e ) {
  7355. }
  7356. return result;
  7357. },
  7358. setItem: function ( key, value ) {
  7359. document.body.appendChild( container );
  7360. container.setAttribute( key, value );
  7361. container.save( LOCAL_FILE );
  7362. document.body.removeChild( container );
  7363. },
  7364. // 暂时没有用到
  7365. // clear: function () {
  7366. //
  7367. // var expiresTime = new Date();
  7368. // expiresTime.setFullYear( expiresTime.getFullYear() - 1 );
  7369. // document.body.appendChild( container );
  7370. // container.expires = expiresTime.toUTCString();
  7371. // container.save( LOCAL_FILE );
  7372. // document.body.removeChild( container );
  7373. //
  7374. // },
  7375. removeItem: function ( key ) {
  7376. document.body.appendChild( container );
  7377. container.removeAttribute( key );
  7378. container.save( LOCAL_FILE );
  7379. document.body.removeChild( container );
  7380. }
  7381. };
  7382. }
  7383. } )();
  7384. function save ( editor ) {
  7385. var saveData = null;
  7386. if ( new Date() - lastSaveTime < MIN_TIME ) {
  7387. return;
  7388. }
  7389. if ( !editor.hasContents() ) {
  7390. //这里不能调用命令来删除, 会造成事件死循环
  7391. saveKey && LocalStorage.removeItem( saveKey );
  7392. return;
  7393. }
  7394. lastSaveTime = new Date();
  7395. editor._saveFlag = null;
  7396. saveData = me.body.innerHTML;
  7397. if ( editor.fireEvent( "beforeautosave", {
  7398. content: saveData
  7399. } ) === false ) {
  7400. return;
  7401. }
  7402. LocalStorage.saveLocalData( saveKey, saveData );
  7403. editor.fireEvent( "afterautosave", {
  7404. content: saveData
  7405. } );
  7406. }
  7407. me.addListener('ready', function(){
  7408. var _suffix = "-drafts-data",
  7409. key = null;
  7410. if ( me.key ) {
  7411. key = me.key + _suffix;
  7412. } else {
  7413. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  7414. }
  7415. //页面地址+编辑器ID 保持唯一
  7416. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  7417. });
  7418. me.addListener('contentchange', function(){
  7419. return;
  7420. if ( !saveKey ) {
  7421. return;
  7422. }
  7423. if ( me._saveFlag ) {
  7424. window.clearTimeout( me._saveFlag );
  7425. }
  7426. if ( me.options.saveInterval > 0 ) {
  7427. me._saveFlag = window.setTimeout( function () {
  7428. save( me );
  7429. }, me.options.saveInterval );
  7430. } else {
  7431. save(me);
  7432. }
  7433. })
  7434. me.commands['clearlocaldata'] = {
  7435. execCommand:function (cmd, name) {
  7436. if ( saveKey && LocalStorage.getLocalData( saveKey ) ) {
  7437. LocalStorage.removeItem( saveKey )
  7438. }
  7439. },
  7440. notNeedUndo: true,
  7441. ignoreContentChange:true
  7442. };
  7443. me.commands['getlocaldata'] = {
  7444. execCommand:function (cmd, name) {
  7445. return saveKey ? LocalStorage.getLocalData( saveKey ) || '' : '';
  7446. },
  7447. notNeedUndo: true,
  7448. ignoreContentChange:true
  7449. };
  7450. me.commands['drafts'] = {
  7451. execCommand:function (cmd, name) {
  7452. if ( saveKey ) {
  7453. me.body.innerHTML = LocalStorage.getLocalData( saveKey ) || '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>';
  7454. me.focus(true);
  7455. }
  7456. },
  7457. queryCommandState: function () {
  7458. return saveKey ? ( LocalStorage.getLocalData( saveKey ) === null ? -1 : 0 ) : -1;
  7459. },
  7460. notNeedUndo: true,
  7461. ignoreContentChange:true
  7462. }
  7463. };
  7464. /**
  7465. * @description
  7466. * 1.拖放文件到编辑区域,自动上传并插入到选区
  7467. * 2.插入粘贴板的图片,自动上传并插入到选区
  7468. * @author Jinqn
  7469. * @date 2013-10-14
  7470. */
  7471. UM.plugins['autoupload'] = function () {
  7472. var me = this;
  7473. me.setOpt('pasteImageEnabled', true);
  7474. me.setOpt('dropFileEnabled', true);
  7475. var sendAndInsertImage = function (file, editor) {
  7476. //模拟数据
  7477. var fd = new FormData();
  7478. fd.append(editor.options.imageFieldName || 'upfile', file, file.name || ('blob.' + file.type.substr('image/'.length)));
  7479. fd.append('type', 'ajax');
  7480. var xhr = new XMLHttpRequest();
  7481. xhr.open("post", me.options.imageUrl, true);
  7482. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  7483. xhr.addEventListener('load', function (e) {
  7484. try {
  7485. var json = eval('('+e.target.response+')'),
  7486. link = json.url,
  7487. picLink = me.options.imagePath + link;
  7488. editor.execCommand('insertimage', {
  7489. src: picLink,
  7490. _src: picLink
  7491. });
  7492. } catch (er) {
  7493. }
  7494. });
  7495. xhr.send(fd);
  7496. };
  7497. function getPasteImage(e) {
  7498. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items : null;
  7499. }
  7500. function getDropImage(e) {
  7501. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : null;
  7502. }
  7503. me.addListener('ready', function () {
  7504. if (window.FormData && window.FileReader) {
  7505. var autoUploadHandler = function (e) {
  7506. var hasImg = false,
  7507. items;
  7508. //获取粘贴板文件列表或者拖放文件列表
  7509. items = e.type == 'paste' ? getPasteImage(e.originalEvent) : getDropImage(e.originalEvent);
  7510. if (items) {
  7511. var len = items.length,
  7512. file;
  7513. while (len--) {
  7514. file = items[len];
  7515. if (file.getAsFile) file = file.getAsFile();
  7516. if (file && file.size > 0 && /image\/\w+/i.test(file.type)) {
  7517. sendAndInsertImage(file, me);
  7518. hasImg = true;
  7519. }
  7520. }
  7521. if (hasImg) return false;
  7522. }
  7523. };
  7524. me.getOpt('pasteImageEnabled') && me.$body.on('paste', autoUploadHandler);
  7525. me.getOpt('dropFileEnabled') && me.$body.on('drop', autoUploadHandler);
  7526. //取消拖放图片时出现的文字光标位置提示
  7527. me.$body.on('dragover', function (e) {
  7528. if (e.originalEvent.dataTransfer.types[0] == 'Files') {
  7529. return false;
  7530. }
  7531. });
  7532. }
  7533. });
  7534. };
  7535. /**
  7536. * 公式插件
  7537. */
  7538. UM.plugins['formula'] = function () {
  7539. var me = this;
  7540. function getActiveIframe() {
  7541. return me.$body.find('iframe.edui-formula-active')[0] || null;
  7542. }
  7543. function blurActiveIframe(){
  7544. var iframe = getActiveIframe();
  7545. iframe && iframe.contentWindow.formula.blur();
  7546. }
  7547. me.addInputRule(function (root) {
  7548. $.each(root.getNodesByTagName('span'), function (i, node) {
  7549. if (node.hasClass('mathquill-embedded-latex')) {
  7550. var firstChild, latex = '';
  7551. while(firstChild = node.firstChild()){
  7552. latex += firstChild.data;
  7553. node.removeChild(firstChild);
  7554. }
  7555. node.tagName = 'iframe';
  7556. node.setAttr({
  7557. 'frameborder': '0',
  7558. 'src': me.getOpt('UMEDITOR_HOME_URL') + 'dialogs/formula/formula.html',
  7559. 'data-latex': utils.unhtml(latex)
  7560. });
  7561. }
  7562. });
  7563. });
  7564. me.addOutputRule(function (root) {
  7565. $.each(root.getNodesByTagName('iframe'), function (i, node) {
  7566. if (node.hasClass('mathquill-embedded-latex')) {
  7567. node.tagName = 'span';
  7568. node.appendChild(UM.uNode.createText(node.getAttr('data-latex')));
  7569. node.setAttr({
  7570. 'frameborder': '',
  7571. 'src': '',
  7572. 'data-latex': ''
  7573. });
  7574. }
  7575. });
  7576. });
  7577. me.addListener('click', function(){
  7578. blurActiveIframe();
  7579. });
  7580. me.addListener('afterexeccommand', function(type, cmd){
  7581. if(cmd != 'formula') {
  7582. blurActiveIframe();
  7583. }
  7584. });
  7585. me.commands['formula'] = {
  7586. execCommand: function (cmd, latex) {
  7587. var iframe = getActiveIframe();
  7588. if (iframe) {
  7589. iframe.contentWindow.formula.insertLatex(latex);
  7590. } else {
  7591. me.execCommand('inserthtml', '<span class="mathquill-embedded-latex">' + latex + '</span>');
  7592. browser.ie && browser.ie9below && setTimeout(function(){
  7593. var rng = me.selection.getRange(),
  7594. startContainer = rng.startContainer;
  7595. if(startContainer.nodeType == 1 && !startContainer.childNodes[rng.startOffset]){
  7596. rng.insertNode(me.document.createTextNode(' '));
  7597. rng.setCursor()
  7598. }
  7599. },100)
  7600. }
  7601. },
  7602. queryCommandState: function (cmd) {
  7603. return 0;
  7604. },
  7605. queryCommandValue: function (cmd) {
  7606. var iframe = getActiveIframe();
  7607. return iframe && iframe.contentWindow.formula.getLatex();
  7608. }
  7609. }
  7610. };
  7611. (function ($) {
  7612. //对jquery的扩展
  7613. $.parseTmpl = function parse(str, data) {
  7614. 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) {
  7615. return "'," + code.replace(/\\'/g, "'") + ",'";
  7616. }).replace(/<%([\s\S]+?)%>/g,function (match, code) {
  7617. return "');" + code.replace(/\\'/g, "'").replace(/[\r\n\t]/g, ' ') + "__p.push('";
  7618. }).replace(/\r/g, '\\r').replace(/\n/g, '\\n').replace(/\t/g, '\\t') + "');}return __p.join('');";
  7619. var func = new Function('obj', tmpl);
  7620. return data ? func(data) : func;
  7621. };
  7622. $.extend2 = function (t, s) {
  7623. var a = arguments,
  7624. notCover = $.type(a[a.length - 1]) == 'boolean' ? a[a.length - 1] : false,
  7625. len = $.type(a[a.length - 1]) == 'boolean' ? a.length - 1 : a.length;
  7626. for (var i = 1; i < len; i++) {
  7627. var x = a[i];
  7628. for (var k in x) {
  7629. if (!notCover || !t.hasOwnProperty(k)) {
  7630. t[k] = x[k];
  7631. }
  7632. }
  7633. }
  7634. return t;
  7635. };
  7636. $.IE6 = !!window.ActiveXObject && parseFloat(navigator.userAgent.match(/msie (\d+)/i)[1]) == 6;
  7637. //所有ui的基类
  7638. var _eventHandler = [];
  7639. var _widget = function () {
  7640. };
  7641. var _prefix = 'edui';
  7642. _widget.prototype = {
  7643. on: function (ev, cb) {
  7644. this.root().on(ev, $.proxy(cb, this));
  7645. return this;
  7646. },
  7647. off: function (ev, cb) {
  7648. this.root().off(ev, $.proxy(cb, this));
  7649. return this;
  7650. },
  7651. trigger: function (ev, data) {
  7652. return this.root().trigger(ev, data) === false ? false : this;
  7653. },
  7654. root: function ($el) {
  7655. return this._$el || (this._$el = $el);
  7656. },
  7657. destroy: function () {
  7658. },
  7659. data: function (key, val) {
  7660. if (val !== undefined) {
  7661. this.root().data(_prefix + key, val);
  7662. return this;
  7663. } else {
  7664. return this.root().data(_prefix + key)
  7665. }
  7666. },
  7667. register: function (eventName, $el, fn) {
  7668. _eventHandler.push({
  7669. 'evtname': eventName,
  7670. '$els': $.isArray($el) ? $el : [$el],
  7671. handler: $.proxy(fn, $el)
  7672. })
  7673. }
  7674. };
  7675. //从jq实例上拿到绑定的widget实例
  7676. $.fn.edui = function (obj) {
  7677. return obj ? this.data('eduiwidget', obj) : this.data('eduiwidget');
  7678. };
  7679. function _createClass(ClassObj, properties, supperClass) {
  7680. ClassObj.prototype = $.extend2(
  7681. $.extend({}, properties),
  7682. (UM.ui[supperClass] || _widget).prototype,
  7683. true
  7684. );
  7685. ClassObj.prototype.supper = (UM.ui[supperClass] || _widget).prototype;
  7686. //父class的defaultOpt 合并
  7687. if( UM.ui[supperClass] && UM.ui[supperClass].prototype.defaultOpt ) {
  7688. var parentDefaultOptions = UM.ui[supperClass].prototype.defaultOpt,
  7689. subDefaultOptions = ClassObj.prototype.defaultOpt;
  7690. ClassObj.prototype.defaultOpt = $.extend( {}, parentDefaultOptions, subDefaultOptions || {} );
  7691. }
  7692. return ClassObj
  7693. }
  7694. var _guid = 1;
  7695. function mergeToJQ(ClassObj, className) {
  7696. $[_prefix + className] = ClassObj;
  7697. $.fn[_prefix + className] = function (opt) {
  7698. var result, args = Array.prototype.slice.call(arguments, 1);
  7699. this.each(function (i, el) {
  7700. var $this = $(el);
  7701. var obj = $this.edui();
  7702. if (!obj) {
  7703. ClassObj(!opt || !$.isPlainObject(opt) ? {} : opt, $this);
  7704. $this.edui(obj)
  7705. }
  7706. if ($.type(opt) == 'string') {
  7707. if (opt == 'this') {
  7708. result = obj;
  7709. } else {
  7710. result = obj[opt].apply(obj, args);
  7711. if (result !== obj && result !== undefined) {
  7712. return false;
  7713. }
  7714. result = null;
  7715. }
  7716. }
  7717. });
  7718. return result !== null ? result : this;
  7719. }
  7720. }
  7721. UM.ui = {
  7722. define: function (className, properties, supperClass) {
  7723. var ClassObj = UM.ui[className] = _createClass(function (options, $el) {
  7724. var _obj = function () {
  7725. };
  7726. $.extend(_obj.prototype, ClassObj.prototype, {
  7727. guid: className + _guid++,
  7728. widgetName: className
  7729. }
  7730. );
  7731. var obj = new _obj;
  7732. if ($.type(options) == 'string') {
  7733. obj.init && obj.init({});
  7734. obj.root().edui(obj);
  7735. obj.root().find('a').click(function (evt) {
  7736. evt.preventDefault()
  7737. });
  7738. return obj.root()[_prefix + className].apply(obj.root(), arguments)
  7739. } else {
  7740. $el && obj.root($el);
  7741. obj.init && obj.init(!options || $.isPlainObject(options) ? $.extend2(options || {}, obj.defaultOpt || {}, true) : options);
  7742. try{
  7743. obj.root().find('a').click(function (evt) {
  7744. evt.preventDefault()
  7745. });
  7746. }catch(e){
  7747. }
  7748. return obj.root().edui(obj);
  7749. }
  7750. },properties, supperClass);
  7751. mergeToJQ(ClassObj, className);
  7752. }
  7753. };
  7754. $(function () {
  7755. $(document).on('click mouseup mousedown dblclick mouseover', function (evt) {
  7756. $.each(_eventHandler, function (i, obj) {
  7757. if (obj.evtname == evt.type) {
  7758. $.each(obj.$els, function (i, $el) {
  7759. if ($el[0] !== evt.target && !$.contains($el[0], evt.target)) {
  7760. obj.handler(evt);
  7761. }
  7762. })
  7763. }
  7764. })
  7765. })
  7766. })
  7767. })(jQuery);
  7768. //button 类
  7769. UM.ui.define('button', {
  7770. 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%>" <%};%>> ' +
  7771. '<% 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><%}%>' +
  7772. '<%if(caret && text){%><span class="edui-button-spacing"></span><%}%>' +
  7773. '<% if(caret) {%><span unselectable="on" onmousedown="return false" class="edui-caret"></span><% };%></<%if(!texttype){%>div<%}else{%>a<%}%>>',
  7774. defaultOpt: {
  7775. text: '',
  7776. title: '',
  7777. icon: '',
  7778. width: '',
  7779. caret: false,
  7780. texttype: false,
  7781. click: function () {
  7782. }
  7783. },
  7784. init: function (options) {
  7785. var me = this;
  7786. me.root($($.parseTmpl(me.tpl, options)))
  7787. .click(function (evt) {
  7788. me.wrapclick(options.click, evt)
  7789. });
  7790. me.root().hover(function () {
  7791. if(!me.root().hasClass("edui-disabled")){
  7792. me.root().toggleClass('edui-hover')
  7793. }
  7794. })
  7795. return me;
  7796. },
  7797. wrapclick: function (fn, evt) {
  7798. if (!this.disabled()) {
  7799. this.root().trigger('wrapclick');
  7800. $.proxy(fn, this, evt)()
  7801. }
  7802. return this;
  7803. },
  7804. label: function (text) {
  7805. if (text === undefined) {
  7806. return this.root().find('.edui-button-label').text();
  7807. } else {
  7808. this.root().find('.edui-button-label').text(text);
  7809. return this;
  7810. }
  7811. },
  7812. disabled: function (state) {
  7813. if (state === undefined) {
  7814. return this.root().hasClass('edui-disabled')
  7815. }
  7816. this.root().toggleClass('edui-disabled', state);
  7817. if(this.root().hasClass('edui-disabled')){
  7818. this.root().removeClass('edui-hover')
  7819. }
  7820. return this;
  7821. },
  7822. active: function (state) {
  7823. if (state === undefined) {
  7824. return this.root().hasClass('edui-active')
  7825. }
  7826. this.root().toggleClass('edui-active', state)
  7827. return this;
  7828. },
  7829. mergeWith: function ($obj) {
  7830. var me = this;
  7831. me.data('$mergeObj', $obj);
  7832. $obj.edui().data('$mergeObj', me.root());
  7833. if (!$.contains(document.body, $obj[0])) {
  7834. $obj.appendTo(me.root());
  7835. }
  7836. me.on('click',function () {
  7837. me.wrapclick(function () {
  7838. $obj.edui().show();
  7839. })
  7840. }).register('click', me.root(), function (evt) {
  7841. $obj.hide()
  7842. });
  7843. }
  7844. });
  7845. //toolbar 类
  7846. (function () {
  7847. UM.ui.define('toolbar', {
  7848. tpl: '<div class="edui-toolbar" ><div class="edui-btn-toolbar" unselectable="on" onmousedown="return false" ></div></div>'
  7849. ,
  7850. init: function () {
  7851. var $root = this.root($(this.tpl));
  7852. this.data('$btnToolbar', $root.find('.edui-btn-toolbar'))
  7853. },
  7854. appendToBtnmenu : function(data){
  7855. var $cont = this.data('$btnToolbar');
  7856. data = $.isArray(data) ? data : [data];
  7857. $.each(data,function(i,$item){
  7858. $cont.append($item)
  7859. })
  7860. }
  7861. });
  7862. })();
  7863. //menu 类
  7864. UM.ui.define('menu',{
  7865. show : function($obj,dir,fnname,topOffset,leftOffset){
  7866. fnname = fnname || 'position';
  7867. if(this.trigger('beforeshow') === false){
  7868. return;
  7869. }else{
  7870. this.root().css($.extend({display:'block'},$obj ? {
  7871. top : $obj[fnname]().top + ( dir == 'right' ? 0 : $obj.outerHeight()) - (topOffset || 0),
  7872. left : $obj[fnname]().left + (dir == 'right' ? $obj.outerWidth() : 0) - (leftOffset || 0)
  7873. }:{}))
  7874. this.trigger('aftershow');
  7875. }
  7876. },
  7877. hide : function(all){
  7878. var $parentmenu;
  7879. if(this.trigger('beforehide') === false){
  7880. return;
  7881. } else {
  7882. if($parentmenu = this.root().data('parentmenu')){
  7883. if($parentmenu.data('parentmenu')|| all)
  7884. $parentmenu.edui().hide();
  7885. }
  7886. this.root().css('display','none');
  7887. this.trigger('afterhide');
  7888. }
  7889. },
  7890. attachTo : function($obj){
  7891. var me = this;
  7892. if(!$obj.data('$mergeObj')){
  7893. $obj.data('$mergeObj',me.root());
  7894. $obj.on('wrapclick',function(evt){
  7895. me.show()
  7896. });
  7897. me.register('click',$obj,function(evt){
  7898. me.hide()
  7899. });
  7900. me.data('$mergeObj',$obj)
  7901. }
  7902. }
  7903. });
  7904. //dropmenu 类
  7905. UM.ui.define('dropmenu', {
  7906. tmpl: '<ul class="edui-dropdown-menu" aria-labelledby="dropdownMenu" >' +
  7907. '<%for(var i=0,ci;ci=data[i++];){%>' +
  7908. '<%if(ci.divider){%><li class="edui-divider"></li><%}else{%>' +
  7909. '<li <%if(ci.active||ci.disabled){%>class="<%= ci.active|| \'\' %> <%=ci.disabled||\'\' %>" <%}%> data-value="<%= ci.value%>">' +
  7910. '<a href="#" tabindex="-1"><em class="edui-dropmenu-checkbox"><i class="edui-icon-ok"></i></em><%= ci.label%></a>' +
  7911. '</li><%}%>' +
  7912. '<%}%>' +
  7913. '</ul>',
  7914. defaultOpt: {
  7915. data: [],
  7916. click: function () {
  7917. }
  7918. },
  7919. init: function (options) {
  7920. var me = this;
  7921. var eventName = {
  7922. click: 1,
  7923. mouseover: 1,
  7924. mouseout: 1
  7925. };
  7926. this.root($($.parseTmpl(this.tmpl, options))).on('click', 'li[class!="edui-disabled edui-divider edui-dropdown-submenu"]',function (evt) {
  7927. $.proxy(options.click, me, evt, $(this).data('value'), $(this))()
  7928. }).find('li').each(function (i, el) {
  7929. var $this = $(this);
  7930. if (!$this.hasClass("edui-disabled edui-divider edui-dropdown-submenu")) {
  7931. var data = options.data[i];
  7932. $.each(eventName, function (k) {
  7933. data[k] && $this[k](function (evt) {
  7934. $.proxy(data[k], el)(evt, data, me.root)
  7935. })
  7936. })
  7937. }
  7938. })
  7939. },
  7940. disabled: function (cb) {
  7941. $('li[class!=edui-divider]', this.root()).each(function () {
  7942. var $el = $(this);
  7943. if (cb === true) {
  7944. $el.addClass('edui-disabled')
  7945. } else if ($.isFunction(cb)) {
  7946. $el.toggleClass('edui-disabled', cb(li))
  7947. } else {
  7948. $el.removeClass('edui-disabled')
  7949. }
  7950. });
  7951. },
  7952. val: function (val) {
  7953. var currentVal;
  7954. $('li[class!="edui-divider edui-disabled edui-dropdown-submenu"]', this.root()).each(function () {
  7955. var $el = $(this);
  7956. if (val === undefined) {
  7957. if ($el.find('em.edui-dropmenu-checked').length) {
  7958. currentVal = $el.data('value');
  7959. return false
  7960. }
  7961. } else {
  7962. $el.find('em').toggleClass('edui-dropmenu-checked', $el.data('value') == val)
  7963. }
  7964. });
  7965. if (val === undefined) {
  7966. return currentVal
  7967. }
  7968. },
  7969. addSubmenu: function (label, menu, index) {
  7970. index = index || 0;
  7971. var $list = $('li[class!=edui-divider]', this.root());
  7972. var $node = $('<li class="edui-dropdown-submenu"><a tabindex="-1" href="#">' + label + '</a></li>').append(menu);
  7973. if (index >= 0 && index < $list.length) {
  7974. $node.insertBefore($list[index]);
  7975. } else if (index < 0) {
  7976. $node.insertBefore($list[0]);
  7977. } else if (index >= $list.length) {
  7978. $node.appendTo($list);
  7979. }
  7980. }
  7981. }, 'menu');
  7982. //splitbutton 类
  7983. ///import button
  7984. UM.ui.define('splitbutton',{
  7985. 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>'+
  7986. '<div unselectable="on" class="edui-btn edui-dropdown-toggle" >'+
  7987. '<div unselectable="on" class="edui-caret"><\/div>'+
  7988. '</div>'+
  7989. '</div>',
  7990. defaultOpt:{
  7991. text:'',
  7992. title:'',
  7993. click:function(){}
  7994. },
  7995. init : function(options){
  7996. var me = this;
  7997. me.root( $($.parseTmpl(me.tpl,options)));
  7998. me.root().find('.edui-btn:first').click(function(evt){
  7999. if(!me.disabled()){
  8000. $.proxy(options.click,me)();
  8001. }
  8002. });
  8003. me.root().find('.edui-dropdown-toggle').click(function(){
  8004. if(!me.disabled()){
  8005. me.trigger('arrowclick')
  8006. }
  8007. });
  8008. me.root().hover(function () {
  8009. if(!me.root().hasClass("edui-disabled")){
  8010. me.root().toggleClass('edui-hover')
  8011. }
  8012. });
  8013. return me;
  8014. },
  8015. wrapclick:function(fn,evt){
  8016. if(!this.disabled()){
  8017. $.proxy(fn,this,evt)()
  8018. }
  8019. return this;
  8020. },
  8021. disabled : function(state){
  8022. if(state === undefined){
  8023. return this.root().hasClass('edui-disabled')
  8024. }
  8025. this.root().toggleClass('edui-disabled',state).find('.edui-btn').toggleClass('edui-disabled',state);
  8026. return this;
  8027. },
  8028. active:function(state){
  8029. if(state === undefined){
  8030. return this.root().hasClass('edui-active')
  8031. }
  8032. this.root().toggleClass('edui-active',state).find('.edui-btn:first').toggleClass('edui-active',state);
  8033. return this;
  8034. },
  8035. mergeWith:function($obj){
  8036. var me = this;
  8037. me.data('$mergeObj',$obj);
  8038. $obj.edui().data('$mergeObj',me.root());
  8039. if(!$.contains(document.body,$obj[0])){
  8040. $obj.appendTo(me.root());
  8041. }
  8042. me.root().delegate('.edui-dropdown-toggle','click',function(){
  8043. me.wrapclick(function(){
  8044. $obj.edui().show();
  8045. })
  8046. });
  8047. me.register('click',me.root().find('.edui-dropdown-toggle'),function(evt){
  8048. $obj.hide()
  8049. });
  8050. }
  8051. });
  8052. /**
  8053. * Created with JetBrains PhpStorm.
  8054. * User: hn
  8055. * Date: 13-7-10
  8056. * Time: 下午3:07
  8057. * To change this template use File | Settings | File Templates.
  8058. */
  8059. UM.ui.define('colorsplitbutton',{
  8060. 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>'+
  8061. '<div unselectable="on" class="edui-btn edui-dropdown-toggle" >'+
  8062. '<div unselectable="on" class="edui-caret"><\/div>'+
  8063. '</div>'+
  8064. '</div>',
  8065. defaultOpt: {
  8066. color: ''
  8067. },
  8068. init: function( options ){
  8069. var me = this;
  8070. me.supper.init.call( me, options );
  8071. },
  8072. colorLabel: function(){
  8073. return this.root().find('.edui-splitbutton-color-label');
  8074. }
  8075. }, 'splitbutton');
  8076. //popup 类
  8077. UM.ui.define('popup', {
  8078. tpl: '<div class="edui-dropdown-menu edui-popup"'+
  8079. '<%if(!<%=stopprop%>){%>onmousedown="return false"<%}%>'+
  8080. '><div class="edui-popup-body" unselectable="on" onmousedown="return false"><%=subtpl%></div>' +
  8081. '<div class="edui-popup-caret"></div>' +
  8082. '</div>',
  8083. defaultOpt: {
  8084. stopprop:false,
  8085. subtpl: '',
  8086. width: '',
  8087. height: ''
  8088. },
  8089. init: function (options) {
  8090. this.root($($.parseTmpl(this.tpl, options)));
  8091. return this;
  8092. },
  8093. mergeTpl: function (data) {
  8094. return $.parseTmpl(this.tpl, {subtpl: data});
  8095. },
  8096. show: function ($obj, posObj) {
  8097. if (!posObj) posObj = {};
  8098. var fnname = posObj.fnname || 'position';
  8099. if (this.trigger('beforeshow') === false) {
  8100. return;
  8101. } else {
  8102. this.root().css($.extend({display: 'block'}, $obj ? {
  8103. top: $obj[fnname]().top + ( posObj.dir == 'right' ? 0 : $obj.outerHeight()) - (posObj.offsetTop || 0),
  8104. left: $obj[fnname]().left + (posObj.dir == 'right' ? $obj.outerWidth() : 0) - (posObj.offsetLeft || 0),
  8105. position: 'absolute'
  8106. } : {}));
  8107. this.root().find('.edui-popup-caret').css({
  8108. top: posObj.caretTop || 0,
  8109. left: posObj.caretLeft || 0,
  8110. position: 'absolute'
  8111. }).addClass(posObj.caretDir || "up")
  8112. }
  8113. this.trigger("aftershow");
  8114. },
  8115. hide: function () {
  8116. this.root().css('display', 'none');
  8117. this.trigger('afterhide')
  8118. },
  8119. attachTo: function ($obj, posObj) {
  8120. var me = this
  8121. if (!$obj.data('$mergeObj')) {
  8122. $obj.data('$mergeObj', me.root());
  8123. $obj.on('wrapclick', function (evt) {
  8124. me.show($obj, posObj)
  8125. });
  8126. me.register('click', $obj, function (evt) {
  8127. me.hide()
  8128. });
  8129. me.data('$mergeObj', $obj)
  8130. }
  8131. },
  8132. getBodyContainer: function () {
  8133. return this.root().find(".edui-popup-body");
  8134. }
  8135. });
  8136. //scale 类
  8137. UM.ui.define('scale', {
  8138. tpl: '<div class="edui-scale" unselectable="on">' +
  8139. '<span class="edui-scale-hand0"></span>' +
  8140. '<span class="edui-scale-hand1"></span>' +
  8141. '<span class="edui-scale-hand2"></span>' +
  8142. '<span class="edui-scale-hand3"></span>' +
  8143. '<span class="edui-scale-hand4"></span>' +
  8144. '<span class="edui-scale-hand5"></span>' +
  8145. '<span class="edui-scale-hand6"></span>' +
  8146. '<span class="edui-scale-hand7"></span>' +
  8147. '</div>',
  8148. defaultOpt: {
  8149. $doc: $(document),
  8150. $wrap: $(document)
  8151. },
  8152. init: function (options) {
  8153. if(options.$doc) this.defaultOpt.$doc = options.$doc;
  8154. if(options.$wrap) this.defaultOpt.$wrap = options.$wrap;
  8155. this.root($($.parseTmpl(this.tpl, options)));
  8156. this.initStyle();
  8157. this.startPos = this.prePos = {x: 0, y: 0};
  8158. this.dragId = -1;
  8159. return this;
  8160. },
  8161. initStyle: function () {
  8162. utils.cssRule('edui-style-scale', '.edui-scale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;}' +
  8163. '.edui-scale span{position:absolute;left:0;top:0;width:7px;height:7px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  8164. + '.edui-scale .edui-scale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  8165. + '.edui-scale .edui-scale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  8166. + '.edui-scale .edui-scale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  8167. + '.edui-scale .edui-scale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  8168. + '.edui-scale .edui-scale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  8169. + '.edui-scale .edui-scale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  8170. + '.edui-scale .edui-scale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  8171. + '.edui-scale .edui-scale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  8172. },
  8173. _eventHandler: function (e) {
  8174. var me = this,
  8175. $doc = me.defaultOpt.$doc;
  8176. switch (e.type) {
  8177. case 'mousedown':
  8178. var hand = e.target || e.srcElement, hand;
  8179. if (hand.className.indexOf('edui-scale-hand') != -1) {
  8180. me.dragId = hand.className.slice(-1);
  8181. me.startPos.x = me.prePos.x = e.clientX;
  8182. me.startPos.y = me.prePos.y = e.clientY;
  8183. $doc.bind('mousemove', $.proxy(me._eventHandler, me));
  8184. }
  8185. break;
  8186. case 'mousemove':
  8187. if (me.dragId != -1) {
  8188. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  8189. me.prePos.x = e.clientX;
  8190. me.prePos.y = e.clientY;
  8191. me.updateTargetElement();
  8192. }
  8193. break;
  8194. case 'mouseup':
  8195. if (me.dragId != -1) {
  8196. me.dragId = -1;
  8197. me.updateTargetElement();
  8198. var $target = me.data('$scaleTarget');
  8199. if ($target.parent()) me.attachTo(me.data('$scaleTarget'));
  8200. }
  8201. $doc.unbind('mousemove', $.proxy(me._eventHandler, me));
  8202. break;
  8203. default:
  8204. break;
  8205. }
  8206. },
  8207. updateTargetElement: function () {
  8208. var me = this,
  8209. $root = me.root(),
  8210. $target = me.data('$scaleTarget');
  8211. $target.css({width: $root.width(), height: $root.height()});
  8212. me.attachTo($target);
  8213. },
  8214. updateContainerStyle: function (dir, offset) {
  8215. var me = this,
  8216. $dom = me.root(),
  8217. tmp,
  8218. rect = [
  8219. //[left, top, width, height]
  8220. [0, 0, -1, -1],
  8221. [0, 0, 0, -1],
  8222. [0, 0, 1, -1],
  8223. [0, 0, -1, 0],
  8224. [0, 0, 1, 0],
  8225. [0, 0, -1, 1],
  8226. [0, 0, 0, 1],
  8227. [0, 0, 1, 1]
  8228. ];
  8229. if (rect[dir][0] != 0) {
  8230. tmp = parseInt($dom.offset().left) + offset.x;
  8231. $dom.css('left', me._validScaledProp('left', tmp));
  8232. }
  8233. if (rect[dir][1] != 0) {
  8234. tmp = parseInt($dom.offset().top) + offset.y;
  8235. $dom.css('top', me._validScaledProp('top', tmp));
  8236. }
  8237. if (rect[dir][2] != 0) {
  8238. tmp = $dom.width() + rect[dir][2] * offset.x;
  8239. $dom.css('width', me._validScaledProp('width', tmp));
  8240. }
  8241. if (rect[dir][3] != 0) {
  8242. tmp = $dom.height() + rect[dir][3] * offset.y;
  8243. $dom.css('height', me._validScaledProp('height', tmp));
  8244. }
  8245. },
  8246. _validScaledProp: function (prop, value) {
  8247. var $ele = this.root(),
  8248. $wrap = this.defaultOpt.$doc,
  8249. calc = function(val, a, b){
  8250. return (val + a) > b ? b - a : value;
  8251. };
  8252. value = isNaN(value) ? 0 : value;
  8253. switch (prop) {
  8254. case 'left':
  8255. return value < 0 ? 0 : calc(value, $ele.width(), $wrap.width());
  8256. case 'top':
  8257. return value < 0 ? 0 : calc(value, $ele.height(),$wrap.height());
  8258. case 'width':
  8259. return value <= 0 ? 1 : calc(value, $ele.offset().left, $wrap.width());
  8260. case 'height':
  8261. return value <= 0 ? 1 : calc(value, $ele.offset().top, $wrap.height());
  8262. }
  8263. },
  8264. show: function ($obj) {
  8265. var me = this;
  8266. if ($obj) me.attachTo($obj);
  8267. me.root().bind('mousedown', $.proxy(me._eventHandler, me));
  8268. me.defaultOpt.$doc.bind('mouseup', $.proxy(me._eventHandler, me));
  8269. me.root().show();
  8270. me.trigger("aftershow");
  8271. },
  8272. hide: function () {
  8273. var me = this;
  8274. me.root().unbind('mousedown', $.proxy(me._eventHandler, me));
  8275. me.defaultOpt.$doc.unbind('mouseup', $.proxy(me._eventHandler, me));
  8276. me.root().hide();
  8277. me.trigger('afterhide')
  8278. },
  8279. attachTo: function ($obj) {
  8280. var me = this,
  8281. imgPos = $obj.offset(),
  8282. $root = me.root(),
  8283. $wrap = me.defaultOpt.$wrap,
  8284. posObj = $wrap.offset();
  8285. me.data('$scaleTarget', $obj);
  8286. me.root().css({
  8287. position: 'absolute',
  8288. width: $obj.width(),
  8289. height: $obj.height(),
  8290. left: imgPos.left - posObj.left - parseInt($wrap.css('border-left-width')) - parseInt($root.css('border-left-width')),
  8291. top: imgPos.top - posObj.top - parseInt($wrap.css('border-top-width')) - parseInt($root.css('border-top-width'))
  8292. });
  8293. },
  8294. getScaleTarget: function () {
  8295. return this.data('$scaleTarget')[0];
  8296. }
  8297. });
  8298. //colorpicker 类
  8299. UM.ui.define('colorpicker', {
  8300. tpl: function (opt) {
  8301. var COLORS = (
  8302. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  8303. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  8304. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  8305. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  8306. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  8307. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  8308. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  8309. var html = '<div unselectable="on" onmousedown="return false" class="edui-colorpicker<%if (name){%> edui-colorpicker-<%=name%><%}%>" >' +
  8310. '<table unselectable="on" onmousedown="return false">' +
  8311. '<tr><td colspan="10">'+opt.lang_themeColor+'</td> </tr>' +
  8312. '<tr class="edui-colorpicker-firstrow" >';
  8313. for (var i = 0; i < COLORS.length; i++) {
  8314. if (i && i % 10 === 0) {
  8315. html += '</tr>' + (i == 60 ? '<tr><td colspan="10">'+opt.lang_standardColor+'</td></tr>' : '') + '<tr' + (i == 60 ? ' class="edui-colorpicker-firstrow"' : '') + '>';
  8316. }
  8317. html += i < 70 ? '<td><a unselectable="on" onmousedown="return false" title="' + COLORS[i] + '" class="edui-colorpicker-colorcell"' +
  8318. ' data-color="#' + COLORS[i] + '"' +
  8319. ' style="background-color:#' + COLORS[i] + ';border:solid #ccc;' +
  8320. (i < 10 || i >= 60 ? 'border-width:1px;' :
  8321. i >= 10 && i < 20 ? 'border-width:1px 1px 0 1px;' :
  8322. 'border-width:0 1px 0 1px;') +
  8323. '"' +
  8324. '></a></td>' : '';
  8325. }
  8326. html += '</tr></table></div>';
  8327. return html;
  8328. },
  8329. init: function (options) {
  8330. var me = this;
  8331. me.root($($.parseTmpl(me.supper.mergeTpl(me.tpl(options)),options)));
  8332. me.root().on("click",function (e) {
  8333. me.trigger('pickcolor', $(e.target).data('color'));
  8334. });
  8335. }
  8336. }, 'popup');
  8337. /**
  8338. * Created with JetBrains PhpStorm.
  8339. * User: hn
  8340. * Date: 13-5-29
  8341. * Time: 下午8:01
  8342. * To change this template use File | Settings | File Templates.
  8343. */
  8344. (function(){
  8345. var widgetName = 'combobox',
  8346. itemClassName = 'edui-combobox-item',
  8347. HOVER_CLASS = 'edui-combobox-item-hover',
  8348. ICON_CLASS = 'edui-combobox-checked-icon',
  8349. labelClassName = 'edui-combobox-item-label';
  8350. UM.ui.define( widgetName, ( function(){
  8351. return {
  8352. tpl: "<ul class=\"dropdown-menu edui-combobox-menu<%if (comboboxName!=='') {%> edui-combobox-<%=comboboxName%><%}%>\" unselectable=\"on\" onmousedown=\"return false\" role=\"menu\" aria-labelledby=\"dropdownMenu\">" +
  8353. "<%if(autoRecord) {%>" +
  8354. "<%for( var i=0, len = recordStack.length; i<len; i++ ) {%>" +
  8355. "<%var index = recordStack[i];%>" +
  8356. "<li class=\"<%=itemClassName%><%if( selected == index ) {%> edui-combobox-checked<%}%>\" data-item-index=\"<%=index%>\" unselectable=\"on\" onmousedown=\"return false\">" +
  8357. "<span class=\"edui-combobox-icon\" unselectable=\"on\" onmousedown=\"return false\"></span>" +
  8358. "<label class=\"<%=labelClassName%>\" style=\"<%=itemStyles[ index ]%>\" unselectable=\"on\" onmousedown=\"return false\"><%=items[index]%></label>" +
  8359. "</li>" +
  8360. "<%}%>" +
  8361. "<%if( i ) {%>" +
  8362. "<li class=\"edui-combobox-item-separator\"></li>" +
  8363. "<%}%>" +
  8364. "<%}%>" +
  8365. "<%for( var i=0, label; label = items[i]; i++ ) {%>" +
  8366. "<li class=\"<%=itemClassName%><%if( selected == i ) {%> edui-combobox-checked<%}%> edui-combobox-item-<%=i%>\" data-item-index=\"<%=i%>\" unselectable=\"on\" onmousedown=\"return false\">" +
  8367. "<span class=\"edui-combobox-icon\" unselectable=\"on\" onmousedown=\"return false\"></span>" +
  8368. "<label class=\"<%=labelClassName%>\" style=\"<%=itemStyles[ i ]%>\" unselectable=\"on\" onmousedown=\"return false\"><%=label%></label>" +
  8369. "</li>" +
  8370. "<%}%>" +
  8371. "</ul>",
  8372. defaultOpt: {
  8373. //记录栈初始列表
  8374. recordStack: [],
  8375. //可用项列表
  8376. items: [],
  8377. //item对应的值列表
  8378. value: [],
  8379. comboboxName: '',
  8380. selected: '',
  8381. //自动记录
  8382. autoRecord: true,
  8383. //最多记录条数
  8384. recordCount: 5
  8385. },
  8386. init: function( options ){
  8387. var me = this;
  8388. $.extend( me._optionAdaptation( options ), me._createItemMapping( options.recordStack, options.items ), {
  8389. itemClassName: itemClassName,
  8390. iconClass: ICON_CLASS,
  8391. labelClassName: labelClassName
  8392. } );
  8393. this._transStack( options );
  8394. me.root( $( $.parseTmpl( me.tpl, options ) ) );
  8395. this.data( 'options', options ).initEvent();
  8396. },
  8397. initEvent: function(){
  8398. var me = this;
  8399. me.initSelectItem();
  8400. this.initItemActive();
  8401. },
  8402. /**
  8403. * 初始化选择项
  8404. */
  8405. initSelectItem: function(){
  8406. var me = this,
  8407. labelClass = "."+labelClassName;
  8408. me.root().delegate('.' + itemClassName, 'click', function(){
  8409. var $li = $(this),
  8410. index = $li.attr('data-item-index');
  8411. me.trigger('comboboxselect', {
  8412. index: index,
  8413. label: $li.find(labelClass).text(),
  8414. value: me.data('options').value[ index ]
  8415. }).select( index );
  8416. me.hide();
  8417. return false;
  8418. });
  8419. },
  8420. initItemActive: function(){
  8421. var fn = {
  8422. mouseenter: 'addClass',
  8423. mouseleave: 'removeClass'
  8424. };
  8425. if ($.IE6) {
  8426. this.root().delegate( '.'+itemClassName, 'mouseenter mouseleave', function( evt ){
  8427. $(this)[ fn[ evt.type ] ]( HOVER_CLASS );
  8428. }).one('afterhide', function(){
  8429. });
  8430. }
  8431. },
  8432. /**
  8433. * 选择给定索引的项
  8434. * @param index 项索引
  8435. * @returns {*} 如果存在对应索引的项,则返回该项;否则返回null
  8436. */
  8437. select: function( index ){
  8438. var itemCount = this.data('options').itemCount,
  8439. items = this.data('options').autowidthitem;
  8440. if ( items && !items.length ) {
  8441. items = this.data('options').items;
  8442. }
  8443. if( itemCount == 0 ) {
  8444. return null;
  8445. }
  8446. if( index < 0 ) {
  8447. index = itemCount + index % itemCount;
  8448. } else if ( index >= itemCount ) {
  8449. index = itemCount-1;
  8450. }
  8451. this.trigger( 'changebefore', items[ index ] );
  8452. this._update( index );
  8453. this.trigger( 'changeafter', items[ index ] );
  8454. return null;
  8455. },
  8456. selectItemByLabel: function( label ){
  8457. var itemMapping = this.data('options').itemMapping,
  8458. me = this,
  8459. index = null;
  8460. !$.isArray( label ) && ( label = [ label ] );
  8461. $.each( label, function( i, item ){
  8462. index = itemMapping[ item ];
  8463. if( index !== undefined ) {
  8464. me.select( index );
  8465. return false;
  8466. }
  8467. } );
  8468. },
  8469. /**
  8470. * 转换记录栈
  8471. */
  8472. _transStack: function( options ) {
  8473. var temp = [],
  8474. itemIndex = -1,
  8475. selected = -1;
  8476. $.each( options.recordStack, function( index, item ){
  8477. itemIndex = options.itemMapping[ item ];
  8478. if( $.isNumeric( itemIndex ) ) {
  8479. temp.push( itemIndex );
  8480. //selected的合法性检测
  8481. if( item == options.selected ) {
  8482. selected = itemIndex;
  8483. }
  8484. }
  8485. } );
  8486. options.recordStack = temp;
  8487. options.selected = selected;
  8488. temp = null;
  8489. },
  8490. _optionAdaptation: function( options ) {
  8491. if( !( 'itemStyles' in options ) ) {
  8492. options.itemStyles = [];
  8493. for( var i = 0, len = options.items.length; i < len; i++ ) {
  8494. options.itemStyles.push('');
  8495. }
  8496. }
  8497. options.autowidthitem = options.autowidthitem || options.items;
  8498. options.itemCount = options.items.length;
  8499. return options;
  8500. },
  8501. _createItemMapping: function( stackItem, items ){
  8502. var temp = {},
  8503. result = {
  8504. recordStack: [],
  8505. mapping: {}
  8506. };
  8507. $.each( items, function( index, item ){
  8508. temp[ item ] = index;
  8509. } );
  8510. result.itemMapping = temp;
  8511. $.each( stackItem, function( index, item ){
  8512. if( temp[ item ] !== undefined ) {
  8513. result.recordStack.push( temp[ item ] );
  8514. result.mapping[ item ] = temp[ item ];
  8515. }
  8516. } );
  8517. return result;
  8518. },
  8519. _update: function ( index ) {
  8520. var options = this.data("options"),
  8521. newStack = [],
  8522. newChilds = null;
  8523. $.each( options.recordStack, function( i, item ){
  8524. if( item != index ) {
  8525. newStack.push( item );
  8526. }
  8527. } );
  8528. //压入最新的记录
  8529. newStack.unshift( index );
  8530. if( newStack.length > options.recordCount ) {
  8531. newStack.length = options.recordCount;
  8532. }
  8533. options.recordStack = newStack;
  8534. options.selected = index;
  8535. newChilds = $( $.parseTmpl( this.tpl, options ) );
  8536. //重新渲染
  8537. this.root().html( newChilds.html() );
  8538. newChilds = null;
  8539. newStack = null;
  8540. }
  8541. };
  8542. } )(), 'menu' );
  8543. })();
  8544. /**
  8545. * Combox 抽象基类
  8546. * User: hn
  8547. * Date: 13-5-29
  8548. * Time: 下午8:01
  8549. * To change this template use File | Settings | File Templates.
  8550. */
  8551. (function(){
  8552. var widgetName = 'buttoncombobox';
  8553. UM.ui.define( widgetName, ( function(){
  8554. return {
  8555. defaultOpt: {
  8556. //按钮初始文字
  8557. label: '',
  8558. title: ''
  8559. },
  8560. init: function( options ) {
  8561. var me = this;
  8562. var btnWidget = $.eduibutton({
  8563. caret: true,
  8564. name: options.comboboxName,
  8565. title: options.title,
  8566. text: options.label,
  8567. click: function(){
  8568. me.show( this.root() );
  8569. }
  8570. });
  8571. me.supper.init.call( me, options );
  8572. //监听change, 改变button显示内容
  8573. me.on('changebefore', function( e, label ){
  8574. btnWidget.eduibutton('label', label );
  8575. });
  8576. me.data( 'button', btnWidget );
  8577. me.attachTo(btnWidget)
  8578. },
  8579. button: function(){
  8580. return this.data( 'button' );
  8581. }
  8582. }
  8583. } )(), 'combobox' );
  8584. })();
  8585. /*modal 类*/
  8586. UM.ui.define('modal', {
  8587. tpl: '<div class="edui-modal" tabindex="-1" >' +
  8588. '<div class="edui-modal-header">' +
  8589. '<div class="edui-close" data-hide="modal"></div>' +
  8590. '<h3 class="edui-title"><%=title%></h3>' +
  8591. '</div>' +
  8592. '<div class="edui-modal-body" style="<%if(width){%>width:<%=width%>px;<%}%>' +
  8593. '<%if(height){%>height:<%=height%>px;<%}%>">' +
  8594. ' </div>' +
  8595. '<% if(cancellabel || oklabel) {%>' +
  8596. '<div class="edui-modal-footer">' +
  8597. '<div class="edui-modal-tip"></div>' +
  8598. '<%if(oklabel){%><div class="edui-btn edui-btn-primary" data-ok="modal"><%=oklabel%></div><%}%>' +
  8599. '<%if(cancellabel){%><div class="edui-btn" data-hide="modal"><%=cancellabel%></div><%}%>' +
  8600. '</div>' +
  8601. '<%}%></div>',
  8602. defaultOpt: {
  8603. title: "",
  8604. cancellabel: "",
  8605. oklabel: "",
  8606. width: '',
  8607. height: '',
  8608. backdrop: true,
  8609. keyboard: true
  8610. },
  8611. init: function (options) {
  8612. var me = this;
  8613. me.root($($.parseTmpl(me.tpl, options || {})));
  8614. me.data("options", options);
  8615. if (options.okFn) {
  8616. me.on('ok', $.proxy(options.okFn, me))
  8617. }
  8618. if (options.cancelFn) {
  8619. me.on('beforehide', $.proxy(options.cancelFn, me))
  8620. }
  8621. me.root().delegate('[data-hide="modal"]', 'click', $.proxy(me.hide, me))
  8622. .delegate('[data-ok="modal"]', 'click', $.proxy(me.ok, me));
  8623. $('[data-hide="modal"],[data-ok="modal"]',me.root()).hover(function(){
  8624. $(this).toggleClass('edui-hover')
  8625. });
  8626. },
  8627. toggle: function () {
  8628. var me = this;
  8629. return me[!me.data("isShown") ? 'show' : 'hide']();
  8630. },
  8631. show: function () {
  8632. var me = this;
  8633. me.trigger("beforeshow");
  8634. if (me.data("isShown")) return;
  8635. me.data("isShown", true);
  8636. me.escape();
  8637. me.backdrop(function () {
  8638. me.autoCenter();
  8639. me.root()
  8640. .show()
  8641. .focus()
  8642. .trigger('aftershow');
  8643. })
  8644. },
  8645. showTip: function ( text ) {
  8646. $( '.edui-modal-tip', this.root() ).html( text ).fadeIn();
  8647. },
  8648. hideTip: function ( text ) {
  8649. $( '.edui-modal-tip', this.root() ).fadeOut( function (){
  8650. $(this).html('');
  8651. } );
  8652. },
  8653. autoCenter: function () {
  8654. //ie6下不用处理了
  8655. !$.IE6 && this.root().css("margin-left", -(this.root().width() / 2));
  8656. },
  8657. hide: function () {
  8658. var me = this;
  8659. me.trigger("beforehide");
  8660. if (!me.data("isShown")) return;
  8661. me.data("isShown", false);
  8662. me.escape();
  8663. me.hideModal();
  8664. },
  8665. escape: function () {
  8666. var me = this;
  8667. if (me.data("isShown") && me.data("options").keyboard) {
  8668. me.root().on('keyup', function (e) {
  8669. e.which == 27 && me.hide();
  8670. })
  8671. }
  8672. else if (!me.data("isShown")) {
  8673. me.root().off('keyup');
  8674. }
  8675. },
  8676. hideModal: function () {
  8677. var me = this;
  8678. me.root().hide();
  8679. me.backdrop(function () {
  8680. me.removeBackdrop();
  8681. me.trigger('afterhide');
  8682. })
  8683. },
  8684. removeBackdrop: function () {
  8685. this.$backdrop && this.$backdrop.remove();
  8686. this.$backdrop = null;
  8687. },
  8688. backdrop: function (callback) {
  8689. var me = this;
  8690. if (me.data("isShown") && me.data("options").backdrop) {
  8691. me.$backdrop = $('<div class="edui-modal-backdrop" />').click(
  8692. me.data("options").backdrop == 'static' ?
  8693. $.proxy(me.root()[0].focus, me.root()[0])
  8694. : $.proxy(me.hide, me)
  8695. )
  8696. }
  8697. me.trigger('afterbackdrop');
  8698. callback && callback();
  8699. },
  8700. attachTo: function ($obj) {
  8701. var me = this
  8702. if (!$obj.data('$mergeObj')) {
  8703. $obj.data('$mergeObj', me.root());
  8704. $obj.on('click', function () {
  8705. me.toggle($obj)
  8706. });
  8707. me.data('$mergeObj', $obj)
  8708. }
  8709. },
  8710. ok: function () {
  8711. var me = this;
  8712. me.trigger('beforeok');
  8713. if (me.trigger("ok", me) === false) {
  8714. return;
  8715. }
  8716. me.hide();
  8717. },
  8718. getBodyContainer: function () {
  8719. return this.root().find('.edui-modal-body')
  8720. }
  8721. });
  8722. /*tooltip 类*/
  8723. UM.ui.define('tooltip', {
  8724. tpl: '<div class="edui-tooltip" unselectable="on" onmousedown="return false">' +
  8725. '<div class="edui-tooltip-arrow" unselectable="on" onmousedown="return false"></div>' +
  8726. '<div class="edui-tooltip-inner" unselectable="on" onmousedown="return false"></div>' +
  8727. '</div>',
  8728. init: function (options) {
  8729. var me = this;
  8730. me.root($($.parseTmpl(me.tpl, options || {})));
  8731. },
  8732. content: function (e) {
  8733. var me = this,
  8734. title = $(e.currentTarget).attr("data-original-title");
  8735. me.root().find('.edui-tooltip-inner')['text'](title);
  8736. },
  8737. position: function (e) {
  8738. var me = this,
  8739. $obj = $(e.currentTarget);
  8740. me.root().css($.extend({display: 'block'}, $obj ? {
  8741. top: $obj.outerHeight(),
  8742. left: (($obj.outerWidth() - me.root().outerWidth()) / 2)
  8743. } : {}))
  8744. },
  8745. show: function (e) {
  8746. if ($(e.currentTarget).hasClass('edui-disabled')) return;
  8747. var me = this;
  8748. me.content(e);
  8749. me.root().appendTo($(e.currentTarget));
  8750. me.position(e);
  8751. me.root().css('display', 'block');
  8752. },
  8753. hide: function () {
  8754. var me = this;
  8755. me.root().css('display', 'none')
  8756. },
  8757. attachTo: function ($obj) {
  8758. var me = this;
  8759. function tmp($obj) {
  8760. var me = this;
  8761. if (!$.contains(document.body, me.root()[0])) {
  8762. me.root().appendTo($obj);
  8763. }
  8764. me.data('tooltip', me.root());
  8765. $obj.each(function () {
  8766. if ($(this).attr("data-original-title")) {
  8767. $(this).on('mouseenter', $.proxy(me.show, me))
  8768. .on('mouseleave click', $.proxy(me.hide, me))
  8769. }
  8770. });
  8771. }
  8772. if ($.type($obj) === "undefined") {
  8773. $("[data-original-title]").each(function (i, el) {
  8774. tmp.call(me, $(el));
  8775. })
  8776. } else {
  8777. if (!$obj.data('tooltip')) {
  8778. tmp.call(me, $obj);
  8779. }
  8780. }
  8781. }
  8782. });
  8783. /*tab 类*/
  8784. UM.ui.define('tab', {
  8785. init: function (options) {
  8786. var me = this,
  8787. slr = options.selector;
  8788. if ($.type(slr)) {
  8789. me.root($(slr, options.context));
  8790. me.data("context", options.context);
  8791. $(slr, me.data("context")).on('click', function (e) {
  8792. me.show(e);
  8793. });
  8794. }
  8795. },
  8796. show: function (e) {
  8797. var me = this,
  8798. $cur = $(e.target),
  8799. $ul = $cur.closest('ul'),
  8800. selector,
  8801. previous,
  8802. $target,
  8803. e;
  8804. selector = $cur.attr('data-context');
  8805. selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '');
  8806. var $tmp = $cur.parent('li');
  8807. if (!$tmp.length || $tmp.hasClass('edui-active')) return;
  8808. previous = $ul.find('.edui-active:last a')[0];
  8809. e = $.Event('beforeshow', {
  8810. target: $cur[0],
  8811. relatedTarget: previous
  8812. });
  8813. me.trigger(e);
  8814. if (e.isDefaultPrevented()) return;
  8815. $target = $(selector, me.data("context"));
  8816. me.activate($cur.parent('li'), $ul);
  8817. me.activate($target, $target.parent(), function () {
  8818. me.trigger({
  8819. type: 'aftershow', relatedTarget: previous
  8820. })
  8821. });
  8822. },
  8823. activate: function (element, container, callback) {
  8824. if (element === undefined) {
  8825. return $(".edui-tab-item.edui-active",this.root()).index();
  8826. }
  8827. var $active = container.find('> .edui-active');
  8828. $active.removeClass('edui-active');
  8829. element.addClass('edui-active');
  8830. callback && callback();
  8831. }
  8832. });
  8833. //button 类
  8834. UM.ui.define('separator', {
  8835. tpl: '<div class="edui-separator" unselectable="on" onmousedown="return false" ></div>',
  8836. init: function (options) {
  8837. var me = this;
  8838. me.root($($.parseTmpl(me.tpl, options)));
  8839. return me;
  8840. }
  8841. });
  8842. /**
  8843. * @file adapter.js
  8844. * @desc adapt ui to editor
  8845. * @import core/Editor.js, core/utils.js
  8846. */
  8847. (function () {
  8848. var _editorUI = {},
  8849. _editors = {},
  8850. _readyFn = [],
  8851. _activeWidget = null,
  8852. _widgetData = {},
  8853. _widgetCallBack = {},
  8854. _cacheUI = {},
  8855. _maxZIndex = null;
  8856. utils.extend(UM, {
  8857. defaultWidth : 500,
  8858. defaultHeight : 500,
  8859. registerUI: function (name, fn) {
  8860. utils.each(name.split(/\s+/), function (uiname) {
  8861. _editorUI[uiname] = fn;
  8862. })
  8863. },
  8864. setEditor : function(editor){
  8865. !_editors[editor.id] && (_editors[editor.id] = editor);
  8866. },
  8867. registerWidget : function(name,pro,cb){
  8868. _widgetData[name] = $.extend2(pro,{
  8869. $root : '',
  8870. _preventDefault:false,
  8871. root:function($el){
  8872. return this.$root || (this.$root = $el);
  8873. },
  8874. preventDefault:function(){
  8875. this._preventDefault = true;
  8876. },
  8877. clear:false
  8878. });
  8879. if(cb){
  8880. _widgetCallBack[name] = cb;
  8881. }
  8882. },
  8883. getWidgetData : function(name){
  8884. return _widgetData[name]
  8885. },
  8886. setWidgetBody : function(name,$widget,editor){
  8887. if(!editor._widgetData){
  8888. utils.extend(editor,{
  8889. _widgetData : {},
  8890. getWidgetData : function(name){
  8891. return this._widgetData[name];
  8892. },
  8893. getWidgetCallback : function(widgetName){
  8894. var me = this;
  8895. return function(){
  8896. return _widgetCallBack[widgetName].apply(me,[me,$widget].concat(Array.prototype.slice.call(arguments,0)))
  8897. }
  8898. }
  8899. })
  8900. }
  8901. var pro = _widgetData[name];
  8902. if(!pro){
  8903. return null;
  8904. }
  8905. pro = editor._widgetData[name];
  8906. if(!pro){
  8907. pro = _widgetData[name];
  8908. pro = editor._widgetData[name] = $.type(pro) == 'function' ? pro : utils.clone(pro);
  8909. }
  8910. pro.root($widget.edui().getBodyContainer());
  8911. pro.initContent(editor,$widget);
  8912. if(!pro._preventDefault){
  8913. pro.initEvent(editor,$widget);
  8914. }
  8915. pro.width && $widget.width(pro.width);
  8916. },
  8917. setActiveWidget : function($widget){
  8918. _activeWidget = $widget;
  8919. },
  8920. getEditor: function (id, options) {
  8921. var editor = _editors[id] || (_editors[id] = this.createEditor(id, options));
  8922. _maxZIndex = _maxZIndex ? Math.max(editor.getOpt('zIndex'), _maxZIndex):editor.getOpt('zIndex');
  8923. return editor;
  8924. },
  8925. setTopEditor: function(editor){
  8926. $.each(_editors, function(i, o){
  8927. if(editor == o) {
  8928. editor.$container && editor.$container.css('zIndex', _maxZIndex + 1);
  8929. } else {
  8930. o.$container && o.$container.css('zIndex', o.getOpt('zIndex'));
  8931. }
  8932. });
  8933. },
  8934. clearCache : function(id){
  8935. if ( _editors[id]) {
  8936. delete _editors[id]
  8937. }
  8938. },
  8939. delEditor: function (id) {
  8940. var editor;
  8941. if (editor = _editors[id]) {
  8942. editor.destroy();
  8943. }
  8944. },
  8945. ready: function( fn ){
  8946. _readyFn.push( fn );
  8947. },
  8948. createEditor: function (id, opt) {
  8949. var editor = new UM.Editor(opt);
  8950. var T = this;
  8951. editor.langIsReady ? $.proxy(renderUI,T)() : editor.addListener("langReady", $.proxy(renderUI,T));
  8952. function renderUI(){
  8953. var $container = this.createUI('#' + id, editor);
  8954. editor.key=id;
  8955. editor.ready(function(){
  8956. $.each( _readyFn, function( index, fn ){
  8957. $.proxy( fn, editor )();
  8958. } );
  8959. });
  8960. var options = editor.options;
  8961. if(options.initialFrameWidth){
  8962. options.minFrameWidth = options.initialFrameWidth
  8963. }else{
  8964. options.minFrameWidth = options.initialFrameWidth = editor.$body.width() || UM.defaultWidth;
  8965. }
  8966. $container.css({
  8967. width: options.initialFrameWidth,
  8968. zIndex:editor.getOpt('zIndex')
  8969. });
  8970. //ie6下缓存图片
  8971. UM.browser.ie && UM.browser.version === 6 && document.execCommand("BackgroundImageCache", false, true);
  8972. editor.render(id);
  8973. //添加tooltip;
  8974. $.eduitooltip && $.eduitooltip('attachTo', $("[data-original-title]",$container)).css('z-index',editor.getOpt('zIndex')+1);
  8975. $container.find('a').click(function(evt){
  8976. evt.preventDefault()
  8977. });
  8978. editor.fireEvent("afteruiready");
  8979. }
  8980. return editor;
  8981. },
  8982. createUI: function (id, editor) {
  8983. var $editorCont = $(id),
  8984. $container = $('<div class="edui-container"><div class="edui-editor-body"></div></div>').insertBefore($editorCont);
  8985. editor.$container = $container;
  8986. editor.container = $container[0];
  8987. editor.$body = $editorCont;
  8988. //修正在ie9+以上的版本中,自动长高收起时的,残影问题
  8989. if(browser.ie && browser.ie9above){
  8990. var $span = $('<span style="padding:0;margin:0;height:0;width:0"></span>');
  8991. $span.insertAfter($container);
  8992. }
  8993. //初始化注册的ui组件
  8994. $.each(_editorUI,function(n,v){
  8995. var widget = v.call(editor,n);
  8996. if(widget){
  8997. _cacheUI[n] = widget;
  8998. }
  8999. });
  9000. $container.find('.edui-editor-body').append($editorCont).before(this.createToolbar(editor.options, editor));
  9001. $container.find('.edui-toolbar').append($('<div class="edui-dialog-container"></div>'));
  9002. return $container;
  9003. },
  9004. createToolbar: function (options, editor) {
  9005. var $toolbar = $.eduitoolbar(), toolbar = $toolbar.edui();
  9006. //创建下来菜单列表
  9007. if (options.toolbar && options.toolbar.length) {
  9008. var btns = [];
  9009. $.each(options.toolbar,function(i,uiNames){
  9010. $.each(uiNames.split(/\s+/),function(index,name){
  9011. if(name == '|'){
  9012. $.eduiseparator && btns.push($.eduiseparator());
  9013. }else{
  9014. var ui = _cacheUI[name];
  9015. if(name=="fullscreen"){
  9016. ui&&btns.unshift(ui);
  9017. }else{
  9018. ui && btns.push(ui);
  9019. }
  9020. }
  9021. });
  9022. btns.length && toolbar.appendToBtnmenu(btns);
  9023. });
  9024. } else {
  9025. $toolbar.find('.edui-btn-toolbar').remove()
  9026. }
  9027. return $toolbar;
  9028. }
  9029. })
  9030. })();
  9031. UM.registerUI('bold italic redo undo underline strikethrough superscript subscript insertorderedlist insertunorderedlist ' +
  9032. 'cleardoc selectall link unlink print preview justifyleft justifycenter justifyright justifyfull removeformat horizontal drafts image',
  9033. function(name) {
  9034. var me = this;
  9035. var $btn = $.eduibutton({
  9036. icon : name,
  9037. click : function(){
  9038. me.execCommand(name);
  9039. },
  9040. title: this.getLang('labelMap')[name] || ''
  9041. });
  9042. this.addListener('selectionchange',function(){
  9043. var state = this.queryCommandState(name);
  9044. $btn.edui().disabled(state == -1).active(state == 1)
  9045. });
  9046. return $btn;
  9047. }
  9048. );
  9049. /**
  9050. * 全屏组件
  9051. */
  9052. (function(){
  9053. //状态缓存
  9054. var STATUS_CACHE = {},
  9055. //状态值列表
  9056. STATUS_LIST = [ 'width', 'height', 'position', 'top', 'left', 'margin', 'padding', 'overflowX', 'overflowY' ],
  9057. CONTENT_AREA_STATUS = {},
  9058. //页面状态
  9059. DOCUMENT_STATUS = {},
  9060. DOCUMENT_ELEMENT_STATUS = {},
  9061. FULLSCREENS = {};
  9062. UM.registerUI('fullscreen', function( name ){
  9063. var me = this,
  9064. $button = $.eduibutton({
  9065. 'icon': 'fullscreen',
  9066. 'title': (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9067. 'click': function(){
  9068. //切换
  9069. me.execCommand( name );
  9070. UM.setTopEditor(me);
  9071. }
  9072. });
  9073. me.addListener( "selectionchange", function () {
  9074. var state = this.queryCommandState( name );
  9075. $button.edui().disabled( state == -1 ).active( state == 1 );
  9076. } );
  9077. //切换至全屏
  9078. me.addListener('ready', function(){
  9079. me.options.fullscreen && Fullscreen.getInstance( me ).toggle();
  9080. });
  9081. return $button;
  9082. });
  9083. UM.commands[ 'fullscreen' ] = {
  9084. execCommand: function (cmdName) {
  9085. Fullscreen.getInstance( this ).toggle();
  9086. },
  9087. queryCommandState: function (cmdName) {
  9088. return this._edui_fullscreen_status;
  9089. },
  9090. notNeedUndo: 1
  9091. };
  9092. function Fullscreen( editor ) {
  9093. var me = this;
  9094. if( !editor ) {
  9095. throw new Error('invalid params, notfound editor');
  9096. }
  9097. me.editor = editor;
  9098. //记录初始化的全屏组件
  9099. FULLSCREENS[ editor.uid ] = this;
  9100. editor.addListener('destroy', function(){
  9101. delete FULLSCREENS[ editor.uid ];
  9102. me.editor = null;
  9103. });
  9104. }
  9105. Fullscreen.prototype = {
  9106. /**
  9107. * 全屏状态切换
  9108. */
  9109. toggle: function(){
  9110. var editor = this.editor,
  9111. //当前编辑器的缩放状态
  9112. _edui_fullscreen_status = this.isFullState();
  9113. editor.fireEvent('beforefullscreenchange', !_edui_fullscreen_status );
  9114. //更新状态
  9115. this.update( !_edui_fullscreen_status );
  9116. !_edui_fullscreen_status ? this.enlarge() : this.revert();
  9117. editor.fireEvent('afterfullscreenchange', !_edui_fullscreen_status );
  9118. if(editor.body.contentEditable === 'true'){
  9119. editor.fireEvent( 'fullscreenchanged', !_edui_fullscreen_status );
  9120. }
  9121. editor.fireEvent( 'selectionchange' );
  9122. },
  9123. /**
  9124. * 执行放大
  9125. */
  9126. enlarge: function(){
  9127. this.saveSataus();
  9128. this.setDocumentStatus();
  9129. this.resize();
  9130. },
  9131. /**
  9132. * 全屏还原
  9133. */
  9134. revert: function(){
  9135. //还原CSS表达式
  9136. var options = this.editor.options,
  9137. height = /%$/.test(options.initialFrameHeight) ? '100%' : (options.initialFrameHeight - this.getStyleValue("padding-top")- this.getStyleValue("padding-bottom") - this.getStyleValue('border-width'));
  9138. $.IE6 && this.getEditorHolder().style.setExpression('height', 'this.scrollHeight <= ' + height + ' ? "' + height + 'px" : "auto"');
  9139. //还原容器状态
  9140. this.revertContainerStatus();
  9141. this.revertContentAreaStatus();
  9142. this.revertDocumentStatus();
  9143. },
  9144. /**
  9145. * 更新状态
  9146. * @param isFull 当前状态是否是全屏状态
  9147. */
  9148. update: function( isFull ) {
  9149. this.editor._edui_fullscreen_status = isFull;
  9150. },
  9151. /**
  9152. * 调整当前编辑器的大小, 如果当前编辑器不处于全屏状态, 则不做调整
  9153. */
  9154. resize: function(){
  9155. var $win = null,
  9156. height = 0,
  9157. width = 0,
  9158. borderWidth = 0,
  9159. paddingWidth = 0,
  9160. editor = this.editor,
  9161. me = this,
  9162. bound = null,
  9163. editorBody = null;
  9164. if( !this.isFullState() ) {
  9165. return;
  9166. }
  9167. $win = $( window );
  9168. width = $win.width();
  9169. height = $win.height();
  9170. editorBody = this.getEditorHolder();
  9171. //文本编辑区border宽度
  9172. borderWidth = parseInt( domUtils.getComputedStyle( editorBody, 'border-width' ), 10 ) || 0;
  9173. //容器border宽度
  9174. borderWidth += parseInt( domUtils.getComputedStyle( editor.container, 'border-width' ), 10 ) || 0;
  9175. //容器padding
  9176. paddingWidth += parseInt( domUtils.getComputedStyle( editorBody, 'padding-left' ), 10 ) + parseInt( domUtils.getComputedStyle( editorBody, 'padding-right' ), 10 ) || 0;
  9177. //干掉css表达式
  9178. $.IE6 && editorBody.style.setExpression( 'height', null );
  9179. bound = this.getBound();
  9180. $( editor.container ).css( {
  9181. width: width + 'px',
  9182. height: height + 'px',
  9183. position: !$.IE6 ? 'fixed' : 'absolute',
  9184. top: bound.top,
  9185. left: bound.left,
  9186. margin: 0,
  9187. padding: 0,
  9188. overflowX: 'hidden',
  9189. overflowY: 'hidden'
  9190. } );
  9191. $( editorBody ).css({
  9192. width: width - 2*borderWidth - paddingWidth + 'px',
  9193. height: height - 2*borderWidth - ( editor.options.withoutToolbar ? 0 : $( '.edui-toolbar', editor.container ).outerHeight() ) - $( '.edui-bottombar', editor.container).outerHeight() + 'px',
  9194. overflowX: 'hidden',
  9195. overflowY: 'auto'
  9196. });
  9197. },
  9198. /**
  9199. * 保存状态
  9200. */
  9201. saveSataus: function(){
  9202. var styles = this.editor.container.style,
  9203. tmp = null,
  9204. cache = {};
  9205. for( var i= 0, len = STATUS_LIST.length; i<len; i++ ) {
  9206. tmp = STATUS_LIST[ i ];
  9207. cache[ tmp ] = styles[ tmp ];
  9208. }
  9209. STATUS_CACHE[ this.editor.uid ] = cache;
  9210. this.saveContentAreaStatus();
  9211. this.saveDocumentStatus();
  9212. },
  9213. saveContentAreaStatus: function(){
  9214. var $holder = $(this.getEditorHolder());
  9215. CONTENT_AREA_STATUS[ this.editor.uid ] = {
  9216. width: $holder.css("width"),
  9217. overflowX: $holder.css("overflowX"),
  9218. overflowY: $holder.css("overflowY"),
  9219. height: $holder.css("height")
  9220. };
  9221. },
  9222. /**
  9223. * 保存与指定editor相关的页面的状态
  9224. */
  9225. saveDocumentStatus: function(){
  9226. var $doc = $( this.getEditorDocumentBody() );
  9227. DOCUMENT_STATUS[ this.editor.uid ] = {
  9228. overflowX: $doc.css( 'overflowX' ),
  9229. overflowY: $doc.css( 'overflowY' )
  9230. };
  9231. DOCUMENT_ELEMENT_STATUS[ this.editor.uid ] = {
  9232. overflowX: $( this.getEditorDocumentElement() ).css( 'overflowX'),
  9233. overflowY: $( this.getEditorDocumentElement() ).css( 'overflowY' )
  9234. };
  9235. },
  9236. /**
  9237. * 恢复容器状态
  9238. */
  9239. revertContainerStatus: function(){
  9240. $( this.editor.container ).css( this.getEditorStatus() );
  9241. },
  9242. /**
  9243. * 恢复编辑区状态
  9244. */
  9245. revertContentAreaStatus: function(){
  9246. var holder = this.getEditorHolder(),
  9247. state = this.getContentAreaStatus();
  9248. if ( this.supportMin() ) {
  9249. delete state.height;
  9250. holder.style.height = null;
  9251. }
  9252. $( holder ).css( state );
  9253. },
  9254. /**
  9255. * 恢复页面状态
  9256. */
  9257. revertDocumentStatus: function() {
  9258. var status = this.getDocumentStatus();
  9259. $( this.getEditorDocumentBody() ).css( 'overflowX', status.body.overflowX );
  9260. $( this.getEditorDocumentElement() ).css( 'overflowY', status.html.overflowY );
  9261. },
  9262. setDocumentStatus: function(){
  9263. $(this.getEditorDocumentBody()).css( {
  9264. overflowX: 'hidden',
  9265. overflowY: 'hidden'
  9266. } );
  9267. $(this.getEditorDocumentElement()).css( {
  9268. overflowX: 'hidden',
  9269. overflowY: 'hidden'
  9270. } );
  9271. },
  9272. /**
  9273. * 检测当前编辑器是否处于全屏状态全屏状态
  9274. * @returns {boolean} 是否处于全屏状态
  9275. */
  9276. isFullState: function(){
  9277. return !!this.editor._edui_fullscreen_status;
  9278. },
  9279. /**
  9280. * 获取编辑器状态
  9281. */
  9282. getEditorStatus: function(){
  9283. return STATUS_CACHE[ this.editor.uid ];
  9284. },
  9285. getContentAreaStatus: function(){
  9286. return CONTENT_AREA_STATUS[ this.editor.uid ];
  9287. },
  9288. getEditorDocumentElement: function(){
  9289. return this.editor.container.ownerDocument.documentElement;
  9290. },
  9291. getEditorDocumentBody: function(){
  9292. return this.editor.container.ownerDocument.body;
  9293. },
  9294. /**
  9295. * 获取编辑区包裹对象
  9296. */
  9297. getEditorHolder: function(){
  9298. return this.editor.body;
  9299. },
  9300. /**
  9301. * 获取编辑器状态
  9302. * @returns {*}
  9303. */
  9304. getDocumentStatus: function(){
  9305. return {
  9306. 'body': DOCUMENT_STATUS[ this.editor.uid ],
  9307. 'html': DOCUMENT_ELEMENT_STATUS[ this.editor.uid ]
  9308. };
  9309. },
  9310. supportMin: function () {
  9311. var node = null;
  9312. if ( !this._support ) {
  9313. node = document.createElement("div");
  9314. this._support = "minWidth" in node.style;
  9315. node = null;
  9316. }
  9317. return this._support;
  9318. },
  9319. getBound: function () {
  9320. var tags = {
  9321. html: true,
  9322. body: true
  9323. },
  9324. result = {
  9325. top: 0,
  9326. left: 0
  9327. },
  9328. offsetParent = null;
  9329. if ( !$.IE6 ) {
  9330. return result;
  9331. }
  9332. offsetParent = this.editor.container.offsetParent;
  9333. if( offsetParent && !tags[ offsetParent.nodeName.toLowerCase() ] ) {
  9334. tags = offsetParent.getBoundingClientRect();
  9335. result.top = -tags.top;
  9336. result.left = -tags.left;
  9337. }
  9338. return result;
  9339. },
  9340. getStyleValue: function (attr) {
  9341. return parseInt(domUtils.getComputedStyle( this.getEditorHolder() ,attr));
  9342. }
  9343. };
  9344. $.extend( Fullscreen, {
  9345. /**
  9346. * 监听resize
  9347. */
  9348. listen: function(){
  9349. var timer = null;
  9350. if( Fullscreen._hasFullscreenListener ) {
  9351. return;
  9352. }
  9353. Fullscreen._hasFullscreenListener = true;
  9354. $( window ).on( 'resize', function(){
  9355. if( timer !== null ) {
  9356. window.clearTimeout( timer );
  9357. timer = null;
  9358. }
  9359. timer = window.setTimeout(function(){
  9360. for( var key in FULLSCREENS ) {
  9361. FULLSCREENS[ key ].resize();
  9362. }
  9363. timer = null;
  9364. }, 50);
  9365. } );
  9366. },
  9367. getInstance: function ( editor ) {
  9368. if ( !FULLSCREENS[editor.uid ] ) {
  9369. new Fullscreen( editor );
  9370. }
  9371. return FULLSCREENS[editor.uid ];
  9372. }
  9373. });
  9374. //开始监听
  9375. Fullscreen.listen();
  9376. })();
  9377. UM.registerUI('link video map formula',function(name){
  9378. var me = this, currentRange, $dialog,
  9379. opt = {
  9380. title: (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9381. url: me.options.UMEDITOR_HOME_URL + 'dialogs/' + name + '/' + name + '.js'
  9382. };
  9383. var $btn = $.eduibutton({
  9384. icon: name,
  9385. title: this.getLang('labelMap')[name] || ''
  9386. });
  9387. //加载模版数据
  9388. utils.loadFile(document,{
  9389. src: opt.url,
  9390. tag: "script",
  9391. type: "text/javascript",
  9392. defer: "defer"
  9393. },function(){
  9394. //调整数据
  9395. var data = UM.getWidgetData(name);
  9396. if(!data) return;
  9397. if(data.buttons){
  9398. var ok = data.buttons.ok;
  9399. if(ok){
  9400. opt.oklabel = ok.label || me.getLang('ok');
  9401. if(ok.exec){
  9402. opt.okFn = function(){
  9403. return $.proxy(ok.exec,null,me,$dialog)()
  9404. }
  9405. }
  9406. }
  9407. var cancel = data.buttons.cancel;
  9408. if(cancel){
  9409. opt.cancellabel = cancel.label || me.getLang('cancel');
  9410. if(cancel.exec){
  9411. opt.cancelFn = function(){
  9412. return $.proxy(cancel.exec,null,me,$dialog)()
  9413. }
  9414. }
  9415. }
  9416. }
  9417. data.width && (opt.width = data.width);
  9418. data.height && (opt.height = data.height);
  9419. $dialog = $.eduimodal(opt);
  9420. $dialog.attr('id', 'edui-dialog-' + name).addClass('edui-dialog-' + name)
  9421. .find('.edui-modal-body').addClass('edui-dialog-' + name + '-body');
  9422. $dialog.edui().on('beforehide',function () {
  9423. var rng = me.selection.getRange();
  9424. if (rng.equals(currentRange)) {
  9425. rng.select()
  9426. }
  9427. }).on('beforeshow', function () {
  9428. var $root = this.root(),
  9429. win = null,
  9430. offset = null;
  9431. currentRange = me.selection.getRange();
  9432. if (!$root.parent()[0]) {
  9433. me.$container.find('.edui-dialog-container').append($root);
  9434. }
  9435. //IE6下 特殊处理, 通过计算进行定位
  9436. if( $.IE6 ) {
  9437. win = {
  9438. width: $( window ).width(),
  9439. height: $( window ).height()
  9440. };
  9441. offset = $root.parents(".edui-toolbar")[0].getBoundingClientRect();
  9442. $root.css({
  9443. position: 'absolute',
  9444. margin: 0,
  9445. left: ( win.width - $root.width() ) / 2 - offset.left,
  9446. top: 100 - offset.top
  9447. });
  9448. }
  9449. UM.setWidgetBody(name,$dialog,me);
  9450. UM.setTopEditor(me);
  9451. }).on('afterbackdrop',function(){
  9452. this.$backdrop.css('zIndex',me.getOpt('zIndex')+1).appendTo(me.$container.find('.edui-dialog-container'))
  9453. $dialog.css('zIndex',me.getOpt('zIndex')+2)
  9454. }).on('beforeok',function(){
  9455. try{
  9456. currentRange.select()
  9457. }catch(e){}
  9458. }).attachTo($btn)
  9459. });
  9460. me.addListener('selectionchange', function () {
  9461. var state = this.queryCommandState(name);
  9462. $btn.edui().disabled(state == -1).active(state == 1)
  9463. });
  9464. return $btn;
  9465. });
  9466. UM.registerUI( 'emotion formula', function( name ){
  9467. var me = this,
  9468. url = me.options.UMEDITOR_HOME_URL + 'dialogs/' +name+ '/'+name+'.js';
  9469. var $btn = $.eduibutton({
  9470. icon: name,
  9471. title: this.getLang('labelMap')[name] || ''
  9472. });
  9473. //加载模版数据
  9474. utils.loadFile(document,{
  9475. src: url,
  9476. tag: "script",
  9477. type: "text/javascript",
  9478. defer: "defer"
  9479. },function(){
  9480. var opt = {
  9481. url : url
  9482. };
  9483. //调整数据
  9484. var data = UM.getWidgetData(name);
  9485. data.width && (opt.width = data.width);
  9486. data.height && (opt.height = data.height);
  9487. $.eduipopup(opt).css('zIndex',me.options.zIndex + 1)
  9488. .addClass('edui-popup-' + name)
  9489. .edui()
  9490. .on('beforeshow',function(){
  9491. var $root = this.root();
  9492. if(!$root.parent().length){
  9493. me.$container.find('.edui-dialog-container').append($root);
  9494. }
  9495. UM.setWidgetBody(name,$root,me);
  9496. UM.setTopEditor(me);
  9497. }).attachTo($btn,{
  9498. offsetTop:-5,
  9499. offsetLeft:10,
  9500. caretLeft:11,
  9501. caretTop:-8
  9502. });
  9503. me.addListener('selectionchange', function () {
  9504. var state = this.queryCommandState(name);
  9505. $btn.edui().disabled(state == -1).active(state == 1);
  9506. });
  9507. });
  9508. return $btn;
  9509. } );
  9510. UM.registerUI('imagescale',function () {
  9511. var me = this,
  9512. $imagescale;
  9513. me.setOpt('imageScaleEnabled', true);
  9514. if (browser.webkit && me.getOpt('imageScaleEnabled')) {
  9515. me.addListener('click', function (type, e) {
  9516. var range = me.selection.getRange(),
  9517. img = range.getClosedNode(),
  9518. target = e.target;
  9519. /* 点击第一个图片的后面,八个角不消失 fix:3652 */
  9520. if (img && img.tagName == 'IMG' && target == img) {
  9521. if (!$imagescale) {
  9522. $imagescale = $.eduiscale({'$wrap':me.$container}).css('zIndex', me.options.zIndex);
  9523. me.$container.append($imagescale);
  9524. var _keyDownHandler = function () {
  9525. $imagescale.edui().hide();
  9526. }, _mouseDownHandler = function (e) {
  9527. var ele = e.target || e.srcElement;
  9528. if (ele && ele.className.indexOf('edui-scale') == -1) {
  9529. _keyDownHandler(e);
  9530. }
  9531. }, timer;
  9532. $imagescale.edui()
  9533. .on('aftershow', function () {
  9534. $(document).bind('keydown', _keyDownHandler);
  9535. $(document).bind('mousedown', _mouseDownHandler);
  9536. me.selection.getNative().removeAllRanges();
  9537. })
  9538. .on('afterhide', function () {
  9539. $(document).unbind('keydown', _keyDownHandler);
  9540. $(document).unbind('mousedown', _mouseDownHandler);
  9541. var target = $imagescale.edui().getScaleTarget();
  9542. if (target.parentNode) {
  9543. me.selection.getRange().selectNode(target).select();
  9544. }
  9545. })
  9546. .on('mousedown', function (e) {
  9547. me.selection.getNative().removeAllRanges();
  9548. var ele = e.target || e.srcElement;
  9549. if (ele && ele.className.indexOf('edui-scale-hand') == -1) {
  9550. timer = setTimeout(function() {
  9551. $imagescale.edui().hide();
  9552. }, 200);
  9553. }
  9554. })
  9555. .on('mouseup', function (e) {
  9556. var ele = e.target || e.srcElement;
  9557. if (ele && ele.className.indexOf('edui-scale-hand') == -1) {
  9558. clearTimeout(timer);
  9559. }
  9560. });
  9561. }
  9562. $imagescale.edui().show($(img));
  9563. } else {
  9564. if ($imagescale && $imagescale.css('display') != 'none') $imagescale.edui().hide();
  9565. }
  9566. });
  9567. me.addListener('click', function (type, e) {
  9568. if (e.target.tagName == 'IMG') {
  9569. var range = new dom.Range(me.document, me.body);
  9570. range.selectNode(e.target).select();
  9571. }
  9572. });
  9573. }
  9574. });
  9575. UM.registerUI('autofloat',function(){
  9576. var me = this,
  9577. lang = me.getLang();
  9578. me.setOpt({
  9579. autoFloatEnabled: true,
  9580. topOffset: 0
  9581. });
  9582. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  9583. topOffset = me.options.topOffset;
  9584. //如果不固定toolbar的位置,则直接退出
  9585. if(!optsAutoFloatEnabled){
  9586. return;
  9587. }
  9588. me.ready(function(){
  9589. var LteIE6 = browser.ie && browser.version <= 6,
  9590. quirks = browser.quirks;
  9591. function checkHasUI(){
  9592. if(!UM.ui){
  9593. alert(lang.autofloatMsg);
  9594. return 0;
  9595. }
  9596. return 1;
  9597. }
  9598. function fixIE6FixedPos(){
  9599. var docStyle = document.body.style;
  9600. docStyle.backgroundImage = 'url("about:blank")';
  9601. docStyle.backgroundAttachment = 'fixed';
  9602. }
  9603. var bakCssText,
  9604. placeHolder = document.createElement('div'),
  9605. toolbarBox,orgTop,
  9606. getPosition=function(element){
  9607. var bcr;
  9608. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  9609. try{
  9610. bcr = element.getBoundingClientRect();
  9611. }catch(e){
  9612. bcr={left:0,top:0,height:0,width:0}
  9613. }
  9614. var rect = {
  9615. left: Math.round(bcr.left),
  9616. top: Math.round(bcr.top),
  9617. height: Math.round(bcr.bottom - bcr.top),
  9618. width: Math.round(bcr.right - bcr.left)
  9619. };
  9620. var doc;
  9621. while ((doc = element.ownerDocument) !== document &&
  9622. (element = domUtils.getWindow(doc).frameElement)) {
  9623. bcr = element.getBoundingClientRect();
  9624. rect.left += bcr.left;
  9625. rect.top += bcr.top;
  9626. }
  9627. rect.bottom = rect.top + rect.height;
  9628. rect.right = rect.left + rect.width;
  9629. return rect;
  9630. };
  9631. var isFullScreening = false;
  9632. function setFloating(){
  9633. if(isFullScreening){
  9634. return;
  9635. }
  9636. var toobarBoxPos = domUtils.getXY(toolbarBox),
  9637. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  9638. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  9639. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  9640. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  9641. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  9642. if (LteIE6 || (quirks && browser.ie)) {
  9643. if(toolbarBox.style.position != 'absolute'){
  9644. toolbarBox.style.position = 'absolute';
  9645. }
  9646. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  9647. } else {
  9648. if(toolbarBox.style.position != 'fixed'){
  9649. toolbarBox.style.position = 'fixed';
  9650. toolbarBox.style.top = topOffset +"px";
  9651. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  9652. }
  9653. }
  9654. }
  9655. function unsetFloating(){
  9656. if(placeHolder.parentNode){
  9657. placeHolder.parentNode.removeChild(placeHolder);
  9658. }
  9659. toolbarBox.style.cssText = bakCssText;
  9660. }
  9661. function updateFloating(){
  9662. var rect3 = getPosition(me.container);
  9663. var offset=me.options.toolbarTopOffset||0;
  9664. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  9665. setFloating();
  9666. }else{
  9667. unsetFloating();
  9668. }
  9669. }
  9670. var defer_updateFloating = utils.defer(function(){
  9671. updateFloating();
  9672. },browser.ie ? 200 : 100,true);
  9673. me.addListener('destroy',function(){
  9674. $(window).off('scroll resize',updateFloating);
  9675. me.removeListener('keydown', defer_updateFloating);
  9676. });
  9677. if(checkHasUI(me)){
  9678. toolbarBox = $('.edui-toolbar',me.container)[0];
  9679. me.addListener("afteruiready",function(){
  9680. setTimeout(function(){
  9681. orgTop = $(toolbarBox).offset().top;
  9682. },100);
  9683. });
  9684. bakCssText = toolbarBox.style.cssText;
  9685. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  9686. if(LteIE6){
  9687. fixIE6FixedPos();
  9688. }
  9689. $(window).on('scroll resize',updateFloating);
  9690. me.addListener('keydown', defer_updateFloating);
  9691. me.addListener('resize', function(){
  9692. unsetFloating();
  9693. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  9694. updateFloating();
  9695. });
  9696. me.addListener('beforefullscreenchange', function (t, enabled){
  9697. if (enabled) {
  9698. unsetFloating();
  9699. isFullScreening = enabled;
  9700. }
  9701. });
  9702. me.addListener('fullscreenchanged', function (t, enabled){
  9703. if (!enabled) {
  9704. updateFloating();
  9705. }
  9706. isFullScreening = enabled;
  9707. });
  9708. me.addListener('sourcemodechanged', function (t, enabled){
  9709. setTimeout(function (){
  9710. updateFloating();
  9711. },0);
  9712. });
  9713. me.addListener("clearDoc",function(){
  9714. setTimeout(function(){
  9715. updateFloating();
  9716. },0);
  9717. })
  9718. }
  9719. })
  9720. });
  9721. UM.registerUI('source',function(name){
  9722. var me = this;
  9723. me.addListener('fullscreenchanged',function(){
  9724. me.$container.find('textarea').width(me.$body.width() - 10).height(me.$body.height())
  9725. });
  9726. var $btn = $.eduibutton({
  9727. icon : name,
  9728. click : function(){
  9729. me.execCommand(name);
  9730. UM.setTopEditor(me);
  9731. },
  9732. title: this.getLang('labelMap')[name] || ''
  9733. });
  9734. this.addListener('selectionchange',function(){
  9735. var state = this.queryCommandState(name);
  9736. $btn.edui().disabled(state == -1).active(state == 1)
  9737. });
  9738. return $btn;
  9739. });
  9740. UM.registerUI('paragraph fontfamily fontsize', function( name ) {
  9741. var me = this,
  9742. label = (me.options.labelMap && me.options.labelMap[name]) || me.getLang("labelMap." + name),
  9743. options = {
  9744. label: label,
  9745. title: label,
  9746. comboboxName: name,
  9747. items: me.options[ name ] || [],
  9748. itemStyles: [],
  9749. value: [],
  9750. autowidthitem: []
  9751. },
  9752. $combox = null,
  9753. comboboxWidget = null;
  9754. if(options.items.length == 0){
  9755. return null;
  9756. }
  9757. switch ( name ) {
  9758. case 'paragraph':
  9759. options = transForParagraph( options );
  9760. break;
  9761. case 'fontfamily':
  9762. options = transForFontfamily( options );
  9763. break;
  9764. case 'fontsize':
  9765. options = transForFontsize( options );
  9766. break;
  9767. }
  9768. //实例化
  9769. $combox = $.eduibuttoncombobox(options).css('zIndex',me.getOpt('zIndex') + 1);
  9770. comboboxWidget = $combox.edui();
  9771. comboboxWidget.on('comboboxselect', function( evt, res ){
  9772. me.execCommand( name, res.value );
  9773. }).on("beforeshow", function(){
  9774. if( $combox.parent().length === 0 ) {
  9775. $combox.appendTo( me.$container.find('.edui-dialog-container') );
  9776. }
  9777. UM.setTopEditor(me);
  9778. });
  9779. //状态反射
  9780. this.addListener('selectionchange',function( evt ){
  9781. var state = this.queryCommandState( name ),
  9782. value = this.queryCommandValue( name );
  9783. //设置按钮状态
  9784. comboboxWidget.button().edui().disabled( state == -1 ).active( state == 1 );
  9785. if(value){
  9786. //设置label
  9787. value = value.replace(/['"]/g, '').toLowerCase().split(/['|"]?\s*,\s*[\1]?/);
  9788. comboboxWidget.selectItemByLabel( value );
  9789. }
  9790. });
  9791. return comboboxWidget.button().addClass('edui-combobox');
  9792. /**
  9793. * 宽度自适应工具函数
  9794. * @param word 单词内容
  9795. * @param hasSuffix 是否含有后缀
  9796. */
  9797. function wordCountAdaptive ( word, hasSuffix ) {
  9798. var $tmpNode = $('<span>' ).html( word ).css( {
  9799. display: 'inline',
  9800. position: 'absolute',
  9801. top: -10000000,
  9802. left: -100000
  9803. } ).appendTo( document.body),
  9804. width = $tmpNode.width();
  9805. $tmpNode.remove();
  9806. $tmpNode = null;
  9807. if( width < 50 ) {
  9808. return word;
  9809. } else {
  9810. word = word.slice( 0, hasSuffix ? -4 : -1 );
  9811. if( !word.length ) {
  9812. return '...';
  9813. }
  9814. return wordCountAdaptive( word + '...', true );
  9815. }
  9816. }
  9817. //段落参数转换
  9818. function transForParagraph ( options ) {
  9819. var tempItems = [];
  9820. for( var key in options.items ) {
  9821. options.value.push( key );
  9822. tempItems.push( key );
  9823. options.autowidthitem.push( wordCountAdaptive( key ) );
  9824. }
  9825. options.items = tempItems;
  9826. options.autoRecord = false;
  9827. return options;
  9828. }
  9829. //字体参数转换
  9830. function transForFontfamily ( options ) {
  9831. var temp = null,
  9832. tempItems = [];
  9833. for( var i = 0, len = options.items.length; i < len; i++ ) {
  9834. temp = options.items[ i ].val;
  9835. tempItems.push( temp.split(/\s*,\s*/)[0] );
  9836. options.itemStyles.push('font-family: ' + temp);
  9837. options.value.push( temp );
  9838. options.autowidthitem.push( wordCountAdaptive( tempItems[ i ] ) );
  9839. }
  9840. options.items = tempItems;
  9841. return options;
  9842. }
  9843. //字体大小参数转换
  9844. function transForFontsize ( options ) {
  9845. var temp = null,
  9846. tempItems = [];
  9847. options.itemStyles = [];
  9848. options.value = [];
  9849. for( var i = 0, len = options.items.length; i < len; i++ ) {
  9850. temp = options.items[ i ];
  9851. tempItems.push( temp );
  9852. options.itemStyles.push('font-size: ' + temp +'px');
  9853. }
  9854. options.value = options.items;
  9855. options.items = tempItems;
  9856. options.autoRecord = false;
  9857. return options;
  9858. }
  9859. });
  9860. UM.registerUI('forecolor backcolor', function( name ) {
  9861. function getCurrentColor() {
  9862. return domUtils.getComputedStyle( $colorLabel[0], 'background-color' );
  9863. }
  9864. var me = this,
  9865. $colorPickerWidget = null,
  9866. $colorLabel = null,
  9867. $btn = null;
  9868. //querycommand
  9869. this.addListener('selectionchange', function(){
  9870. var state = this.queryCommandState( name );
  9871. $btn.edui().disabled( state == -1 ).active( state == 1 );
  9872. });
  9873. $btn = $.eduicolorsplitbutton({
  9874. icon: name,
  9875. caret: true,
  9876. name: name,
  9877. title: me.getLang("labelMap")[name],
  9878. click: function() {
  9879. me.execCommand( name, getCurrentColor() );
  9880. }
  9881. });
  9882. $colorLabel = $btn.edui().colorLabel();
  9883. $colorPickerWidget = $.eduicolorpicker({
  9884. name: name,
  9885. lang_clearColor: me.getLang('clearColor') || '',
  9886. lang_themeColor: me.getLang('themeColor') || '',
  9887. lang_standardColor: me.getLang('standardColor') || ''
  9888. })
  9889. .on('pickcolor', function( evt, color ){
  9890. window.setTimeout( function(){
  9891. $colorLabel.css("backgroundColor", color);
  9892. me.execCommand( name, color );
  9893. }, 0 );
  9894. })
  9895. .on('show',function(){
  9896. UM.setActiveWidget( colorPickerWidget.root() );
  9897. }).css('zIndex',me.getOpt('zIndex') + 1);
  9898. $btn.edui().on('arrowclick',function(){
  9899. if(!$colorPickerWidget.parent().length){
  9900. me.$container.find('.edui-dialog-container').append($colorPickerWidget);
  9901. }
  9902. $colorPickerWidget.edui().show($btn,{
  9903. caretDir:"down",
  9904. offsetTop:-5,
  9905. offsetLeft:8,
  9906. caretLeft:11,
  9907. caretTop:-8
  9908. });
  9909. UM.setTopEditor(me);
  9910. }).register('click', $btn, function () {
  9911. $colorPickerWidget.edui().hide()
  9912. });
  9913. return $btn;
  9914. });
  9915. })(jQuery)