ueditor_all.js 1022 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535
  1. /*!
  2. * UEditor
  3. * version: 1.3.6
  4. * build: Wed Dec 25 2013 12:38:31 GMT+0800 (中国标准时间)
  5. */
  6. (function(){
  7. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  8. var baidu = window.baidu || {};
  9. window.baidu = baidu;
  10. window.UE = baidu.editor = window.UE || {};
  11. UE.plugins = {};
  12. UE.commands = {};
  13. UE.instants = {};
  14. UE.I18N = {};
  15. UE.version = "1.3.6";
  16. var dom = UE.dom = {};
  17. /**
  18. * 浏览器判断模块
  19. * @file
  20. * @module UE.browser
  21. * @since 1.2.6.1
  22. */
  23. /**
  24. * 提供浏览器检测的模块
  25. * @unfile
  26. * @module UE.browser
  27. */
  28. var browser = UE.browser = function(){
  29. var agent = navigator.userAgent.toLowerCase(),
  30. opera = window.opera,
  31. browser = {
  32. /**
  33. * @property {boolean} ie 检测当前浏览器是否为IE
  34. * @example
  35. * ```javascript
  36. * if ( UE.browser.ie ) {
  37. * console.log( '当前浏览器是IE' );
  38. * }
  39. * ```
  40. */
  41. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  42. /**
  43. * @property {boolean} opera 检测当前浏览器是否为Opera
  44. * @example
  45. * ```javascript
  46. * if ( UE.browser.opera ) {
  47. * console.log( '当前浏览器是Opera' );
  48. * }
  49. * ```
  50. */
  51. opera : ( !!opera && opera.version ),
  52. /**
  53. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  54. * @example
  55. * ```javascript
  56. * if ( UE.browser.webkit ) {
  57. * console.log( '当前浏览器是webkit内核浏览器' );
  58. * }
  59. * ```
  60. */
  61. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  62. /**
  63. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  64. * @example
  65. * ```javascript
  66. * if ( UE.browser.mac ) {
  67. * console.log( '当前浏览器运行在mac平台下' );
  68. * }
  69. * ```
  70. */
  71. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  72. /**
  73. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  74. * @example
  75. * ```javascript
  76. * if ( UE.browser.quirks ) {
  77. * console.log( '当前浏览器运行处于“怪异模式”' );
  78. * }
  79. * ```
  80. */
  81. quirks : ( document.compatMode == 'BackCompat' )
  82. };
  83. /**
  84. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  85. * @example
  86. * ```javascript
  87. * if ( UE.browser.gecko ) {
  88. * console.log( '当前浏览器内核是gecko内核' );
  89. * }
  90. * ```
  91. */
  92. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  93. var version = 0;
  94. // Internet Explorer 6.0+
  95. if ( browser.ie ){
  96. version = (agent.match(/(msie\s|trident.*rv:)([\w.]+)/)[2] || 0) * 1;
  97. browser.ie11Compat = document.documentMode == 11;
  98. /**
  99. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  100. * @warning 如果浏览器不是IE, 则该值为undefined
  101. * @example
  102. * ```javascript
  103. * if ( UE.browser.ie9Compat ) {
  104. * console.log( '当前浏览器运行在IE9兼容模式下' );
  105. * }
  106. * ```
  107. */
  108. browser.ie9Compat = document.documentMode == 9;
  109. /**
  110. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  111. * @warning 如果浏览器不是IE, 则该值为undefined
  112. * @example
  113. * ```javascript
  114. * if ( UE.browser.ie8 ) {
  115. * console.log( '当前浏览器是IE8浏览器' );
  116. * }
  117. * ```
  118. */
  119. browser.ie8 = !!document.documentMode;
  120. /**
  121. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  122. * @warning 如果浏览器不是IE, 则该值为undefined
  123. * @example
  124. * ```javascript
  125. * if ( UE.browser.ie8Compat ) {
  126. * console.log( '当前浏览器运行在IE8兼容模式下' );
  127. * }
  128. * ```
  129. */
  130. browser.ie8Compat = document.documentMode == 8;
  131. /**
  132. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  133. * @warning 如果浏览器不是IE, 则该值为undefined
  134. * @example
  135. * ```javascript
  136. * if ( UE.browser.ie7Compat ) {
  137. * console.log( '当前浏览器运行在IE7兼容模式下' );
  138. * }
  139. * ```
  140. */
  141. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  142. || document.documentMode == 7 );
  143. /**
  144. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  145. * @warning 如果浏览器不是IE, 则该值为undefined
  146. * @example
  147. * ```javascript
  148. * if ( UE.browser.ie6Compat ) {
  149. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  150. * }
  151. * ```
  152. */
  153. browser.ie6Compat = ( version < 7 || browser.quirks );
  154. browser.ie9above = version > 8;
  155. browser.ie9below = version < 9;
  156. }
  157. // Gecko.
  158. if ( browser.gecko ){
  159. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  160. if ( geckoRelease )
  161. {
  162. geckoRelease = geckoRelease[1].split( '.' );
  163. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  164. }
  165. }
  166. /**
  167. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  168. * @warning 如果浏览器不是chrome, 则该值为undefined
  169. * @example
  170. * ```javascript
  171. * if ( UE.browser.chrome ) {
  172. * console.log( '当前浏览器是Chrome' );
  173. * }
  174. * ```
  175. */
  176. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  177. browser.chrome = + RegExp['\x241'];
  178. }
  179. /**
  180. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  181. * @warning 如果浏览器不是safari, 则该值为undefined
  182. * @example
  183. * ```javascript
  184. * if ( UE.browser.safari ) {
  185. * console.log( '当前浏览器是Safari' );
  186. * }
  187. * ```
  188. */
  189. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  190. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  191. }
  192. // Opera 9.50+
  193. if ( browser.opera )
  194. version = parseFloat( opera.version() );
  195. // WebKit 522+ (Safari 3+)
  196. if ( browser.webkit )
  197. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  198. /**
  199. * @property { Number } version 检测当前浏览器版本号
  200. * @remind
  201. * <ul>
  202. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  203. * <li>gecko系列会返回10900,158900等</li>
  204. * <li>webkit系列会返回其build号 (如 522等)</li>
  205. * </ul>
  206. * @example
  207. * ```javascript
  208. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  209. * ```
  210. */
  211. browser.version = version;
  212. /**
  213. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  214. * @example
  215. * ```javascript
  216. * if ( UE.browser.isCompatible ) {
  217. * console.log( '浏览器与UEditor能够良好兼容' );
  218. * }
  219. * ```
  220. */
  221. browser.isCompatible =
  222. !browser.mobile && (
  223. ( browser.ie && version >= 6 ) ||
  224. ( browser.gecko && version >= 10801 ) ||
  225. ( browser.opera && version >= 9.5 ) ||
  226. ( browser.air && version >= 1 ) ||
  227. ( browser.webkit && version >= 522 ) ||
  228. false );
  229. return browser;
  230. }();
  231. //快捷方式
  232. var ie = browser.ie,
  233. webkit = browser.webkit,
  234. gecko = browser.gecko,
  235. opera = browser.opera;
  236. /**
  237. * 工具函数包
  238. * @file
  239. * @module UE.utils
  240. * @since 1.2.6.1
  241. */
  242. /**
  243. * UEditor封装使用的静态工具函数
  244. * @module UE.utils
  245. * @unfile
  246. */
  247. var utils = UE.utils = {
  248. /**
  249. * 用给定的迭代器遍历对象
  250. * @method each
  251. * @param { Object } obj 需要遍历的对象
  252. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  253. * @example
  254. * ```javascript
  255. * var demoObj = {
  256. * key1: 1,
  257. * key2: 2
  258. * };
  259. *
  260. * //output: key1: 1, key2: 2
  261. * UE.utils.each( demoObj, funciton ( value, key ) {
  262. *
  263. * console.log( key + ":" + value );
  264. *
  265. * } );
  266. * ```
  267. */
  268. /**
  269. * 用给定的迭代器遍历数组或类数组对象
  270. * @method each
  271. * @param { Array } array 需要遍历的数组或者类数组
  272. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  273. * @example
  274. * ```javascript
  275. * var divs = document.getElmentByTagNames( "div" );
  276. *
  277. * //output: 0: DIV, 1: DIV ...
  278. * UE.utils.each( divs, funciton ( value, key ) {
  279. *
  280. * console.log( key + ":" + value.tagName );
  281. *
  282. * } );
  283. * ```
  284. */
  285. each : function(obj, iterator, context) {
  286. if (obj == null) return;
  287. if (obj.length === +obj.length) {
  288. for (var i = 0, l = obj.length; i < l; i++) {
  289. if(iterator.call(context, obj[i], i, obj) === false)
  290. return false;
  291. }
  292. } else {
  293. for (var key in obj) {
  294. if (obj.hasOwnProperty(key)) {
  295. if(iterator.call(context, obj[key], key, obj) === false)
  296. return false;
  297. }
  298. }
  299. }
  300. },
  301. /**
  302. * 以给定对象作为原型创建一个新对象
  303. * @method makeInstance
  304. * @param { Object } protoObject 该对象将作为新创建对象的原型
  305. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  306. * @example
  307. * ```javascript
  308. *
  309. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  310. *
  311. * var newObject = UE.utils.makeInstance( protoObject );
  312. * //output: Hello UEditor!
  313. * newObject.sayHello();
  314. * ```
  315. */
  316. makeInstance:function (obj) {
  317. var noop = new Function();
  318. noop.prototype = obj;
  319. obj = new noop;
  320. noop.prototype = null;
  321. return obj;
  322. },
  323. /**
  324. * 将source对象中的属性扩展到target对象上
  325. * @method extend
  326. * @remind 该方法将强制把source对象上的属性复制到target对象上
  327. * @see UE.utils.extend(Object,Object,Boolean)
  328. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  329. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  330. * @return { Object } 返回target对象
  331. * @example
  332. * ```javascript
  333. *
  334. * var target = { name: 'target', sex: 1 },
  335. * source = { name: 'source', age: 17 };
  336. *
  337. * UE.utils.extend( target, source );
  338. *
  339. * //output: { name: 'source', sex: 1, age: 17 }
  340. * console.log( target );
  341. *
  342. * ```
  343. */
  344. /**
  345. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  346. * 源对象属性名相同的属性值。
  347. * @method extend
  348. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  349. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  350. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  351. * @return { Object } 返回target对象
  352. * @example
  353. * ```javascript
  354. *
  355. * var target = { name: 'target', sex: 1 },
  356. * source = { name: 'source', age: 17 };
  357. *
  358. * UE.utils.extend( target, source, true );
  359. *
  360. * //output: { name: 'target', sex: 1, age: 17 }
  361. * console.log( target );
  362. *
  363. * ```
  364. */
  365. extend:function (t, s, b) {
  366. if (s) {
  367. for (var k in s) {
  368. if (!b || !t.hasOwnProperty(k)) {
  369. t[k] = s[k];
  370. }
  371. }
  372. }
  373. return t;
  374. },
  375. /**
  376. * 将给定的多个对象的属性复制到目标对象target上
  377. * @method extend2
  378. * @remind 该方法将强制把源对象上的属性复制到target对象上
  379. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  380. * 将会覆盖掉之前的值。
  381. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  382. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  383. * @return { Object } 返回target对象
  384. * @example
  385. * ```javascript
  386. *
  387. * var target = {},
  388. * source1 = { name: 'source', age: 17 },
  389. * source2 = { title: 'dev' };
  390. *
  391. * UE.utils.extend2( target, source1, source2 );
  392. *
  393. * //output: { name: 'source', age: 17, title: 'dev' }
  394. * console.log( target );
  395. *
  396. * ```
  397. */
  398. extend2:function (t) {
  399. var a = arguments;
  400. for (var i = 1; i < a.length; i++) {
  401. var x = a[i];
  402. for (var k in x) {
  403. if (!t.hasOwnProperty(k)) {
  404. t[k] = x[k];
  405. }
  406. }
  407. }
  408. return t;
  409. },
  410. /**
  411. * 模拟继承机制, 使得subClass继承自superClass
  412. * @method inherits
  413. * @param { Object } subClass 子类对象
  414. * @param { Object } superClass 超类对象
  415. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  416. * @return { Object } 继承superClass后的子类对象
  417. * @example
  418. * ```javascript
  419. * function SuperClass(){
  420. * this.name = "小李";
  421. * }
  422. *
  423. * SuperClass.prototype = {
  424. * hello:function(str){
  425. * console.log(this.name + str);
  426. * }
  427. * }
  428. *
  429. * function SubClass(){
  430. * this.name = "小张";
  431. * }
  432. *
  433. * UE.utils.inherits(SubClass,SuperClass);
  434. *
  435. * var sub = new SubClass();
  436. * //output: '小张早上好!
  437. * sub.hello("早上好!");
  438. * ```
  439. */
  440. inherits:function (subClass, superClass) {
  441. var oldP = subClass.prototype,
  442. newP = utils.makeInstance(superClass.prototype);
  443. utils.extend(newP, oldP, true);
  444. subClass.prototype = newP;
  445. return (newP.constructor = subClass);
  446. },
  447. /**
  448. * 用指定的context对象作为函数fn的上下文
  449. * @method bind
  450. * @param { Function } fn 需要绑定上下文的函数对象
  451. * @param { Object } content 函数fn新的上下文对象
  452. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  453. * @example
  454. * ```javascript
  455. *
  456. * var name = 'window',
  457. * newTest = null;
  458. *
  459. * function test () {
  460. * console.log( this.name );
  461. * }
  462. *
  463. * newTest = UE.utils.bind( test, { name: 'object' } );
  464. *
  465. * //output: object
  466. * newTest();
  467. *
  468. * //output: window
  469. * test();
  470. *
  471. * ```
  472. */
  473. bind:function (fn, context) {
  474. return function () {
  475. return fn.apply(context, arguments);
  476. };
  477. },
  478. /**
  479. * 创建延迟指定时间后执行的函数fn
  480. * @method defer
  481. * @param { Function } fn 需要延迟执行的函数对象
  482. * @param { int } delay 延迟的时间, 单位是毫秒
  483. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  484. * 而不能保证刚好到达延迟时间时执行。
  485. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  486. * @example
  487. * ```javascript
  488. * var start = 0;
  489. *
  490. * function test(){
  491. * console.log( new Date() - start );
  492. * }
  493. *
  494. * var testDefer = UE.utils.defer( test, 1000 );
  495. * //
  496. * start = new Date();
  497. * //output: (大约在1000毫秒之后输出) 1000
  498. * testDefer();
  499. * ```
  500. */
  501. /**
  502. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  503. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  504. * @method defer
  505. * @param { Function } fn 需要延迟执行的函数对象
  506. * @param { int } delay 延迟的时间, 单位是毫秒
  507. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  508. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  509. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  510. * 而不能保证刚好到达延迟时间时执行。
  511. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  512. * @example
  513. * ```javascript
  514. *
  515. * function test(){
  516. * console.log(1);
  517. * }
  518. *
  519. * var testDefer = UE.utils.defer( test, 1000, true );
  520. *
  521. * //output: (两次调用仅有一次输出) 1
  522. * testDefer();
  523. * testDefer();
  524. * ```
  525. */
  526. defer:function (fn, delay, exclusion) {
  527. var timerID;
  528. return function () {
  529. if (exclusion) {
  530. clearTimeout(timerID);
  531. }
  532. timerID = setTimeout(fn, delay);
  533. };
  534. },
  535. /**
  536. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  537. * @method indexOf
  538. * @remind 该方法的匹配过程使用的是恒等“===”
  539. * @param { Array } array 需要查找的数组对象
  540. * @param { * } item 需要在目标数组中查找的值
  541. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  542. * @example
  543. * ```javascript
  544. * var item = 1,
  545. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  546. *
  547. * //output: 4
  548. * console.log( UE.utils.indexOf( arr, item ) );
  549. * ```
  550. */
  551. /**
  552. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  553. * @method indexOf
  554. * @remind 该方法的匹配过程使用的是恒等“===”
  555. * @param { Array } array 需要查找的数组对象
  556. * @param { * } item 需要在目标数组中查找的值
  557. * @param { int } start 搜索的起始位置
  558. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  559. * @example
  560. * ```javascript
  561. * var item = 1,
  562. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  563. *
  564. * //output: 9
  565. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  566. * ```
  567. */
  568. indexOf:function (array, item, start) {
  569. var index = -1;
  570. start = this.isNumber(start) ? start : 0;
  571. this.each(array, function (v, i) {
  572. if (i >= start && v === item) {
  573. index = i;
  574. return false;
  575. }
  576. });
  577. return index;
  578. },
  579. /**
  580. * 移除数组array中所有的元素item
  581. * @method removeItem
  582. * @param { Array } array 要移除元素的目标数组
  583. * @param { * } item 将要被移除的元素
  584. * @remind 该方法的匹配过程使用的是恒等“===”
  585. * @example
  586. * ```javascript
  587. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  588. *
  589. * UE.utils.removeItem( arr, 4 );
  590. * //output: [ 5, 7, 1, 3, 6 ]
  591. * console.log( arr );
  592. *
  593. * ```
  594. */
  595. removeItem:function (array, item) {
  596. for (var i = 0, l = array.length; i < l; i++) {
  597. if (array[i] === item) {
  598. array.splice(i, 1);
  599. i--;
  600. }
  601. }
  602. },
  603. /**
  604. * 删除字符串str的首尾空格
  605. * @method trim
  606. * @param { String } str 需要删除首尾空格的字符串
  607. * @return { String } 删除了首尾的空格后的字符串
  608. * @example
  609. * ```javascript
  610. *
  611. * var str = " UEdtior ";
  612. *
  613. * //output: 9
  614. * console.log( str.length );
  615. *
  616. * //output: 7
  617. * console.log( UE.utils.trim( " UEdtior " ).length );
  618. *
  619. * //output: 9
  620. * console.log( str.length );
  621. *
  622. * ```
  623. */
  624. trim:function (str) {
  625. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  626. },
  627. /**
  628. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  629. * @method listToMap
  630. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  631. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  632. * @return { Object } 转化之后的hash对象
  633. * @example
  634. * ```javascript
  635. *
  636. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  637. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  638. *
  639. * ```
  640. */
  641. /**
  642. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  643. * @method listToMap
  644. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  645. * @param { Array } arr 字符串数组
  646. * @return { Object } 转化之后的hash对象
  647. * @example
  648. * ```javascript
  649. *
  650. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  651. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  652. *
  653. * ```
  654. */
  655. listToMap:function (list) {
  656. if (!list)return {};
  657. list = utils.isArray(list) ? list : list.split(',');
  658. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  659. obj[ci.toUpperCase()] = obj[ci] = 1;
  660. }
  661. return obj;
  662. },
  663. /**
  664. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  665. * @method unhtml
  666. * @param { String } str 需要转义的字符串
  667. * @return { String } 转义后的字符串
  668. * @example
  669. * ```javascript
  670. * var html = '<body>&</body>';
  671. *
  672. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  673. * console.log( UE.utils.unhtml( html ) );
  674. *
  675. * ```
  676. */
  677. unhtml:function (str, reg) {
  678. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) {
  679. if (b) {
  680. return a;
  681. } else {
  682. return {
  683. '<':'&lt;',
  684. '&':'&amp;',
  685. '"':'&quot;',
  686. '>':'&gt;',
  687. "'":'&#39;'
  688. }[a]
  689. }
  690. }) : '';
  691. },
  692. /**
  693. * 将str中的转义字符还原成html字符
  694. * @see UE.utils.unhtml(String);
  695. * @method html
  696. * @param { String } str 需要逆转义的字符串
  697. * @return { String } 逆转义后的字符串
  698. * @example
  699. * ```javascript
  700. *
  701. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  702. *
  703. * //output: <body>&</body>
  704. * console.log( UE.utils.html( str ) );
  705. *
  706. * ```
  707. */
  708. html:function (str) {
  709. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  710. return {
  711. '&lt;':'<',
  712. '&amp;':'&',
  713. '&quot;':'"',
  714. '&gt;':'>',
  715. '&#39;':"'",
  716. '&nbsp;':' '
  717. }[m]
  718. }) : '';
  719. },
  720. /**
  721. * 将css样式转换为驼峰的形式
  722. * @method cssStyleToDomStyle
  723. * @param { String } cssName 需要转换的css样式名
  724. * @return { String } 转换成驼峰形式后的css样式名
  725. * @example
  726. * ```javascript
  727. *
  728. * var str = 'border-top';
  729. *
  730. * //output: borderTop
  731. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  732. *
  733. * ```
  734. */
  735. cssStyleToDomStyle:function () {
  736. var test = document.createElement('div').style,
  737. cache = {
  738. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  739. };
  740. return function (cssName) {
  741. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  742. return match.charAt(1).toUpperCase();
  743. }));
  744. };
  745. }(),
  746. /**
  747. * 动态加载文件到doc中
  748. * @method loadFile
  749. * @param { DomDocument } document 需要加载资源文件的文档对象
  750. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  751. * @example
  752. * ```javascript
  753. *
  754. * UE.utils.loadFile( document, {
  755. * src:"test.js",
  756. * tag:"script",
  757. * type:"text/javascript",
  758. * defer:"defer"
  759. * } );
  760. *
  761. * ```
  762. */
  763. /**
  764. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  765. * @method loadFile
  766. * @param { DomDocument } document 需要加载资源文件的文档对象
  767. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  768. * @param { Function } fn 资源文件加载成功之后执行的回调
  769. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  770. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  771. * @example
  772. * ```javascript
  773. *
  774. * UE.utils.loadFile( document, {
  775. * src:"test.js",
  776. * tag:"script",
  777. * type:"text/javascript",
  778. * defer:"defer"
  779. * }, function () {
  780. * console.log('加载成功');
  781. * } );
  782. *
  783. * ```
  784. */
  785. loadFile:function () {
  786. var tmpList = [];
  787. function getItem(doc, obj) {
  788. try {
  789. for (var i = 0, ci; ci = tmpList[i++];) {
  790. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  791. return ci;
  792. }
  793. }
  794. } catch (e) {
  795. return null;
  796. }
  797. }
  798. return function (doc, obj, fn) {
  799. var item = getItem(doc, obj);
  800. if (item) {
  801. if (item.ready) {
  802. fn && fn();
  803. } else {
  804. item.funs.push(fn)
  805. }
  806. return;
  807. }
  808. tmpList.push({
  809. doc:doc,
  810. url:obj.src || obj.href,
  811. funs:[fn]
  812. });
  813. if (!doc.body) {
  814. var html = [];
  815. for (var p in obj) {
  816. if (p == 'tag')continue;
  817. html.push(p + '="' + obj[p] + '"')
  818. }
  819. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  820. return;
  821. }
  822. if (obj.id && doc.getElementById(obj.id)) {
  823. return;
  824. }
  825. var element = doc.createElement(obj.tag);
  826. delete obj.tag;
  827. for (var p in obj) {
  828. element.setAttribute(p, obj[p]);
  829. }
  830. element.onload = element.onreadystatechange = function () {
  831. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  832. item = getItem(doc, obj);
  833. if (item.funs.length > 0) {
  834. item.ready = 1;
  835. for (var fi; fi = item.funs.pop();) {
  836. fi();
  837. }
  838. }
  839. element.onload = element.onreadystatechange = null;
  840. }
  841. };
  842. element.onerror = function () {
  843. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  844. };
  845. doc.getElementsByTagName("head")[0].appendChild(element);
  846. }
  847. }(),
  848. /**
  849. * 判断obj对象是否为空
  850. * @method isEmptyObject
  851. * @param { * } obj 需要判断的对象
  852. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  853. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  854. * @return { Boolean } 对象是否为空
  855. * @example
  856. * ```javascript
  857. *
  858. * //output: true
  859. * console.log( UE.utils.isEmptyObject( {} ) );
  860. *
  861. * //output: true
  862. * console.log( UE.utils.isEmptyObject( [] ) );
  863. *
  864. * //output: true
  865. * console.log( UE.utils.isEmptyObject( "" ) );
  866. *
  867. * //output: false
  868. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  869. *
  870. * //output: false
  871. * console.log( UE.utils.isEmptyObject( [1] ) );
  872. *
  873. * //output: false
  874. * console.log( UE.utils.isEmptyObject( "1" ) );
  875. *
  876. * ```
  877. */
  878. isEmptyObject:function (obj) {
  879. if (obj == null) return true;
  880. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  881. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  882. return true;
  883. },
  884. /*
  885. * 把rgb格式的颜色值转换成16进制格式
  886. * @method fixColor
  887. * @param { String } rgb格式的颜色值
  888. * @param { String }
  889. * @example
  890. * rgb(255,255,255) => "#ffffff"
  891. */
  892. fixColor:function (name, value) {
  893. if (/color/i.test(name) && /rgba?/.test(value)) {
  894. var array = value.split(",");
  895. if (array.length > 3)
  896. return "";
  897. value = "#";
  898. for (var i = 0, color; color = array[i++];) {
  899. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  900. value += color.length == 1 ? "0" + color : color;
  901. }
  902. value = value.toUpperCase();
  903. }
  904. return value;
  905. },
  906. /*
  907. * 只针对border,padding,margin做了处理,因为性能问题
  908. * @public
  909. * @function
  910. * @param {String} val style字符串
  911. */
  912. optCss:function (val) {
  913. var padding, margin, border;
  914. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  915. if (val.split(' ').length == 1) {
  916. switch (key) {
  917. case 'padding':
  918. !padding && (padding = {});
  919. padding[name] = val;
  920. return '';
  921. case 'margin':
  922. !margin && (margin = {});
  923. margin[name] = val;
  924. return '';
  925. case 'border':
  926. return val == 'initial' ? '' : str;
  927. }
  928. }
  929. return str;
  930. });
  931. function opt(obj, name) {
  932. if (!obj) {
  933. return '';
  934. }
  935. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  936. if (!t || !l || !b || !r) {
  937. for (var p in obj) {
  938. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  939. }
  940. } else {
  941. val += ';' + name + ':' +
  942. (t == b && b == l && l == r ? t :
  943. t == b && l == r ? (t + ' ' + l) :
  944. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  945. }
  946. return val;
  947. }
  948. val += opt(padding, 'padding') + opt(margin, 'margin');
  949. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  950. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  951. return b ? b + ";;" : ';'
  952. });
  953. },
  954. /**
  955. * 克隆对象
  956. * @method clone
  957. * @param { Object } source 源对象
  958. * @return { Object } source的一个副本
  959. */
  960. /**
  961. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  962. * @method clone
  963. * @param { Object } source 源对象
  964. * @param { Object } target 目标对象
  965. * @return { Object } 附加了source对象所有属性的target对象
  966. */
  967. clone:function (source, target) {
  968. var tmp;
  969. target = target || {};
  970. for (var i in source) {
  971. if (source.hasOwnProperty(i)) {
  972. tmp = source[i];
  973. if (typeof tmp == 'object') {
  974. target[i] = utils.isArray(tmp) ? [] : {};
  975. utils.clone(source[i], target[i])
  976. } else {
  977. target[i] = tmp;
  978. }
  979. }
  980. }
  981. return target;
  982. },
  983. /**
  984. * 把cm/pt为单位的值转换为px为单位的值
  985. * @method transUnitToPx
  986. * @param { String } 待转换的带单位的字符串
  987. * @return { String } 转换为px为计量单位的值的字符串
  988. * @example
  989. * ```javascript
  990. *
  991. * //output: 500px
  992. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  993. *
  994. * //output: 27px
  995. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  996. *
  997. * ```
  998. */
  999. transUnitToPx:function (val) {
  1000. if (!/(pt|cm)/.test(val)) {
  1001. return val
  1002. }
  1003. var unit;
  1004. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1005. val = v;
  1006. unit = u;
  1007. });
  1008. switch (unit) {
  1009. case 'cm':
  1010. val = parseFloat(val) * 25;
  1011. break;
  1012. case 'pt':
  1013. val = Math.round(parseFloat(val) * 96 / 72);
  1014. }
  1015. return val + (val ? 'px' : '');
  1016. },
  1017. /**
  1018. * 在dom树ready之后执行给定的回调函数
  1019. * @method domReady
  1020. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1021. * @param { Function } fn dom树ready之后的回调函数
  1022. * @example
  1023. * ```javascript
  1024. *
  1025. * UE.utils.domReady( function () {
  1026. *
  1027. * console.log('123');
  1028. *
  1029. * } );
  1030. *
  1031. * ```
  1032. */
  1033. domReady:function () {
  1034. var fnArr = [];
  1035. function doReady(doc) {
  1036. //确保onready只执行一次
  1037. doc.isReady = true;
  1038. for (var ci; ci = fnArr.pop(); ci()) {
  1039. }
  1040. }
  1041. return function (onready, win) {
  1042. win = win || window;
  1043. var doc = win.document;
  1044. onready && fnArr.push(onready);
  1045. if (doc.readyState === "complete") {
  1046. doReady(doc);
  1047. } else {
  1048. doc.isReady && doReady(doc);
  1049. if (browser.ie && browser.version != 11) {
  1050. (function () {
  1051. if (doc.isReady) return;
  1052. try {
  1053. doc.documentElement.doScroll("left");
  1054. } catch (error) {
  1055. setTimeout(arguments.callee, 0);
  1056. return;
  1057. }
  1058. doReady(doc);
  1059. })();
  1060. win.attachEvent('onload', function () {
  1061. doReady(doc)
  1062. });
  1063. } else {
  1064. doc.addEventListener("DOMContentLoaded", function () {
  1065. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1066. doReady(doc);
  1067. }, false);
  1068. win.addEventListener('load', function () {
  1069. doReady(doc)
  1070. }, false);
  1071. }
  1072. }
  1073. }
  1074. }(),
  1075. /*
  1076. * 动态添加css样式
  1077. * @method cssRule
  1078. * @param { String } 节点名称
  1079. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1080. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1081. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1082. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1083. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1084. */
  1085. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1086. var indexList, index;
  1087. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1088. //获取样式
  1089. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1090. indexList = doc.indexList || (doc.indexList = {});
  1091. index = indexList[key];
  1092. if(index !== undefined){
  1093. return doc.styleSheets[index].cssText
  1094. }
  1095. return undefined;
  1096. }
  1097. doc = doc || document;
  1098. indexList = doc.indexList || (doc.indexList = {});
  1099. index = indexList[key];
  1100. //清除样式
  1101. if(style === ''){
  1102. if(index!== undefined){
  1103. doc.styleSheets[index].cssText = '';
  1104. delete indexList[key];
  1105. return true
  1106. }
  1107. return false;
  1108. }
  1109. //添加样式
  1110. if(index!== undefined){
  1111. sheetStyle = doc.styleSheets[index];
  1112. }else{
  1113. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1114. indexList[key] = index;
  1115. }
  1116. sheetStyle.cssText = style;
  1117. }: function (key, style, doc) {
  1118. var head, node;
  1119. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1120. //获取样式
  1121. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1122. node = doc.getElementById(key);
  1123. return node ? node.innerHTML : undefined;
  1124. }
  1125. doc = doc || document;
  1126. node = doc.getElementById(key);
  1127. //清除样式
  1128. if(style === ''){
  1129. if(node){
  1130. node.parentNode.removeChild(node);
  1131. return true
  1132. }
  1133. return false;
  1134. }
  1135. //添加样式
  1136. if(node){
  1137. node.innerHTML = style;
  1138. }else{
  1139. node = doc.createElement('style');
  1140. node.id = key;
  1141. node.innerHTML = style;
  1142. doc.getElementsByTagName('head')[0].appendChild(node);
  1143. }
  1144. },
  1145. sort:function(array,compareFn){
  1146. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1147. for(var i= 0,len = array.length; i<len; i++){
  1148. for(var j = i,length = array.length; j<length; j++){
  1149. if(compareFn(array[i], array[j]) > 0){
  1150. var t = array[i];
  1151. array[i] = array[j];
  1152. array[j] = t;
  1153. }
  1154. }
  1155. }
  1156. return array;
  1157. },
  1158. clearEmptyAttrs : function(obj){
  1159. for(var p in obj){
  1160. if(obj[p] === ''){
  1161. delete obj[p]
  1162. }
  1163. }
  1164. return obj;
  1165. }
  1166. };
  1167. /**
  1168. * 判断给定的对象是否是字符串
  1169. * @method isString
  1170. * @param { * } object 需要判断的对象
  1171. * @return { Boolean } 给定的对象是否是字符串
  1172. */
  1173. /**
  1174. * 判断给定的对象是否是数组
  1175. * @method isArray
  1176. * @param { * } object 需要判断的对象
  1177. * @return { Boolean } 给定的对象是否是数组
  1178. */
  1179. /**
  1180. * 判断给定的对象是否是一个Function
  1181. * @method isFunction
  1182. * @param { * } object 需要判断的对象
  1183. * @return { Boolean } 给定的对象是否是Function
  1184. */
  1185. /**
  1186. * 判断给定的对象是否是Number
  1187. * @method isNumber
  1188. * @param { * } object 需要判断的对象
  1189. * @return { Boolean } 给定的对象是否是Number
  1190. */
  1191. /**
  1192. * 判断给定的对象是否是一个正则表达式
  1193. * @method isRegExp
  1194. * @param { * } object 需要判断的对象
  1195. * @return { Boolean } 给定的对象是否是正则表达式
  1196. */
  1197. /**
  1198. * 判断给定的对象是否是一个普通对象
  1199. * @method isObject
  1200. * @param { * } object 需要判断的对象
  1201. * @return { Boolean } 给定的对象是否是普通对象
  1202. */
  1203. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'], function (v) {
  1204. UE.utils['is' + v] = function (obj) {
  1205. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1206. }
  1207. });
  1208. /**
  1209. * UE采用的事件基类
  1210. * @file
  1211. * @module UE
  1212. * @class EventBase
  1213. * @since 1.2.6.1
  1214. */
  1215. /**
  1216. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1217. * @unfile
  1218. * @module UE
  1219. */
  1220. /**
  1221. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1222. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1223. * @unfile
  1224. * @module UE
  1225. * @class EventBase
  1226. */
  1227. /**
  1228. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1229. * @constructor
  1230. * @example
  1231. * ```javascript
  1232. * UE.EventBase.call(editor);
  1233. * ```
  1234. */
  1235. var EventBase = UE.EventBase = function () {};
  1236. EventBase.prototype = {
  1237. /**
  1238. * 注册事件监听器
  1239. * @method addListener
  1240. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1241. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1242. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1243. * @example
  1244. * ```javascript
  1245. * editor.addListener('selectionchange',function(){
  1246. * console.log("选区已经变化!");
  1247. * })
  1248. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1249. * if(type == 'beforegetcontent'){
  1250. * //do something
  1251. * }else{
  1252. * //do something
  1253. * }
  1254. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1255. * })
  1256. * ```
  1257. * @see UE.EventBase:fireEvent(String)
  1258. */
  1259. addListener:function (types, listener) {
  1260. types = utils.trim(types).split(/\s+/);
  1261. for (var i = 0, ti; ti = types[i++];) {
  1262. getListener(this, ti, true).push(listener);
  1263. }
  1264. },
  1265. on : function(types, listener){
  1266. return this.addListener(types,listener);
  1267. },
  1268. off : function(types, listener){
  1269. return this.removeListener(types, listener)
  1270. },
  1271. trigger:function(){
  1272. return this.fireEvent.apply(this,arguments);
  1273. },
  1274. /**
  1275. * 移除事件监听器
  1276. * @method removeListener
  1277. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1278. * @param { Function } fn 移除监听事件的函数引用
  1279. * @example
  1280. * ```javascript
  1281. * //changeCallback为方法体
  1282. * editor.removeListener("selectionchange",changeCallback);
  1283. * ```
  1284. */
  1285. removeListener:function (types, listener) {
  1286. types = utils.trim(types).split(/\s+/);
  1287. for (var i = 0, ti; ti = types[i++];) {
  1288. utils.removeItem(getListener(this, ti) || [], listener);
  1289. }
  1290. },
  1291. /**
  1292. * 触发事件
  1293. * @method fireEvent
  1294. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1295. * @remind 该方法会触发addListener
  1296. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1297. * @example
  1298. * ```javascript
  1299. * editor.fireEvent("selectionchange");
  1300. * ```
  1301. */
  1302. /**
  1303. * 触发事件
  1304. * @method fireEvent
  1305. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1306. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1307. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1308. * @example
  1309. * ```javascript
  1310. *
  1311. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1312. *
  1313. * console.log( arg1 + " " + arg2 );
  1314. *
  1315. * } );
  1316. *
  1317. * //触发selectionchange事件, 会执行上面的事件监听器
  1318. * //output: Hello World
  1319. * editor.fireEvent("selectionchange", "Hello", "World");
  1320. * ```
  1321. */
  1322. fireEvent:function () {
  1323. var types = arguments[0];
  1324. types = utils.trim(types).split(' ');
  1325. for (var i = 0, ti; ti = types[i++];) {
  1326. var listeners = getListener(this, ti),
  1327. r, t, k;
  1328. if (listeners) {
  1329. k = listeners.length;
  1330. while (k--) {
  1331. if(!listeners[k])continue;
  1332. t = listeners[k].apply(this, arguments);
  1333. if(t === true){
  1334. return t;
  1335. }
  1336. if (t !== undefined) {
  1337. r = t;
  1338. }
  1339. }
  1340. }
  1341. if (t = this['on' + ti.toLowerCase()]) {
  1342. r = t.apply(this, arguments);
  1343. }
  1344. }
  1345. return r;
  1346. }
  1347. };
  1348. /**
  1349. * 获得对象所拥有监听类型的所有监听器
  1350. * @unfile
  1351. * @module UE
  1352. * @since 1.2.6.1
  1353. * @method getListener
  1354. * @public
  1355. * @param { Object } obj 查询监听器的对象
  1356. * @param { String } type 事件类型
  1357. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1358. * @return { Array } 监听器数组
  1359. */
  1360. function getListener(obj, type, force) {
  1361. var allListeners;
  1362. type = type.toLowerCase();
  1363. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1364. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1365. }
  1366. ///import editor.js
  1367. ///import core/dom/dom.js
  1368. ///import core/utils.js
  1369. /*
  1370. * dtd html语义化的体现类
  1371. * @constructor
  1372. * @namespace dtd
  1373. */
  1374. var dtd = dom.dtd = (function() {
  1375. function _( s ) {
  1376. for (var k in s) {
  1377. s[k.toUpperCase()] = s[k];
  1378. }
  1379. return s;
  1380. }
  1381. var X = utils.extend2;
  1382. var A = _({isindex:1,fieldset:1}),
  1383. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1384. C = X( _({a:1}), B ),
  1385. D = X( {iframe:1}, C ),
  1386. 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}),
  1387. F = _({ins:1,del:1,script:1,style:1}),
  1388. 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 ),
  1389. 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 ),
  1390. I = X( _({p:1}), H ),
  1391. J = X( _({iframe:1}), H, B ),
  1392. 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}),
  1393. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1394. M = _({tr:1}),
  1395. N = _({'#':1}),
  1396. O = X( _({param:1}), K ),
  1397. P = X( _({form:1}), A, D, E, I ),
  1398. Q = _({li:1,ol:1,ul:1}),
  1399. R = _({style:1,script:1}),
  1400. S = _({base:1,link:1,meta:1,title:1}),
  1401. T = X( S, R ),
  1402. U = _({head:1,body:1}),
  1403. V = _({html:1});
  1404. 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}),
  1405. 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});
  1406. return _({
  1407. // $ 表示自定的属性
  1408. // body外的元素列表.
  1409. $nonBodyContent: X( V, U, S ),
  1410. //块结构元素列表
  1411. $block : block,
  1412. //内联元素列表
  1413. $inline : L,
  1414. $inlineWithA : X(_({a:1}),L),
  1415. $body : X( _({script:1,style:1}), block ),
  1416. $cdata : _({script:1,style:1}),
  1417. //自闭和元素
  1418. $empty : empty,
  1419. //不是自闭合,但不能让range选中里边
  1420. $nonChild : _({iframe:1,textarea:1}),
  1421. //列表元素列表
  1422. $listItem : _({dd:1,dt:1,li:1}),
  1423. //列表根元素列表
  1424. $list: _({ul:1,ol:1,dl:1}),
  1425. //不能认为是空的元素
  1426. $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}),
  1427. //如果没有子节点就可以删除的元素列表,像span,a
  1428. $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}),
  1429. $removeEmptyBlock : _({'p':1,'div':1}),
  1430. //在table元素里的元素列表
  1431. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1432. //不转换的标签
  1433. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1434. html: U,
  1435. head: T,
  1436. style: N,
  1437. script: N,
  1438. body: P,
  1439. base: {},
  1440. link: {},
  1441. meta: {},
  1442. title: N,
  1443. col : {},
  1444. tr : _({td:1,th:1}),
  1445. img : {},
  1446. embed: {},
  1447. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1448. noscript : P,
  1449. td : P,
  1450. br : {},
  1451. th : P,
  1452. center : P,
  1453. kbd : L,
  1454. button : X( I, E ),
  1455. basefont : {},
  1456. h5 : L,
  1457. h4 : L,
  1458. samp : L,
  1459. h6 : L,
  1460. ol : Q,
  1461. h1 : L,
  1462. h3 : L,
  1463. option : N,
  1464. h2 : L,
  1465. form : X( A, D, E, I ),
  1466. select : _({optgroup:1,option:1}),
  1467. font : L,
  1468. ins : L,
  1469. menu : Q,
  1470. abbr : L,
  1471. label : L,
  1472. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1473. code : L,
  1474. tfoot : M,
  1475. cite : L,
  1476. li : P,
  1477. input : {},
  1478. iframe : P,
  1479. strong : L,
  1480. textarea : N,
  1481. noframes : P,
  1482. big : L,
  1483. small : L,
  1484. //trace:
  1485. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1486. hr : L,
  1487. dt : L,
  1488. sub : L,
  1489. optgroup : _({option:1}),
  1490. param : {},
  1491. bdo : L,
  1492. 'var' : L,
  1493. div : P,
  1494. object : O,
  1495. sup : L,
  1496. dd : P,
  1497. strike : L,
  1498. area : {},
  1499. dir : Q,
  1500. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1501. applet : O,
  1502. dl : _({dt:1,dd:1}),
  1503. del : L,
  1504. isindex : {},
  1505. fieldset : X( _({legend:1}), K ),
  1506. thead : M,
  1507. ul : Q,
  1508. acronym : L,
  1509. b : L,
  1510. a : X( _({a:1}), J ),
  1511. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1512. caption : L,
  1513. i : L,
  1514. u : L,
  1515. tbody : M,
  1516. s : L,
  1517. address : X( D, I ),
  1518. tt : L,
  1519. legend : L,
  1520. q : L,
  1521. pre : X( G, C ),
  1522. p : X(_({'a':1}),L),
  1523. em :L,
  1524. dfn : L
  1525. });
  1526. })();
  1527. /**
  1528. * Dom操作工具包
  1529. * @file
  1530. * @module UE.dom.domUtils
  1531. * @since 1.2.6.1
  1532. */
  1533. /**
  1534. * Dom操作工具包
  1535. * @unfile
  1536. * @module UE.dom.domUtils
  1537. */
  1538. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1539. var tmpNode = startFromChild && node[start],
  1540. parent;
  1541. !tmpNode && (tmpNode = node[ltr]);
  1542. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1543. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1544. return null;
  1545. }
  1546. tmpNode = parent[ltr];
  1547. }
  1548. if (tmpNode && fn && !fn(tmpNode)) {
  1549. return getDomNode(tmpNode, start, ltr, false, fn);
  1550. }
  1551. return tmpNode;
  1552. }
  1553. var attrFix = ie && browser.version < 9 ? {
  1554. tabindex:"tabIndex",
  1555. readonly:"readOnly",
  1556. "for":"htmlFor",
  1557. "class":"className",
  1558. maxlength:"maxLength",
  1559. cellspacing:"cellSpacing",
  1560. cellpadding:"cellPadding",
  1561. rowspan:"rowSpan",
  1562. colspan:"colSpan",
  1563. usemap:"useMap",
  1564. frameborder:"frameBorder"
  1565. } : {
  1566. tabindex:"tabIndex",
  1567. readonly:"readOnly"
  1568. },
  1569. styleBlock = utils.listToMap([
  1570. '-webkit-box', '-moz-box', 'block' ,
  1571. 'list-item' , 'table' , 'table-row-group' ,
  1572. 'table-header-group', 'table-footer-group' ,
  1573. 'table-row' , 'table-column-group' , 'table-column' ,
  1574. 'table-cell' , 'table-caption'
  1575. ]);
  1576. var domUtils = dom.domUtils = {
  1577. //节点常量
  1578. NODE_ELEMENT:1,
  1579. NODE_DOCUMENT:9,
  1580. NODE_TEXT:3,
  1581. NODE_COMMENT:8,
  1582. NODE_DOCUMENT_FRAGMENT:11,
  1583. //位置关系
  1584. POSITION_IDENTICAL:0,
  1585. POSITION_DISCONNECTED:1,
  1586. POSITION_FOLLOWING:2,
  1587. POSITION_PRECEDING:4,
  1588. POSITION_IS_CONTAINED:8,
  1589. POSITION_CONTAINS:16,
  1590. //ie6使用其他的会有一段空白出现
  1591. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1592. //-------------------------Node部分--------------------------------
  1593. keys:{
  1594. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1595. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1596. 37:1, 38:1, 39:1, 40:1,
  1597. 13:1 /*enter*/
  1598. },
  1599. /**
  1600. * 获取节点A相对于节点B的位置关系
  1601. * @method getPosition
  1602. * @param { Node } nodeA 需要查询位置关系的节点A
  1603. * @param { Node } nodeB 需要查询位置关系的节点B
  1604. * @return { Number } 节点A与节点B的关系
  1605. * @example
  1606. * ```javascript
  1607. * //output: 20
  1608. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1609. *
  1610. * switch ( position ) {
  1611. *
  1612. * //0
  1613. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1614. * console.log('元素相同');
  1615. * break;
  1616. * //1
  1617. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1618. * console.log('两个节点在不同的文档中');
  1619. * break;
  1620. * //2
  1621. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1622. * console.log('节点A在节点B之后');
  1623. * break;
  1624. * //4
  1625. * case UE.dom.domUtils.POSITION_PRECEDING;
  1626. * console.log('节点A在节点B之前');
  1627. * break;
  1628. * //8
  1629. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1630. * console.log('节点A被节点B包含');
  1631. * break;
  1632. * case 10:
  1633. * console.log('节点A被节点B包含且节点A在节点B之后');
  1634. * break;
  1635. * //16
  1636. * case UE.dom.domUtils.POSITION_CONTAINS:
  1637. * console.log('节点A包含节点B');
  1638. * break;
  1639. * case 20:
  1640. * console.log('节点A包含节点B且节点A在节点B之前');
  1641. * break;
  1642. *
  1643. * }
  1644. * ```
  1645. */
  1646. getPosition:function (nodeA, nodeB) {
  1647. // 如果两个节点是同一个节点
  1648. if (nodeA === nodeB) {
  1649. // domUtils.POSITION_IDENTICAL
  1650. return 0;
  1651. }
  1652. var node,
  1653. parentsA = [nodeA],
  1654. parentsB = [nodeB];
  1655. node = nodeA;
  1656. while (node = node.parentNode) {
  1657. // 如果nodeB是nodeA的祖先节点
  1658. if (node === nodeB) {
  1659. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1660. return 10;
  1661. }
  1662. parentsA.push(node);
  1663. }
  1664. node = nodeB;
  1665. while (node = node.parentNode) {
  1666. // 如果nodeA是nodeB的祖先节点
  1667. if (node === nodeA) {
  1668. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1669. return 20;
  1670. }
  1671. parentsB.push(node);
  1672. }
  1673. parentsA.reverse();
  1674. parentsB.reverse();
  1675. if (parentsA[0] !== parentsB[0]) {
  1676. // domUtils.POSITION_DISCONNECTED
  1677. return 1;
  1678. }
  1679. var i = -1;
  1680. while (i++, parentsA[i] === parentsB[i]) {
  1681. }
  1682. nodeA = parentsA[i];
  1683. nodeB = parentsB[i];
  1684. while (nodeA = nodeA.nextSibling) {
  1685. if (nodeA === nodeB) {
  1686. // domUtils.POSITION_PRECEDING
  1687. return 4
  1688. }
  1689. }
  1690. // domUtils.POSITION_FOLLOWING
  1691. return 2;
  1692. },
  1693. /**
  1694. * 检测节点node在父节点中的索引位置
  1695. * @method getNodeIndex
  1696. * @param { Node } node 需要检测的节点对象
  1697. * @return { Number } 该节点在父节点中的位置
  1698. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1699. */
  1700. /**
  1701. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1702. * @method getNodeIndex
  1703. * @param { Node } node 需要检测的节点对象
  1704. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1705. * @return { Number } 该节点在父节点中的位置
  1706. * @example
  1707. * ```javascript
  1708. *
  1709. * var node = document.createElement("div");
  1710. *
  1711. * node.appendChild( document.createTextNode( "hello" ) );
  1712. * node.appendChild( document.createTextNode( "world" ) );
  1713. * node.appendChild( node = document.createElement( "div" ) );
  1714. *
  1715. * //output: 2
  1716. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1717. *
  1718. * //output: 1
  1719. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1720. *
  1721. * ```
  1722. */
  1723. getNodeIndex:function (node, ignoreTextNode) {
  1724. var preNode = node,
  1725. i = 0;
  1726. while (preNode = preNode.previousSibling) {
  1727. if (ignoreTextNode && preNode.nodeType == 3) {
  1728. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1729. i++;
  1730. }
  1731. continue;
  1732. }
  1733. i++;
  1734. }
  1735. return i;
  1736. },
  1737. /**
  1738. * 检测节点node是否在给定的document对象上
  1739. * @method inDoc
  1740. * @param { Node } node 需要检测的节点对象
  1741. * @param { DomDocument } doc 需要检测的document对象
  1742. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1743. * @example
  1744. * ```javascript
  1745. *
  1746. * var node = document.createElement("div");
  1747. *
  1748. * //output: false
  1749. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1750. *
  1751. * document.body.appendChild( node );
  1752. *
  1753. * //output: true
  1754. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1755. *
  1756. * ```
  1757. */
  1758. inDoc:function (node, doc) {
  1759. return domUtils.getPosition(node, doc) == 10;
  1760. },
  1761. /**
  1762. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1763. * 查找的起点是给定node节点的父节点。
  1764. * @method findParent
  1765. * @param { Node } node 需要查找的节点
  1766. * @param { Function } filterFn 自定义的过滤方法。
  1767. * @warning 查找的终点是到body节点为止
  1768. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1769. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1770. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1771. * @example
  1772. * ```javascript
  1773. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1774. *
  1775. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1776. * return node.tagName === "HTML";
  1777. *
  1778. * } );
  1779. *
  1780. * //output: true
  1781. * console.log( filterNode === null );
  1782. * ```
  1783. */
  1784. /**
  1785. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1786. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1787. * @method findParent
  1788. * @param { Node } node 需要查找的节点
  1789. * @param { Function } filterFn 自定义的过滤方法。
  1790. * @param { Boolean } includeSelf 查找过程是否包含自身
  1791. * @warning 查找的终点是到body节点为止
  1792. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1793. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1794. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1795. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1796. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1797. * @example
  1798. * ```html
  1799. * <body>
  1800. *
  1801. * <div id="test">
  1802. * </div>
  1803. *
  1804. * <script type="text/javascript">
  1805. *
  1806. * //output: DIV, BODY
  1807. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1808. *
  1809. * console.log( node.tagName );
  1810. * return false;
  1811. *
  1812. * }, true );
  1813. *
  1814. * </script>
  1815. * </body>
  1816. * ```
  1817. */
  1818. findParent:function (node, filterFn, includeSelf) {
  1819. if (node && !domUtils.isBody(node)) {
  1820. node = includeSelf ? node : node.parentNode;
  1821. while (node) {
  1822. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1823. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1824. }
  1825. node = node.parentNode;
  1826. }
  1827. }
  1828. return null;
  1829. },
  1830. /**
  1831. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  1832. * @method findParentByTagName
  1833. * @param { Node } node 需要查找的节点对象
  1834. * @param { Array } tagNames 需要查找的父节点的名称数组
  1835. * @warning 查找的终点是到body节点为止
  1836. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  1837. * @example
  1838. * ```javascript
  1839. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  1840. * //output: BODY
  1841. * console.log( node.tagName );
  1842. * ```
  1843. */
  1844. /**
  1845. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  1846. * 否则, 起点是node的父节点。
  1847. * @method findParentByTagName
  1848. * @param { Node } node 需要查找的节点对象
  1849. * @param { Array } tagNames 需要查找的父节点的名称数组
  1850. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  1851. * @warning 查找的终点是到body节点为止
  1852. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  1853. * @example
  1854. * ```javascript
  1855. * var queryTarget = document.getElementsByTagName("div")[0];
  1856. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  1857. * //output: true
  1858. * console.log( queryTarget === node );
  1859. * ```
  1860. */
  1861. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  1862. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  1863. return domUtils.findParent(node, function (node) {
  1864. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  1865. }, includeSelf);
  1866. },
  1867. /**
  1868. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  1869. * @method findParents
  1870. * @param { Node } node 需要查找的节点对象
  1871. * @return { Array } 给定节点的祖先节点数组
  1872. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  1873. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  1874. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  1875. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  1876. */
  1877. /**
  1878. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  1879. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  1880. * @method findParents
  1881. * @param { Node } node 需要查找的节点对象
  1882. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  1883. * @return { Array } 给定节点的祖先节点数组
  1884. */
  1885. findParents:function (node, includeSelf, filterFn, closerFirst) {
  1886. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  1887. while (node = domUtils.findParent(node, filterFn)) {
  1888. parents.push(node);
  1889. }
  1890. return closerFirst ? parents : parents.reverse();
  1891. },
  1892. /**
  1893. * 在节点node后面插入新节点newNode
  1894. * @method insertAfter
  1895. * @param { Node } node 目标节点
  1896. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  1897. * @return { Node } 新插入的节点
  1898. */
  1899. insertAfter:function (node, newNode) {
  1900. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  1901. node.parentNode.appendChild(newNode);
  1902. },
  1903. /**
  1904. * 删除节点node及其下属的所有节点
  1905. * @method remove
  1906. * @param { Node } node 需要删除的节点对象
  1907. * @return { Node } 返回刚删除的节点对象
  1908. * @example
  1909. * ```html
  1910. * <div id="test">
  1911. * <div id="child">你好</div>
  1912. * </div>
  1913. * <script>
  1914. * UE.dom.domUtils.remove( document.body, false );
  1915. * //output: false
  1916. * console.log( document.getElementById( "child" ) !== null );
  1917. * </script>
  1918. * ```
  1919. */
  1920. /**
  1921. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  1922. * @method remove
  1923. * @param { Node } node 需要删除的节点对象
  1924. * @param { Boolean } keepChildren 是否需要保留子节点
  1925. * @return { Node } 返回刚删除的节点对象
  1926. * @example
  1927. * ```html
  1928. * <div id="test">
  1929. * <div id="child">你好</div>
  1930. * </div>
  1931. * <script>
  1932. * UE.dom.domUtils.remove( document.body, true );
  1933. * //output: true
  1934. * console.log( document.getElementById( "child" ) !== null );
  1935. * </script>
  1936. * ```
  1937. */
  1938. remove:function (node, keepChildren) {
  1939. var parent = node.parentNode,
  1940. child;
  1941. if (parent) {
  1942. if (keepChildren && node.hasChildNodes()) {
  1943. while (child = node.firstChild) {
  1944. parent.insertBefore(child, node);
  1945. }
  1946. }
  1947. parent.removeChild(node);
  1948. }
  1949. return node;
  1950. },
  1951. /**
  1952. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  1953. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  1954. * @method getNextDomNode
  1955. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1956. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1957. * @example
  1958. * ```html
  1959. * <body>
  1960. * <div id="test">
  1961. * <span></span>
  1962. * </div>
  1963. * <i>xxx</i>
  1964. * </body>
  1965. * <script>
  1966. *
  1967. * //output: i节点
  1968. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1969. *
  1970. * </script>
  1971. * ```
  1972. * @example
  1973. * ```html
  1974. * <body>
  1975. * <div>
  1976. * <span></span>
  1977. * <i id="test">xxx</i>
  1978. * </div>
  1979. * <b>xxx</b>
  1980. * </body>
  1981. * <script>
  1982. *
  1983. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  1984. * //output: b节点
  1985. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1986. *
  1987. * </script>
  1988. * ```
  1989. */
  1990. /**
  1991. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  1992. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  1993. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  1994. * @method getNextDomNode
  1995. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1996. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  1997. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1998. * @see UE.dom.domUtils.getNextDomNode(Node)
  1999. */
  2000. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2001. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2002. },
  2003. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2004. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2005. },
  2006. /**
  2007. * 检测节点node是否属是UEditor定义的bookmark节点
  2008. * @method isBookmarkNode
  2009. * @private
  2010. * @param { Node } node 需要检测的节点对象
  2011. * @return { Boolean } 是否是bookmark节点
  2012. * @example
  2013. * ```html
  2014. * <span id="_baidu_bookmark_1"></span>
  2015. * <script>
  2016. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2017. * //output: true
  2018. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2019. * </script>
  2020. * ```
  2021. */
  2022. isBookmarkNode:function (node) {
  2023. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2024. },
  2025. /**
  2026. * 获取节点node所属的window对象
  2027. * @method getWindow
  2028. * @param { Node } node 节点对象
  2029. * @return { Window } 当前节点所属的window对象
  2030. * @example
  2031. * ```javascript
  2032. * //output: true
  2033. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2034. * ```
  2035. */
  2036. getWindow:function (node) {
  2037. var doc = node.ownerDocument || node;
  2038. return doc.defaultView || doc.parentWindow;
  2039. },
  2040. /**
  2041. * 获取离nodeA与nodeB最近的公共的祖先节点
  2042. * @method getCommonAncestor
  2043. * @param { Node } nodeA 第一个节点
  2044. * @param { Node } nodeB 第二个节点
  2045. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2046. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2047. * @example
  2048. * ```javascript
  2049. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2050. * //output: true
  2051. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2052. * ```
  2053. */
  2054. getCommonAncestor:function (nodeA, nodeB) {
  2055. if (nodeA === nodeB)
  2056. return nodeA;
  2057. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2058. while (parent = parent.parentNode) {
  2059. if (parent === nodeB) {
  2060. return parent;
  2061. }
  2062. parentsA.push(parent);
  2063. }
  2064. parent = nodeB;
  2065. while (parent = parent.parentNode) {
  2066. if (parent === nodeA)
  2067. return parent;
  2068. parentsB.push(parent);
  2069. }
  2070. parentsA.reverse();
  2071. parentsB.reverse();
  2072. while (i++, parentsA[i] === parentsB[i]) {
  2073. }
  2074. return i == 0 ? null : parentsA[i - 1];
  2075. },
  2076. /**
  2077. * 清除node节点左右连续为空的兄弟inline节点
  2078. * @method clearEmptySibling
  2079. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2080. * 则这些兄弟节点将被删除
  2081. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2082. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2083. * @example
  2084. * ```html
  2085. * <body>
  2086. * <div></div>
  2087. * <span id="test"></span>
  2088. * <i></i>
  2089. * <b></b>
  2090. * <em>xxx</em>
  2091. * <span></span>
  2092. * </body>
  2093. * <script>
  2094. *
  2095. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2096. *
  2097. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2098. * console.log( document.body.innerHTML );
  2099. *
  2100. * </script>
  2101. * ```
  2102. */
  2103. /**
  2104. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2105. * 则忽略对右边兄弟节点的操作。
  2106. * @method clearEmptySibling
  2107. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2108. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2109. * 则这些兄弟节点将被删除
  2110. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2111. */
  2112. /**
  2113. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2114. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2115. * @method clearEmptySibling
  2116. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2117. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2118. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2119. * 则这些兄弟节点将被删除
  2120. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2121. */
  2122. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2123. function clear(next, dir) {
  2124. var tmpNode;
  2125. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2126. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2127. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2128. tmpNode = next[dir];
  2129. domUtils.remove(next);
  2130. next = tmpNode;
  2131. }
  2132. }
  2133. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2134. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2135. },
  2136. /**
  2137. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2138. * @method split
  2139. * @param { Node } textNode 需要拆分的文本节点对象
  2140. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2141. * @return { Node } 拆分后形成的新节点
  2142. * @example
  2143. * ```html
  2144. * <div id="test">abcdef</div>
  2145. * <script>
  2146. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2147. * //output: def
  2148. * console.log( newNode.nodeValue );
  2149. * </script>
  2150. * ```
  2151. */
  2152. split:function (node, offset) {
  2153. var doc = node.ownerDocument;
  2154. if (browser.ie && offset == node.nodeValue.length) {
  2155. var next = doc.createTextNode('');
  2156. return domUtils.insertAfter(node, next);
  2157. }
  2158. var retval = node.splitText(offset);
  2159. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2160. if (browser.ie8) {
  2161. var tmpNode = doc.createTextNode('');
  2162. domUtils.insertAfter(retval, tmpNode);
  2163. domUtils.remove(tmpNode);
  2164. }
  2165. return retval;
  2166. },
  2167. /**
  2168. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2169. * @method isWhitespace
  2170. * @param { Node } node 需要检测的节点对象
  2171. * @return { Boolean } 检测的节点是否为空
  2172. * @example
  2173. * ```html
  2174. * <div id="test">
  2175. *
  2176. * </div>
  2177. * <script>
  2178. * //output: true
  2179. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2180. * </script>
  2181. * ```
  2182. */
  2183. isWhitespace:function (node) {
  2184. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2185. },
  2186. /**
  2187. * 获取元素element相对于viewport的位置坐标
  2188. * @method getXY
  2189. * @param { Node } element 需要计算位置的节点对象
  2190. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2191. * y代表垂直偏移距离。
  2192. *
  2193. * @example
  2194. * ```javascript
  2195. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2196. * //output: test的坐标为: 12, 24
  2197. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2198. * ```
  2199. */
  2200. getXY:function (element) {
  2201. var x = 0, y = 0;
  2202. while (element.offsetParent) {
  2203. y += element.offsetTop;
  2204. x += element.offsetLeft;
  2205. element = element.offsetParent;
  2206. }
  2207. return { 'x':x, 'y':y};
  2208. },
  2209. /**
  2210. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2211. * @method on
  2212. * @param { Node } element 需要绑定事件的节点对象
  2213. * @param { String } type 绑定的事件类型
  2214. * @param { Function } handler 事件处理器
  2215. * @example
  2216. * ```javascript
  2217. * UE.dom.domUtils.on(document.body,"click",function(e){
  2218. * //e为事件对象,this为被点击元素对戏那个
  2219. * });
  2220. * ```
  2221. */
  2222. /**
  2223. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2224. * @method on
  2225. * @param { Node } element 需要绑定事件的节点对象
  2226. * @param { Array } type 绑定的事件类型数组
  2227. * @param { Function } handler 事件处理器
  2228. * @example
  2229. * ```javascript
  2230. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2231. * //evt为事件对象,this为被点击元素对象
  2232. * });
  2233. * ```
  2234. */
  2235. on:function (element, type, handler) {
  2236. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2237. k = types.length;
  2238. if (k) while (k--) {
  2239. type = types[k];
  2240. if (element.addEventListener) {
  2241. element.addEventListener(type, handler, false);
  2242. } else {
  2243. if (!handler._d) {
  2244. handler._d = {
  2245. els : []
  2246. };
  2247. }
  2248. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2249. if (!handler._d[key] || index == -1) {
  2250. if(index == -1){
  2251. handler._d.els.push(element);
  2252. }
  2253. if(!handler._d[key]){
  2254. handler._d[key] = function (evt) {
  2255. return handler.call(evt.srcElement, evt || window.event);
  2256. };
  2257. }
  2258. element.attachEvent('on' + type, handler._d[key]);
  2259. }
  2260. }
  2261. }
  2262. element = null;
  2263. },
  2264. /**
  2265. * 解除DOM事件绑定
  2266. * @method un
  2267. * @param { Node } element 需要解除事件绑定的节点对象
  2268. * @param { String } type 需要接触绑定的事件类型
  2269. * @param { Function } handler 对应的事件处理器
  2270. * @example
  2271. * ```javascript
  2272. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2273. * //evt为事件对象,this为被点击元素对象
  2274. * });
  2275. * ```
  2276. */
  2277. /**
  2278. * 解除DOM事件绑定
  2279. * @method un
  2280. * @param { Node } element 需要解除事件绑定的节点对象
  2281. * @param { Array } type 需要接触绑定的事件类型数组
  2282. * @param { Function } handler 对应的事件处理器
  2283. * @example
  2284. * ```javascript
  2285. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2286. * //evt为事件对象,this为被点击元素对象
  2287. * });
  2288. * ```
  2289. */
  2290. un:function (element, type, handler) {
  2291. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2292. k = types.length;
  2293. if (k) while (k--) {
  2294. type = types[k];
  2295. if (element.removeEventListener) {
  2296. element.removeEventListener(type, handler, false);
  2297. } else {
  2298. var key = type + handler.toString();
  2299. try{
  2300. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2301. }catch(e){}
  2302. if (handler._d && handler._d[key]) {
  2303. var index = utils.indexOf(handler._d.els,element);
  2304. if(index!=-1){
  2305. handler._d.els.splice(index,1);
  2306. }
  2307. handler._d.els.length == 0 && delete handler._d[key];
  2308. }
  2309. }
  2310. }
  2311. },
  2312. /**
  2313. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2314. * @method isSameElement
  2315. * @param { Node } nodeA 需要比较的节点
  2316. * @param { Node } nodeB 需要比较的节点
  2317. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2318. * @example
  2319. * ```html
  2320. * <span style="font-size:12px">ssss</span>
  2321. * <span style="font-size:12px">bbbbb</span>
  2322. * <span style="font-size:13px">ssss</span>
  2323. * <span style="font-size:14px">bbbbb</span>
  2324. *
  2325. * <script>
  2326. *
  2327. * var nodes = document.getElementsByTagName( "span" );
  2328. *
  2329. * //output: true
  2330. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2331. *
  2332. * //output: false
  2333. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2334. *
  2335. * </script>
  2336. * ```
  2337. */
  2338. isSameElement:function (nodeA, nodeB) {
  2339. if (nodeA.tagName != nodeB.tagName) {
  2340. return false;
  2341. }
  2342. var thisAttrs = nodeA.attributes,
  2343. otherAttrs = nodeB.attributes;
  2344. if (!ie && thisAttrs.length != otherAttrs.length) {
  2345. return false;
  2346. }
  2347. var attrA, attrB, al = 0, bl = 0;
  2348. for (var i = 0; attrA = thisAttrs[i++];) {
  2349. if (attrA.nodeName == 'style') {
  2350. if (attrA.specified) {
  2351. al++;
  2352. }
  2353. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2354. continue;
  2355. } else {
  2356. return false;
  2357. }
  2358. }
  2359. if (ie) {
  2360. if (attrA.specified) {
  2361. al++;
  2362. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2363. } else {
  2364. continue;
  2365. }
  2366. } else {
  2367. attrB = nodeB.attributes[attrA.nodeName];
  2368. }
  2369. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2370. return false;
  2371. }
  2372. }
  2373. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2374. if (ie) {
  2375. for (i = 0; attrB = otherAttrs[i++];) {
  2376. if (attrB.specified) {
  2377. bl++;
  2378. }
  2379. }
  2380. if (al != bl) {
  2381. return false;
  2382. }
  2383. }
  2384. return true;
  2385. },
  2386. /**
  2387. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2388. * @method isSameStyle
  2389. * @param { Node } nodeA 需要比较的节点
  2390. * @param { Node } nodeB 需要比较的节点
  2391. * @return { Boolean } 两个节点是否具有相同的style属性值
  2392. * @example
  2393. * ```html
  2394. * <span style="font-size:12px">ssss</span>
  2395. * <span style="font-size:12px">bbbbb</span>
  2396. * <span style="font-size:13px">ssss</span>
  2397. * <span style="font-size:14px">bbbbb</span>
  2398. *
  2399. * <script>
  2400. *
  2401. * var nodes = document.getElementsByTagName( "span" );
  2402. *
  2403. * //output: true
  2404. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2405. *
  2406. * //output: false
  2407. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2408. *
  2409. * </script>
  2410. * ```
  2411. */
  2412. isSameStyle:function (nodeA, nodeB) {
  2413. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2414. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2415. if (browser.opera) {
  2416. styleA = nodeA.style;
  2417. styleB = nodeB.style;
  2418. if (styleA.length != styleB.length)
  2419. return false;
  2420. for (var p in styleA) {
  2421. if (/^(\d+|csstext)$/i.test(p)) {
  2422. continue;
  2423. }
  2424. if (styleA[p] != styleB[p]) {
  2425. return false;
  2426. }
  2427. }
  2428. return true;
  2429. }
  2430. if (!styleA || !styleB) {
  2431. return styleA == styleB;
  2432. }
  2433. styleA = styleA.split(';');
  2434. styleB = styleB.split(';');
  2435. if (styleA.length != styleB.length) {
  2436. return false;
  2437. }
  2438. for (var i = 0, ci; ci = styleA[i++];) {
  2439. if (utils.indexOf(styleB, ci) == -1) {
  2440. return false;
  2441. }
  2442. }
  2443. return true;
  2444. },
  2445. /**
  2446. * 检查节点node是否为block元素
  2447. * @method isBlockElm
  2448. * @param { Node } node 需要检测的节点对象
  2449. * @return { Boolean } 是否是block元素节点
  2450. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2451. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2452. * @example
  2453. * ```html
  2454. * <span id="test1" style="display: block"></span>
  2455. * <span id="test2"></span>
  2456. * <div id="test3" style="display: inline"></div>
  2457. *
  2458. * <script>
  2459. *
  2460. * //output: true
  2461. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2462. *
  2463. * //output: false
  2464. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2465. *
  2466. * //output: true
  2467. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2468. *
  2469. * </script>
  2470. * ```
  2471. */
  2472. isBlockElm:function (node) {
  2473. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2474. },
  2475. /**
  2476. * 检测node节点是否为body节点
  2477. * @method isBody
  2478. * @param { Element } node 需要检测的dom元素
  2479. * @return { Boolean } 给定的元素是否是body元素
  2480. * @example
  2481. * ```javascript
  2482. * //output: true
  2483. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2484. * ```
  2485. */
  2486. isBody:function (node) {
  2487. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2488. },
  2489. /**
  2490. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2491. * 拆分形成的两个节点之间是node节点
  2492. * @method breakParent
  2493. * @param { Node } node 作为分界的节点对象
  2494. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2495. * @return { Node } 给定的node分界节点
  2496. * @example
  2497. * ```javascript
  2498. *
  2499. * var node = document.createElement("span"),
  2500. * wrapNode = document.createElement( "div" ),
  2501. * parent = document.createElement("p");
  2502. *
  2503. * parent.appendChild( node );
  2504. * wrapNode.appendChild( parent );
  2505. *
  2506. * //拆分前
  2507. * //output: <p><span></span></p>
  2508. * console.log( wrapNode.innerHTML );
  2509. *
  2510. *
  2511. * UE.dom.domUtils.breakParent( node, parent );
  2512. * //拆分后
  2513. * //output: <p></p><span></span><p></p>
  2514. * console.log( wrapNode.innerHTML );
  2515. *
  2516. * ```
  2517. */
  2518. breakParent:function (node, parent) {
  2519. var tmpNode,
  2520. parentClone = node,
  2521. clone = node,
  2522. leftNodes,
  2523. rightNodes;
  2524. do {
  2525. parentClone = parentClone.parentNode;
  2526. if (leftNodes) {
  2527. tmpNode = parentClone.cloneNode(false);
  2528. tmpNode.appendChild(leftNodes);
  2529. leftNodes = tmpNode;
  2530. tmpNode = parentClone.cloneNode(false);
  2531. tmpNode.appendChild(rightNodes);
  2532. rightNodes = tmpNode;
  2533. } else {
  2534. leftNodes = parentClone.cloneNode(false);
  2535. rightNodes = leftNodes.cloneNode(false);
  2536. }
  2537. while (tmpNode = clone.previousSibling) {
  2538. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2539. }
  2540. while (tmpNode = clone.nextSibling) {
  2541. rightNodes.appendChild(tmpNode);
  2542. }
  2543. clone = parentClone;
  2544. } while (parent !== parentClone);
  2545. tmpNode = parent.parentNode;
  2546. tmpNode.insertBefore(leftNodes, parent);
  2547. tmpNode.insertBefore(rightNodes, parent);
  2548. tmpNode.insertBefore(node, rightNodes);
  2549. domUtils.remove(parent);
  2550. return node;
  2551. },
  2552. /**
  2553. * 检查节点node是否是空inline节点
  2554. * @method isEmptyInlineElement
  2555. * @param { Node } node 需要检测的节点对象
  2556. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2557. * @example
  2558. * ```html
  2559. * <b><i></i></b> => 1
  2560. * <b><i></i><u></u></b> => 1
  2561. * <b></b> => 1
  2562. * <b>xx<i></i></b> => 0
  2563. * ```
  2564. */
  2565. isEmptyInlineElement:function (node) {
  2566. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2567. return 0;
  2568. }
  2569. node = node.firstChild;
  2570. while (node) {
  2571. //如果是创建的bookmark就跳过
  2572. if (domUtils.isBookmarkNode(node)) {
  2573. return 0;
  2574. }
  2575. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2576. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2577. ) {
  2578. return 0;
  2579. }
  2580. node = node.nextSibling;
  2581. }
  2582. return 1;
  2583. },
  2584. /**
  2585. * 删除node节点下首尾两端的空白文本子节点
  2586. * @method trimWhiteTextNode
  2587. * @param { Element } node 需要执行删除操作的元素对象
  2588. * @example
  2589. * ```javascript
  2590. * var node = document.createElement("div");
  2591. *
  2592. * node.appendChild( document.createTextNode( "" ) );
  2593. *
  2594. * node.appendChild( document.createElement("div") );
  2595. *
  2596. * node.appendChild( document.createTextNode( "" ) );
  2597. *
  2598. * //3
  2599. * console.log( node.childNodes.length );
  2600. *
  2601. * UE.dom.domUtils.trimWhiteTextNode( node );
  2602. *
  2603. * //1
  2604. * console.log( node.childNodes.length );
  2605. * ```
  2606. */
  2607. trimWhiteTextNode:function (node) {
  2608. function remove(dir) {
  2609. var child;
  2610. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2611. node.removeChild(child);
  2612. }
  2613. }
  2614. remove('firstChild');
  2615. remove('lastChild');
  2616. },
  2617. /*
  2618. * 合并node节点下相同的子节点
  2619. * @name mergeChild
  2620. * @desc
  2621. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2622. * @example
  2623. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2624. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2625. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2626. */
  2627. mergeChild:function (node, tagName, attrs) {
  2628. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2629. for (var i = 0, ci; ci = list[i++];) {
  2630. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2631. continue;
  2632. }
  2633. //span单独处理
  2634. if (ci.tagName.toLowerCase() == 'span') {
  2635. if (node === ci.parentNode) {
  2636. domUtils.trimWhiteTextNode(node);
  2637. if (node.childNodes.length == 1) {
  2638. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2639. domUtils.remove(ci, true);
  2640. continue;
  2641. }
  2642. }
  2643. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2644. if (attrs) {
  2645. var style = attrs.style;
  2646. if (style) {
  2647. style = style.split(';');
  2648. for (var j = 0, s; s = style[j++];) {
  2649. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2650. }
  2651. }
  2652. }
  2653. if (domUtils.isSameStyle(ci, node)) {
  2654. domUtils.remove(ci, true);
  2655. }
  2656. continue;
  2657. }
  2658. if (domUtils.isSameElement(node, ci)) {
  2659. domUtils.remove(ci, true);
  2660. }
  2661. }
  2662. },
  2663. /**
  2664. * 原生方法getElementsByTagName的封装
  2665. * @method getElementsByTagName
  2666. * @param { Node } node 目标节点对象
  2667. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2668. * @return { Array } 符合条件的节点集合
  2669. */
  2670. getElementsByTagName:function (node, name,filter) {
  2671. if(filter && utils.isString(filter)){
  2672. var className = filter;
  2673. filter = function(node){return domUtils.hasClass(node,className)}
  2674. }
  2675. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2676. var arr = [];
  2677. for(var n = 0,ni;ni=name[n++];){
  2678. var list = node.getElementsByTagName(ni);
  2679. for (var i = 0, ci; ci = list[i++];) {
  2680. if(!filter || filter(ci))
  2681. arr.push(ci);
  2682. }
  2683. }
  2684. return arr;
  2685. },
  2686. /**
  2687. * 将节点node提取到父节点上
  2688. * @method mergeToParent
  2689. * @param { Element } node 需要提取的元素对象
  2690. * @example
  2691. * ```html
  2692. * <div id="parent">
  2693. * <div id="sub">
  2694. * <span id="child"></span>
  2695. * </div>
  2696. * </div>
  2697. *
  2698. * <script>
  2699. *
  2700. * var child = document.getElementById( "child" );
  2701. *
  2702. * //output: sub
  2703. * console.log( child.parentNode.id );
  2704. *
  2705. * UE.dom.domUtils.mergeToParent( child );
  2706. *
  2707. * //output: parent
  2708. * console.log( child.parentNode.id );
  2709. *
  2710. * </script>
  2711. * ```
  2712. */
  2713. mergeToParent:function (node) {
  2714. var parent = node.parentNode;
  2715. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2716. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2717. domUtils.trimWhiteTextNode(parent);
  2718. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2719. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2720. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2721. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2722. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2723. parent = parent.parentNode;
  2724. continue;
  2725. } else {
  2726. parent.style.cssText += ";" + node.style.cssText;
  2727. //trace:952 a标签要保持下划线
  2728. if (parent.tagName == 'A') {
  2729. parent.style.textDecoration = 'underline';
  2730. }
  2731. }
  2732. }
  2733. if (parent.tagName != 'A') {
  2734. parent === node.parentNode && domUtils.remove(node, true);
  2735. break;
  2736. }
  2737. }
  2738. parent = parent.parentNode;
  2739. }
  2740. },
  2741. /**
  2742. * 合并节点node的左右兄弟节点
  2743. * @method mergeSibling
  2744. * @param { Element } node 需要合并的目标节点
  2745. * @example
  2746. * ```html
  2747. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2748. *
  2749. * <script>
  2750. * var demoNode = document.getElementById("test");
  2751. * UE.dom.domUtils.mergeSibling( demoNode );
  2752. * //output: xxxxoooxxxx
  2753. * console.log( demoNode.innerHTML );
  2754. * </script>
  2755. * ```
  2756. */
  2757. /**
  2758. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2759. * @method mergeSibling
  2760. * @param { Element } node 需要合并的目标节点
  2761. * @param { Boolean } ignorePre 是否忽略合并左节点
  2762. * @example
  2763. * ```html
  2764. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2765. *
  2766. * <script>
  2767. * var demoNode = document.getElementById("test");
  2768. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2769. * //output: oooxxxx
  2770. * console.log( demoNode.innerHTML );
  2771. * </script>
  2772. * ```
  2773. */
  2774. /**
  2775. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2776. * @method mergeSibling
  2777. * @param { Element } node 需要合并的目标节点
  2778. * @param { Boolean } ignorePre 是否忽略合并左节点
  2779. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2780. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2781. * @example
  2782. * ```html
  2783. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2784. *
  2785. * <script>
  2786. * var demoNode = document.getElementById("test");
  2787. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2788. * //output: xxxxooo
  2789. * console.log( demoNode.innerHTML );
  2790. * </script>
  2791. * ```
  2792. */
  2793. mergeSibling:function (node, ignorePre, ignoreNext) {
  2794. function merge(rtl, start, node) {
  2795. var next;
  2796. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2797. while (next.firstChild) {
  2798. if (start == 'firstChild') {
  2799. node.insertBefore(next.lastChild, node.firstChild);
  2800. } else {
  2801. node.appendChild(next.firstChild);
  2802. }
  2803. }
  2804. domUtils.remove(next);
  2805. }
  2806. }
  2807. !ignorePre && merge('previousSibling', 'firstChild', node);
  2808. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2809. },
  2810. /**
  2811. * 设置节点node及其子节点不会被选中
  2812. * @method unSelectable
  2813. * @param { Element } node 需要执行操作的dom元素
  2814. * @remind 执行该操作后的节点, 将不能被鼠标选中
  2815. * @example
  2816. * ```javascript
  2817. * UE.dom.domUtils.unSelectable( document.body );
  2818. * ```
  2819. */
  2820. unSelectable:ie || browser.opera ? function (node) {
  2821. //for ie9
  2822. node.onselectstart = function () {
  2823. return false;
  2824. };
  2825. node.onclick = node.onkeyup = node.onkeydown = function () {
  2826. return false;
  2827. };
  2828. node.unselectable = 'on';
  2829. node.setAttribute("unselectable", "on");
  2830. for (var i = 0, ci; ci = node.all[i++];) {
  2831. switch (ci.tagName.toLowerCase()) {
  2832. case 'iframe' :
  2833. case 'textarea' :
  2834. case 'input' :
  2835. case 'select' :
  2836. break;
  2837. default :
  2838. ci.unselectable = 'on';
  2839. node.setAttribute("unselectable", "on");
  2840. }
  2841. }
  2842. } : function (node) {
  2843. node.style.MozUserSelect =
  2844. node.style.webkitUserSelect =
  2845. node.style.KhtmlUserSelect = 'none';
  2846. },
  2847. /**
  2848. * 删除节点node上的指定属性名称的属性
  2849. * @method removeAttributes
  2850. * @param { Node } node 需要删除属性的节点对象
  2851. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  2852. * @example
  2853. * ```html
  2854. * <div id="wrap">
  2855. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  2856. * </div>
  2857. *
  2858. * <script>
  2859. *
  2860. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  2861. *
  2862. * //output: <span style="font-size:14px;">xxxxx</span>
  2863. * console.log( document.getElementById("wrap").innerHTML );
  2864. *
  2865. * </script>
  2866. * ```
  2867. */
  2868. /**
  2869. * 删除节点node上的指定属性名称的属性
  2870. * @method removeAttributes
  2871. * @param { Node } node 需要删除属性的节点对象
  2872. * @param { Array } attrNames 需要删除的属性名数组
  2873. * @example
  2874. * ```html
  2875. * <div id="wrap">
  2876. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  2877. * </div>
  2878. *
  2879. * <script>
  2880. *
  2881. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  2882. *
  2883. * //output: <span style="font-size:14px;">xxxxx</span>
  2884. * console.log( document.getElementById("wrap").innerHTML );
  2885. *
  2886. * </script>
  2887. * ```
  2888. */
  2889. removeAttributes:function (node, attrNames) {
  2890. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  2891. for (var i = 0, ci; ci = attrNames[i++];) {
  2892. ci = attrFix[ci] || ci;
  2893. switch (ci) {
  2894. case 'className':
  2895. node[ci] = '';
  2896. break;
  2897. case 'style':
  2898. node.style.cssText = '';
  2899. !browser.ie && node.removeAttributeNode(node.getAttributeNode('style'))
  2900. }
  2901. node.removeAttribute(ci);
  2902. }
  2903. },
  2904. /**
  2905. * 在doc下创建一个标签名为tag,属性为attrs的元素
  2906. * @method createElement
  2907. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  2908. * @param { String } tagName 需要创建的元素的标签名
  2909. * @param { Object } attrs 新创建的元素的属性key-value集合
  2910. * @return { Element } 新创建的元素对象
  2911. * @example
  2912. * ```javascript
  2913. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  2914. * id: 'test'
  2915. * } );
  2916. *
  2917. * //output: DIV
  2918. * console.log( ele.tagName );
  2919. *
  2920. * //output: test
  2921. * console.log( ele.id );
  2922. *
  2923. * ```
  2924. */
  2925. createElement:function (doc, tag, attrs) {
  2926. return domUtils.setAttributes(doc.createElement(tag), attrs)
  2927. },
  2928. /**
  2929. * 为节点node添加属性attrs,attrs为属性键值对
  2930. * @method setAttributes
  2931. * @param { Element } node 需要设置属性的元素对象
  2932. * @param { Object } attrs 需要设置的属性名-值对
  2933. * @return { Element } 设置属性的元素对象
  2934. * @example
  2935. * ```html
  2936. * <span id="test"></span>
  2937. *
  2938. * <script>
  2939. *
  2940. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  2941. * id: 'demo'
  2942. * } );
  2943. *
  2944. * //output: demo
  2945. * console.log( testNode.id );
  2946. *
  2947. * </script>
  2948. *
  2949. */
  2950. setAttributes:function (node, attrs) {
  2951. for (var attr in attrs) {
  2952. if(attrs.hasOwnProperty(attr)){
  2953. var value = attrs[attr];
  2954. switch (attr) {
  2955. case 'class':
  2956. //ie下要这样赋值,setAttribute不起作用
  2957. node.className = value;
  2958. break;
  2959. case 'style' :
  2960. node.style.cssText = node.style.cssText + ";" + value;
  2961. break;
  2962. case 'innerHTML':
  2963. node[attr] = value;
  2964. break;
  2965. case 'value':
  2966. node.value = value;
  2967. break;
  2968. default:
  2969. node.setAttribute(attrFix[attr] || attr, value);
  2970. }
  2971. }
  2972. }
  2973. return node;
  2974. },
  2975. /**
  2976. * 获取元素element经过计算后的样式值
  2977. * @method getComputedStyle
  2978. * @param { Element } element 需要获取样式的元素对象
  2979. * @param { String } styleName 需要获取的样式名
  2980. * @return { String } 获取到的样式值
  2981. * @example
  2982. * ```html
  2983. * <style type="text/css">
  2984. * #test {
  2985. * font-size: 15px;
  2986. * }
  2987. * </style>
  2988. *
  2989. * <span id="test"></span>
  2990. *
  2991. * <script>
  2992. * //output: 15px
  2993. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  2994. * </script>
  2995. * ```
  2996. */
  2997. getComputedStyle:function (element, styleName) {
  2998. //一下的属性单独处理
  2999. var pros = 'width height top left';
  3000. if(pros.indexOf(styleName) > -1){
  3001. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3002. }
  3003. //忽略文本节点
  3004. if (element.nodeType == 3) {
  3005. element = element.parentNode;
  3006. }
  3007. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3008. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3009. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3010. var span = element.ownerDocument.createElement('span');
  3011. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3012. span.innerHTML = '.';
  3013. element.appendChild(span);
  3014. var result = span.offsetHeight;
  3015. element.removeChild(span);
  3016. span = null;
  3017. return result + 'px';
  3018. }
  3019. try {
  3020. var value = domUtils.getStyle(element, styleName) ||
  3021. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3022. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3023. } catch (e) {
  3024. return "";
  3025. }
  3026. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3027. },
  3028. /**
  3029. * 删除元素element指定的className
  3030. * @method removeClasses
  3031. * @param { Element } ele 需要删除class的元素节点
  3032. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3033. * @example
  3034. * ```html
  3035. * <span id="test" class="test1 test2 test3">xxx</span>
  3036. *
  3037. * <script>
  3038. *
  3039. * var testNode = document.getElementById( "test" );
  3040. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3041. *
  3042. * //output: test3
  3043. * console.log( testNode.className );
  3044. *
  3045. * </script>
  3046. * ```
  3047. */
  3048. /**
  3049. * 删除元素element指定的className
  3050. * @method removeClasses
  3051. * @param { Element } ele 需要删除class的元素节点
  3052. * @param { Array } classNames 需要删除的className数组
  3053. * @example
  3054. * ```html
  3055. * <span id="test" class="test1 test2 test3">xxx</span>
  3056. *
  3057. * <script>
  3058. *
  3059. * var testNode = document.getElementById( "test" );
  3060. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3061. *
  3062. * //output: test3
  3063. * console.log( testNode.className );
  3064. *
  3065. * </script>
  3066. * ```
  3067. */
  3068. removeClasses:function (elm, classNames) {
  3069. classNames = utils.isArray(classNames) ? classNames :
  3070. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3071. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3072. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3073. }
  3074. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3075. if(cls){
  3076. elm.className = cls;
  3077. }else{
  3078. domUtils.removeAttributes(elm,['class']);
  3079. }
  3080. },
  3081. /**
  3082. * 给元素element添加className
  3083. * @method addClass
  3084. * @param { Node } ele 需要增加className的元素
  3085. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3086. * @remind 相同的类名不会被重复添加
  3087. * @example
  3088. * ```html
  3089. * <span id="test" class="cls1 cls2"></span>
  3090. *
  3091. * <script>
  3092. * var testNode = document.getElementById("test");
  3093. *
  3094. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3095. *
  3096. * //output: cl1 cls2 cls3 cls4
  3097. * console.log( testNode.className );
  3098. *
  3099. * <script>
  3100. * ```
  3101. */
  3102. /**
  3103. * 给元素element添加className
  3104. * @method addClass
  3105. * @param { Node } ele 需要增加className的元素
  3106. * @param { Array } classNames 需要添加的className的数组
  3107. * @remind 相同的类名不会被重复添加
  3108. * @example
  3109. * ```html
  3110. * <span id="test" class="cls1 cls2"></span>
  3111. *
  3112. * <script>
  3113. * var testNode = document.getElementById("test");
  3114. *
  3115. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3116. *
  3117. * //output: cl1 cls2 cls3 cls4
  3118. * console.log( testNode.className );
  3119. *
  3120. * <script>
  3121. * ```
  3122. */
  3123. addClass:function (elm, classNames) {
  3124. if(!elm)return;
  3125. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3126. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3127. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3128. cls += ' ' + ci;
  3129. }
  3130. }
  3131. elm.className = utils.trim(cls);
  3132. },
  3133. /**
  3134. * 判断元素element是否包含给定的样式类名className
  3135. * @method hasClass
  3136. * @param { Node } ele 需要检测的元素
  3137. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3138. * @return { Boolean } 元素是否包含所有给定的className
  3139. * @example
  3140. * ```html
  3141. * <span id="test1" class="cls1 cls2"></span>
  3142. *
  3143. * <script>
  3144. * var test1 = document.getElementById("test1");
  3145. *
  3146. * //output: false
  3147. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3148. *
  3149. * //output: true
  3150. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3151. * </script>
  3152. * ```
  3153. */
  3154. /**
  3155. * 判断元素element是否包含给定的样式类名className
  3156. * @method hasClass
  3157. * @param { Node } ele 需要检测的元素
  3158. * @param { Array } classNames 需要检测的className数组
  3159. * @return { Boolean } 元素是否包含所有给定的className
  3160. * @example
  3161. * ```html
  3162. * <span id="test1" class="cls1 cls2"></span>
  3163. *
  3164. * <script>
  3165. * var test1 = document.getElementById("test1");
  3166. *
  3167. * //output: false
  3168. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3169. *
  3170. * //output: true
  3171. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3172. * </script>
  3173. * ```
  3174. */
  3175. hasClass:function (element, className) {
  3176. if(utils.isRegExp(className)){
  3177. return className.test(element.className)
  3178. }
  3179. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3180. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3181. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3182. return false;
  3183. }
  3184. }
  3185. return i - 1 == className.length;
  3186. },
  3187. /**
  3188. * 阻止事件默认行为
  3189. * @method preventDefault
  3190. * @param { Event } evt 需要阻止默认行为的事件对象
  3191. * @example
  3192. * ```javascript
  3193. * UE.dom.domUtils.preventDefault( evt );
  3194. * ```
  3195. */
  3196. preventDefault:function (evt) {
  3197. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3198. },
  3199. /**
  3200. * 删除元素element指定的样式
  3201. * @method removeStyle
  3202. * @param { Element } element 需要删除样式的元素
  3203. * @param { String } styleName 需要删除的样式名
  3204. * @example
  3205. * ```html
  3206. * <span id="test" style="color: red; background: blue;"></span>
  3207. *
  3208. * <script>
  3209. *
  3210. * var testNode = document.getElementById("test");
  3211. *
  3212. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3213. *
  3214. * //output: background: blue;
  3215. * console.log( testNode.style.cssText );
  3216. *
  3217. * </script>
  3218. * ```
  3219. */
  3220. removeStyle:function (element, name) {
  3221. if(browser.ie ){
  3222. //针对color先单独处理一下
  3223. if(name == 'color'){
  3224. name = '(^|;)' + name;
  3225. }
  3226. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3227. }else{
  3228. if (element.style.removeProperty) {
  3229. element.style.removeProperty (name);
  3230. }else {
  3231. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3232. }
  3233. }
  3234. if (!element.style.cssText) {
  3235. domUtils.removeAttributes(element, ['style']);
  3236. }
  3237. },
  3238. /**
  3239. * 获取元素element的style属性的指定值
  3240. * @method getStyle
  3241. * @param { Element } element 需要获取属性值的元素
  3242. * @param { String } styleName 需要获取的style的名称
  3243. * @warning 该方法仅获取元素style属性中所标明的值
  3244. * @return { String } 该元素包含指定的style属性值
  3245. * @example
  3246. * ```html
  3247. * <div id="test" style="color: red;"></div>
  3248. *
  3249. * <script>
  3250. *
  3251. * var testNode = document.getElementById( "test" );
  3252. *
  3253. * //output: red
  3254. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3255. *
  3256. * //output: ""
  3257. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3258. *
  3259. * </script>
  3260. * ```
  3261. */
  3262. getStyle:function (element, name) {
  3263. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3264. return utils.fixColor(name, value);
  3265. },
  3266. /**
  3267. * 为元素element设置样式属性值
  3268. * @method setStyle
  3269. * @param { Element } element 需要设置样式的元素
  3270. * @param { String } styleName 样式名
  3271. * @param { String } styleValue 样式值
  3272. * @example
  3273. * ```html
  3274. * <div id="test"></div>
  3275. *
  3276. * <script>
  3277. *
  3278. * var testNode = document.getElementById( "test" );
  3279. *
  3280. * //output: ""
  3281. * console.log( testNode.style.color );
  3282. *
  3283. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3284. * //output: "red"
  3285. * console.log( testNode.style.color );
  3286. *
  3287. * </script>
  3288. * ```
  3289. */
  3290. setStyle:function (element, name, value) {
  3291. element.style[utils.cssStyleToDomStyle(name)] = value;
  3292. if(!utils.trim(element.style.cssText)){
  3293. this.removeAttributes(element,'style')
  3294. }
  3295. },
  3296. /**
  3297. * 为元素element设置多个样式属性值
  3298. * @method setStyles
  3299. * @param { Element } element 需要设置样式的元素
  3300. * @param { Object } styles 样式名值对
  3301. * @example
  3302. * ```html
  3303. * <div id="test"></div>
  3304. *
  3305. * <script>
  3306. *
  3307. * var testNode = document.getElementById( "test" );
  3308. *
  3309. * //output: ""
  3310. * console.log( testNode.style.color );
  3311. *
  3312. * UE.dom.domUtils.setStyles( testNode, {
  3313. * 'color': 'red'
  3314. * } );
  3315. * //output: "red"
  3316. * console.log( testNode.style.color );
  3317. *
  3318. * </script>
  3319. * ```
  3320. */
  3321. setStyles:function (element, styles) {
  3322. for (var name in styles) {
  3323. if (styles.hasOwnProperty(name)) {
  3324. domUtils.setStyle(element, name, styles[name]);
  3325. }
  3326. }
  3327. },
  3328. /**
  3329. * 删除_moz_dirty属性
  3330. * @private
  3331. * @method removeDirtyAttr
  3332. */
  3333. removeDirtyAttr:function (node) {
  3334. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3335. ci.removeAttribute('_moz_dirty');
  3336. }
  3337. node.removeAttribute('_moz_dirty');
  3338. },
  3339. /**
  3340. * 获取子节点的数量
  3341. * @method getChildCount
  3342. * @param { Element } node 需要检测的元素
  3343. * @return { Number } 给定的node元素的子节点数量
  3344. * @example
  3345. * ```html
  3346. * <div id="test">
  3347. * <span></span>
  3348. * </div>
  3349. *
  3350. * <script>
  3351. *
  3352. * //output: 3
  3353. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3354. *
  3355. * </script>
  3356. * ```
  3357. */
  3358. /**
  3359. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3360. * @method getChildCount
  3361. * @param { Element } node 需要检测的元素
  3362. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3363. * @return { Number } 符合过滤条件的node元素的子节点数量
  3364. * @example
  3365. * ```html
  3366. * <div id="test">
  3367. * <span></span>
  3368. * </div>
  3369. *
  3370. * <script>
  3371. *
  3372. * //output: 1
  3373. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3374. *
  3375. * return node.nodeType === 1;
  3376. *
  3377. * } ) );
  3378. *
  3379. * </script>
  3380. * ```
  3381. */
  3382. getChildCount:function (node, fn) {
  3383. var count = 0, first = node.firstChild;
  3384. fn = fn || function () {
  3385. return 1;
  3386. };
  3387. while (first) {
  3388. if (fn(first)) {
  3389. count++;
  3390. }
  3391. first = first.nextSibling;
  3392. }
  3393. return count;
  3394. },
  3395. /**
  3396. * 判断给定节点是否为空节点
  3397. * @method isEmptyNode
  3398. * @param { Node } node 需要检测的节点对象
  3399. * @return { Boolean } 节点是否为空
  3400. * @example
  3401. * ```javascript
  3402. * UE.dom.domUtils.isEmptyNode( document.body );
  3403. * ```
  3404. */
  3405. isEmptyNode:function (node) {
  3406. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3407. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3408. }) == 0
  3409. },
  3410. clearSelectedArr:function (nodes) {
  3411. var node;
  3412. while (node = nodes.pop()) {
  3413. domUtils.removeAttributes(node, ['class']);
  3414. }
  3415. },
  3416. /**
  3417. * 将显示区域滚动到指定节点的位置
  3418. * @method scrollToView
  3419. * @param {Node} node 节点
  3420. * @param {window} win window对象
  3421. * @param {Number} offsetTop 距离上方的偏移量
  3422. */
  3423. scrollToView:function (node, win, offsetTop) {
  3424. var getViewPaneSize = function () {
  3425. var doc = win.document,
  3426. mode = doc.compatMode == 'CSS1Compat';
  3427. return {
  3428. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3429. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3430. };
  3431. },
  3432. getScrollPosition = function (win) {
  3433. if ('pageXOffset' in win) {
  3434. return {
  3435. x:win.pageXOffset || 0,
  3436. y:win.pageYOffset || 0
  3437. };
  3438. }
  3439. else {
  3440. var doc = win.document;
  3441. return {
  3442. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3443. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3444. };
  3445. }
  3446. };
  3447. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3448. offset += (node.offsetHeight || 0);
  3449. var elementPosition = domUtils.getXY(node);
  3450. offset += elementPosition.y;
  3451. var currentScroll = getScrollPosition(win).y;
  3452. // offset += 50;
  3453. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3454. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3455. }
  3456. },
  3457. /**
  3458. * 判断给定节点是否为br
  3459. * @method isBr
  3460. * @param { Node } node 需要判断的节点对象
  3461. * @return { Boolean } 给定的节点是否是br节点
  3462. */
  3463. isBr:function (node) {
  3464. return node.nodeType == 1 && node.tagName == 'BR';
  3465. },
  3466. /**
  3467. * 判断给定的节点是否是一个“填充”节点
  3468. * @private
  3469. * @method isFillChar
  3470. * @param { Node } node 需要判断的节点
  3471. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3472. * @returns { Boolean } 节点是否是填充节点
  3473. */
  3474. isFillChar:function (node,isInStart) {
  3475. if(node.nodeType != 3)
  3476. return false;
  3477. var text = node.nodeValue;
  3478. if(isInStart){
  3479. return new RegExp('^' + domUtils.fillChar).test(text)
  3480. }
  3481. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3482. },
  3483. isStartInblock:function (range) {
  3484. var tmpRange = range.cloneRange(),
  3485. flag = 0,
  3486. start = tmpRange.startContainer,
  3487. tmp;
  3488. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3489. start = start.childNodes[tmpRange.startOffset];
  3490. var pre = start.previousSibling;
  3491. while(pre && domUtils.isFillChar(pre)){
  3492. start = pre;
  3493. pre = pre.previousSibling;
  3494. }
  3495. }
  3496. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3497. tmpRange.setStartBefore(start);
  3498. start = tmpRange.startContainer;
  3499. }
  3500. while (start && domUtils.isFillChar(start)) {
  3501. tmp = start;
  3502. start = start.previousSibling
  3503. }
  3504. if (tmp) {
  3505. tmpRange.setStartBefore(tmp);
  3506. start = tmpRange.startContainer;
  3507. }
  3508. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3509. tmpRange.setStart(start, 0).collapse(true);
  3510. }
  3511. while (!tmpRange.startOffset) {
  3512. start = tmpRange.startContainer;
  3513. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3514. flag = 1;
  3515. break;
  3516. }
  3517. var pre = tmpRange.startContainer.previousSibling,
  3518. tmpNode;
  3519. if (!pre) {
  3520. tmpRange.setStartBefore(tmpRange.startContainer);
  3521. } else {
  3522. while (pre && domUtils.isFillChar(pre)) {
  3523. tmpNode = pre;
  3524. pre = pre.previousSibling;
  3525. }
  3526. if (tmpNode) {
  3527. tmpRange.setStartBefore(tmpNode);
  3528. } else {
  3529. tmpRange.setStartBefore(tmpRange.startContainer);
  3530. }
  3531. }
  3532. }
  3533. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3534. },
  3535. /**
  3536. * 判断给定的元素是否是一个空元素
  3537. * @method isEmptyBlock
  3538. * @param { Element } node 需要判断的元素
  3539. * @return { Boolean } 是否是空元素
  3540. * @example
  3541. * ```html
  3542. * <div id="test"></div>
  3543. *
  3544. * <script>
  3545. * //output: true
  3546. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3547. * </script>
  3548. * ```
  3549. */
  3550. /**
  3551. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3552. * @method isEmptyBlock
  3553. * @param { Element } node 需要判断的元素
  3554. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3555. * @return { Boolean } 是否是空元素
  3556. */
  3557. isEmptyBlock:function (node,reg) {
  3558. if(node.nodeType != 1)
  3559. return 0;
  3560. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  3561. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3562. return 0;
  3563. }
  3564. for (var n in dtd.$isNotEmpty) {
  3565. if (node.getElementsByTagName(n).length) {
  3566. return 0;
  3567. }
  3568. }
  3569. return 1;
  3570. },
  3571. /**
  3572. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3573. * @method setViewportOffset
  3574. * @param { Element } element 需要设置偏移量的元素
  3575. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3576. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3577. * offset.top的距离
  3578. * @example
  3579. * ```html
  3580. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3581. *
  3582. * <script>
  3583. *
  3584. * var testNode = document.getElementById("test");
  3585. *
  3586. * UE.dom.domUtils.setViewportOffset( testNode, {
  3587. * left: 200,
  3588. * top: 50
  3589. * } );
  3590. *
  3591. * //output: top: 300px; left: 100px; position: absolute;
  3592. * console.log( testNode.style.cssText );
  3593. *
  3594. * </script>
  3595. * ```
  3596. */
  3597. setViewportOffset:function (element, offset) {
  3598. var left = parseInt(element.style.left) | 0;
  3599. var top = parseInt(element.style.top) | 0;
  3600. var rect = element.getBoundingClientRect();
  3601. var offsetLeft = offset.left - rect.left;
  3602. var offsetTop = offset.top - rect.top;
  3603. if (offsetLeft) {
  3604. element.style.left = left + offsetLeft + 'px';
  3605. }
  3606. if (offsetTop) {
  3607. element.style.top = top + offsetTop + 'px';
  3608. }
  3609. },
  3610. /**
  3611. * 用“填充字符”填充节点
  3612. * @method fillNode
  3613. * @private
  3614. * @param { DomDocument } doc 填充的节点所在的docment对象
  3615. * @param { Node } node 需要填充的节点对象
  3616. * @example
  3617. * ```html
  3618. * <div id="test"></div>
  3619. *
  3620. * <script>
  3621. * var testNode = document.getElementById("test");
  3622. *
  3623. * //output: 0
  3624. * console.log( testNode.childNodes.length );
  3625. *
  3626. * UE.dom.domUtils.fillNode( document, testNode );
  3627. *
  3628. * //output: 1
  3629. * console.log( testNode.childNodes.length );
  3630. *
  3631. * </script>
  3632. * ```
  3633. */
  3634. fillNode:function (doc, node) {
  3635. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3636. node.innerHTML = '';
  3637. node.appendChild(tmpNode);
  3638. },
  3639. /**
  3640. * 把节点src的所有子节点追加到另一个节点tag上去
  3641. * @method moveChild
  3642. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3643. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3644. * @example
  3645. * ```html
  3646. * <div id="test1">
  3647. * <span></span>
  3648. * </div>
  3649. * <div id="test2">
  3650. * <div></div>
  3651. * </div>
  3652. *
  3653. * <script>
  3654. *
  3655. * var test1 = document.getElementById("test1"),
  3656. * test2 = document.getElementById("test2");
  3657. *
  3658. * UE.dom.domUtils.moveChild( test1, test2 );
  3659. *
  3660. * //output: ""(空字符串)
  3661. * console.log( test1.innerHTML );
  3662. *
  3663. * //output: "<div></div><span></span>"
  3664. * console.log( test2.innerHTML );
  3665. *
  3666. * </script>
  3667. * ```
  3668. */
  3669. /**
  3670. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3671. * @method moveChild
  3672. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3673. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3674. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3675. * @example
  3676. * ```html
  3677. * <div id="test1">
  3678. * <span></span>
  3679. * </div>
  3680. * <div id="test2">
  3681. * <div></div>
  3682. * </div>
  3683. *
  3684. * <script>
  3685. *
  3686. * var test1 = document.getElementById("test1"),
  3687. * test2 = document.getElementById("test2");
  3688. *
  3689. * UE.dom.domUtils.moveChild( test1, test2, true );
  3690. *
  3691. * //output: ""(空字符串)
  3692. * console.log( test1.innerHTML );
  3693. *
  3694. * //output: "<span></span><div></div>"
  3695. * console.log( test2.innerHTML );
  3696. *
  3697. * </script>
  3698. * ```
  3699. */
  3700. moveChild:function (src, tag, dir) {
  3701. while (src.firstChild) {
  3702. if (dir && tag.firstChild) {
  3703. tag.insertBefore(src.lastChild, tag.firstChild);
  3704. } else {
  3705. tag.appendChild(src.firstChild);
  3706. }
  3707. }
  3708. },
  3709. /**
  3710. * 判断节点的标签上是否不存在任何属性
  3711. * @method hasNoAttributes
  3712. * @private
  3713. * @param { Node } node 需要检测的节点对象
  3714. * @return { Boolean } 节点是否不包含任何属性
  3715. * @example
  3716. * ```html
  3717. * <div id="test"><span>xxxx</span></div>
  3718. *
  3719. * <script>
  3720. *
  3721. * //output: false
  3722. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3723. *
  3724. * //output: true
  3725. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3726. *
  3727. * </script>
  3728. * ```
  3729. */
  3730. hasNoAttributes:function (node) {
  3731. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3732. },
  3733. /**
  3734. * 检测节点是否是UEditor所使用的辅助节点
  3735. * @method isCustomeNode
  3736. * @private
  3737. * @param { Node } node 需要检测的节点
  3738. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3739. * @return { Boolean } 给定的节点是否是一个辅助节点
  3740. */
  3741. isCustomeNode:function (node) {
  3742. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3743. },
  3744. /**
  3745. * 检测节点的标签是否是给定的标签
  3746. * @method isTagNode
  3747. * @param { Node } node 需要检测的节点对象
  3748. * @param { String } tagName 标签
  3749. * @return { Boolean } 节点的标签是否是给定的标签
  3750. * @example
  3751. * ```html
  3752. * <div id="test"></div>
  3753. *
  3754. * <script>
  3755. *
  3756. * //output: true
  3757. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3758. *
  3759. * </script>
  3760. * ```
  3761. */
  3762. isTagNode:function (node, tagNames) {
  3763. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3764. },
  3765. /**
  3766. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3767. * @method filterNodeList
  3768. * @param { Array } nodeList 需要过滤的节点数组
  3769. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3770. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3771. * @example
  3772. * ```javascript
  3773. * var divNodes = document.getElementsByTagName("div");
  3774. * divNodes = [].slice.call( divNodes, 0 );
  3775. *
  3776. * //output: null
  3777. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3778. * return node.tagName.toLowerCase() !== 'div';
  3779. * } ) );
  3780. * ```
  3781. */
  3782. /**
  3783. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3784. * @method filterNodeList
  3785. * @param { Array } nodeList 需要过滤的节点数组
  3786. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3787. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3788. * @example
  3789. * ```javascript
  3790. * var divNodes = document.getElementsByTagName("div");
  3791. * divNodes = [].slice.call( divNodes, 0 );
  3792. *
  3793. * //output: null
  3794. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3795. * ```
  3796. */
  3797. /**
  3798. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3799. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3800. * @method filterNodeList
  3801. * @param { Array } nodeList 需要过滤的节点数组
  3802. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3803. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3804. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3805. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3806. * @example
  3807. * ```javascript
  3808. * var divNodes = document.getElementsByTagName("div");
  3809. * divNodes = [].slice.call( divNodes, 0 );
  3810. *
  3811. * //output: 3(假定有3个div)
  3812. * console.log( divNodes.length );
  3813. *
  3814. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3815. * return node.tagName.toLowerCase() === 'div';
  3816. * }, true );
  3817. *
  3818. * //output: 3
  3819. * console.log( nodes.length );
  3820. *
  3821. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3822. * return node.tagName.toLowerCase() === 'div';
  3823. * }, false );
  3824. *
  3825. * //output: div
  3826. * console.log( node.nodeName );
  3827. * ```
  3828. */
  3829. filterNodeList : function(nodelist,filter,forAll){
  3830. var results = [];
  3831. if(!utils .isFunction(filter)){
  3832. var str = filter;
  3833. filter = function(n){
  3834. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  3835. };
  3836. }
  3837. utils.each(nodelist,function(n){
  3838. filter(n) && results.push(n)
  3839. });
  3840. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  3841. },
  3842. /**
  3843. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  3844. * @method isInNodeEndBoundary
  3845. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  3846. * @param node 需要检测的节点对象
  3847. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  3848. */
  3849. isInNodeEndBoundary : function (rng,node){
  3850. var start = rng.startContainer;
  3851. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  3852. return 0;
  3853. }
  3854. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  3855. return 0;
  3856. }
  3857. while(start !== node){
  3858. if(start.nextSibling){
  3859. return 0
  3860. };
  3861. start = start.parentNode;
  3862. }
  3863. return 1;
  3864. },
  3865. isBoundaryNode : function (node,dir){
  3866. var tmp;
  3867. while(!domUtils.isBody(node)){
  3868. tmp = node;
  3869. node = node.parentNode;
  3870. if(tmp !== node[dir]){
  3871. return false;
  3872. }
  3873. }
  3874. return true;
  3875. }
  3876. };
  3877. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  3878. /**
  3879. * Range封装
  3880. * @file
  3881. * @module UE.dom
  3882. * @class Range
  3883. * @since 1.2.6.1
  3884. */
  3885. /**
  3886. * dom操作封装
  3887. * @unfile
  3888. * @module UE.dom
  3889. */
  3890. /**
  3891. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  3892. * @unfile
  3893. * @module UE.dom
  3894. * @class Range
  3895. */
  3896. (function () {
  3897. var guid = 0,
  3898. fillChar = domUtils.fillChar,
  3899. fillData;
  3900. /*
  3901. * 更新range的collapse状态
  3902. * @param {Range} range range对象
  3903. */
  3904. function updateCollapse(range) {
  3905. range.collapsed =
  3906. range.startContainer && range.endContainer &&
  3907. range.startContainer === range.endContainer &&
  3908. range.startOffset == range.endOffset;
  3909. }
  3910. function selectOneNode(rng){
  3911. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  3912. }
  3913. function setEndPoint(toStart, node, offset, range) {
  3914. //如果node是自闭合标签要处理
  3915. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  3916. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  3917. node = node.parentNode;
  3918. }
  3919. if (toStart) {
  3920. range.startContainer = node;
  3921. range.startOffset = offset;
  3922. if (!range.endContainer) {
  3923. range.collapse(true);
  3924. }
  3925. } else {
  3926. range.endContainer = node;
  3927. range.endOffset = offset;
  3928. if (!range.startContainer) {
  3929. range.collapse(false);
  3930. }
  3931. }
  3932. updateCollapse(range);
  3933. return range;
  3934. }
  3935. function execContentsAction(range, action) {
  3936. //调整边界
  3937. //range.includeBookmark();
  3938. var start = range.startContainer,
  3939. end = range.endContainer,
  3940. startOffset = range.startOffset,
  3941. endOffset = range.endOffset,
  3942. doc = range.document,
  3943. frag = doc.createDocumentFragment(),
  3944. tmpStart, tmpEnd;
  3945. if (start.nodeType == 1) {
  3946. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  3947. }
  3948. if (end.nodeType == 1) {
  3949. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  3950. }
  3951. if (start === end && start.nodeType == 3) {
  3952. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  3953. //is not clone
  3954. if (action) {
  3955. start.deleteData(startOffset, endOffset - startOffset);
  3956. range.collapse(true);
  3957. }
  3958. return frag;
  3959. }
  3960. var current, currentLevel, clone = frag,
  3961. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  3962. for (var i = 0; startParents[i] == endParents[i];) {
  3963. i++;
  3964. }
  3965. for (var j = i, si; si = startParents[j]; j++) {
  3966. current = si.nextSibling;
  3967. if (si == start) {
  3968. if (!tmpStart) {
  3969. if (range.startContainer.nodeType == 3) {
  3970. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  3971. //is not clone
  3972. if (action) {
  3973. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  3974. }
  3975. } else {
  3976. clone.appendChild(!action ? start.cloneNode(true) : start);
  3977. }
  3978. }
  3979. } else {
  3980. currentLevel = si.cloneNode(false);
  3981. clone.appendChild(currentLevel);
  3982. }
  3983. while (current) {
  3984. if (current === end || current === endParents[j]) {
  3985. break;
  3986. }
  3987. si = current.nextSibling;
  3988. clone.appendChild(!action ? current.cloneNode(true) : current);
  3989. current = si;
  3990. }
  3991. clone = currentLevel;
  3992. }
  3993. clone = frag;
  3994. if (!startParents[i]) {
  3995. clone.appendChild(startParents[i - 1].cloneNode(false));
  3996. clone = clone.firstChild;
  3997. }
  3998. for (var j = i, ei; ei = endParents[j]; j++) {
  3999. current = ei.previousSibling;
  4000. if (ei == end) {
  4001. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4002. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4003. //is not clone
  4004. if (action) {
  4005. end.deleteData(0, endOffset);
  4006. }
  4007. }
  4008. } else {
  4009. currentLevel = ei.cloneNode(false);
  4010. clone.appendChild(currentLevel);
  4011. }
  4012. //如果两端同级,右边第一次已经被开始做了
  4013. if (j != i || !startParents[i]) {
  4014. while (current) {
  4015. if (current === start) {
  4016. break;
  4017. }
  4018. ei = current.previousSibling;
  4019. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4020. current = ei;
  4021. }
  4022. }
  4023. clone = currentLevel;
  4024. }
  4025. if (action) {
  4026. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4027. }
  4028. tmpStart && domUtils.remove(tmpStart);
  4029. tmpEnd && domUtils.remove(tmpEnd);
  4030. return frag;
  4031. }
  4032. /**
  4033. * 创建一个跟document绑定的空的Range实例
  4034. * @constructor
  4035. * @param { Document } document 新建的选区所属的文档对象
  4036. */
  4037. /**
  4038. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4039. */
  4040. /**
  4041. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4042. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4043. */
  4044. /**
  4045. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4046. */
  4047. /**
  4048. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4049. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4050. */
  4051. /**
  4052. * @property { Boolean } collapsed 当前Range是否闭合
  4053. * @default true
  4054. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4055. */
  4056. /**
  4057. * @property { Document } document 当前Range所属的Document对象
  4058. * @remind 不同range的的document属性可以是不同的
  4059. */
  4060. var Range = dom.Range = function (document) {
  4061. var me = this;
  4062. me.startContainer =
  4063. me.startOffset =
  4064. me.endContainer =
  4065. me.endOffset = null;
  4066. me.document = document;
  4067. me.collapsed = true;
  4068. };
  4069. /*
  4070. * 删除fillData
  4071. * @param doc
  4072. * @param excludeNode
  4073. */
  4074. function removeFillData(doc, excludeNode) {
  4075. try {
  4076. if (fillData && domUtils.inDoc(fillData, doc)) {
  4077. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4078. var tmpNode = fillData.parentNode;
  4079. domUtils.remove(fillData);
  4080. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4081. //safari的contains有bug
  4082. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4083. ) {
  4084. fillData = tmpNode.parentNode;
  4085. domUtils.remove(tmpNode);
  4086. tmpNode = fillData;
  4087. }
  4088. } else {
  4089. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4090. }
  4091. }
  4092. } catch (e) {
  4093. }
  4094. }
  4095. /*
  4096. * @param node
  4097. * @param dir
  4098. */
  4099. function mergeSibling(node, dir) {
  4100. var tmpNode;
  4101. node = node[dir];
  4102. while (node && domUtils.isFillChar(node)) {
  4103. tmpNode = node[dir];
  4104. domUtils.remove(node);
  4105. node = tmpNode;
  4106. }
  4107. }
  4108. Range.prototype = {
  4109. /**
  4110. * 克隆选区的内容到一个DocumentFragment里
  4111. * @method cloneContents
  4112. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4113. * @example
  4114. * ```html
  4115. * <body>
  4116. * <!-- 中括号表示选区 -->
  4117. * <b>x<i>x[x</i>xx]x</b>
  4118. *
  4119. * <script>
  4120. * //range是已选中的选区
  4121. * var fragment = range.cloneContents(),
  4122. * node = document.createElement("div");
  4123. *
  4124. * node.appendChild( fragment );
  4125. *
  4126. * //output: <i>x</i>xx
  4127. * console.log( node.innerHTML );
  4128. *
  4129. * </script>
  4130. * </body>
  4131. * ```
  4132. */
  4133. cloneContents:function () {
  4134. return this.collapsed ? null : execContentsAction(this, 0);
  4135. },
  4136. /**
  4137. * 删除当前选区范围中的所有内容
  4138. * @method deleteContents
  4139. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4140. * @return { UE.dom.Range } 当前操作的Range对象
  4141. * @example
  4142. * ```html
  4143. * <body>
  4144. * <!-- 中括号表示选区 -->
  4145. * <b>x<i>x[x</i>xx]x</b>
  4146. *
  4147. * <script>
  4148. * //range是已选中的选区
  4149. * range.deleteContents();
  4150. *
  4151. * //竖线表示闭合后的选区位置
  4152. * //output: <b>x<i>x</i>|x</b>
  4153. * console.log( document.body.innerHTML );
  4154. *
  4155. * //此时, range的各项属性为
  4156. * //output: B
  4157. * console.log( range.startContainer.tagName );
  4158. * //output: 2
  4159. * console.log( range.startOffset );
  4160. * //output: B
  4161. * console.log( range.endContainer.tagName );
  4162. * //output: 2
  4163. * console.log( range.endOffset );
  4164. * //output: true
  4165. * console.log( range.collapsed );
  4166. *
  4167. * </script>
  4168. * </body>
  4169. * ```
  4170. */
  4171. deleteContents:function () {
  4172. var txt;
  4173. if (!this.collapsed) {
  4174. execContentsAction(this, 1);
  4175. }
  4176. if (browser.webkit) {
  4177. txt = this.startContainer;
  4178. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4179. this.setStartBefore(txt).collapse(true);
  4180. domUtils.remove(txt);
  4181. }
  4182. }
  4183. return this;
  4184. },
  4185. /**
  4186. * 将当前选区的内容提取到一个DocumentFragment里
  4187. * @method extractContents
  4188. * @remind 执行该操作后, 选区将变成闭合状态
  4189. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4190. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4191. * @example
  4192. * ```html
  4193. * <body>
  4194. * <!-- 中括号表示选区 -->
  4195. * <b>x<i>x[x</i>xx]x</b>
  4196. *
  4197. * <script>
  4198. * //range是已选中的选区
  4199. * var fragment = range.extractContents(),
  4200. * node = document.createElement( "div" );
  4201. *
  4202. * node.appendChild( fragment );
  4203. *
  4204. * //竖线表示闭合后的选区位置
  4205. *
  4206. * //output: <b>x<i>x</i>|x</b>
  4207. * console.log( document.body.innerHTML );
  4208. * //output: <i>x</i>xx
  4209. * console.log( node.innerHTML );
  4210. *
  4211. * //此时, range的各项属性为
  4212. * //output: B
  4213. * console.log( range.startContainer.tagName );
  4214. * //output: 2
  4215. * console.log( range.startOffset );
  4216. * //output: B
  4217. * console.log( range.endContainer.tagName );
  4218. * //output: 2
  4219. * console.log( range.endOffset );
  4220. * //output: true
  4221. * console.log( range.collapsed );
  4222. *
  4223. * </script>
  4224. * </body>
  4225. */
  4226. extractContents:function () {
  4227. return this.collapsed ? null : execContentsAction(this, 2);
  4228. },
  4229. /**
  4230. * 设置Range的开始容器节点和偏移量
  4231. * @method setStart
  4232. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4233. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4234. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4235. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4236. * 中的索引
  4237. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4238. * @param { int } offset 选区的开始位置偏移量
  4239. * @return { UE.dom.Range } 当前range对象
  4240. * @example
  4241. * ```html
  4242. * <!-- 选区 -->
  4243. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4244. *
  4245. * <script>
  4246. *
  4247. * //执行操作
  4248. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4249. *
  4250. * //此时, 选区变成了
  4251. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4252. *
  4253. * </script>
  4254. * ```
  4255. * @example
  4256. * ```html
  4257. * <!-- 选区 -->
  4258. * <b>xxx<img>[xx]x</b>
  4259. *
  4260. * <script>
  4261. *
  4262. * //执行操作
  4263. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4264. *
  4265. * //此时, 选区变成了
  4266. * //<b>xxx[<img>xx]x</b>
  4267. *
  4268. * </script>
  4269. * ```
  4270. */
  4271. setStart:function (node, offset) {
  4272. return setEndPoint(true, node, offset, this);
  4273. },
  4274. /**
  4275. * 设置Range的结束容器和偏移量
  4276. * @method setEnd
  4277. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4278. * @param { int } offset 结束边界的偏移量
  4279. * @see UE.dom.Range:setStart(Node,int)
  4280. * @return { UE.dom.Range } 当前range对象
  4281. */
  4282. setEnd:function (node, offset) {
  4283. return setEndPoint(false, node, offset, this);
  4284. },
  4285. /**
  4286. * 将Range开始位置设置到node节点之后
  4287. * @method setStartAfter
  4288. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4289. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4290. * @return { UE.dom.Range } 当前range对象
  4291. * @example
  4292. * ```html
  4293. * <!-- 选区示例 -->
  4294. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4295. *
  4296. * <script>
  4297. *
  4298. * //执行操作
  4299. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4300. *
  4301. * //结果选区
  4302. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4303. *
  4304. * </script>
  4305. * ```
  4306. */
  4307. setStartAfter:function (node) {
  4308. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4309. },
  4310. /**
  4311. * 将Range开始位置设置到node节点之前
  4312. * @method setStartBefore
  4313. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4314. * @param { Node } node 新的选区开始位置在该节点之前
  4315. * @see UE.dom.Range:setStartAfter(Node)
  4316. * @return { UE.dom.Range } 当前range对象
  4317. */
  4318. setStartBefore:function (node) {
  4319. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4320. },
  4321. /**
  4322. * 将Range结束位置设置到node节点之后
  4323. * @method setEndAfter
  4324. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4325. * @param { Node } node 目标节点
  4326. * @see UE.dom.Range:setStartAfter(Node)
  4327. * @return { UE.dom.Range } 当前range对象
  4328. * @example
  4329. * ```html
  4330. * <!-- 选区示例 -->
  4331. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4332. *
  4333. * <script>
  4334. *
  4335. * //执行操作
  4336. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4337. *
  4338. * //结果选区
  4339. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4340. *
  4341. * </script>
  4342. * ```
  4343. */
  4344. setEndAfter:function (node) {
  4345. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4346. },
  4347. /**
  4348. * 将Range结束位置设置到node节点之前
  4349. * @method setEndBefore
  4350. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4351. * @param { Node } node 目标节点
  4352. * @see UE.dom.Range:setEndAfter(Node)
  4353. * @return { UE.dom.Range } 当前range对象
  4354. */
  4355. setEndBefore:function (node) {
  4356. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4357. },
  4358. /**
  4359. * 设置Range的开始位置到node节点内的第一个子节点之前
  4360. * @method setStartAtFirst
  4361. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4362. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4363. * @param { Node } node 目标节点
  4364. * @see UE.dom.Range:setStartBefore(Node)
  4365. * @return { UE.dom.Range } 当前range对象
  4366. * @example
  4367. * ```html
  4368. * <!-- 选区示例 -->
  4369. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4370. *
  4371. * <script>
  4372. *
  4373. * //执行操作
  4374. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4375. *
  4376. * //结果选区
  4377. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4378. *
  4379. * </script>
  4380. * ```
  4381. */
  4382. setStartAtFirst:function (node) {
  4383. return this.setStart(node, 0);
  4384. },
  4385. /**
  4386. * 设置Range的开始位置到node节点内的最后一个节点之后
  4387. * @method setStartAtLast
  4388. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4389. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4390. * @param { Node } node 目标节点
  4391. * @see UE.dom.Range:setStartAtFirst(Node)
  4392. * @return { UE.dom.Range } 当前range对象
  4393. */
  4394. setStartAtLast:function (node) {
  4395. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4396. },
  4397. /**
  4398. * 设置Range的结束位置到node节点内的第一个节点之前
  4399. * @method setEndAtFirst
  4400. * @param { Node } node 目标节点
  4401. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4402. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4403. * @see UE.dom.Range:setStartAtFirst(Node)
  4404. * @return { UE.dom.Range } 当前range对象
  4405. */
  4406. setEndAtFirst:function (node) {
  4407. return this.setEnd(node, 0);
  4408. },
  4409. /**
  4410. * 设置Range的结束位置到node节点内的最后一个节点之后
  4411. * @method setEndAtLast
  4412. * @param { Node } node 目标节点
  4413. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4414. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4415. * @see UE.dom.Range:setStartAtFirst(Node)
  4416. * @return { UE.dom.Range } 当前range对象
  4417. */
  4418. setEndAtLast:function (node) {
  4419. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4420. },
  4421. /**
  4422. * 选中给定节点
  4423. * @method selectNode
  4424. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4425. * 而endOffset为startOffset+1
  4426. * @param { Node } node 需要选中的节点
  4427. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4428. * @example
  4429. * ```html
  4430. * <!-- 选区示例 -->
  4431. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4432. *
  4433. * <script>
  4434. *
  4435. * //执行操作
  4436. * range.selectNode( document.getElementsByTagName("i")[0] );
  4437. *
  4438. * //结果选区
  4439. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4440. *
  4441. * </script>
  4442. * ```
  4443. */
  4444. selectNode:function (node) {
  4445. return this.setStartBefore(node).setEndAfter(node);
  4446. },
  4447. /**
  4448. * 选中给定节点内部的所有节点
  4449. * @method selectNodeContents
  4450. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4451. * 而endOffset是该节点的子节点数。
  4452. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4453. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4454. * @example
  4455. * ```html
  4456. * <!-- 选区示例 -->
  4457. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4458. *
  4459. * <script>
  4460. *
  4461. * //执行操作
  4462. * range.selectNode( document.getElementsByTagName("b")[0] );
  4463. *
  4464. * //结果选区
  4465. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4466. *
  4467. * </script>
  4468. * ```
  4469. */
  4470. selectNodeContents:function (node) {
  4471. return this.setStart(node, 0).setEndAtLast(node);
  4472. },
  4473. /**
  4474. * clone当前Range对象
  4475. * @method cloneRange
  4476. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4477. * @return { UE.dom.Range } 当前range对象的一个副本
  4478. */
  4479. cloneRange:function () {
  4480. var me = this;
  4481. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4482. },
  4483. /**
  4484. * 向当前选区的结束处闭合选区
  4485. * @method collapse
  4486. * @return { UE.dom.Range } 当前range对象
  4487. * @example
  4488. * ```html
  4489. * <!-- 选区示例 -->
  4490. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4491. *
  4492. * <script>
  4493. *
  4494. * //执行操作
  4495. * range.collapse();
  4496. *
  4497. * //结果选区
  4498. * //“|”表示选区已闭合
  4499. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4500. *
  4501. * </script>
  4502. * ```
  4503. */
  4504. /**
  4505. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4506. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4507. * @method collapse
  4508. * @param { Boolean } toStart 是否向选区开始处闭合
  4509. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4510. * @see UE.dom.Range:collapse()
  4511. * @example
  4512. * ```html
  4513. * <!-- 选区示例 -->
  4514. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4515. *
  4516. * <script>
  4517. *
  4518. * //执行操作
  4519. * range.collapse( true );
  4520. *
  4521. * //结果选区
  4522. * //“|”表示选区已闭合
  4523. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4524. *
  4525. * </script>
  4526. * ```
  4527. */
  4528. collapse:function (toStart) {
  4529. var me = this;
  4530. if (toStart) {
  4531. me.endContainer = me.startContainer;
  4532. me.endOffset = me.startOffset;
  4533. } else {
  4534. me.startContainer = me.endContainer;
  4535. me.startOffset = me.endOffset;
  4536. }
  4537. me.collapsed = true;
  4538. return me;
  4539. },
  4540. /**
  4541. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4542. * @method shrinkBoundary
  4543. * @return { UE.dom.Range } 当前range对象
  4544. * @example
  4545. * ```html
  4546. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4547. * ```
  4548. *
  4549. * @example
  4550. * ```html
  4551. * <!-- 选区示例 -->
  4552. * <b>x[xx</b><i>]xxx</i>
  4553. *
  4554. * <script>
  4555. *
  4556. * //执行收缩
  4557. * range.shrinkBoundary();
  4558. *
  4559. * //结果选区
  4560. * //<b>x[xx]</b><i>xxx</i>
  4561. * </script>
  4562. * ```
  4563. *
  4564. * @example
  4565. * ```html
  4566. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4567. * ```
  4568. */
  4569. /**
  4570. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4571. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4572. * @method shrinkBoundary
  4573. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4574. * @return { UE.dom.Range } 当前range对象
  4575. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4576. */
  4577. shrinkBoundary:function (ignoreEnd) {
  4578. var me = this, child,
  4579. collapsed = me.collapsed;
  4580. function check(node){
  4581. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4582. }
  4583. while (me.startContainer.nodeType == 1 //是element
  4584. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4585. && check(child)) {
  4586. me.setStart(child, 0);
  4587. }
  4588. if (collapsed) {
  4589. return me.collapse(true);
  4590. }
  4591. if (!ignoreEnd) {
  4592. while (me.endContainer.nodeType == 1//是element
  4593. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4594. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4595. && check(child)) {
  4596. me.setEnd(child, child.childNodes.length);
  4597. }
  4598. }
  4599. return me;
  4600. },
  4601. /**
  4602. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4603. * @method getCommonAncestor
  4604. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4605. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4606. * @example
  4607. * ```html
  4608. * //选区示例
  4609. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4610. * <script>
  4611. *
  4612. * var node = range.getCommonAncestor();
  4613. *
  4614. * //公共祖先节点是: b节点
  4615. * //输出: B
  4616. * console.log(node.tagName);
  4617. *
  4618. * </script>
  4619. * ```
  4620. */
  4621. /**
  4622. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4623. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4624. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4625. * @method getCommonAncestor
  4626. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4627. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4628. * @see UE.dom.Range:getCommonAncestor()
  4629. * @example
  4630. * ```html
  4631. * <body>
  4632. *
  4633. * <!-- 选区示例 -->
  4634. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4635. *
  4636. * <script>
  4637. *
  4638. * var node = range.getCommonAncestor( false );
  4639. *
  4640. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4641. * //output: B
  4642. * console.log( node.tagName );
  4643. *
  4644. * </script>
  4645. *
  4646. * </body>
  4647. * ```
  4648. */
  4649. /**
  4650. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4651. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4652. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4653. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4654. * @method getCommonAncestor
  4655. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4656. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4657. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4658. * @see UE.dom.Range:getCommonAncestor()
  4659. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4660. * @example
  4661. * ```html
  4662. * <body>
  4663. *
  4664. * <!-- 选区示例 -->
  4665. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4666. *
  4667. * <script>
  4668. *
  4669. * var node = range.getCommonAncestor( true, false );
  4670. *
  4671. * //output: SPAN
  4672. * console.log( node.tagName );
  4673. *
  4674. * </script>
  4675. *
  4676. * </body>
  4677. * ```
  4678. */
  4679. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4680. var me = this,
  4681. start = me.startContainer,
  4682. end = me.endContainer;
  4683. if (start === end) {
  4684. if (includeSelf && selectOneNode(this)) {
  4685. start = start.childNodes[me.startOffset];
  4686. if(start.nodeType == 1)
  4687. return start;
  4688. }
  4689. //只有在上来就相等的情况下才会出现是文本的情况
  4690. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4691. }
  4692. return domUtils.getCommonAncestor(start, end);
  4693. },
  4694. /**
  4695. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4696. * @method trimBoundary
  4697. * @remind 该操作有可能会引起文本节点被切开
  4698. * @return { UE.dom.Range } 当前range对象
  4699. * @example
  4700. * ```html
  4701. *
  4702. * //选区示例
  4703. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4704. *
  4705. * <script>
  4706. * //未调整前, 选区的开始容器和结束都是文本节点
  4707. * //执行调整
  4708. * range.trimBoundary();
  4709. *
  4710. * //调整之后, 容器节点变成了i节点
  4711. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4712. * </script>
  4713. * ```
  4714. */
  4715. /**
  4716. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4717. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4718. * @method trimBoundary
  4719. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4720. * @return { UE.dom.Range } 当前range对象
  4721. * @example
  4722. * ```html
  4723. *
  4724. * //选区示例
  4725. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4726. *
  4727. * <script>
  4728. * //未调整前, 选区的开始容器和结束都是文本节点
  4729. * //执行调整
  4730. * range.trimBoundary( true );
  4731. *
  4732. * //调整之后, 开始容器节点变成了i节点
  4733. * //但是, 结束容器没有发生变化
  4734. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4735. * </script>
  4736. * ```
  4737. */
  4738. trimBoundary:function (ignoreEnd) {
  4739. this.txtToElmBoundary();
  4740. var start = this.startContainer,
  4741. offset = this.startOffset,
  4742. collapsed = this.collapsed,
  4743. end = this.endContainer;
  4744. if (start.nodeType == 3) {
  4745. if (offset == 0) {
  4746. this.setStartBefore(start);
  4747. } else {
  4748. if (offset >= start.nodeValue.length) {
  4749. this.setStartAfter(start);
  4750. } else {
  4751. var textNode = domUtils.split(start, offset);
  4752. //跟新结束边界
  4753. if (start === end) {
  4754. this.setEnd(textNode, this.endOffset - offset);
  4755. } else if (start.parentNode === end) {
  4756. this.endOffset += 1;
  4757. }
  4758. this.setStartBefore(textNode);
  4759. }
  4760. }
  4761. if (collapsed) {
  4762. return this.collapse(true);
  4763. }
  4764. }
  4765. if (!ignoreEnd) {
  4766. offset = this.endOffset;
  4767. end = this.endContainer;
  4768. if (end.nodeType == 3) {
  4769. if (offset == 0) {
  4770. this.setEndBefore(end);
  4771. } else {
  4772. offset < end.nodeValue.length && domUtils.split(end, offset);
  4773. this.setEndAfter(end);
  4774. }
  4775. }
  4776. }
  4777. return this;
  4778. },
  4779. /**
  4780. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4781. * @method txtToElmBoundary
  4782. * @remind 该操作不会修改dom节点
  4783. * @return { UE.dom.Range } 当前range对象
  4784. */
  4785. /**
  4786. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4787. * ignoreCollapsed 的值决定是否执行该调整
  4788. * @method txtToElmBoundary
  4789. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4790. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4791. * @return { UE.dom.Range } 当前range对象
  4792. */
  4793. txtToElmBoundary:function (ignoreCollapsed) {
  4794. function adjust(r, c) {
  4795. var container = r[c + 'Container'],
  4796. offset = r[c + 'Offset'];
  4797. if (container.nodeType == 3) {
  4798. if (!offset) {
  4799. r['set' + c.replace(/(\w)/, function (a) {
  4800. return a.toUpperCase();
  4801. }) + 'Before'](container);
  4802. } else if (offset >= container.nodeValue.length) {
  4803. r['set' + c.replace(/(\w)/, function (a) {
  4804. return a.toUpperCase();
  4805. }) + 'After' ](container);
  4806. }
  4807. }
  4808. }
  4809. if (ignoreCollapsed || !this.collapsed) {
  4810. adjust(this, 'start');
  4811. adjust(this, 'end');
  4812. }
  4813. return this;
  4814. },
  4815. /**
  4816. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  4817. * @method insertNode
  4818. * @param { Node } node 需要插入的节点
  4819. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  4820. * @return { UE.dom.Range } 当前range对象
  4821. */
  4822. insertNode:function (node) {
  4823. var first = node, length = 1;
  4824. if (node.nodeType == 11) {
  4825. first = node.firstChild;
  4826. length = node.childNodes.length;
  4827. }
  4828. this.trimBoundary(true);
  4829. var start = this.startContainer,
  4830. offset = this.startOffset;
  4831. var nextNode = start.childNodes[ offset ];
  4832. if (nextNode) {
  4833. start.insertBefore(node, nextNode);
  4834. } else {
  4835. start.appendChild(node);
  4836. }
  4837. if (first.parentNode === this.endContainer) {
  4838. this.endOffset = this.endOffset + length;
  4839. }
  4840. return this.setStartBefore(first);
  4841. },
  4842. /**
  4843. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  4844. * @method setCursor
  4845. * @return { UE.dom.Range } 当前range对象
  4846. * @see UE.dom.Range:collapse()
  4847. */
  4848. /**
  4849. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  4850. * @method setCursor
  4851. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  4852. * 反之,则向开始容器方向闭合
  4853. * @return { UE.dom.Range } 当前range对象
  4854. * @see UE.dom.Range:collapse(Boolean)
  4855. */
  4856. setCursor:function (toEnd, noFillData) {
  4857. return this.collapse(!toEnd).select(noFillData);
  4858. },
  4859. /**
  4860. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  4861. * @method createBookmark
  4862. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  4863. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  4864. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  4865. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  4866. * 返回的记录的类型为ID, 反之则为引用
  4867. */
  4868. createBookmark:function (serialize, same) {
  4869. var endNode,
  4870. startNode = this.document.createElement('span');
  4871. startNode.style.cssText = 'display:none;line-height:0px;';
  4872. startNode.appendChild(this.document.createTextNode('\u200D'));
  4873. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  4874. if (!this.collapsed) {
  4875. endNode = startNode.cloneNode(true);
  4876. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  4877. }
  4878. this.insertNode(startNode);
  4879. if (endNode) {
  4880. this.collapse().insertNode(endNode).setEndBefore(endNode);
  4881. }
  4882. this.setStartAfter(startNode);
  4883. return {
  4884. start:serialize ? startNode.id : startNode,
  4885. end:endNode ? serialize ? endNode.id : endNode : null,
  4886. id:serialize
  4887. }
  4888. },
  4889. /**
  4890. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  4891. * @method moveToBookmark
  4892. * @param { BookMark } bookmark createBookmark所创建的标签对象
  4893. * @return { UE.dom.Range } 当前range对象
  4894. * @see UE.dom.Range:createBookmark(Boolean)
  4895. */
  4896. moveToBookmark:function (bookmark) {
  4897. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  4898. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  4899. this.setStartBefore(start);
  4900. domUtils.remove(start);
  4901. if (end) {
  4902. this.setEndBefore(end);
  4903. domUtils.remove(end);
  4904. } else {
  4905. this.collapse(true);
  4906. }
  4907. return this;
  4908. },
  4909. /**
  4910. * 调整range的边界,使其"放大"到最近的父节点
  4911. * @method enlarge
  4912. * @remind 会引起选区的变化
  4913. * @return { UE.dom.Range } 当前range对象
  4914. */
  4915. /**
  4916. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  4917. * 要求扩大之后的父节点是block节点
  4918. * @method enlarge
  4919. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  4920. * @return { UE.dom.Range } 当前range对象
  4921. */
  4922. enlarge:function (toBlock, stopFn) {
  4923. var isBody = domUtils.isBody,
  4924. pre, node, tmp = this.document.createTextNode('');
  4925. if (toBlock) {
  4926. node = this.startContainer;
  4927. if (node.nodeType == 1) {
  4928. if (node.childNodes[this.startOffset]) {
  4929. pre = node = node.childNodes[this.startOffset]
  4930. } else {
  4931. node.appendChild(tmp);
  4932. pre = node = tmp;
  4933. }
  4934. } else {
  4935. pre = node;
  4936. }
  4937. while (1) {
  4938. if (domUtils.isBlockElm(node)) {
  4939. node = pre;
  4940. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  4941. node = pre;
  4942. }
  4943. this.setStartBefore(node);
  4944. break;
  4945. }
  4946. pre = node;
  4947. node = node.parentNode;
  4948. }
  4949. node = this.endContainer;
  4950. if (node.nodeType == 1) {
  4951. if (pre = node.childNodes[this.endOffset]) {
  4952. node.insertBefore(tmp, pre);
  4953. } else {
  4954. node.appendChild(tmp);
  4955. }
  4956. pre = node = tmp;
  4957. } else {
  4958. pre = node;
  4959. }
  4960. while (1) {
  4961. if (domUtils.isBlockElm(node)) {
  4962. node = pre;
  4963. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  4964. node = pre;
  4965. }
  4966. this.setEndAfter(node);
  4967. break;
  4968. }
  4969. pre = node;
  4970. node = node.parentNode;
  4971. }
  4972. if (tmp.parentNode === this.endContainer) {
  4973. this.endOffset--;
  4974. }
  4975. domUtils.remove(tmp);
  4976. }
  4977. // 扩展边界到最大
  4978. if (!this.collapsed) {
  4979. while (this.startOffset == 0) {
  4980. if (stopFn && stopFn(this.startContainer)) {
  4981. break;
  4982. }
  4983. if (isBody(this.startContainer)) {
  4984. break;
  4985. }
  4986. this.setStartBefore(this.startContainer);
  4987. }
  4988. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  4989. if (stopFn && stopFn(this.endContainer)) {
  4990. break;
  4991. }
  4992. if (isBody(this.endContainer)) {
  4993. break;
  4994. }
  4995. this.setEndAfter(this.endContainer);
  4996. }
  4997. }
  4998. return this;
  4999. },
  5000. enlargeToBlockElm:function(ignoreEnd){
  5001. while(!domUtils.isBlockElm(this.startContainer)){
  5002. this.setStartBefore(this.startContainer);
  5003. }
  5004. if(!ignoreEnd){
  5005. while(!domUtils.isBlockElm(this.endContainer)){
  5006. this.setEndAfter(this.endContainer);
  5007. }
  5008. }
  5009. return this;
  5010. },
  5011. /**
  5012. * 调整Range的边界,使其"缩小"到最合适的位置
  5013. * @method adjustmentBoundary
  5014. * @return { UE.dom.Range } 当前range对象
  5015. * @see UE.dom.Range:shrinkBoundary()
  5016. */
  5017. adjustmentBoundary:function () {
  5018. if (!this.collapsed) {
  5019. while (!domUtils.isBody(this.startContainer) &&
  5020. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5021. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5022. ) {
  5023. this.setStartAfter(this.startContainer);
  5024. }
  5025. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5026. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5027. ) {
  5028. this.setEndBefore(this.endContainer);
  5029. }
  5030. }
  5031. return this;
  5032. },
  5033. /**
  5034. * 给range选区中的内容添加给定的inline标签
  5035. * @method applyInlineStyle
  5036. * @param { String } tagName 需要添加的标签名
  5037. * @example
  5038. * ```html
  5039. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5040. * ```
  5041. */
  5042. /**
  5043. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5044. * @method applyInlineStyle
  5045. * @param { String } tagName 需要添加的标签名
  5046. * @param { Object } attrs 跟随新添加的标签的属性
  5047. * @return { UE.dom.Range } 当前选区
  5048. * @example
  5049. * ```html
  5050. * <p>xxxx[xxxx]x</p>
  5051. *
  5052. * ==>
  5053. *
  5054. * <!-- 执行操作 -->
  5055. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5056. *
  5057. * ==>
  5058. *
  5059. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5060. * ```
  5061. */
  5062. applyInlineStyle:function (tagName, attrs, list) {
  5063. if (this.collapsed)return this;
  5064. this.trimBoundary().enlarge(false,
  5065. function (node) {
  5066. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5067. }).adjustmentBoundary();
  5068. var bookmark = this.createBookmark(),
  5069. end = bookmark.end,
  5070. filterFn = function (node) {
  5071. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5072. },
  5073. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5074. node,
  5075. pre,
  5076. range = this.cloneRange();
  5077. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5078. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5079. range.setStartBefore(current);
  5080. node = current;
  5081. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5082. pre = node;
  5083. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5084. return dtd[tagName][parent.tagName];
  5085. });
  5086. }
  5087. var frag = range.setEndAfter(pre).extractContents(), elm;
  5088. if (list && list.length > 0) {
  5089. var level, top;
  5090. top = level = list[0].cloneNode(false);
  5091. for (var i = 1, ci; ci = list[i++];) {
  5092. level.appendChild(ci.cloneNode(false));
  5093. level = level.firstChild;
  5094. }
  5095. elm = level;
  5096. } else {
  5097. elm = range.document.createElement(tagName);
  5098. }
  5099. if (attrs) {
  5100. domUtils.setAttributes(elm, attrs);
  5101. }
  5102. elm.appendChild(frag);
  5103. range.insertNode(list ? top : elm);
  5104. //处理下滑线在a上的情况
  5105. var aNode;
  5106. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5107. domUtils.setAttributes(aNode, attrs);
  5108. domUtils.remove(elm, true);
  5109. elm = aNode;
  5110. } else {
  5111. domUtils.mergeSibling(elm);
  5112. domUtils.clearEmptySibling(elm);
  5113. }
  5114. //去除子节点相同的
  5115. domUtils.mergeChild(elm, attrs);
  5116. current = domUtils.getNextDomNode(elm, false, filterFn);
  5117. domUtils.mergeToParent(elm);
  5118. if (node === end) {
  5119. break;
  5120. }
  5121. } else {
  5122. current = domUtils.getNextDomNode(current, true, filterFn);
  5123. }
  5124. }
  5125. return this.moveToBookmark(bookmark);
  5126. },
  5127. /**
  5128. * 移除当前选区内指定的inline标签,但保留其中的内容
  5129. * @method removeInlineStyle
  5130. * @param { String } tagName 需要移除的标签名
  5131. * @return { UE.dom.Range } 当前的range对象
  5132. * @example
  5133. * ```html
  5134. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5135. * ```
  5136. */
  5137. /**
  5138. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5139. * @method removeInlineStyle
  5140. * @param { Array } tagNameArr 需要移除的标签名的数组
  5141. * @return { UE.dom.Range } 当前的range对象
  5142. * @see UE.dom.Range:removeInlineStyle(String)
  5143. */
  5144. removeInlineStyle:function (tagNames) {
  5145. if (this.collapsed)return this;
  5146. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5147. this.shrinkBoundary().adjustmentBoundary();
  5148. var start = this.startContainer, end = this.endContainer;
  5149. while (1) {
  5150. if (start.nodeType == 1) {
  5151. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5152. break;
  5153. }
  5154. if (start.tagName.toLowerCase() == 'body') {
  5155. start = null;
  5156. break;
  5157. }
  5158. }
  5159. start = start.parentNode;
  5160. }
  5161. while (1) {
  5162. if (end.nodeType == 1) {
  5163. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5164. break;
  5165. }
  5166. if (end.tagName.toLowerCase() == 'body') {
  5167. end = null;
  5168. break;
  5169. }
  5170. }
  5171. end = end.parentNode;
  5172. }
  5173. var bookmark = this.createBookmark(),
  5174. frag,
  5175. tmpRange;
  5176. if (start) {
  5177. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5178. frag = tmpRange.extractContents();
  5179. tmpRange.insertNode(frag);
  5180. domUtils.clearEmptySibling(start, true);
  5181. start.parentNode.insertBefore(bookmark.start, start);
  5182. }
  5183. if (end) {
  5184. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5185. frag = tmpRange.extractContents();
  5186. tmpRange.insertNode(frag);
  5187. domUtils.clearEmptySibling(end, false, true);
  5188. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5189. }
  5190. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5191. return node.nodeType == 1;
  5192. }), next;
  5193. while (current && current !== bookmark.end) {
  5194. next = domUtils.getNextDomNode(current, true, function (node) {
  5195. return node.nodeType == 1;
  5196. });
  5197. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5198. domUtils.remove(current, true);
  5199. }
  5200. current = next;
  5201. }
  5202. return this.moveToBookmark(bookmark);
  5203. },
  5204. /**
  5205. * 获取当前选中的自闭合的节点
  5206. * @method getClosedNode
  5207. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5208. */
  5209. getClosedNode:function () {
  5210. var node;
  5211. if (!this.collapsed) {
  5212. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5213. if (selectOneNode(range)) {
  5214. var child = range.startContainer.childNodes[range.startOffset];
  5215. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5216. node = child;
  5217. }
  5218. }
  5219. }
  5220. return node;
  5221. },
  5222. /**
  5223. * 在页面上高亮range所表示的选区
  5224. * @method select
  5225. * @return { UE.dom.Range } 返回当前Range对象
  5226. */
  5227. //这里不区分ie9以上,trace:3824
  5228. select:browser.ie ? function (noFillData, textRange) {
  5229. var nativeRange;
  5230. if (!this.collapsed)
  5231. this.shrinkBoundary();
  5232. var node = this.getClosedNode();
  5233. if (node && !textRange) {
  5234. try {
  5235. nativeRange = this.document.body.createControlRange();
  5236. nativeRange.addElement(node);
  5237. nativeRange.select();
  5238. } catch (e) {}
  5239. return this;
  5240. }
  5241. var bookmark = this.createBookmark(),
  5242. start = bookmark.start,
  5243. end;
  5244. nativeRange = this.document.body.createTextRange();
  5245. nativeRange.moveToElementText(start);
  5246. nativeRange.moveStart('character', 1);
  5247. if (!this.collapsed) {
  5248. var nativeRangeEnd = this.document.body.createTextRange();
  5249. end = bookmark.end;
  5250. nativeRangeEnd.moveToElementText(end);
  5251. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5252. } else {
  5253. if (!noFillData && this.startContainer.nodeType != 3) {
  5254. //使用<span>|x<span>固定住光标
  5255. var tmpText = this.document.createTextNode(fillChar),
  5256. tmp = this.document.createElement('span');
  5257. tmp.appendChild(this.document.createTextNode(fillChar));
  5258. start.parentNode.insertBefore(tmp, start);
  5259. start.parentNode.insertBefore(tmpText, start);
  5260. //当点b,i,u时,不能清除i上边的b
  5261. removeFillData(this.document, tmpText);
  5262. fillData = tmpText;
  5263. mergeSibling(tmp, 'previousSibling');
  5264. mergeSibling(start, 'nextSibling');
  5265. nativeRange.moveStart('character', -1);
  5266. nativeRange.collapse(true);
  5267. }
  5268. }
  5269. this.moveToBookmark(bookmark);
  5270. tmp && domUtils.remove(tmp);
  5271. //IE在隐藏状态下不支持range操作,catch一下
  5272. try {
  5273. nativeRange.select();
  5274. } catch (e) {
  5275. }
  5276. return this;
  5277. } : function (notInsertFillData) {
  5278. function checkOffset(rng){
  5279. function check(node,offset,dir){
  5280. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5281. rng[dir + 'Offset'] = node.nodeValue.length
  5282. }
  5283. }
  5284. check(rng.startContainer,rng.startOffset,'start');
  5285. check(rng.endContainer,rng.endOffset,'end');
  5286. }
  5287. var win = domUtils.getWindow(this.document),
  5288. sel = win.getSelection(),
  5289. txtNode;
  5290. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5291. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5292. browser.gecko ? this.document.body.focus() : win.focus();
  5293. if (sel) {
  5294. sel.removeAllRanges();
  5295. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5296. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5297. if (this.collapsed && !notInsertFillData) {
  5298. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5299. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5300. // var tmp = this.document.createTextNode('');
  5301. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5302. // }
  5303. //
  5304. //处理光标落在文本节点的情况
  5305. //处理以下的情况
  5306. //<b>|xxxx</b>
  5307. //<b>xxxx</b>|xxxx
  5308. //xxxx<b>|</b>
  5309. var start = this.startContainer,child = start;
  5310. if(start.nodeType == 1){
  5311. child = start.childNodes[this.startOffset];
  5312. }
  5313. if( !(start.nodeType == 3 && this.startOffset) &&
  5314. (child ?
  5315. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5316. :
  5317. (!start.lastChild || start.lastChild.nodeType != 3)
  5318. )
  5319. ){
  5320. txtNode = this.document.createTextNode(fillChar);
  5321. //跟着前边走
  5322. this.insertNode(txtNode);
  5323. removeFillData(this.document, txtNode);
  5324. mergeSibling(txtNode, 'previousSibling');
  5325. mergeSibling(txtNode, 'nextSibling');
  5326. fillData = txtNode;
  5327. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5328. }
  5329. }
  5330. var nativeRange = this.document.createRange();
  5331. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5332. var child = this.startContainer.childNodes[this.startOffset];
  5333. if(!child){
  5334. //往前靠拢
  5335. child = this.startContainer.lastChild;
  5336. if( child && domUtils.isBr(child)){
  5337. this.setStartBefore(child).collapse(true);
  5338. }
  5339. }else{
  5340. //向后靠拢
  5341. while(child && domUtils.isBlockElm(child)){
  5342. if(child.nodeType == 1 && child.childNodes[0]){
  5343. child = child.childNodes[0]
  5344. }else{
  5345. break;
  5346. }
  5347. }
  5348. child && this.setStartBefore(child).collapse(true)
  5349. }
  5350. }
  5351. //是createAddress最后一位算的不准,现在这里进行微调
  5352. checkOffset(this);
  5353. nativeRange.setStart(this.startContainer, this.startOffset);
  5354. nativeRange.setEnd(this.endContainer, this.endOffset);
  5355. sel.addRange(nativeRange);
  5356. }
  5357. return this;
  5358. },
  5359. /**
  5360. * 滚动到当前range开始的位置
  5361. * @method scrollToView
  5362. * @param { Window } win 当前range对象所属的window对象
  5363. * @return { UE.dom.Range } 当前Range对象
  5364. */
  5365. /**
  5366. * 滚动到距离当前range开始位置 offset 的位置处
  5367. * @method scrollToView
  5368. * @param { Window } win 当前range对象所属的window对象
  5369. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5370. * @return { UE.dom.Range } 当前Range对象
  5371. */
  5372. scrollToView:function (win, offset) {
  5373. win = win ? window : domUtils.getWindow(this.document);
  5374. var me = this,
  5375. span = me.document.createElement('span');
  5376. //trace:717
  5377. span.innerHTML = '&nbsp;';
  5378. me.cloneRange().insertNode(span);
  5379. domUtils.scrollToView(span, win, offset);
  5380. domUtils.remove(span);
  5381. return me;
  5382. },
  5383. /**
  5384. * 判断当前选区内容是否占位符
  5385. * @private
  5386. * @method inFillChar
  5387. * @return { Boolean } 如果是占位符返回true,否则返回false
  5388. */
  5389. inFillChar : function(){
  5390. var start = this.startContainer;
  5391. if(this.collapsed && start.nodeType == 3
  5392. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5393. ){
  5394. return true;
  5395. }
  5396. return false;
  5397. },
  5398. /**
  5399. * 保存
  5400. * @method createAddress
  5401. * @private
  5402. * @return { Boolean } 返回开始和结束的位置
  5403. * @example
  5404. * ```html
  5405. * <body>
  5406. * <p>
  5407. * aaaa
  5408. * <em>
  5409. * <!-- 选区开始 -->
  5410. * bbbb
  5411. * <!-- 选区结束 -->
  5412. * </em>
  5413. * </p>
  5414. *
  5415. * <script>
  5416. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5417. * console.log( range.createAddress() );
  5418. * </script>
  5419. * </body>
  5420. * ```
  5421. */
  5422. createAddress : function(ignoreEnd,ignoreTxt){
  5423. var addr = {},me = this;
  5424. function getAddress(isStart){
  5425. var node = isStart ? me.startContainer : me.endContainer;
  5426. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5427. addrs = [];
  5428. for(var i = 0,ci;ci = parents[i++];){
  5429. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5430. }
  5431. var firstIndex = 0;
  5432. if(ignoreTxt){
  5433. if(node.nodeType == 3){
  5434. var tmpNode = node.previousSibling;
  5435. while(tmpNode && tmpNode.nodeType == 3){
  5436. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5437. tmpNode = tmpNode.previousSibling;
  5438. }
  5439. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5440. }else{
  5441. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5442. if(node){
  5443. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5444. }else{
  5445. node = isStart ? me.startContainer : me.endContainer;
  5446. var first = node.firstChild;
  5447. while(first){
  5448. if(domUtils.isFillChar(first)){
  5449. first = first.nextSibling;
  5450. continue;
  5451. }
  5452. firstIndex++;
  5453. if(first.nodeType == 3){
  5454. while( first && first.nodeType == 3){
  5455. first = first.nextSibling;
  5456. }
  5457. }else{
  5458. first = first.nextSibling;
  5459. }
  5460. }
  5461. }
  5462. }
  5463. }else{
  5464. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5465. }
  5466. if(firstIndex < 0){
  5467. firstIndex = 0;
  5468. }
  5469. addrs.push(firstIndex);
  5470. return addrs;
  5471. }
  5472. addr.startAddress = getAddress(true);
  5473. if(!ignoreEnd){
  5474. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5475. }
  5476. return addr;
  5477. },
  5478. /**
  5479. * 保存
  5480. * @method createAddress
  5481. * @private
  5482. * @return { Boolean } 返回开始和结束的位置
  5483. * @example
  5484. * ```html
  5485. * <body>
  5486. * <p>
  5487. * aaaa
  5488. * <em>
  5489. * <!-- 选区开始 -->
  5490. * bbbb
  5491. * <!-- 选区结束 -->
  5492. * </em>
  5493. * </p>
  5494. *
  5495. * <script>
  5496. * var range = editor.selection.getRange();
  5497. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5498. * range.select();
  5499. * //output: 'bbbb'
  5500. * console.log(editor.selection.getText());
  5501. * </script>
  5502. * </body>
  5503. * ```
  5504. */
  5505. moveToAddress : function(addr,ignoreEnd){
  5506. var me = this;
  5507. function getNode(address,isStart){
  5508. var tmpNode = me.document.body,
  5509. parentNode,offset;
  5510. for(var i= 0,ci,l=address.length;i<l;i++){
  5511. ci = address[i];
  5512. parentNode = tmpNode;
  5513. tmpNode = tmpNode.childNodes[ci];
  5514. if(!tmpNode){
  5515. offset = ci;
  5516. break;
  5517. }
  5518. }
  5519. if(isStart){
  5520. if(tmpNode){
  5521. me.setStartBefore(tmpNode)
  5522. }else{
  5523. me.setStart(parentNode,offset)
  5524. }
  5525. }else{
  5526. if(tmpNode){
  5527. me.setEndBefore(tmpNode)
  5528. }else{
  5529. me.setEnd(parentNode,offset)
  5530. }
  5531. }
  5532. }
  5533. getNode(addr.startAddress,true);
  5534. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5535. return me;
  5536. },
  5537. /**
  5538. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5539. * @method equals
  5540. * @param { UE.dom.Range } 需要判断的Range对象
  5541. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5542. */
  5543. equals : function(rng){
  5544. for(var p in this){
  5545. if(this.hasOwnProperty(p)){
  5546. if(this[p] !== rng[p])
  5547. return false
  5548. }
  5549. }
  5550. return true;
  5551. },
  5552. /**
  5553. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5554. * 作为其参数。
  5555. * @method traversal
  5556. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5557. * @return { UE.dom.Range } 当前range对象
  5558. * @example
  5559. * ```html
  5560. *
  5561. * <body>
  5562. *
  5563. * <!-- 选区开始 -->
  5564. * <span></span>
  5565. * <a></a>
  5566. * <!-- 选区结束 -->
  5567. * </body>
  5568. *
  5569. * <script>
  5570. *
  5571. * //output: <span></span><a></a>
  5572. * console.log( range.cloneContents() );
  5573. *
  5574. * range.traversal( function ( node ) {
  5575. *
  5576. * if ( node.nodeType === 1 ) {
  5577. * node.className = "test";
  5578. * }
  5579. *
  5580. * } );
  5581. *
  5582. * //output: <span class="test"></span><a class="test"></a>
  5583. * console.log( range.cloneContents() );
  5584. *
  5585. * </script>
  5586. * ```
  5587. */
  5588. /**
  5589. * 遍历range内的节点。
  5590. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5591. * 作为其参数。
  5592. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5593. * 发doFn函数的执行
  5594. * @method traversal
  5595. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5596. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5597. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5598. * 会触发doFn。
  5599. * @return { UE.dom.Range } 当前range对象
  5600. * @see UE.dom.Range:traversal(Function)
  5601. * @example
  5602. * ```html
  5603. *
  5604. * <body>
  5605. *
  5606. * <!-- 选区开始 -->
  5607. * <span></span>
  5608. * <a></a>
  5609. * <!-- 选区结束 -->
  5610. * </body>
  5611. *
  5612. * <script>
  5613. *
  5614. * //output: <span></span><a></a>
  5615. * console.log( range.cloneContents() );
  5616. *
  5617. * range.traversal( function ( node ) {
  5618. *
  5619. * node.className = "test";
  5620. *
  5621. * }, function ( node ) {
  5622. * return node.nodeType === 1;
  5623. * } );
  5624. *
  5625. * //output: <span class="test"></span><a class="test"></a>
  5626. * console.log( range.cloneContents() );
  5627. *
  5628. * </script>
  5629. * ```
  5630. */
  5631. traversal:function(doFn,filterFn){
  5632. if (this.collapsed)
  5633. return this;
  5634. var bookmark = this.createBookmark(),
  5635. end = bookmark.end,
  5636. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5637. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5638. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5639. doFn(current);
  5640. current = tmpNode;
  5641. }
  5642. return this.moveToBookmark(bookmark);
  5643. }
  5644. };
  5645. })();
  5646. /**
  5647. * 选集
  5648. * @file
  5649. * @module UE.dom
  5650. * @class Selection
  5651. * @since 1.2.6.1
  5652. */
  5653. /**
  5654. * 选区集合
  5655. * @unfile
  5656. * @module UE.dom
  5657. * @class Selection
  5658. */
  5659. (function () {
  5660. function getBoundaryInformation( range, start ) {
  5661. var getIndex = domUtils.getNodeIndex;
  5662. range = range.duplicate();
  5663. range.collapse( start );
  5664. var parent = range.parentElement();
  5665. //如果节点里没有子节点,直接退出
  5666. if ( !parent.hasChildNodes() ) {
  5667. return {container:parent, offset:0};
  5668. }
  5669. var siblings = parent.children,
  5670. child,
  5671. testRange = range.duplicate(),
  5672. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5673. distance;
  5674. while ( startIndex <= endIndex ) {
  5675. index = Math.floor( (startIndex + endIndex) / 2 );
  5676. child = siblings[index];
  5677. testRange.moveToElementText( child );
  5678. var position = testRange.compareEndPoints( 'StartToStart', range );
  5679. if ( position > 0 ) {
  5680. endIndex = index - 1;
  5681. } else if ( position < 0 ) {
  5682. startIndex = index + 1;
  5683. } else {
  5684. //trace:1043
  5685. return {container:parent, offset:getIndex( child )};
  5686. }
  5687. }
  5688. if ( index == -1 ) {
  5689. testRange.moveToElementText( parent );
  5690. testRange.setEndPoint( 'StartToStart', range );
  5691. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5692. siblings = parent.childNodes;
  5693. if ( !distance ) {
  5694. child = siblings[siblings.length - 1];
  5695. return {container:child, offset:child.nodeValue.length};
  5696. }
  5697. var i = siblings.length;
  5698. while ( distance > 0 ){
  5699. distance -= siblings[ --i ].nodeValue.length;
  5700. }
  5701. return {container:siblings[i], offset:-distance};
  5702. }
  5703. testRange.collapse( position > 0 );
  5704. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5705. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5706. if ( !distance ) {
  5707. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5708. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5709. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5710. }
  5711. while ( distance > 0 ) {
  5712. try {
  5713. var pre = child;
  5714. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5715. distance -= child.nodeValue.length;
  5716. } catch ( e ) {
  5717. return {container:parent, offset:getIndex( pre )};
  5718. }
  5719. }
  5720. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5721. }
  5722. /*
  5723. * 将ieRange转换为Range对象
  5724. * @param {Range} ieRange ieRange对象
  5725. * @param {Range} range Range对象
  5726. * @return {Range} range 返回转换后的Range对象
  5727. */
  5728. function transformIERangeToRange( ieRange, range ) {
  5729. if ( ieRange.item ) {
  5730. range.selectNode( ieRange.item( 0 ) );
  5731. } else {
  5732. var bi = getBoundaryInformation( ieRange, true );
  5733. range.setStart( bi.container, bi.offset );
  5734. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5735. bi = getBoundaryInformation( ieRange, false );
  5736. range.setEnd( bi.container, bi.offset );
  5737. }
  5738. }
  5739. return range;
  5740. }
  5741. /*
  5742. * 获得ieRange
  5743. * @param {Selection} sel Selection对象
  5744. * @return {ieRange} 得到ieRange
  5745. */
  5746. function _getIERange( sel ) {
  5747. var ieRange;
  5748. //ie下有可能报错
  5749. try {
  5750. ieRange = sel.getNative().createRange();
  5751. } catch ( e ) {
  5752. return null;
  5753. }
  5754. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5755. if ( ( el.ownerDocument || el ) === sel.document ) {
  5756. return ieRange;
  5757. }
  5758. return null;
  5759. }
  5760. var Selection = dom.Selection = function ( doc ) {
  5761. var me = this, iframe;
  5762. me.document = doc;
  5763. if ( browser.ie9below ) {
  5764. iframe = domUtils.getWindow( doc ).frameElement;
  5765. domUtils.on( iframe, 'beforedeactivate', function () {
  5766. me._bakIERange = me.getIERange();
  5767. } );
  5768. domUtils.on( iframe, 'activate', function () {
  5769. try {
  5770. if ( !_getIERange( me ) && me._bakIERange ) {
  5771. me._bakIERange.select();
  5772. }
  5773. } catch ( ex ) {
  5774. }
  5775. me._bakIERange = null;
  5776. } );
  5777. }
  5778. iframe = doc = null;
  5779. };
  5780. Selection.prototype = {
  5781. rangeInBody : function(rng,txtRange){
  5782. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5783. return node === this.document.body || domUtils.inDoc(node,this.document);
  5784. },
  5785. /**
  5786. * 获取原生seleciton对象
  5787. * @method getNative
  5788. * @return { Object } 获得selection对象
  5789. * @example
  5790. * ```javascript
  5791. * editor.selection.getNative();
  5792. * ```
  5793. */
  5794. getNative:function () {
  5795. var doc = this.document;
  5796. try {
  5797. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5798. } catch ( e ) {
  5799. return null;
  5800. }
  5801. },
  5802. /**
  5803. * 获得ieRange
  5804. * @method getIERange
  5805. * @return { Object } 返回ie原生的Range
  5806. * @example
  5807. * ```javascript
  5808. * editor.selection.getIERange();
  5809. * ```
  5810. */
  5811. getIERange:function () {
  5812. var ieRange = _getIERange( this );
  5813. if ( !ieRange ) {
  5814. if ( this._bakIERange ) {
  5815. return this._bakIERange;
  5816. }
  5817. }
  5818. return ieRange;
  5819. },
  5820. /**
  5821. * 缓存当前选区的range和选区的开始节点
  5822. * @method cache
  5823. */
  5824. cache:function () {
  5825. this.clear();
  5826. this._cachedRange = this.getRange();
  5827. this._cachedStartElement = this.getStart();
  5828. this._cachedStartElementPath = this.getStartElementPath();
  5829. },
  5830. /**
  5831. * 获取选区开始位置的父节点到body
  5832. * @method getStartElementPath
  5833. * @return { Array } 返回父节点集合
  5834. * @example
  5835. * ```javascript
  5836. * editor.selection.getStartElementPath();
  5837. * ```
  5838. */
  5839. getStartElementPath:function () {
  5840. if ( this._cachedStartElementPath ) {
  5841. return this._cachedStartElementPath;
  5842. }
  5843. var start = this.getStart();
  5844. if ( start ) {
  5845. return domUtils.findParents( start, true, null, true )
  5846. }
  5847. return [];
  5848. },
  5849. /**
  5850. * 清空缓存
  5851. * @method clear
  5852. */
  5853. clear:function () {
  5854. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  5855. },
  5856. /**
  5857. * 编辑器是否得到了选区
  5858. * @method isFocus
  5859. */
  5860. isFocus:function () {
  5861. try {
  5862. if(browser.ie9below){
  5863. var nativeRange = _getIERange(this);
  5864. return !!(nativeRange && this.rangeInBody(nativeRange));
  5865. }else{
  5866. return !!this.getNative().rangeCount;
  5867. }
  5868. } catch ( e ) {
  5869. return false;
  5870. }
  5871. },
  5872. /**
  5873. * 获取选区对应的Range
  5874. * @method getRange
  5875. * @return { Object } 得到Range对象
  5876. * @example
  5877. * ```javascript
  5878. * editor.selection.getRange();
  5879. * ```
  5880. */
  5881. getRange:function () {
  5882. var me = this;
  5883. function optimze( range ) {
  5884. var child = me.document.body.firstChild,
  5885. collapsed = range.collapsed;
  5886. while ( child && child.firstChild ) {
  5887. range.setStart( child, 0 );
  5888. child = child.firstChild;
  5889. }
  5890. if ( !range.startContainer ) {
  5891. range.setStart( me.document.body, 0 )
  5892. }
  5893. if ( collapsed ) {
  5894. range.collapse( true );
  5895. }
  5896. }
  5897. if ( me._cachedRange != null ) {
  5898. return this._cachedRange;
  5899. }
  5900. var range = new baidu.editor.dom.Range( me.document );
  5901. if ( browser.ie9below ) {
  5902. var nativeRange = me.getIERange();
  5903. if ( nativeRange ) {
  5904. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  5905. try{
  5906. transformIERangeToRange( nativeRange, range );
  5907. }catch(e){
  5908. optimze( range );
  5909. }
  5910. } else {
  5911. optimze( range );
  5912. }
  5913. } else {
  5914. var sel = me.getNative();
  5915. if ( sel && sel.rangeCount ) {
  5916. var firstRange = sel.getRangeAt( 0 );
  5917. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  5918. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  5919. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  5920. optimze( range );
  5921. }
  5922. } else {
  5923. //trace:1734 有可能已经不在dom树上了,标识的节点
  5924. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  5925. return this._bakRange;
  5926. }
  5927. optimze( range );
  5928. }
  5929. }
  5930. return this._bakRange = range;
  5931. },
  5932. /**
  5933. * 获取开始元素,用于状态反射
  5934. * @method getStart
  5935. * @return { Element } 获得开始元素
  5936. * @example
  5937. * ```javascript
  5938. * editor.selection.getStart();
  5939. * ```
  5940. */
  5941. getStart:function () {
  5942. if ( this._cachedStartElement ) {
  5943. return this._cachedStartElement;
  5944. }
  5945. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  5946. tmpRange,
  5947. start, tmp, parent;
  5948. if ( browser.ie9below ) {
  5949. if ( !range ) {
  5950. //todo 给第一个值可能会有问题
  5951. return this.document.body.firstChild;
  5952. }
  5953. //control元素
  5954. if ( range.item ){
  5955. return range.item( 0 );
  5956. }
  5957. tmpRange = range.duplicate();
  5958. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  5959. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  5960. tmpRange.collapse( 1 );
  5961. start = tmpRange.parentElement();
  5962. parent = tmp = range.parentElement();
  5963. while ( tmp = tmp.parentNode ) {
  5964. if ( tmp == start ) {
  5965. start = parent;
  5966. break;
  5967. }
  5968. }
  5969. } else {
  5970. range.shrinkBoundary();
  5971. start = range.startContainer;
  5972. if ( start.nodeType == 1 && start.hasChildNodes() ){
  5973. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  5974. }
  5975. if ( start.nodeType == 3 ){
  5976. return start.parentNode;
  5977. }
  5978. }
  5979. return start;
  5980. },
  5981. /**
  5982. * 得到选区中的文本
  5983. * @method getText
  5984. * @return { String } 选区中包含的文本
  5985. * @example
  5986. * ```javascript
  5987. * editor.selection.getText();
  5988. * ```
  5989. */
  5990. getText:function () {
  5991. var nativeSel, nativeRange;
  5992. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  5993. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  5994. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  5995. }
  5996. return '';
  5997. },
  5998. /**
  5999. * 清除选区
  6000. * @method clearRange
  6001. * @example
  6002. * ```javascript
  6003. * editor.selection.clearRange();
  6004. * ```
  6005. */
  6006. clearRange : function(){
  6007. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6008. }
  6009. };
  6010. })();
  6011. /**
  6012. * 编辑器主类,包含编辑器提供的大部分公用接口
  6013. * @file
  6014. * @module UE
  6015. * @class Editor
  6016. * @since 1.2.6.1
  6017. */
  6018. /**
  6019. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6020. * @unfile
  6021. * @module UE
  6022. */
  6023. /**
  6024. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6025. * @unfile
  6026. * @module UE
  6027. * @class Editor
  6028. */
  6029. (function () {
  6030. var uid = 0, _selectionChangeTimer;
  6031. /**
  6032. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6033. * @private
  6034. * @method setValue
  6035. * @param { UE.Editor } editor 编辑器事例
  6036. */
  6037. function setValue(form, editor) {
  6038. var textarea;
  6039. if (editor.textarea) {
  6040. if (utils.isString(editor.textarea)) {
  6041. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6042. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6043. textarea = ti;
  6044. break;
  6045. }
  6046. }
  6047. } else {
  6048. textarea = editor.textarea;
  6049. }
  6050. }
  6051. if (!textarea) {
  6052. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6053. 'name': editor.options.textarea,
  6054. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6055. 'style': "display:none"
  6056. }));
  6057. //不要产生多个textarea
  6058. editor.textarea = textarea;
  6059. }
  6060. textarea.value = editor.hasContents() ?
  6061. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6062. ''
  6063. }
  6064. function loadPlugins(me){
  6065. //初始化插件
  6066. for (var pi in UE.plugins) {
  6067. UE.plugins[pi].call(me);
  6068. }
  6069. }
  6070. function checkCurLang(I18N){
  6071. for(var lang in I18N){
  6072. return lang
  6073. }
  6074. }
  6075. function langReadied(me){
  6076. me.langIsReady = true;
  6077. me.fireEvent("langReady");
  6078. }
  6079. /**
  6080. * 编辑器准备就绪后会触发该事件
  6081. * @module UE
  6082. * @class Editor
  6083. * @event ready
  6084. * @remind render方法执行完成之后,会触发该事件
  6085. * @remind
  6086. * @example
  6087. * ```javascript
  6088. * editor.addListener( 'ready', function( editor ) {
  6089. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6090. * } );
  6091. * ```
  6092. */
  6093. /**
  6094. * 执行destroy方法,会触发该事件
  6095. * @module UE
  6096. * @class Editor
  6097. * @event destroy
  6098. * @see UE.Editor:destroy()
  6099. */
  6100. /**
  6101. * 执行reset方法,会触发该事件
  6102. * @module UE
  6103. * @class Editor
  6104. * @event reset
  6105. * @see UE.Editor:reset()
  6106. */
  6107. /**
  6108. * 执行focus方法,会触发该事件
  6109. * @module UE
  6110. * @class Editor
  6111. * @event focus
  6112. * @see UE.Editor:focus(Boolean)
  6113. */
  6114. /**
  6115. * 语言加载完成会触发该事件
  6116. * @module UE
  6117. * @class Editor
  6118. * @event langReady
  6119. */
  6120. /**
  6121. * 运行命令之后会触发该命令
  6122. * @module UE
  6123. * @class Editor
  6124. * @event beforeExecCommand
  6125. */
  6126. /**
  6127. * 运行命令之后会触发该命令
  6128. * @module UE
  6129. * @class Editor
  6130. * @event afterExecCommand
  6131. */
  6132. /**
  6133. * 运行命令之前会触发该命令
  6134. * @module UE
  6135. * @class Editor
  6136. * @event firstBeforeExecCommand
  6137. */
  6138. /**
  6139. * 在getContent方法执行之前会触发该事件
  6140. * @module UE
  6141. * @class Editor
  6142. * @event beforeGetContent
  6143. * @see UE.Editor:getContent()
  6144. */
  6145. /**
  6146. * 在getContent方法执行之后会触发该事件
  6147. * @module UE
  6148. * @class Editor
  6149. * @event afterGetContent
  6150. * @see UE.Editor:getContent()
  6151. */
  6152. /**
  6153. * 在getAllHtml方法执行时会触发该事件
  6154. * @module UE
  6155. * @class Editor
  6156. * @event getAllHtml
  6157. * @see UE.Editor:getAllHtml()
  6158. */
  6159. /**
  6160. * 在setContent方法执行之前会触发该事件
  6161. * @module UE
  6162. * @class Editor
  6163. * @event beforeSetContent
  6164. * @see UE.Editor:setContent(String)
  6165. */
  6166. /**
  6167. * 在setContent方法执行之后会触发该事件
  6168. * @module UE
  6169. * @class Editor
  6170. * @event afterSetContent
  6171. * @see UE.Editor:setContent(String)
  6172. */
  6173. /**
  6174. * 每当编辑器内部选区发生改变时,将触发该事件
  6175. * @event selectionchange
  6176. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6177. * @example
  6178. * ```javascript
  6179. * editor.addListener( 'selectionchange', function( editor ) {
  6180. * console.log('选区发生改变');
  6181. * }
  6182. */
  6183. /**
  6184. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6185. * @module UE
  6186. * @class Editor
  6187. * @event beforeSelectionChange
  6188. * @see UE.Editor:selectionchange
  6189. */
  6190. /**
  6191. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6192. * @module UE
  6193. * @class Editor
  6194. * @event afterSelectionChange
  6195. * @see UE.Editor:selectionchange
  6196. */
  6197. /**
  6198. * 编辑器内容发生改变时会触发该事件
  6199. * @module UE
  6200. * @class Editor
  6201. * @event contentChange
  6202. */
  6203. /**
  6204. * 以默认参数构建一个编辑器实例
  6205. * @constructor
  6206. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6207. * @example
  6208. * ```javascript
  6209. * var editor = new UE.Editor();
  6210. * editor.execCommand('blod');
  6211. * ```
  6212. * @see UE.Config
  6213. */
  6214. /**
  6215. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6216. * @constructor
  6217. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6218. * @param { Object } setting 创建编辑器的参数
  6219. * @example
  6220. * ```javascript
  6221. * var editor = new UE.Editor();
  6222. * editor.execCommand('blod');
  6223. * ```
  6224. * @see UE.Config
  6225. */
  6226. var Editor = UE.Editor = function (options) {
  6227. var me = this;
  6228. me.uid = uid++;
  6229. EventBase.call(me);
  6230. me.commands = {};
  6231. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6232. me.shortcutkeys = {};
  6233. me.inputRules = [];
  6234. me.outputRules = [];
  6235. //设置默认的常用属性
  6236. me.setOpt({
  6237. isShow: true,
  6238. initialContent: '',
  6239. initialStyle:'',
  6240. autoClearinitialContent: false,
  6241. iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css',
  6242. textarea: 'editorValue',
  6243. focus: false,
  6244. focusInEnd: true,
  6245. autoClearEmptyNode: true,
  6246. fullscreen: false,
  6247. readonly: false,
  6248. zIndex: 999,
  6249. imagePopup: true,
  6250. enterTag: 'p',
  6251. customDomain: false,
  6252. lang: 'zh-cn',
  6253. langPath: me.options.UEDITOR_HOME_URL + 'lang/',
  6254. theme: 'default',
  6255. themePath: me.options.UEDITOR_HOME_URL + 'themes/',
  6256. allHtmlEnabled: false,
  6257. scaleEnabled: false,
  6258. tableNativeEditInFF: false,
  6259. autoSyncData : true,
  6260. fileNameFormat: '{time}{rand:6}'
  6261. });
  6262. if(!utils.isEmptyObject(UE.I18N)){
  6263. //修改默认的语言类型
  6264. me.options.lang = checkCurLang(UE.I18N);
  6265. UE.plugin.load(me);
  6266. langReadied(me);
  6267. }else{
  6268. utils.loadFile(document, {
  6269. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6270. tag: "script",
  6271. type: "text/javascript",
  6272. defer: "defer"
  6273. }, function () {
  6274. UE.plugin.load(me);
  6275. langReadied(me);
  6276. });
  6277. }
  6278. UE.instants['ueditorInstant' + me.uid] = me;
  6279. };
  6280. Editor.prototype = {
  6281. /**
  6282. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6283. * @method ready
  6284. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6285. * 立即触发该回调。
  6286. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6287. * @example
  6288. * ```javascript
  6289. * editor.ready( function( editor ) {
  6290. * editor.setContent('初始化完毕');
  6291. * } );
  6292. * ```
  6293. * @see UE.Editor.event:ready
  6294. */
  6295. ready: function (fn) {
  6296. var me = this;
  6297. if (fn) {
  6298. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6299. }
  6300. },
  6301. /**
  6302. * 该方法是提供给插件里面使用,设置配置项默认值
  6303. * @method setOpt
  6304. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6305. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6306. * @param { String } key 编辑器的可接受的选项名称
  6307. * @param { * } val 该选项可接受的值
  6308. * @example
  6309. * ```javascript
  6310. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6311. * ```
  6312. */
  6313. /**
  6314. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6315. * @method setOpt
  6316. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6317. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6318. * @param { Object } options 将要设置的选项的键值对对象
  6319. * @example
  6320. * ```javascript
  6321. * editor.setOpt( {
  6322. * 'initContent': '欢迎使用编辑器'
  6323. * } );
  6324. * ```
  6325. */
  6326. setOpt: function (key, val) {
  6327. var obj = {};
  6328. if (utils.isString(key)) {
  6329. obj[key] = val
  6330. } else {
  6331. obj = key;
  6332. }
  6333. utils.extend(this.options, obj, true);
  6334. },
  6335. /**
  6336. * 销毁编辑器实例,使用textarea代替
  6337. * @method destroy
  6338. * @example
  6339. * ```javascript
  6340. * editor.destroy();
  6341. * ```
  6342. */
  6343. destroy: function () {
  6344. var me = this;
  6345. me.fireEvent('destroy');
  6346. var container = me.container.parentNode;
  6347. var textarea = me.textarea;
  6348. if (!textarea) {
  6349. textarea = document.createElement('textarea');
  6350. container.parentNode.insertBefore(textarea, container);
  6351. } else {
  6352. textarea.style.display = ''
  6353. }
  6354. textarea.style.width = me.iframe.offsetWidth + 'px';
  6355. textarea.style.height = me.iframe.offsetHeight + 'px';
  6356. textarea.value = me.getContent();
  6357. textarea.id = me.key;
  6358. container.innerHTML = '';
  6359. domUtils.remove(container);
  6360. var key = me.key;
  6361. //trace:2004
  6362. for (var p in me) {
  6363. if (me.hasOwnProperty(p)) {
  6364. delete this[p];
  6365. }
  6366. }
  6367. UE.delEditor(key);
  6368. },
  6369. /**
  6370. * 渲染编辑器的DOM到指定容器
  6371. * @method render
  6372. * @param { String } containerId 指定一个容器ID
  6373. * @remind 执行该方法,会触发ready事件
  6374. * @warning 必须且只能调用一次
  6375. */
  6376. /**
  6377. * 渲染编辑器的DOM到指定容器
  6378. * @method render
  6379. * @param { Element } containerDom 直接指定容器对象
  6380. * @remind 执行该方法,会触发ready事件
  6381. * @warning 必须且只能调用一次
  6382. */
  6383. render: function (container) {
  6384. var me = this,
  6385. options = me.options,
  6386. getStyleValue=function(attr){
  6387. return parseInt(domUtils.getComputedStyle(container,attr));
  6388. };
  6389. if (utils.isString(container)) {
  6390. container = document.getElementById(container);
  6391. }
  6392. if (container) {
  6393. if(options.initialFrameWidth){
  6394. options.minFrameWidth = options.initialFrameWidth
  6395. }else{
  6396. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6397. }
  6398. if(options.initialFrameHeight){
  6399. options.minFrameHeight = options.initialFrameHeight
  6400. }else{
  6401. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6402. }
  6403. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6404. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6405. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6406. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6407. container.style.zIndex = options.zIndex;
  6408. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6409. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6410. '<style type=\'text/css\'>' +
  6411. //设置四周的留边
  6412. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6413. //设置默认字体和字号
  6414. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6415. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6416. //设置段落间距
  6417. 'p{margin:5px 0;}</style>' +
  6418. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6419. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6420. '</head><body class=\'view\' ></body>' +
  6421. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6422. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6423. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6424. container.appendChild(domUtils.createElement(document, 'iframe', {
  6425. id: 'ueditor_' + me.uid,
  6426. width: "100%",
  6427. height: "100%",
  6428. frameborder: "0",
  6429. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6430. // scrolling :'no',
  6431. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6432. 'document.write("' + html + '");document.close();}())'
  6433. }));
  6434. container.style.overflow = 'hidden';
  6435. //解决如果是给定的百分比,会导致高度算不对的问题
  6436. setTimeout(function(){
  6437. if( /%$/.test(options.initialFrameWidth)){
  6438. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6439. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6440. // container.style.width = options.initialFrameWidth + 'px';
  6441. }
  6442. if(/%$/.test(options.initialFrameHeight)){
  6443. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6444. container.style.height = options.initialFrameHeight + 'px';
  6445. }
  6446. })
  6447. }
  6448. },
  6449. /**
  6450. * 编辑器初始化
  6451. * @method _setup
  6452. * @private
  6453. * @param { Element } doc 编辑器Iframe中的文档对象
  6454. */
  6455. _setup: function (doc) {
  6456. var me = this,
  6457. options = me.options;
  6458. if (ie) {
  6459. doc.body.disabled = true;
  6460. doc.body.contentEditable = true;
  6461. doc.body.disabled = false;
  6462. } else {
  6463. doc.body.contentEditable = true;
  6464. }
  6465. doc.body.spellcheck = false;
  6466. me.document = doc;
  6467. me.window = doc.defaultView || doc.parentWindow;
  6468. me.iframe = me.window.frameElement;
  6469. me.body = doc.body;
  6470. me.selection = new dom.Selection(doc);
  6471. //gecko初始化就能得到range,无法判断isFocus了
  6472. var geckoSel;
  6473. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6474. geckoSel.removeAllRanges();
  6475. }
  6476. this._initEvents();
  6477. //为form提交提供一个隐藏的textarea
  6478. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6479. if (form.tagName == 'FORM') {
  6480. me.form = form;
  6481. if(me.options.autoSyncData){
  6482. domUtils.on(me.window,'blur',function(){
  6483. setValue(form,me);
  6484. });
  6485. }else{
  6486. domUtils.on(form, 'submit', function () {
  6487. setValue(this, me);
  6488. });
  6489. }
  6490. break;
  6491. }
  6492. }
  6493. if (options.initialContent) {
  6494. if (options.autoClearinitialContent) {
  6495. var oldExecCommand = me.execCommand;
  6496. me.execCommand = function () {
  6497. me.fireEvent('firstBeforeExecCommand');
  6498. return oldExecCommand.apply(me, arguments);
  6499. };
  6500. this._setDefaultContent(options.initialContent);
  6501. } else
  6502. this.setContent(options.initialContent, false, true);
  6503. }
  6504. //编辑器不能为空内容
  6505. if (domUtils.isEmptyNode(me.body)) {
  6506. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6507. }
  6508. //如果要求focus, 就把光标定位到内容开始
  6509. if (options.focus) {
  6510. setTimeout(function () {
  6511. me.focus(me.options.focusInEnd);
  6512. //如果自动清除开着,就不需要做selectionchange;
  6513. !me.options.autoClearinitialContent && me._selectionChange();
  6514. }, 0);
  6515. }
  6516. if (!me.container) {
  6517. me.container = this.iframe.parentNode;
  6518. }
  6519. if (options.fullscreen && me.ui) {
  6520. me.ui.setFullScreen(true);
  6521. }
  6522. try {
  6523. me.document.execCommand('2D-position', false, false);
  6524. } catch (e) {
  6525. }
  6526. try {
  6527. me.document.execCommand('enableInlineTableEditing', false, false);
  6528. } catch (e) {
  6529. }
  6530. try {
  6531. me.document.execCommand('enableObjectResizing', false, false);
  6532. } catch (e) {
  6533. }
  6534. //挂接快捷键
  6535. me._bindshortcutKeys();
  6536. me.isReady = 1;
  6537. me.fireEvent('ready');
  6538. options.onready && options.onready.call(me);
  6539. if (!browser.ie9below) {
  6540. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6541. //chrome下会出现alt+tab切换时,导致选区位置不对
  6542. if (e.type == 'blur') {
  6543. me._bakRange = me.selection.getRange();
  6544. try {
  6545. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6546. me.selection.getNative().removeAllRanges();
  6547. } catch (e) {
  6548. me._bakNativeRange = null;
  6549. }
  6550. } else {
  6551. try {
  6552. me._bakRange && me._bakRange.select();
  6553. } catch (e) {
  6554. }
  6555. }
  6556. });
  6557. }
  6558. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6559. if (browser.gecko && browser.version <= 10902) {
  6560. //修复ff3.6初始化进来,不能点击获得焦点
  6561. me.body.contentEditable = false;
  6562. setTimeout(function () {
  6563. me.body.contentEditable = true;
  6564. }, 100);
  6565. setInterval(function () {
  6566. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6567. }, 100)
  6568. }
  6569. !options.isShow && me.setHide();
  6570. options.readonly && me.setDisabled();
  6571. },
  6572. /**
  6573. * 同步数据到编辑器所在的form
  6574. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6575. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6576. * @method sync
  6577. * @example
  6578. * ```javascript
  6579. * editor.sync();
  6580. * form.sumbit(); //form变量已经指向了form元素
  6581. * ```
  6582. */
  6583. /**
  6584. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6585. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6586. * @method sync
  6587. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6588. */
  6589. sync: function (formId) {
  6590. var me = this,
  6591. form = formId ? document.getElementById(formId) :
  6592. domUtils.findParent(me.iframe.parentNode, function (node) {
  6593. return node.tagName == 'FORM'
  6594. }, true);
  6595. form && setValue(form, me);
  6596. },
  6597. /**
  6598. * 设置编辑器高度
  6599. * @method setHeight
  6600. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6601. * @param { Number } number 设置的高度值,纯数值,不带单位
  6602. * @example
  6603. * ```javascript
  6604. * editor.setHeight(number);
  6605. * ```
  6606. */
  6607. setHeight: function (height,notSetHeight) {
  6608. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6609. this.iframe.parentNode.style.height = height + 'px';
  6610. }
  6611. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6612. this.body.style.height = height + 'px';
  6613. },
  6614. /**
  6615. * 为编辑器的编辑命令提供快捷键
  6616. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6617. * @method addshortcutkey
  6618. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6619. * @example
  6620. * ```javascript
  6621. * editor.addshortcutkey({
  6622. * "Bold" : "ctrl+66",//^B
  6623. * "Italic" : "ctrl+73", //^I
  6624. * });
  6625. * ```
  6626. */
  6627. /**
  6628. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6629. * @method addshortcutkey
  6630. * @param { String } cmd 触发快捷键时,响应的命令
  6631. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6632. * @example
  6633. * ```javascript
  6634. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6635. * ```
  6636. */
  6637. addshortcutkey: function (cmd, keys) {
  6638. var obj = {};
  6639. if (keys) {
  6640. obj[cmd] = keys
  6641. } else {
  6642. obj = cmd;
  6643. }
  6644. utils.extend(this.shortcutkeys, obj)
  6645. },
  6646. /**
  6647. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6648. * @method _bindshortcutKeys
  6649. * @private
  6650. */
  6651. _bindshortcutKeys: function () {
  6652. var me = this, shortcutkeys = this.shortcutkeys;
  6653. me.addListener('keydown', function (type, e) {
  6654. var keyCode = e.keyCode || e.which;
  6655. for (var i in shortcutkeys) {
  6656. var tmp = shortcutkeys[i].split(',');
  6657. for (var t = 0, ti; ti = tmp[t++];) {
  6658. ti = ti.split(':');
  6659. var key = ti[0], param = ti[1];
  6660. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6661. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6662. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6663. && keyCode == RegExp.$3
  6664. ) ||
  6665. keyCode == RegExp.$1
  6666. ) {
  6667. if (me.queryCommandState(i,param) != -1)
  6668. me.execCommand(i, param);
  6669. domUtils.preventDefault(e);
  6670. }
  6671. }
  6672. }
  6673. }
  6674. });
  6675. },
  6676. /**
  6677. * 获取编辑器的内容
  6678. * @method getContent
  6679. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6680. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6681. * @example
  6682. * ```javascript
  6683. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6684. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6685. * ```
  6686. */
  6687. /**
  6688. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6689. * @method getContent
  6690. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6691. * 代表当前编辑器的内容是否空,
  6692. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6693. * 经过内置过滤规则处理后的内容。
  6694. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6695. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6696. * @return { String } 编辑器的内容字符串
  6697. * @example
  6698. * ```javascript
  6699. * // editor 是一个编辑器的实例
  6700. * var content = editor.getContent( function ( editor ) {
  6701. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6702. * } );
  6703. * ```
  6704. */
  6705. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6706. var me = this;
  6707. if (cmd && utils.isFunction(cmd)) {
  6708. fn = cmd;
  6709. cmd = '';
  6710. }
  6711. if (fn ? !fn() : !this.hasContents()) {
  6712. return '';
  6713. }
  6714. me.fireEvent('beforegetcontent');
  6715. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6716. me.filterOutputRule(root);
  6717. me.fireEvent('aftergetcontent', cmd,root);
  6718. return root.toHtml(formatter);
  6719. },
  6720. /**
  6721. * 取得完整的html代码,可以直接显示成完整的html文档
  6722. * @method getAllHtml
  6723. * @return { String } 编辑器的内容html文档字符串
  6724. * @eaxmple
  6725. * ```javascript
  6726. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6727. * ```
  6728. */
  6729. getAllHtml: function () {
  6730. var me = this,
  6731. headHtml = [],
  6732. html = '';
  6733. me.fireEvent('getAllHtml', headHtml);
  6734. if (browser.ie && browser.version > 8) {
  6735. var headHtmlForIE9 = '';
  6736. utils.each(me.document.styleSheets, function (si) {
  6737. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6738. });
  6739. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6740. headHtmlForIE9 += si.outerHTML;
  6741. });
  6742. }
  6743. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6744. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6745. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6746. },
  6747. /**
  6748. * 得到编辑器的纯文本内容,但会保留段落格式
  6749. * @method getPlainTxt
  6750. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6751. * @example
  6752. * ```javascript
  6753. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6754. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6755. * ```
  6756. */
  6757. getPlainTxt: function () {
  6758. var reg = new RegExp(domUtils.fillChar, 'g'),
  6759. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6760. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6761. .replace(/<br\/?>/gi, '\n')
  6762. .replace(/<[^>/]+>/g, '')
  6763. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6764. return dtd.$block[c] ? '\n' : b ? b : '';
  6765. });
  6766. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6767. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6768. },
  6769. /**
  6770. * 获取编辑器中的纯文本内容,没有段落格式
  6771. * @method getContentTxt
  6772. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6773. * @example
  6774. * ```javascript
  6775. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6776. * console.log(editor.getPlainTxt()); //输出:"12
  6777. * ```
  6778. */
  6779. getContentTxt: function () {
  6780. var reg = new RegExp(domUtils.fillChar, 'g');
  6781. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6782. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6783. },
  6784. /**
  6785. * 设置编辑器的内容,可修改编辑器当前的html内容
  6786. * @method setContent
  6787. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6788. * @warning 该方法会触发selectionchange事件
  6789. * @param { String } html 要插入的html内容
  6790. * @example
  6791. * ```javascript
  6792. * editor.getContent('<p>test</p>');
  6793. * ```
  6794. */
  6795. /**
  6796. * 设置编辑器的内容,可修改编辑器当前的html内容
  6797. * @method setContent
  6798. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6799. * @warning 该方法会触发selectionchange事件
  6800. * @param { String } html 要插入的html内容
  6801. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6802. * @example
  6803. * ```javascript
  6804. * //假设设置前的编辑器内容是 <p>old text</p>
  6805. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6806. * ```
  6807. */
  6808. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6809. var me = this;
  6810. me.fireEvent('beforesetcontent', html);
  6811. var root = UE.htmlparser(html);
  6812. me.filterInputRule(root);
  6813. html = root.toHtml();
  6814. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6815. function isCdataDiv(node){
  6816. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6817. }
  6818. //给文本或者inline节点套p标签
  6819. if (me.options.enterTag == 'p') {
  6820. var child = this.body.firstChild, tmpNode;
  6821. if (!child || child.nodeType == 1 &&
  6822. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  6823. domUtils.isCustomeNode(child)
  6824. )
  6825. && child === this.body.lastChild) {
  6826. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  6827. } else {
  6828. var p = me.document.createElement('p');
  6829. while (child) {
  6830. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  6831. tmpNode = child.nextSibling;
  6832. p.appendChild(child);
  6833. child = tmpNode;
  6834. }
  6835. if (p.firstChild) {
  6836. if (!child) {
  6837. me.body.appendChild(p);
  6838. break;
  6839. } else {
  6840. child.parentNode.insertBefore(p, child);
  6841. p = me.document.createElement('p');
  6842. }
  6843. }
  6844. child = child.nextSibling;
  6845. }
  6846. }
  6847. }
  6848. me.fireEvent('aftersetcontent');
  6849. me.fireEvent('contentchange');
  6850. !notFireSelectionchange && me._selectionChange();
  6851. //清除保存的选区
  6852. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  6853. //trace:1742 setContent后gecko能得到焦点问题
  6854. var geckoSel;
  6855. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6856. geckoSel.removeAllRanges();
  6857. }
  6858. if(me.options.autoSyncData){
  6859. me.form && setValue(me.form,me);
  6860. }
  6861. },
  6862. /**
  6863. * 让编辑器获得焦点,默认focus到编辑器头部
  6864. * @method focus
  6865. * @example
  6866. * ```javascript
  6867. * editor.focus()
  6868. * ```
  6869. */
  6870. /**
  6871. * 让编辑器获得焦点,toEnd确定focus位置
  6872. * @method focus
  6873. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  6874. * @example
  6875. * ```javascript
  6876. * editor.focus(true)
  6877. * ```
  6878. */
  6879. focus: function (toEnd) {
  6880. try {
  6881. var me = this,
  6882. rng = me.selection.getRange();
  6883. if (toEnd) {
  6884. var node = me.body.lastChild;
  6885. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  6886. if(domUtils.isEmptyBlock(node)){
  6887. rng.setStartAtFirst(node)
  6888. }else{
  6889. rng.setStartAtLast(node)
  6890. }
  6891. rng.collapse(true);
  6892. }
  6893. rng.setCursor(true);
  6894. } else {
  6895. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  6896. var node = me.body.firstChild;
  6897. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  6898. rng.setStartAtFirst(node).collapse(true);
  6899. }
  6900. }
  6901. rng.select(true);
  6902. }
  6903. this.fireEvent('focus selectionchange');
  6904. } catch (e) {
  6905. }
  6906. },
  6907. isFocus:function(){
  6908. return this.selection.isFocus();
  6909. },
  6910. blur:function(){
  6911. var sel = this.selection.getNative();
  6912. if(sel.empty && browser.ie){
  6913. var nativeRng = document.body.createTextRange();
  6914. nativeRng.moveToElementText(document.body);
  6915. nativeRng.collapse(true);
  6916. nativeRng.select();
  6917. sel.empty()
  6918. }else{
  6919. sel.removeAllRanges()
  6920. }
  6921. //this.fireEvent('blur selectionchange');
  6922. },
  6923. /**
  6924. * 初始化UE事件及部分事件代理
  6925. * @method _initEvents
  6926. * @private
  6927. */
  6928. _initEvents: function () {
  6929. var me = this,
  6930. doc = me.document,
  6931. win = me.window;
  6932. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  6933. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  6934. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  6935. domUtils.on(me.body,'drop',function(e){
  6936. //阻止ff下默认的弹出新页面打开图片
  6937. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  6938. me.fireEvent('contentchange')
  6939. });
  6940. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  6941. //特殊键不触发selectionchange
  6942. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  6943. return;
  6944. }
  6945. if (evt.button == 2)return;
  6946. me._selectionChange(250, evt);
  6947. });
  6948. },
  6949. /**
  6950. * 触发事件代理
  6951. * @method _proxyDomEvent
  6952. * @private
  6953. * @return { * } fireEvent的返回值
  6954. * @see UE.EventBase:fireEvent(String)
  6955. */
  6956. _proxyDomEvent: function (evt) {
  6957. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  6958. return false;
  6959. }
  6960. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  6961. return false;
  6962. }
  6963. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  6964. },
  6965. /**
  6966. * 变化选区
  6967. * @method _selectionChange
  6968. * @private
  6969. */
  6970. _selectionChange: function (delay, evt) {
  6971. var me = this;
  6972. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  6973. // if ( !me.selection.isFocus() ){
  6974. // return;
  6975. // }
  6976. var hackForMouseUp = false;
  6977. var mouseX, mouseY;
  6978. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  6979. var range = this.selection.getRange();
  6980. if (!range.collapsed) {
  6981. hackForMouseUp = true;
  6982. mouseX = evt.clientX;
  6983. mouseY = evt.clientY;
  6984. }
  6985. }
  6986. clearTimeout(_selectionChangeTimer);
  6987. _selectionChangeTimer = setTimeout(function () {
  6988. if (!me.selection || !me.selection.getNative()) {
  6989. return;
  6990. }
  6991. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  6992. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  6993. var ieRange;
  6994. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  6995. ieRange = me.document.body.createTextRange();
  6996. try {
  6997. ieRange.moveToPoint(mouseX, mouseY);
  6998. } catch (ex) {
  6999. ieRange = null;
  7000. }
  7001. }
  7002. var bakGetIERange;
  7003. if (ieRange) {
  7004. bakGetIERange = me.selection.getIERange;
  7005. me.selection.getIERange = function () {
  7006. return ieRange;
  7007. };
  7008. }
  7009. me.selection.cache();
  7010. if (bakGetIERange) {
  7011. me.selection.getIERange = bakGetIERange;
  7012. }
  7013. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7014. me.fireEvent('beforeselectionchange');
  7015. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7016. me.fireEvent('selectionchange', !!evt);
  7017. me.fireEvent('afterselectionchange');
  7018. me.selection.clear();
  7019. }
  7020. }, delay || 50);
  7021. },
  7022. /**
  7023. * 执行编辑命令
  7024. * @method _callCmdFn
  7025. * @private
  7026. * @param { String } fnName 函数名称
  7027. * @param { * } args 传给命令函数的参数
  7028. * @return { * } 返回命令函数运行的返回值
  7029. */
  7030. _callCmdFn: function (fnName, args) {
  7031. var cmdName = args[0].toLowerCase(),
  7032. cmd, cmdFn;
  7033. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7034. cmdFn = cmd && cmd[fnName];
  7035. //没有querycommandstate或者没有command的都默认返回0
  7036. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7037. return 0;
  7038. } else if (cmdFn) {
  7039. return cmdFn.apply(this, args);
  7040. }
  7041. },
  7042. /**
  7043. * 执行编辑命令cmdName,完成富文本编辑效果
  7044. * @method execCommand
  7045. * @param { String } cmdName 需要执行的命令
  7046. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7047. * @return { * } 返回命令函数运行的返回值
  7048. * @example
  7049. * ```javascript
  7050. * editor.execCommand(cmdName);
  7051. * ```
  7052. */
  7053. execCommand: function (cmdName) {
  7054. cmdName = cmdName.toLowerCase();
  7055. var me = this,
  7056. result,
  7057. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7058. if (!cmd || !cmd.execCommand) {
  7059. return null;
  7060. }
  7061. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7062. me.__hasEnterExecCommand = true;
  7063. if (me.queryCommandState.apply(me,arguments) != -1) {
  7064. me.fireEvent('saveScene');
  7065. me.fireEvent('beforeexeccommand', cmdName);
  7066. result = this._callCmdFn('execCommand', arguments);
  7067. (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7068. me.fireEvent('afterexeccommand', cmdName);
  7069. me.fireEvent('saveScene');
  7070. }
  7071. me.__hasEnterExecCommand = false;
  7072. } else {
  7073. result = this._callCmdFn('execCommand', arguments);
  7074. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7075. }
  7076. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7077. return result;
  7078. },
  7079. /**
  7080. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7081. * @method queryCommandState
  7082. * @param { String } cmdName 需要查询的命令名称
  7083. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7084. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7085. * @example
  7086. * ```javascript
  7087. * editor.queryCommandState(cmdName) => (-1|0|1)
  7088. * ```
  7089. * @see COMMAND.LIST
  7090. */
  7091. queryCommandState: function (cmdName) {
  7092. return this._callCmdFn('queryCommandState', arguments);
  7093. },
  7094. /**
  7095. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7096. * @method queryCommandValue
  7097. * @param { String } cmdName 需要查询的命令名称
  7098. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7099. * @remind 只有部分插件有此方法
  7100. * @return { * } 返回每个命令特定的当前状态值
  7101. * @grammar editor.queryCommandValue(cmdName) => {*}
  7102. * @see COMMAND.LIST
  7103. */
  7104. queryCommandValue: function (cmdName) {
  7105. return this._callCmdFn('queryCommandValue', arguments);
  7106. },
  7107. /**
  7108. * 检查编辑区域中是否有内容
  7109. * @method hasContents
  7110. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7111. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7112. * @return { Boolean } 检查有内容返回true,否则返回false
  7113. * @example
  7114. * ```javascript
  7115. * editor.hasContents()
  7116. * ```
  7117. */
  7118. /**
  7119. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7120. * @method hasContents
  7121. * @param { Array } tags 传入数组判断时用到的节点类型
  7122. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7123. * @example
  7124. * ```javascript
  7125. * editor.hasContents(['span']);
  7126. * ```
  7127. */
  7128. hasContents: function (tags) {
  7129. if (tags) {
  7130. for (var i = 0, ci; ci = tags[i++];) {
  7131. if (this.document.getElementsByTagName(ci).length > 0) {
  7132. return true;
  7133. }
  7134. }
  7135. }
  7136. if (!domUtils.isEmptyBlock(this.body)) {
  7137. return true
  7138. }
  7139. //随时添加,定义的特殊标签如果存在,不能认为是空
  7140. tags = ['div'];
  7141. for (i = 0; ci = tags[i++];) {
  7142. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7143. for (var n = 0, cn; cn = nodes[n++];) {
  7144. if (domUtils.isCustomeNode(cn)) {
  7145. return true;
  7146. }
  7147. }
  7148. }
  7149. return false;
  7150. },
  7151. /**
  7152. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7153. * @method reset
  7154. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7155. * @example
  7156. * ```javascript
  7157. * editor.reset()
  7158. * ```
  7159. */
  7160. reset: function () {
  7161. this.fireEvent('reset');
  7162. },
  7163. /**
  7164. * 设置当前编辑区域可以编辑
  7165. * @method setEnabled
  7166. * @example
  7167. * ```javascript
  7168. * editor.setEnabled()
  7169. * ```
  7170. */
  7171. setEnabled: function () {
  7172. var me = this, range;
  7173. if (me.body.contentEditable == 'false') {
  7174. me.body.contentEditable = true;
  7175. range = me.selection.getRange();
  7176. //有可能内容丢失了
  7177. try {
  7178. range.moveToBookmark(me.lastBk);
  7179. delete me.lastBk
  7180. } catch (e) {
  7181. range.setStartAtFirst(me.body).collapse(true)
  7182. }
  7183. range.select(true);
  7184. if (me.bkqueryCommandState) {
  7185. me.queryCommandState = me.bkqueryCommandState;
  7186. delete me.bkqueryCommandState;
  7187. }
  7188. me.fireEvent('selectionchange');
  7189. }
  7190. },
  7191. enable: function () {
  7192. return this.setEnabled();
  7193. },
  7194. /** 设置当前编辑区域不可编辑
  7195. * @method setDisabled
  7196. */
  7197. /** 设置当前编辑区域不可编辑,except中的命令除外
  7198. * @method setDisabled
  7199. * @param { String } except 例外命令的字符串
  7200. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7201. * @example
  7202. * ```javascript
  7203. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7204. * ```
  7205. */
  7206. /** 设置当前编辑区域不可编辑,except中的命令除外
  7207. * @method setDisabled
  7208. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7209. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7210. * @example
  7211. * ```javascript
  7212. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7213. * ```
  7214. */
  7215. setDisabled: function (except) {
  7216. var me = this;
  7217. except = except ? utils.isArray(except) ? except : [except] : [];
  7218. if (me.body.contentEditable == 'true') {
  7219. if (!me.lastBk) {
  7220. me.lastBk = me.selection.getRange().createBookmark(true);
  7221. }
  7222. me.body.contentEditable = false;
  7223. me.bkqueryCommandState = me.queryCommandState;
  7224. me.queryCommandState = function (type) {
  7225. if (utils.indexOf(except, type) != -1) {
  7226. return me.bkqueryCommandState.apply(me, arguments);
  7227. }
  7228. return -1;
  7229. };
  7230. me.fireEvent('selectionchange');
  7231. }
  7232. },
  7233. disable: function (except) {
  7234. return this.setDisabled(except);
  7235. },
  7236. /**
  7237. * 设置默认内容
  7238. * @method _setDefaultContent
  7239. * @private
  7240. * @param { String } cont 要存入的内容
  7241. */
  7242. _setDefaultContent: function () {
  7243. function clear() {
  7244. var me = this;
  7245. if (me.document.getElementById('initContent')) {
  7246. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7247. me.removeListener('firstBeforeExecCommand focus', clear);
  7248. setTimeout(function () {
  7249. me.focus();
  7250. me._selectionChange();
  7251. }, 0)
  7252. }
  7253. }
  7254. return function (cont) {
  7255. var me = this;
  7256. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7257. me.addListener('firstBeforeExecCommand focus', clear);
  7258. }
  7259. }(),
  7260. /**
  7261. * 显示编辑器
  7262. * @method setShow
  7263. * @example
  7264. * ```javascript
  7265. * editor.setShow()
  7266. * ```
  7267. */
  7268. setShow: function () {
  7269. var me = this, range = me.selection.getRange();
  7270. if (me.container.style.display == 'none') {
  7271. //有可能内容丢失了
  7272. try {
  7273. range.moveToBookmark(me.lastBk);
  7274. delete me.lastBk
  7275. } catch (e) {
  7276. range.setStartAtFirst(me.body).collapse(true)
  7277. }
  7278. //ie下focus实效,所以做了个延迟
  7279. setTimeout(function () {
  7280. range.select(true);
  7281. }, 100);
  7282. me.container.style.display = '';
  7283. }
  7284. },
  7285. show: function () {
  7286. return this.setShow();
  7287. },
  7288. /**
  7289. * 隐藏编辑器
  7290. * @method setHide
  7291. * @example
  7292. * ```javascript
  7293. * editor.setHide()
  7294. * ```
  7295. */
  7296. setHide: function () {
  7297. var me = this;
  7298. if (!me.lastBk) {
  7299. me.lastBk = me.selection.getRange().createBookmark(true);
  7300. }
  7301. me.container.style.display = 'none'
  7302. },
  7303. hide: function () {
  7304. return this.setHide();
  7305. },
  7306. /**
  7307. * 根据指定的路径,获取对应的语言资源
  7308. * @method getLang
  7309. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7310. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7311. * @example
  7312. * ```javascript
  7313. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7314. * ```
  7315. */
  7316. getLang: function (path) {
  7317. var lang = UE.I18N[this.options.lang];
  7318. if (!lang) {
  7319. throw Error("not import language file");
  7320. }
  7321. path = (path || "").split(".");
  7322. for (var i = 0, ci; ci = path[i++];) {
  7323. lang = lang[ci];
  7324. if (!lang)break;
  7325. }
  7326. return lang;
  7327. },
  7328. /**
  7329. * 计算编辑器html内容字符串的长度
  7330. * @method getContentLength
  7331. * @return { Number } 返回计算的长度
  7332. * @example
  7333. * ```javascript
  7334. * //编辑器html内容<p><strong>132</strong></p>
  7335. * editor.getContentLength() //返回27
  7336. * ```
  7337. */
  7338. /**
  7339. * 计算编辑器当前纯文本内容的长度
  7340. * @method getContentLength
  7341. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7342. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7343. * @example
  7344. * ```javascript
  7345. * //编辑器html内容<p><strong>132</strong></p>
  7346. * editor.getContentLength() //返回3
  7347. * ```
  7348. */
  7349. getContentLength: function (ingoneHtml, tagNames) {
  7350. var count = this.getContent(false,false,true).length;
  7351. if (ingoneHtml) {
  7352. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7353. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7354. for (var i = 0, ci; ci = tagNames[i++];) {
  7355. count += this.document.getElementsByTagName(ci).length;
  7356. }
  7357. }
  7358. return count;
  7359. },
  7360. /**
  7361. * 注册输入过滤规则
  7362. * @method addInputRule
  7363. * @param { Function } rule 要添加的过滤规则
  7364. * @example
  7365. * ```javascript
  7366. * editor.addInputRule(function(root){
  7367. * $.each(root.getNodesByTagName('div'),function(i,node){
  7368. * node.tagName="p";
  7369. * });
  7370. * });
  7371. * ```
  7372. */
  7373. addInputRule: function (rule) {
  7374. this.inputRules.push(rule);
  7375. },
  7376. /**
  7377. * 执行注册的过滤规则
  7378. * @method filterInputRule
  7379. * @param { UE.uNode } root 要过滤的uNode节点
  7380. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7381. * @example
  7382. * ```javascript
  7383. * editor.filterInputRule(editor.body);
  7384. * ```
  7385. * @see UE.Editor:addInputRule
  7386. */
  7387. filterInputRule: function (root) {
  7388. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7389. ci.call(this, root)
  7390. }
  7391. },
  7392. /**
  7393. * 注册输出过滤规则
  7394. * @method addOutputRule
  7395. * @param { Function } rule 要添加的过滤规则
  7396. * @example
  7397. * ```javascript
  7398. * editor.addOutputRule(function(root){
  7399. * $.each(root.getNodesByTagName('p'),function(i,node){
  7400. * node.tagName="div";
  7401. * });
  7402. * });
  7403. * ```
  7404. */
  7405. addOutputRule: function (rule) {
  7406. this.outputRules.push(rule)
  7407. },
  7408. /**
  7409. * 根据输出过滤规则,过滤编辑器内容
  7410. * @method filterOutputRule
  7411. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7412. * @param { UE.uNode } root 要过滤的uNode节点
  7413. * @example
  7414. * ```javascript
  7415. * editor.filterOutputRule(editor.body);
  7416. * ```
  7417. * @see UE.Editor:addOutputRule
  7418. */
  7419. filterOutputRule: function (root) {
  7420. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7421. ci.call(this, root)
  7422. }
  7423. }
  7424. };
  7425. utils.inherits(Editor, EventBase);
  7426. })();
  7427. /**
  7428. * @file
  7429. * @module UE.ajax
  7430. * @since 1.2.6.1
  7431. */
  7432. /**
  7433. * 提供对ajax请求的支持
  7434. * @module UE.ajax
  7435. */
  7436. UE.ajax = function() {
  7437. //创建一个ajaxRequest对象
  7438. var fnStr = 'XMLHttpRequest()';
  7439. try {
  7440. new ActiveXObject("Msxml2.XMLHTTP");
  7441. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7442. } catch (e) {
  7443. try {
  7444. new ActiveXObject("Microsoft.XMLHTTP");
  7445. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7446. } catch (e) {
  7447. }
  7448. }
  7449. var creatAjaxRequest = new Function('return new ' + fnStr);
  7450. /*
  7451. * 将json参数转化成适合ajax提交的参数列表
  7452. * @param json
  7453. */
  7454. function json2str(json) {
  7455. var strArr = [];
  7456. for (var i in json) {
  7457. //忽略默认的几个参数
  7458. if(i=="method" || i=="timeout" || i=="async") continue;
  7459. //传递过来的对象和函数不在提交之列
  7460. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7461. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7462. }
  7463. }
  7464. return strArr.join("&");
  7465. }
  7466. return {
  7467. /**
  7468. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7469. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7470. * @method request
  7471. * @param { URLString } url ajax请求的url地址
  7472. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7473. * @example
  7474. * ```javascript
  7475. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7476. * UE.ajax.requeset( 'sayhello.php', {
  7477. *
  7478. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7479. * method: 'GET',
  7480. *
  7481. * //超时时间。 默认为5000, 单位是ms
  7482. * timeout: 10000,
  7483. *
  7484. * //是否是异步请求。 true为异步请求, false为同步请求
  7485. * async: true,
  7486. *
  7487. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7488. * data: {
  7489. * name: 'ueditor'
  7490. * },
  7491. *
  7492. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7493. * onsuccess: function ( xhr ) {
  7494. * console.log( xhr.responseText );
  7495. * },
  7496. *
  7497. * //请求失败或者超时后的回调。
  7498. * onerror: function ( xhr ) {
  7499. * alert( 'Ajax请求失败' );
  7500. * }
  7501. *
  7502. * } );
  7503. * ```
  7504. */
  7505. /**
  7506. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7507. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7508. * @method request
  7509. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7510. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7511. * @example
  7512. * ```javascript
  7513. *
  7514. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7515. * UE.ajax.requeset( 'sayhello.php', {
  7516. *
  7517. * //请求的地址, 该项是必须的。
  7518. * url: 'sayhello.php'
  7519. *
  7520. * } );
  7521. * ```
  7522. */
  7523. request:function(url, ajaxOptions) {
  7524. var ajaxRequest = creatAjaxRequest(),
  7525. //是否超时
  7526. timeIsOut = false,
  7527. //默认参数
  7528. defaultAjaxOptions = {
  7529. method:"POST",
  7530. timeout:5000,
  7531. async:true,
  7532. data:{},//需要传递对象的话只能覆盖
  7533. onsuccess:function() {
  7534. },
  7535. onerror:function() {
  7536. }
  7537. };
  7538. if (typeof url === "object") {
  7539. ajaxOptions = url;
  7540. url = ajaxOptions.url;
  7541. }
  7542. if (!ajaxRequest || !url) return;
  7543. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7544. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7545. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7546. if (!utils.isEmptyObject(ajaxOpts.data)){
  7547. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7548. }
  7549. //超时检测
  7550. var timerID = setTimeout(function() {
  7551. if (ajaxRequest.readyState != 4) {
  7552. timeIsOut = true;
  7553. ajaxRequest.abort();
  7554. clearTimeout(timerID);
  7555. }
  7556. }, ajaxOpts.timeout);
  7557. var method = ajaxOpts.method.toUpperCase();
  7558. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7559. ajaxRequest.open(method, str, ajaxOpts.async);
  7560. ajaxRequest.onreadystatechange = function() {
  7561. if (ajaxRequest.readyState == 4) {
  7562. if (!timeIsOut && ajaxRequest.status == 200) {
  7563. ajaxOpts.onsuccess(ajaxRequest);
  7564. } else {
  7565. ajaxOpts.onerror(ajaxRequest);
  7566. }
  7567. }
  7568. };
  7569. if (method == "POST") {
  7570. ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7571. ajaxRequest.send(submitStr);
  7572. } else {
  7573. ajaxRequest.send(null);
  7574. }
  7575. }
  7576. };
  7577. }();
  7578. /**
  7579. * UE过滤word的静态方法
  7580. * @file
  7581. */
  7582. /**
  7583. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7584. * @module UE
  7585. */
  7586. /**
  7587. * 根据传入html字符串过滤word
  7588. * @module UE
  7589. * @since 1.2.6.1
  7590. * @method filterWord
  7591. * @param { String } html html字符串
  7592. * @return { String } 已过滤后的结果字符串
  7593. * @example
  7594. * ```javascript
  7595. * UE.filterWord(html);
  7596. * ```
  7597. */
  7598. var filterWord = UE.filterWord = function () {
  7599. //是否是word过来的内容
  7600. function isWordDocument( str ) {
  7601. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  7602. }
  7603. //去掉小数
  7604. function transUnit( v ) {
  7605. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  7606. return utils.transUnitToPx(m);
  7607. } );
  7608. return v;
  7609. }
  7610. function filterPasteWord( str ) {
  7611. return str.replace(/[\t\r\n]+/g,' ')
  7612. .replace( /<!--[\s\S]*?-->/ig, "" )
  7613. //转换图片
  7614. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  7615. //opera能自己解析出image所这里直接返回空
  7616. if(browser.opera){
  7617. return '';
  7618. }
  7619. try{
  7620. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  7621. if(/Bitmap/i.test(str)){
  7622. return '';
  7623. }
  7624. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  7625. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  7626. src = str.match(/src=\s*"([^"]*)"/i)[1];
  7627. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  7628. } catch(e){
  7629. return '';
  7630. }
  7631. })
  7632. //针对wps添加的多余标签处理
  7633. .replace(/<\/?div[^>]*>/g,'')
  7634. //去掉多余的属性
  7635. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  7636. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  7637. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  7638. //去掉多余的属性
  7639. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  7640. //保留list的标示
  7641. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  7642. })
  7643. //清除多余的font/span不能匹配&nbsp;有可能是空格
  7644. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  7645. return c.replace(/[\t\r\n ]+/g,' ')
  7646. })
  7647. //处理style的问题
  7648. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  7649. var n = [],
  7650. s = style.replace( /^\s+|\s+$/, '' )
  7651. .replace(/&#39;/g,'\'')
  7652. .replace( /&quot;/gi, "'" )
  7653. .split( /;\s*/g );
  7654. for ( var i = 0,v; v = s[i];i++ ) {
  7655. var name, value,
  7656. parts = v.split( ":" );
  7657. if ( parts.length == 2 ) {
  7658. name = parts[0].toLowerCase();
  7659. value = parts[1].toLowerCase();
  7660. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  7661. ||
  7662. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  7663. ){
  7664. continue;
  7665. }
  7666. switch ( name ) {
  7667. case "mso-padding-alt":
  7668. case "mso-padding-top-alt":
  7669. case "mso-padding-right-alt":
  7670. case "mso-padding-bottom-alt":
  7671. case "mso-padding-left-alt":
  7672. case "mso-margin-alt":
  7673. case "mso-margin-top-alt":
  7674. case "mso-margin-right-alt":
  7675. case "mso-margin-bottom-alt":
  7676. case "mso-margin-left-alt":
  7677. //ie下会出现挤到一起的情况
  7678. //case "mso-table-layout-alt":
  7679. case "mso-height":
  7680. case "mso-width":
  7681. case "mso-vertical-align-alt":
  7682. //trace:1819 ff下会解析出padding在table上
  7683. if(!/<table/.test(tag))
  7684. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  7685. continue;
  7686. case "horiz-align":
  7687. n[i] = "text-align:" + value;
  7688. continue;
  7689. case "vert-align":
  7690. n[i] = "vertical-align:" + value;
  7691. continue;
  7692. case "font-color":
  7693. case "mso-foreground":
  7694. n[i] = "color:" + value;
  7695. continue;
  7696. case "mso-background":
  7697. case "mso-highlight":
  7698. n[i] = "background:" + value;
  7699. continue;
  7700. case "mso-default-height":
  7701. n[i] = "min-height:" + transUnit( value );
  7702. continue;
  7703. case "mso-default-width":
  7704. n[i] = "min-width:" + transUnit( value );
  7705. continue;
  7706. case "mso-padding-between-alt":
  7707. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  7708. continue;
  7709. case "text-line-through":
  7710. if ( (value == "single") || (value == "double") ) {
  7711. n[i] = "text-decoration:line-through";
  7712. }
  7713. continue;
  7714. case "mso-zero-height":
  7715. if ( value == "yes" ) {
  7716. n[i] = "display:none";
  7717. }
  7718. continue;
  7719. // case 'background':
  7720. // break;
  7721. case 'margin':
  7722. if ( !/[1-9]/.test( value ) ) {
  7723. continue;
  7724. }
  7725. }
  7726. 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 )
  7727. ||
  7728. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  7729. ) {
  7730. continue;
  7731. }
  7732. n[i] = name + ":" + parts[1];
  7733. }
  7734. }
  7735. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  7736. })
  7737. .replace(/[\d.]+(cm|pt)/g,function(str){
  7738. return utils.transUnitToPx(str)
  7739. })
  7740. }
  7741. return function ( html ) {
  7742. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  7743. };
  7744. }();
  7745. /**
  7746. * 编辑器模拟的节点类
  7747. * @file
  7748. * @module UE
  7749. * @class uNode
  7750. * @since 1.2.6.1
  7751. */
  7752. /**
  7753. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7754. * @unfile
  7755. * @module UE
  7756. */
  7757. (function () {
  7758. /**
  7759. * 编辑器模拟的节点类
  7760. * @unfile
  7761. * @module UE
  7762. * @class uNode
  7763. */
  7764. /**
  7765. * 通过一个键值对,创建一个uNode对象
  7766. * @constructor
  7767. * @param { Object } attr 传入要创建的uNode的初始属性
  7768. * @example
  7769. * ```javascript
  7770. * var node = new uNode({
  7771. * type:'element',
  7772. * tagName:'span',
  7773. * attrs:{style:'font-size:14px;'}
  7774. * }
  7775. * ```
  7776. */
  7777. var uNode = UE.uNode = function (obj) {
  7778. this.type = obj.type;
  7779. this.data = obj.data;
  7780. this.tagName = obj.tagName;
  7781. this.parentNode = obj.parentNode;
  7782. this.attrs = obj.attrs || {};
  7783. this.children = obj.children;
  7784. };
  7785. var notTransAttrs = {
  7786. 'href':1,
  7787. 'src':1,
  7788. '_src':1,
  7789. '_href':1,
  7790. 'cdata_data':1
  7791. };
  7792. var notTransTagName = {
  7793. style:1,
  7794. script:1
  7795. };
  7796. var indentChar = ' ',
  7797. breakChar = '\n';
  7798. function insertLine(arr, current, begin) {
  7799. arr.push(breakChar);
  7800. return current + (begin ? 1 : -1);
  7801. }
  7802. function insertIndent(arr, current) {
  7803. //插入缩进
  7804. for (var i = 0; i < current; i++) {
  7805. arr.push(indentChar);
  7806. }
  7807. }
  7808. //创建uNode的静态方法
  7809. //支持标签和html
  7810. uNode.createElement = function (html) {
  7811. if (/[<>]/.test(html)) {
  7812. return UE.htmlparser(html).children[0]
  7813. } else {
  7814. return new uNode({
  7815. type:'element',
  7816. children:[],
  7817. tagName:html
  7818. })
  7819. }
  7820. };
  7821. uNode.createText = function (data,noTrans) {
  7822. return new UE.uNode({
  7823. type:'text',
  7824. 'data':noTrans ? data : utils.unhtml(data || '')
  7825. })
  7826. };
  7827. function nodeToHtml(node, arr, formatter, current) {
  7828. switch (node.type) {
  7829. case 'root':
  7830. for (var i = 0, ci; ci = node.children[i++];) {
  7831. //插入新行
  7832. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  7833. insertLine(arr, current, true);
  7834. insertIndent(arr, current)
  7835. }
  7836. nodeToHtml(ci, arr, formatter, current)
  7837. }
  7838. break;
  7839. case 'text':
  7840. isText(node, arr);
  7841. break;
  7842. case 'element':
  7843. isElement(node, arr, formatter, current);
  7844. break;
  7845. case 'comment':
  7846. isComment(node, arr, formatter);
  7847. }
  7848. return arr;
  7849. }
  7850. function isText(node, arr) {
  7851. if(node.parentNode.tagName == 'pre'){
  7852. //源码模式下输入html标签,不能做转换处理,直接输出
  7853. arr.push(node.data)
  7854. }else{
  7855. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  7856. }
  7857. }
  7858. function isElement(node, arr, formatter, current) {
  7859. var attrhtml = '';
  7860. if (node.attrs) {
  7861. attrhtml = [];
  7862. var attrs = node.attrs;
  7863. for (var a in attrs) {
  7864. //这里就针对
  7865. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  7866. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  7867. //有可能做的不够
  7868. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  7869. return '&quot;'
  7870. }) : utils.unhtml(attrs[a])) + '"' : ''))
  7871. }
  7872. attrhtml = attrhtml.join(' ');
  7873. }
  7874. arr.push('<' + node.tagName +
  7875. (attrhtml ? ' ' + attrhtml : '') +
  7876. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  7877. );
  7878. //插入新行
  7879. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  7880. if(node.children && node.children.length){
  7881. current = insertLine(arr, current, true);
  7882. insertIndent(arr, current)
  7883. }
  7884. }
  7885. if (node.children && node.children.length) {
  7886. for (var i = 0, ci; ci = node.children[i++];) {
  7887. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  7888. insertLine(arr, current);
  7889. insertIndent(arr, current)
  7890. }
  7891. nodeToHtml(ci, arr, formatter, current)
  7892. }
  7893. }
  7894. if (!dtd.$empty[node.tagName]) {
  7895. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  7896. if(node.children && node.children.length){
  7897. current = insertLine(arr, current);
  7898. insertIndent(arr, current)
  7899. }
  7900. }
  7901. arr.push('<\/' + node.tagName + '>');
  7902. }
  7903. }
  7904. function isComment(node, arr) {
  7905. arr.push('<!--' + node.data + '-->');
  7906. }
  7907. function getNodeById(root, id) {
  7908. var node;
  7909. if (root.type == 'element' && root.getAttr('id') == id) {
  7910. return root;
  7911. }
  7912. if (root.children && root.children.length) {
  7913. for (var i = 0, ci; ci = root.children[i++];) {
  7914. if (node = getNodeById(ci, id)) {
  7915. return node;
  7916. }
  7917. }
  7918. }
  7919. }
  7920. function getNodesByTagName(node, tagName, arr) {
  7921. if (node.type == 'element' && node.tagName == tagName) {
  7922. arr.push(node);
  7923. }
  7924. if (node.children && node.children.length) {
  7925. for (var i = 0, ci; ci = node.children[i++];) {
  7926. getNodesByTagName(ci, tagName, arr)
  7927. }
  7928. }
  7929. }
  7930. function nodeTraversal(root,fn){
  7931. if(root.children && root.children.length){
  7932. for(var i= 0,ci;ci=root.children[i];){
  7933. nodeTraversal(ci,fn);
  7934. //ci被替换的情况,这里就不再走 fn了
  7935. if(ci.parentNode ){
  7936. if(ci.children && ci.children.length){
  7937. fn(ci)
  7938. }
  7939. if(ci.parentNode) i++
  7940. }
  7941. }
  7942. }else{
  7943. fn(root)
  7944. }
  7945. }
  7946. uNode.prototype = {
  7947. /**
  7948. * 当前节点对象,转换成html文本
  7949. * @method toHtml
  7950. * @return { String } 返回转换后的html字符串
  7951. * @example
  7952. * ```javascript
  7953. * node.toHtml();
  7954. * ```
  7955. */
  7956. /**
  7957. * 当前节点对象,转换成html文本
  7958. * @method toHtml
  7959. * @param { Boolean } formatter 是否格式化返回值
  7960. * @return { String } 返回转换后的html字符串
  7961. * @example
  7962. * ```javascript
  7963. * node.toHtml( true );
  7964. * ```
  7965. */
  7966. toHtml:function (formatter) {
  7967. var arr = [];
  7968. nodeToHtml(this, arr, formatter, 0);
  7969. return arr.join('')
  7970. },
  7971. /**
  7972. * 获取节点的html内容
  7973. * @method innerHTML
  7974. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  7975. * @return { String } 返回节点的html内容
  7976. * @example
  7977. * ```javascript
  7978. * var htmlstr = node.innerHTML();
  7979. * ```
  7980. */
  7981. /**
  7982. * 设置节点的html内容
  7983. * @method innerHTML
  7984. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  7985. * @param { String } htmlstr 传入要设置的html内容
  7986. * @return { UE.uNode } 返回节点本身
  7987. * @example
  7988. * ```javascript
  7989. * node.innerHTML('<span>text</span>');
  7990. * ```
  7991. */
  7992. innerHTML:function (htmlstr) {
  7993. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  7994. return this;
  7995. }
  7996. if (utils.isString(htmlstr)) {
  7997. if(this.children){
  7998. for (var i = 0, ci; ci = this.children[i++];) {
  7999. ci.parentNode = null;
  8000. }
  8001. }
  8002. this.children = [];
  8003. var tmpRoot = UE.htmlparser(htmlstr);
  8004. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8005. this.children.push(ci);
  8006. ci.parentNode = this;
  8007. }
  8008. return this;
  8009. } else {
  8010. var tmpRoot = new UE.uNode({
  8011. type:'root',
  8012. children:this.children
  8013. });
  8014. return tmpRoot.toHtml();
  8015. }
  8016. },
  8017. /**
  8018. * 获取节点的纯文本内容
  8019. * @method innerText
  8020. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8021. * @return { String } 返回节点的存文本内容
  8022. * @example
  8023. * ```javascript
  8024. * var textStr = node.innerText();
  8025. * ```
  8026. */
  8027. /**
  8028. * 设置节点的纯文本内容
  8029. * @method innerText
  8030. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8031. * @param { String } textStr 传入要设置的文本内容
  8032. * @return { UE.uNode } 返回节点本身
  8033. * @example
  8034. * ```javascript
  8035. * node.innerText('<span>text</span>');
  8036. * ```
  8037. */
  8038. innerText:function (textStr,noTrans) {
  8039. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8040. return this;
  8041. }
  8042. if (textStr) {
  8043. if(this.children){
  8044. for (var i = 0, ci; ci = this.children[i++];) {
  8045. ci.parentNode = null;
  8046. }
  8047. }
  8048. this.children = [];
  8049. this.appendChild(uNode.createText(textStr,noTrans));
  8050. return this;
  8051. } else {
  8052. return this.toHtml().replace(/<[^>]+>/g, '');
  8053. }
  8054. },
  8055. /**
  8056. * 获取当前对象的data属性
  8057. * @method getData
  8058. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8059. * @example
  8060. * ```javascript
  8061. * node.getData();
  8062. * ```
  8063. */
  8064. getData:function () {
  8065. if (this.type == 'element')
  8066. return '';
  8067. return this.data
  8068. },
  8069. /**
  8070. * 获取当前节点下的第一个子节点
  8071. * @method firstChild
  8072. * @return { UE.uNode } 返回第一个子节点
  8073. * @example
  8074. * ```javascript
  8075. * node.firstChild(); //返回第一个子节点
  8076. * ```
  8077. */
  8078. firstChild:function () {
  8079. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8080. // return this;
  8081. // }
  8082. return this.children ? this.children[0] : null;
  8083. },
  8084. /**
  8085. * 获取当前节点下的最后一个子节点
  8086. * @method lastChild
  8087. * @return { UE.uNode } 返回最后一个子节点
  8088. * @example
  8089. * ```javascript
  8090. * node.lastChild(); //返回最后一个子节点
  8091. * ```
  8092. */
  8093. lastChild:function () {
  8094. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8095. // return this;
  8096. // }
  8097. return this.children ? this.children[this.children.length - 1] : null;
  8098. },
  8099. /**
  8100. * 获取和当前节点有相同父亲节点的前一个节点
  8101. * @method previousSibling
  8102. * @return { UE.uNode } 返回前一个节点
  8103. * @example
  8104. * ```javascript
  8105. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8106. * ```
  8107. */
  8108. previousSibling : function(){
  8109. var parent = this.parentNode;
  8110. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8111. if (ci === this) {
  8112. return i == 0 ? null : parent.children[i-1];
  8113. }
  8114. }
  8115. },
  8116. /**
  8117. * 获取和当前节点有相同父亲节点的后一个节点
  8118. * @method nextSibling
  8119. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8120. * @example
  8121. * ```javascript
  8122. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8123. * ```
  8124. */
  8125. nextSibling : function(){
  8126. var parent = this.parentNode;
  8127. for (var i = 0, ci; ci = parent.children[i++];) {
  8128. if (ci === this) {
  8129. return parent.children[i];
  8130. }
  8131. }
  8132. },
  8133. /**
  8134. * 用新的节点替换当前节点
  8135. * @method replaceChild
  8136. * @param { UE.uNode } target 要替换成该节点参数
  8137. * @param { UE.uNode } source 要被替换掉的节点
  8138. * @return { UE.uNode } 返回替换之后的节点对象
  8139. * @example
  8140. * ```javascript
  8141. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8142. * ```
  8143. */
  8144. replaceChild:function (target, source) {
  8145. if (this.children) {
  8146. if(target.parentNode){
  8147. target.parentNode.removeChild(target);
  8148. }
  8149. for (var i = 0, ci; ci = this.children[i]; i++) {
  8150. if (ci === source) {
  8151. this.children.splice(i, 1, target);
  8152. source.parentNode = null;
  8153. target.parentNode = this;
  8154. return target;
  8155. }
  8156. }
  8157. }
  8158. },
  8159. /**
  8160. * 在节点的子节点列表最后位置插入一个节点
  8161. * @method appendChild
  8162. * @param { UE.uNode } node 要插入的节点
  8163. * @return { UE.uNode } 返回刚插入的子节点
  8164. * @example
  8165. * ```javascript
  8166. * node.appendChild( newNode ); //在node内插入子节点newNode
  8167. * ```
  8168. */
  8169. appendChild:function (node) {
  8170. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8171. if (!this.children) {
  8172. this.children = []
  8173. }
  8174. if(node.parentNode){
  8175. node.parentNode.removeChild(node);
  8176. }
  8177. for (var i = 0, ci; ci = this.children[i]; i++) {
  8178. if (ci === node) {
  8179. this.children.splice(i, 1);
  8180. break;
  8181. }
  8182. }
  8183. this.children.push(node);
  8184. node.parentNode = this;
  8185. return node;
  8186. }
  8187. },
  8188. /**
  8189. * 在传入节点的前面插入一个节点
  8190. * @method insertBefore
  8191. * @param { UE.uNode } target 要插入的节点
  8192. * @param { UE.uNode } source 在该参数节点前面插入
  8193. * @return { UE.uNode } 返回刚插入的子节点
  8194. * @example
  8195. * ```javascript
  8196. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8197. * ```
  8198. */
  8199. insertBefore:function (target, source) {
  8200. if (this.children) {
  8201. if(target.parentNode){
  8202. target.parentNode.removeChild(target);
  8203. }
  8204. for (var i = 0, ci; ci = this.children[i]; i++) {
  8205. if (ci === source) {
  8206. this.children.splice(i, 0, target);
  8207. target.parentNode = this;
  8208. return target;
  8209. }
  8210. }
  8211. }
  8212. },
  8213. /**
  8214. * 在传入节点的后面插入一个节点
  8215. * @method insertAfter
  8216. * @param { UE.uNode } target 要插入的节点
  8217. * @param { UE.uNode } source 在该参数节点后面插入
  8218. * @return { UE.uNode } 返回刚插入的子节点
  8219. * @example
  8220. * ```javascript
  8221. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8222. * ```
  8223. */
  8224. insertAfter:function (target, source) {
  8225. if (this.children) {
  8226. if(target.parentNode){
  8227. target.parentNode.removeChild(target);
  8228. }
  8229. for (var i = 0, ci; ci = this.children[i]; i++) {
  8230. if (ci === source) {
  8231. this.children.splice(i + 1, 0, target);
  8232. target.parentNode = this;
  8233. return target;
  8234. }
  8235. }
  8236. }
  8237. },
  8238. /**
  8239. * 从当前节点的子节点列表中,移除节点
  8240. * @method removeChild
  8241. * @param { UE.uNode } node 要移除的节点引用
  8242. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8243. * @return { * } 返回刚移除的子节点
  8244. * @example
  8245. * ```javascript
  8246. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8247. * ```
  8248. */
  8249. removeChild:function (node,keepChildren) {
  8250. if (this.children) {
  8251. for (var i = 0, ci; ci = this.children[i]; i++) {
  8252. if (ci === node) {
  8253. this.children.splice(i, 1);
  8254. ci.parentNode = null;
  8255. if(keepChildren && ci.children && ci.children.length){
  8256. for(var j= 0,cj;cj=ci.children[j];j++){
  8257. this.children.splice(i+j,0,cj);
  8258. cj.parentNode = this;
  8259. }
  8260. }
  8261. return ci;
  8262. }
  8263. }
  8264. }
  8265. },
  8266. /**
  8267. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8268. * @method getAttr
  8269. * @param { String } attrName 要获取的属性名称
  8270. * @return { * } 返回attrs对象下的属性值
  8271. * @example
  8272. * ```javascript
  8273. * node.getAttr('title');
  8274. * ```
  8275. */
  8276. getAttr:function (attrName) {
  8277. return this.attrs && this.attrs[attrName.toLowerCase()]
  8278. },
  8279. /**
  8280. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8281. * @method setAttr
  8282. * @param { String } attrName 要设置的属性名称
  8283. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8284. * @return { * } 返回attrs对象下的属性值
  8285. * @example
  8286. * ```javascript
  8287. * node.setAttr('title','标题');
  8288. * ```
  8289. */
  8290. setAttr:function (attrName, attrVal) {
  8291. if (!attrName) {
  8292. delete this.attrs;
  8293. return;
  8294. }
  8295. if(!this.attrs){
  8296. this.attrs = {};
  8297. }
  8298. if (utils.isObject(attrName)) {
  8299. for (var a in attrName) {
  8300. if (!attrName[a]) {
  8301. delete this.attrs[a]
  8302. } else {
  8303. this.attrs[a.toLowerCase()] = attrName[a];
  8304. }
  8305. }
  8306. } else {
  8307. if (!attrVal) {
  8308. delete this.attrs[attrName]
  8309. } else {
  8310. this.attrs[attrName.toLowerCase()] = attrVal;
  8311. }
  8312. }
  8313. },
  8314. /**
  8315. * 获取当前节点在父节点下的位置索引
  8316. * @method getIndex
  8317. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8318. * @example
  8319. * ```javascript
  8320. * node.getIndex();
  8321. * ```
  8322. */
  8323. getIndex:function(){
  8324. var parent = this.parentNode;
  8325. for(var i= 0,ci;ci=parent.children[i];i++){
  8326. if(ci === this){
  8327. return i;
  8328. }
  8329. }
  8330. return -1;
  8331. },
  8332. /**
  8333. * 在当前节点下,根据id查找节点
  8334. * @method getNodeById
  8335. * @param { String } id 要查找的id
  8336. * @return { UE.uNode } 返回找到的节点
  8337. * @example
  8338. * ```javascript
  8339. * node.getNodeById('textId');
  8340. * ```
  8341. */
  8342. getNodeById:function (id) {
  8343. var node;
  8344. if (this.children && this.children.length) {
  8345. for (var i = 0, ci; ci = this.children[i++];) {
  8346. if (node = getNodeById(ci, id)) {
  8347. return node;
  8348. }
  8349. }
  8350. }
  8351. },
  8352. /**
  8353. * 在当前节点下,根据元素名称查找节点列表
  8354. * @method getNodesByTagName
  8355. * @param { String } tagNames 要查找的元素名称
  8356. * @return { Array } 返回找到的节点列表
  8357. * @example
  8358. * ```javascript
  8359. * node.getNodesByTagName('span');
  8360. * ```
  8361. */
  8362. getNodesByTagName:function (tagNames) {
  8363. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8364. var arr = [], me = this;
  8365. utils.each(tagNames, function (tagName) {
  8366. if (me.children && me.children.length) {
  8367. for (var i = 0, ci; ci = me.children[i++];) {
  8368. getNodesByTagName(ci, tagName, arr)
  8369. }
  8370. }
  8371. });
  8372. return arr;
  8373. },
  8374. /**
  8375. * 根据样式名称,获取节点的样式值
  8376. * @method getStyle
  8377. * @param { String } name 要获取的样式名称
  8378. * @return { String } 返回样式值
  8379. * @example
  8380. * ```javascript
  8381. * node.getStyle('font-size');
  8382. * ```
  8383. */
  8384. getStyle:function (name) {
  8385. var cssStyle = this.getAttr('style');
  8386. if (!cssStyle) {
  8387. return ''
  8388. }
  8389. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8390. var match = cssStyle.match(reg);
  8391. if (match && match[0]) {
  8392. return match[2]
  8393. }
  8394. return '';
  8395. },
  8396. /**
  8397. * 给节点设置样式
  8398. * @method setStyle
  8399. * @param { String } name 要设置的的样式名称
  8400. * @param { String } val 要设置的的样值
  8401. * @example
  8402. * ```javascript
  8403. * node.setStyle('font-size', '12px');
  8404. * ```
  8405. */
  8406. setStyle:function (name, val) {
  8407. function exec(name, val) {
  8408. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8409. cssStyle = cssStyle.replace(reg, '$1');
  8410. if (val) {
  8411. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8412. }
  8413. }
  8414. var cssStyle = this.getAttr('style');
  8415. if (!cssStyle) {
  8416. cssStyle = '';
  8417. }
  8418. if (utils.isObject(name)) {
  8419. for (var a in name) {
  8420. exec(a, name[a])
  8421. }
  8422. } else {
  8423. exec(name, val)
  8424. }
  8425. this.setAttr('style', utils.trim(cssStyle))
  8426. },
  8427. /**
  8428. * 传入一个函数,递归遍历当前节点下的所有节点
  8429. * @method traversal
  8430. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8431. * @example
  8432. * ```javascript
  8433. * traversal(node, function(){
  8434. * console.log(node.type);
  8435. * });
  8436. * ```
  8437. */
  8438. traversal:function(fn){
  8439. if(this.children && this.children.length){
  8440. nodeTraversal(this,fn);
  8441. }
  8442. return this;
  8443. }
  8444. }
  8445. })();
  8446. /**
  8447. * html字符串转换成uNode节点
  8448. * @file
  8449. * @module UE
  8450. * @since 1.2.6.1
  8451. */
  8452. /**
  8453. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8454. * @unfile
  8455. * @module UE
  8456. */
  8457. /**
  8458. * html字符串转换成uNode节点的静态方法
  8459. * @method htmlparser
  8460. * @param { String } htmlstr 要转换的html代码
  8461. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8462. * @return { uNode } 给定的html片段转换形成的uNode对象
  8463. * @example
  8464. * ```javascript
  8465. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8466. * ```
  8467. */
  8468. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8469. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8470. //先去掉了,加上的原因忘了,这里先记录
  8471. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8472. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8473. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8474. var allowEmptyTags = {
  8475. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8476. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8477. };
  8478. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8479. if(!ignoreBlank){
  8480. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8481. //br暂时单独处理
  8482. if(b && allowEmptyTags[b.toLowerCase()]){
  8483. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8484. }
  8485. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8486. });
  8487. }
  8488. var notTransAttrs = {
  8489. 'href':1,
  8490. 'src':1
  8491. };
  8492. var uNode = UE.uNode,
  8493. needParentNode = {
  8494. 'td':'tr',
  8495. 'tr':['tbody','thead','tfoot'],
  8496. 'tbody':'table',
  8497. 'th':'tr',
  8498. 'thead':'table',
  8499. 'tfoot':'table',
  8500. 'caption':'table',
  8501. 'li':['ul', 'ol'],
  8502. 'dt':'dl',
  8503. 'dd':'dl',
  8504. 'option':'select'
  8505. },
  8506. needChild = {
  8507. 'ol':'li',
  8508. 'ul':'li'
  8509. };
  8510. function text(parent, data) {
  8511. if(needChild[parent.tagName]){
  8512. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8513. parent.appendChild(tmpNode);
  8514. tmpNode.appendChild(uNode.createText(data));
  8515. parent = tmpNode;
  8516. }else{
  8517. parent.appendChild(uNode.createText(data));
  8518. }
  8519. }
  8520. function element(parent, tagName, htmlattr) {
  8521. var needParentTag;
  8522. if (needParentTag = needParentNode[tagName]) {
  8523. var tmpParent = parent,hasParent;
  8524. while(tmpParent.type != 'root'){
  8525. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8526. parent = tmpParent;
  8527. hasParent = true;
  8528. break;
  8529. }
  8530. tmpParent = tmpParent.parentNode;
  8531. }
  8532. if(!hasParent){
  8533. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8534. }
  8535. }
  8536. //按dtd处理嵌套
  8537. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8538. // parent = parent.parentNode;
  8539. var elm = new uNode({
  8540. parentNode:parent,
  8541. type:'element',
  8542. tagName:tagName.toLowerCase(),
  8543. //是自闭合的处理一下
  8544. children:dtd.$empty[tagName] ? null : []
  8545. });
  8546. //如果属性存在,处理属性
  8547. if (htmlattr) {
  8548. var attrs = {}, match;
  8549. while (match = re_attr.exec(htmlattr)) {
  8550. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8551. }
  8552. elm.attrs = attrs;
  8553. }
  8554. parent.children.push(elm);
  8555. //如果是自闭合节点返回父亲节点
  8556. return dtd.$empty[tagName] ? parent : elm
  8557. }
  8558. function comment(parent, data) {
  8559. parent.children.push(new uNode({
  8560. type:'comment',
  8561. data:data,
  8562. parentNode:parent
  8563. }));
  8564. }
  8565. var match, currentIndex = 0, nextIndex = 0;
  8566. //设置根节点
  8567. var root = new uNode({
  8568. type:'root',
  8569. children:[]
  8570. });
  8571. var currentParent = root;
  8572. while (match = re_tag.exec(htmlstr)) {
  8573. currentIndex = match.index;
  8574. try{
  8575. if (currentIndex > nextIndex) {
  8576. //text node
  8577. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8578. }
  8579. if (match[3]) {
  8580. if(dtd.$cdata[currentParent.tagName]){
  8581. text(currentParent, match[0]);
  8582. }else{
  8583. //start tag
  8584. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8585. }
  8586. } else if (match[1]) {
  8587. if(currentParent.type != 'root'){
  8588. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  8589. text(currentParent, match[0]);
  8590. }else{
  8591. var tmpParent = currentParent;
  8592. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  8593. currentParent = currentParent.parentNode;
  8594. if(currentParent.type == 'root'){
  8595. currentParent = tmpParent;
  8596. throw 'break'
  8597. }
  8598. }
  8599. //end tag
  8600. currentParent = currentParent.parentNode;
  8601. }
  8602. }
  8603. } else if (match[2]) {
  8604. //comment
  8605. comment(currentParent, match[2])
  8606. }
  8607. }catch(e){}
  8608. nextIndex = re_tag.lastIndex;
  8609. }
  8610. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  8611. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  8612. if (nextIndex < htmlstr.length) {
  8613. text(currentParent, htmlstr.slice(nextIndex));
  8614. }
  8615. return root;
  8616. };
  8617. /**
  8618. * UE过滤节点的静态方法
  8619. * @file
  8620. */
  8621. /**
  8622. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8623. * @module UE
  8624. */
  8625. /**
  8626. * 根据传入节点和过滤规则过滤相应节点
  8627. * @module UE
  8628. * @since 1.2.6.1
  8629. * @method filterNode
  8630. * @param { Object } root 指定root节点
  8631. * @param { Object } rules 过滤规则json对象
  8632. * @example
  8633. * ```javascript
  8634. * UE.filterNode(root,editor.options.filterRules);
  8635. * ```
  8636. */
  8637. var filterNode = UE.filterNode = function () {
  8638. function filterNode(node,rules){
  8639. switch (node.type) {
  8640. case 'text':
  8641. break;
  8642. case 'element':
  8643. var val;
  8644. if(val = rules[node.tagName]){
  8645. if(val === '-'){
  8646. node.parentNode.removeChild(node)
  8647. }else if(utils.isFunction(val)){
  8648. var parentNode = node.parentNode,
  8649. index = node.getIndex();
  8650. val(node);
  8651. if(node.parentNode){
  8652. if(node.children){
  8653. for(var i = 0,ci;ci=node.children[i];){
  8654. filterNode(ci,rules);
  8655. if(ci.parentNode){
  8656. i++;
  8657. }
  8658. }
  8659. }
  8660. }else{
  8661. for(var i = index,ci;ci=parentNode.children[i];){
  8662. filterNode(ci,rules);
  8663. if(ci.parentNode){
  8664. i++;
  8665. }
  8666. }
  8667. }
  8668. }else{
  8669. var attrs = val['$'];
  8670. if(attrs && node.attrs){
  8671. var tmpAttrs = {},tmpVal;
  8672. for(var a in attrs){
  8673. tmpVal = node.getAttr(a);
  8674. //todo 只先对style单独处理
  8675. if(a == 'style' && utils.isArray(attrs[a])){
  8676. var tmpCssStyle = [];
  8677. utils.each(attrs[a],function(v){
  8678. var tmp;
  8679. if(tmp = node.getStyle(v)){
  8680. tmpCssStyle.push(v + ':' + tmp);
  8681. }
  8682. });
  8683. tmpVal = tmpCssStyle.join(';')
  8684. }
  8685. if(tmpVal){
  8686. tmpAttrs[a] = tmpVal;
  8687. }
  8688. }
  8689. node.attrs = tmpAttrs;
  8690. }
  8691. if(node.children){
  8692. for(var i = 0,ci;ci=node.children[i];){
  8693. filterNode(ci,rules);
  8694. if(ci.parentNode){
  8695. i++;
  8696. }
  8697. }
  8698. }
  8699. }
  8700. }else{
  8701. //如果不在名单里扣出子节点并删除该节点,cdata除外
  8702. if(dtd.$cdata[node.tagName]){
  8703. node.parentNode.removeChild(node)
  8704. }else{
  8705. var parentNode = node.parentNode,
  8706. index = node.getIndex();
  8707. node.parentNode.removeChild(node,true);
  8708. for(var i = index,ci;ci=parentNode.children[i];){
  8709. filterNode(ci,rules);
  8710. if(ci.parentNode){
  8711. i++;
  8712. }
  8713. }
  8714. }
  8715. }
  8716. break;
  8717. case 'comment':
  8718. node.parentNode.removeChild(node)
  8719. }
  8720. }
  8721. return function(root,rules){
  8722. if(utils.isEmptyObject(rules)){
  8723. return root;
  8724. }
  8725. var val;
  8726. if(val = rules['-']){
  8727. utils.each(val.split(' '),function(k){
  8728. rules[k] = '-'
  8729. })
  8730. }
  8731. for(var i= 0,ci;ci=root.children[i];){
  8732. filterNode(ci,rules);
  8733. if(ci.parentNode){
  8734. i++;
  8735. }
  8736. }
  8737. return root;
  8738. }
  8739. }();
  8740. /*
  8741. * Created with JetBrains PhpStorm.
  8742. * User: campaign
  8743. * Date: 10/8/13
  8744. * Time: 6:15 PM
  8745. * To change this template use File | Settings | File Templates.
  8746. */
  8747. UE.plugin = function(){
  8748. var _plugins = {};
  8749. return {
  8750. register : function(pluginName,fn,oldOptionName,afterDisabled){
  8751. if(oldOptionName && utils.isFunction(oldOptionName)){
  8752. afterDisabled = oldOptionName;
  8753. oldOptionName = null
  8754. }
  8755. _plugins[pluginName] = {
  8756. optionName : oldOptionName || pluginName,
  8757. execFn : fn,
  8758. //当插件被禁用时执行
  8759. afterDisabled : afterDisabled
  8760. }
  8761. },
  8762. load : function(editor){
  8763. utils.each(_plugins,function(plugin){
  8764. var _export = plugin.execFn.call(editor);
  8765. if(editor.options[plugin.optionName] !== false){
  8766. if(_export){
  8767. //后边需要再做扩展
  8768. utils.each(_export,function(v,k){
  8769. switch(k.toLowerCase()){
  8770. case 'shortcutkey':
  8771. editor.addshortcutkey(v);
  8772. break;
  8773. case 'bindevents':
  8774. utils.each(v,function(fn,eventName){
  8775. editor.addListener(eventName,fn);
  8776. });
  8777. break;
  8778. case 'bindmultievents':
  8779. utils.each(utils.isArray(v) ? v:[v],function(event){
  8780. var types = utils.trim(event.type).split(/\s+/);
  8781. utils.each(types,function(eventName){
  8782. editor.addListener(eventName, event.handler);
  8783. });
  8784. });
  8785. break;
  8786. case 'commands':
  8787. utils.each(v,function(execFn,execName){
  8788. editor.commands[execName] = execFn
  8789. });
  8790. break;
  8791. case 'outputrule':
  8792. editor.addOutputRule(v);
  8793. break;
  8794. case 'inputrule':
  8795. editor.addInputRule(v);
  8796. break;
  8797. case 'defaultoptions':
  8798. editor.setOpt(v)
  8799. }
  8800. })
  8801. }
  8802. }else if(plugin.afterDisabled){
  8803. plugin.afterDisabled.call(editor)
  8804. }
  8805. });
  8806. //向下兼容
  8807. utils.each(UE.plugins,function(plugin){
  8808. plugin.call(editor);
  8809. });
  8810. },
  8811. run : function(plugnName,editor){
  8812. var plugin = _plugins[pluginName];
  8813. if(plugin){
  8814. plugin.exeFn.call(editor)
  8815. }
  8816. }
  8817. }
  8818. }();
  8819. ///import core
  8820. ///plugin 编辑器默认的过滤转换机制
  8821. UE.plugins['defaultfilter'] = function () {
  8822. var me = this;
  8823. me.setOpt({
  8824. 'allowDivTransToP':true,
  8825. 'disabledTableInTable':true
  8826. });
  8827. //默认的过滤处理
  8828. //进入编辑器的内容处理
  8829. me.addInputRule(function (root) {
  8830. var allowDivTransToP = this.options.allowDivTransToP;
  8831. var val;
  8832. function tdParent(node){
  8833. while(node && node.type == 'element'){
  8834. if(node.tagName == 'td'){
  8835. return true;
  8836. }
  8837. node = node.parentNode;
  8838. }
  8839. return false;
  8840. }
  8841. //进行默认的处理
  8842. root.traversal(function (node) {
  8843. if (node.type == 'element') {
  8844. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8845. if (!node.firstChild()) node.parentNode.removeChild(node);
  8846. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8847. node.parentNode.removeChild(node, true)
  8848. }
  8849. return;
  8850. }
  8851. switch (node.tagName) {
  8852. case 'style':
  8853. case 'script':
  8854. node.setAttr({
  8855. cdata_tag: node.tagName,
  8856. cdata_data: (node.innerHTML() || ''),
  8857. '_ue_custom_node_':'true'
  8858. });
  8859. node.tagName = 'div';
  8860. node.innerHTML('');
  8861. break;
  8862. case 'a':
  8863. if (val = node.getAttr('href')) {
  8864. node.setAttr('_href', val)
  8865. }
  8866. break;
  8867. case 'img':
  8868. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  8869. if (val = node.getAttr('src')) {
  8870. if (/^data:/.test(val)) {
  8871. node.parentNode.removeChild(node);
  8872. break;
  8873. }
  8874. }
  8875. node.setAttr('_src', node.getAttr('src'));
  8876. break;
  8877. case 'span':
  8878. if (browser.webkit && (val = node.getStyle('white-space'))) {
  8879. if (/nowrap|normal/.test(val)) {
  8880. node.setStyle('white-space', '');
  8881. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  8882. node.parentNode.removeChild(node, true)
  8883. }
  8884. }
  8885. }
  8886. break;
  8887. case 'p':
  8888. if (val = node.getAttr('align')) {
  8889. node.setAttr('align');
  8890. node.setStyle('text-align', val)
  8891. }
  8892. //trace:3431
  8893. // var cssStyle = node.getAttr('style');
  8894. // if (cssStyle) {
  8895. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  8896. // node.setAttr('style', cssStyle)
  8897. //
  8898. // }
  8899. //p标签不允许嵌套
  8900. utils.each(node.children,function(n){
  8901. if(n.type == 'element' && n.tagName == 'p'){
  8902. var next = n.nextSibling();
  8903. node.parentNode.insertAfter(n,node);
  8904. var last = n;
  8905. while(next){
  8906. var tmp = next.nextSibling();
  8907. node.parentNode.insertAfter(next,last);
  8908. last = next;
  8909. next = tmp;
  8910. }
  8911. return false;
  8912. }
  8913. });
  8914. if (!node.firstChild()) {
  8915. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  8916. }
  8917. break;
  8918. case 'div':
  8919. if(node.getAttr('cdata_tag')){
  8920. break;
  8921. }
  8922. //针对代码这里不处理插入代码的div
  8923. val = node.getAttr('class');
  8924. if(val && /^line number\d+/.test(val)){
  8925. break;
  8926. }
  8927. if(!allowDivTransToP){
  8928. break;
  8929. }
  8930. var tmpNode, p = UE.uNode.createElement('p');
  8931. while (tmpNode = node.firstChild()) {
  8932. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  8933. p.appendChild(tmpNode);
  8934. } else {
  8935. if (p.firstChild()) {
  8936. node.parentNode.insertBefore(p, node);
  8937. p = UE.uNode.createElement('p');
  8938. } else {
  8939. node.parentNode.insertBefore(tmpNode, node);
  8940. }
  8941. }
  8942. }
  8943. if (p.firstChild()) {
  8944. node.parentNode.insertBefore(p, node);
  8945. }
  8946. node.parentNode.removeChild(node);
  8947. break;
  8948. case 'dl':
  8949. node.tagName = 'ul';
  8950. break;
  8951. case 'dt':
  8952. case 'dd':
  8953. node.tagName = 'li';
  8954. break;
  8955. case 'li':
  8956. var className = node.getAttr('class');
  8957. if (!className || !/list\-/.test(className)) {
  8958. node.setAttr()
  8959. }
  8960. var tmpNodes = node.getNodesByTagName('ol ul');
  8961. UE.utils.each(tmpNodes, function (n) {
  8962. node.parentNode.insertAfter(n, node);
  8963. });
  8964. break;
  8965. case 'td':
  8966. case 'th':
  8967. case 'caption':
  8968. if(!node.children || !node.children.length){
  8969. node.appendChild(browser.ie ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  8970. }
  8971. break;
  8972. case 'table':
  8973. if(me.options.disabledTableInTable && tdParent(node)){
  8974. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  8975. node.parentNode.removeChild(node)
  8976. }
  8977. }
  8978. }
  8979. // if(node.type == 'comment'){
  8980. // node.parentNode.removeChild(node);
  8981. // }
  8982. })
  8983. });
  8984. //从编辑器出去的内容处理
  8985. me.addOutputRule(function (root) {
  8986. var val;
  8987. root.traversal(function (node) {
  8988. if (node.type == 'element') {
  8989. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8990. if (!node.firstChild()) node.parentNode.removeChild(node);
  8991. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8992. node.parentNode.removeChild(node, true)
  8993. }
  8994. return;
  8995. }
  8996. switch (node.tagName) {
  8997. case 'div':
  8998. if (val = node.getAttr('cdata_tag')) {
  8999. node.tagName = val;
  9000. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9001. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9002. }
  9003. break;
  9004. case 'a':
  9005. if (val = node.getAttr('_href')) {
  9006. node.setAttr({
  9007. 'href': utils.html(val),
  9008. '_href': ''
  9009. })
  9010. }
  9011. break;
  9012. case 'img':
  9013. if (val = node.getAttr('_src')) {
  9014. node.setAttr({
  9015. 'src': node.getAttr('_src'),
  9016. '_src': ''
  9017. })
  9018. }
  9019. }
  9020. }
  9021. })
  9022. });
  9023. };
  9024. /**
  9025. * 插入html字符串插件
  9026. * @file
  9027. * @since 1.2.6.1
  9028. */
  9029. /**
  9030. * 插入html代码
  9031. * @command inserthtml
  9032. * @method execCommand
  9033. * @param { String } cmd 命令字符串
  9034. * @param { String } html 插入的html字符串
  9035. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9036. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9037. * @example
  9038. * ```javascript
  9039. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9040. * //执行命令,插入<b>CC</b>
  9041. * //插入后的效果 xxx<b>CC</b>xxx
  9042. * //<p>xx|xxx</p> 当前选区为闭合状态
  9043. * //插入<p>CC</p>
  9044. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9045. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9046. * //插入 xxxx
  9047. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9048. * ```
  9049. */
  9050. UE.commands['inserthtml'] = {
  9051. execCommand: function (command,html,notNeedFilter){
  9052. var me = this,
  9053. range,
  9054. div;
  9055. if(!html){
  9056. return;
  9057. }
  9058. if(me.fireEvent('beforeinserthtml',html) === true){
  9059. return;
  9060. }
  9061. range = me.selection.getRange();
  9062. div = range.document.createElement( 'div' );
  9063. div.style.display = 'inline';
  9064. if (!notNeedFilter) {
  9065. var root = UE.htmlparser(html);
  9066. //如果给了过滤规则就先进行过滤
  9067. if(me.options.filterRules){
  9068. UE.filterNode(root,me.options.filterRules);
  9069. }
  9070. //执行默认的处理
  9071. me.filterInputRule(root);
  9072. html = root.toHtml()
  9073. }
  9074. div.innerHTML = utils.trim( html );
  9075. if ( !range.collapsed ) {
  9076. var tmpNode = range.startContainer;
  9077. if(domUtils.isFillChar(tmpNode)){
  9078. range.setStartBefore(tmpNode)
  9079. }
  9080. tmpNode = range.endContainer;
  9081. if(domUtils.isFillChar(tmpNode)){
  9082. range.setEndAfter(tmpNode)
  9083. }
  9084. range.txtToElmBoundary();
  9085. //结束边界可能放到了br的前边,要把br包含进来
  9086. // x[xxx]<br/>
  9087. if(range.endContainer && range.endContainer.nodeType == 1){
  9088. tmpNode = range.endContainer.childNodes[range.endOffset];
  9089. if(tmpNode && domUtils.isBr(tmpNode)){
  9090. range.setEndAfter(tmpNode);
  9091. }
  9092. }
  9093. if(range.startOffset == 0){
  9094. tmpNode = range.startContainer;
  9095. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9096. tmpNode = range.endContainer;
  9097. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9098. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9099. range.setStart(me.body.firstChild,0).collapse(true)
  9100. }
  9101. }
  9102. }
  9103. !range.collapsed && range.deleteContents();
  9104. if(range.startContainer.nodeType == 1){
  9105. var child = range.startContainer.childNodes[range.startOffset],pre;
  9106. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9107. range.setEnd(pre,pre.childNodes.length).collapse();
  9108. while(child.firstChild){
  9109. pre.appendChild(child.firstChild);
  9110. }
  9111. domUtils.remove(child);
  9112. }
  9113. }
  9114. }
  9115. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9116. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9117. if(range.inFillChar()){
  9118. child = range.startContainer;
  9119. if(domUtils.isFillChar(child)){
  9120. range.setStartBefore(child).collapse(true);
  9121. domUtils.remove(child);
  9122. }else if(domUtils.isFillChar(child,true)){
  9123. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9124. range.startOffset--;
  9125. range.collapsed && range.collapse(true)
  9126. }
  9127. }
  9128. //列表单独处理
  9129. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9130. if(li){
  9131. var next,last;
  9132. while(child = div.firstChild){
  9133. //针对hr单独处理一下先
  9134. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9135. next = child.nextSibling;
  9136. range.insertNode( child).collapse();
  9137. last = child;
  9138. child = next;
  9139. }
  9140. if(child){
  9141. if(/^(ol|ul)$/i.test(child.tagName)){
  9142. while(child.firstChild){
  9143. last = child.firstChild;
  9144. domUtils.insertAfter(li,child.firstChild);
  9145. li = li.nextSibling;
  9146. }
  9147. domUtils.remove(child)
  9148. }else{
  9149. var tmpLi;
  9150. next = child.nextSibling;
  9151. tmpLi = me.document.createElement('li');
  9152. domUtils.insertAfter(li,tmpLi);
  9153. tmpLi.appendChild(child);
  9154. last = child;
  9155. child = next;
  9156. li = tmpLi;
  9157. }
  9158. }
  9159. }
  9160. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9161. if(domUtils.isEmptyBlock(li)){
  9162. domUtils.remove(li)
  9163. }
  9164. if(last){
  9165. range.setStartAfter(last).collapse(true).select(true)
  9166. }
  9167. }else{
  9168. while ( child = div.firstChild ) {
  9169. if(hadBreak){
  9170. var p = me.document.createElement('p');
  9171. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9172. nextNode = child.nextSibling;
  9173. p.appendChild(child);
  9174. child = nextNode;
  9175. }
  9176. if(p.firstChild){
  9177. child = p
  9178. }
  9179. }
  9180. range.insertNode( child );
  9181. nextNode = child.nextSibling;
  9182. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9183. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9184. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9185. if(!dtd[parent.tagName][child.nodeName]){
  9186. pre = parent;
  9187. }else{
  9188. tmp = child.parentNode;
  9189. while (tmp !== parent){
  9190. pre = tmp;
  9191. tmp = tmp.parentNode;
  9192. }
  9193. }
  9194. domUtils.breakParent( child, pre || tmp );
  9195. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9196. var pre = child.previousSibling;
  9197. domUtils.trimWhiteTextNode(pre);
  9198. if(!pre.childNodes.length){
  9199. domUtils.remove(pre);
  9200. }
  9201. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9202. if(!browser.ie &&
  9203. (next = child.nextSibling) &&
  9204. domUtils.isBlockElm(next) &&
  9205. next.lastChild &&
  9206. !domUtils.isBr(next.lastChild)){
  9207. next.appendChild(me.document.createElement('br'));
  9208. }
  9209. hadBreak = 1;
  9210. }
  9211. }
  9212. var next = child.nextSibling;
  9213. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9214. range.setStart(next,0).collapse(true);
  9215. break;
  9216. }
  9217. range.setEndAfter( child ).collapse();
  9218. }
  9219. child = range.startContainer;
  9220. if(nextNode && domUtils.isBr(nextNode)){
  9221. domUtils.remove(nextNode)
  9222. }
  9223. //用chrome可能有空白展位符
  9224. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9225. if(nextNode = child.nextSibling){
  9226. domUtils.remove(child);
  9227. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9228. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9229. }
  9230. }else{
  9231. try{
  9232. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9233. }catch(e){
  9234. range.setStartBefore(child);
  9235. domUtils.remove(child)
  9236. }
  9237. }
  9238. }
  9239. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9240. try{
  9241. range.select(true);
  9242. }catch(e){}
  9243. }
  9244. setTimeout(function(){
  9245. range = me.selection.getRange();
  9246. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9247. me.fireEvent('afterinserthtml');
  9248. },200);
  9249. }
  9250. };
  9251. /**
  9252. * 自动排版
  9253. * @file
  9254. * @since 1.2.6.1
  9255. */
  9256. /**
  9257. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9258. * @command autotypeset
  9259. * @method execCommand
  9260. * @param { String } cmd 命令字符串
  9261. * @example
  9262. * ```javascript
  9263. * editor.execCommand( 'autotypeset' );
  9264. * ```
  9265. */
  9266. UE.plugins['autotypeset'] = function(){
  9267. this.setOpt({'autotypeset':{
  9268. mergeEmptyline : true, //合并空行
  9269. removeClass : true, //去掉冗余的class
  9270. removeEmptyline : false, //去掉空行
  9271. textAlign : "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9272. imageBlockLine : 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9273. pasteFilter : false, //根据规则过滤没事粘贴进来的内容
  9274. clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9275. clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9276. removeEmptyNode : false, // 去掉空节点
  9277. //可以去掉的标签
  9278. removeTagNames : utils.extend({div:1},dtd.$removeEmpty),
  9279. indent : false, // 行首缩进
  9280. indentValue : '2em' //行首缩进的大小
  9281. }});
  9282. var me = this,
  9283. opt = me.options.autotypeset,
  9284. remainClass = {
  9285. 'selectTdClass':1,
  9286. 'pagebreak':1,
  9287. 'anchorclass':1
  9288. },
  9289. remainTag = {
  9290. 'li':1
  9291. },
  9292. tags = {
  9293. div:1,
  9294. p:1,
  9295. //trace:2183 这些也认为是行
  9296. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9297. span:1
  9298. },
  9299. highlightCont;
  9300. //升级了版本,但配置项目里没有autotypeset
  9301. if(!opt){
  9302. return;
  9303. }
  9304. function isLine(node,notEmpty){
  9305. if(!node || node.nodeType == 3)
  9306. return 0;
  9307. if(domUtils.isBr(node))
  9308. return 1;
  9309. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9310. if(highlightCont && highlightCont.contains(node)
  9311. ||
  9312. node.getAttribute('pagebreak')
  9313. ){
  9314. return 0;
  9315. }
  9316. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9317. +']','g'));
  9318. }
  9319. }
  9320. function removeNotAttributeSpan(node){
  9321. if(!node.style.cssText){
  9322. domUtils.removeAttributes(node,['style']);
  9323. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9324. domUtils.remove(node,true);
  9325. }
  9326. }
  9327. }
  9328. function autotype(type,html){
  9329. var me = this,cont;
  9330. if(html){
  9331. if(!opt.pasteFilter){
  9332. return;
  9333. }
  9334. cont = me.document.createElement('div');
  9335. cont.innerHTML = html.html;
  9336. }else{
  9337. cont = me.document.body;
  9338. }
  9339. var nodes = domUtils.getElementsByTagName(cont,'*');
  9340. // 行首缩进,段落方向,段间距,段内间距
  9341. for(var i=0,ci;ci=nodes[i++];){
  9342. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9343. continue;
  9344. }
  9345. //font-size
  9346. if(opt.clearFontSize && ci.style.fontSize){
  9347. domUtils.removeStyle(ci,'font-size');
  9348. removeNotAttributeSpan(ci);
  9349. }
  9350. //font-family
  9351. if(opt.clearFontFamily && ci.style.fontFamily){
  9352. domUtils.removeStyle(ci,'font-family');
  9353. removeNotAttributeSpan(ci);
  9354. }
  9355. if(isLine(ci)){
  9356. //合并空行
  9357. if(opt.mergeEmptyline ){
  9358. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9359. while(isLine(next)){
  9360. tmpNode = next;
  9361. next = tmpNode.nextSibling;
  9362. if(isBr && (!next || next && !domUtils.isBr(next))){
  9363. break;
  9364. }
  9365. domUtils.remove(tmpNode);
  9366. }
  9367. }
  9368. //去掉空行,保留占位的空行
  9369. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9370. if(domUtils.isBr(ci)){
  9371. next = ci.nextSibling;
  9372. if(next && !domUtils.isBr(next)){
  9373. continue;
  9374. }
  9375. }
  9376. domUtils.remove(ci);
  9377. continue;
  9378. }
  9379. }
  9380. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9381. if(opt.indent){
  9382. ci.style.textIndent = opt.indentValue;
  9383. }
  9384. if(opt.textAlign){
  9385. ci.style.textAlign = opt.textAlign;
  9386. }
  9387. // if(opt.lineHeight)
  9388. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9389. }
  9390. //去掉class,保留的class不去掉
  9391. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9392. if(highlightCont && highlightCont.contains(ci)){
  9393. continue;
  9394. }
  9395. domUtils.removeAttributes(ci,['class']);
  9396. }
  9397. //表情不处理
  9398. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9399. if(html){
  9400. var img = ci;
  9401. switch (opt.imageBlockLine){
  9402. case 'left':
  9403. case 'right':
  9404. case 'none':
  9405. var pN = img.parentNode,tmpNode,pre,next;
  9406. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9407. pN = pN.parentNode;
  9408. }
  9409. tmpNode = pN;
  9410. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9411. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9412. pre = tmpNode.previousSibling;
  9413. next = tmpNode.nextSibling;
  9414. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9415. pre.appendChild(tmpNode.firstChild);
  9416. while(next.firstChild){
  9417. pre.appendChild(next.firstChild);
  9418. }
  9419. domUtils.remove(tmpNode);
  9420. domUtils.remove(next);
  9421. }else{
  9422. domUtils.setStyle(tmpNode,'text-align','');
  9423. }
  9424. }
  9425. }
  9426. domUtils.setStyle(img,'float',opt.imageBlockLine);
  9427. break;
  9428. case 'center':
  9429. if(me.queryCommandValue('imagefloat') != 'center'){
  9430. pN = img.parentNode;
  9431. domUtils.setStyle(img,'float','none');
  9432. tmpNode = img;
  9433. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  9434. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  9435. tmpNode = pN;
  9436. pN = pN.parentNode;
  9437. }
  9438. var pNode = me.document.createElement('p');
  9439. domUtils.setAttributes(pNode,{
  9440. style:'text-align:center'
  9441. });
  9442. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  9443. pNode.appendChild(tmpNode);
  9444. domUtils.setStyle(tmpNode,'float','');
  9445. }
  9446. }
  9447. }else{
  9448. var range = me.selection.getRange();
  9449. range.selectNode(ci).select();
  9450. me.execCommand('imagefloat',opt.imageBlockLine);
  9451. }
  9452. }
  9453. //去掉冗余的标签
  9454. if(opt.removeEmptyNode){
  9455. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  9456. domUtils.remove(ci);
  9457. }
  9458. }
  9459. }
  9460. if(html){
  9461. html.html = cont.innerHTML;
  9462. }
  9463. }
  9464. if(opt.pasteFilter){
  9465. me.addListener('beforepaste',autotype);
  9466. }
  9467. me.commands['autotypeset'] = {
  9468. execCommand:function () {
  9469. me.removeListener('beforepaste',autotype);
  9470. if(opt.pasteFilter){
  9471. me.addListener('beforepaste',autotype);
  9472. }
  9473. autotype.call(me)
  9474. }
  9475. };
  9476. };
  9477. /**
  9478. * 快捷键提交
  9479. * @file
  9480. * @since 1.2.6.1
  9481. */
  9482. /**
  9483. * 提交表单
  9484. * @command autosubmit
  9485. * @method execCommand
  9486. * @param { String } cmd 命令字符串
  9487. * @example
  9488. * ```javascript
  9489. * editor.execCommand( 'autosubmit' );
  9490. * ```
  9491. */
  9492. UE.plugin.register('autosubmit',function(){
  9493. return {
  9494. shortcutkey:{
  9495. "autosubmit":"ctrl+13" //手动提交
  9496. },
  9497. commands:{
  9498. 'autosubmit':{
  9499. execCommand:function () {
  9500. var me=this,
  9501. form = domUtils.findParentByTagName(me.iframe,"form", false);
  9502. if (form){
  9503. if(me.fireEvent("beforesubmit")===false){
  9504. return;
  9505. }
  9506. me.sync();
  9507. form.submit();
  9508. }
  9509. }
  9510. }
  9511. }
  9512. }
  9513. });
  9514. /**
  9515. * 背景插件,为UEditor提供设置背景功能
  9516. * @file
  9517. * @since 1.2.6.1
  9518. */
  9519. UE.plugin.register('background', function () {
  9520. var me = this,
  9521. cssRuleId = 'editor_background',
  9522. isSetColored,
  9523. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  9524. function stringToObj(str) {
  9525. var obj = {}, styles = str.split(';');
  9526. utils.each(styles, function (v) {
  9527. var index = v.indexOf(':'),
  9528. key = utils.trim(v.substr(0, index)).toLowerCase();
  9529. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  9530. });
  9531. return obj;
  9532. }
  9533. function setBackground(obj) {
  9534. if (obj) {
  9535. var styles = [];
  9536. for (var name in obj) {
  9537. if (obj.hasOwnProperty(name)) {
  9538. styles.push(name + ":" + obj[name] + '; ');
  9539. }
  9540. }
  9541. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  9542. } else {
  9543. utils.cssRule(cssRuleId, '', me.document)
  9544. }
  9545. }
  9546. //重写editor.hasContent方法
  9547. var orgFn = me.hasContents;
  9548. me.hasContents = function(){
  9549. if(me.queryCommandValue('background')){
  9550. return true
  9551. }
  9552. return orgFn.apply(me,arguments);
  9553. };
  9554. return {
  9555. bindEvents: {
  9556. 'getAllHtml': function (type, headHtml) {
  9557. var body = this.body,
  9558. su = domUtils.getComputedStyle(body, "background-image"),
  9559. url = "";
  9560. if (su.indexOf(me.options.imagePath) > 0) {
  9561. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  9562. } else {
  9563. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  9564. }
  9565. var html = '<style type="text/css">body{';
  9566. var bgObj = {
  9567. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  9568. 'background-image': url ? 'url(' + url + ')' : '',
  9569. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  9570. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  9571. 'height': domUtils.getComputedStyle(body, "height")
  9572. };
  9573. for (var name in bgObj) {
  9574. if (bgObj.hasOwnProperty(name)) {
  9575. html += name + ":" + bgObj[name] + "; ";
  9576. }
  9577. }
  9578. html += '}</style> ';
  9579. headHtml.push(html);
  9580. },
  9581. 'aftersetcontent': function () {
  9582. if(isSetColored == false) setBackground();
  9583. }
  9584. },
  9585. inputRule: function (root) {
  9586. isSetColored = false;
  9587. utils.each(root.getNodesByTagName('p'), function (p) {
  9588. var styles = p.getAttr('data-background');
  9589. if (styles) {
  9590. isSetColored = true;
  9591. setBackground(stringToObj(styles));
  9592. p.parentNode.removeChild(p);
  9593. }
  9594. })
  9595. },
  9596. outputRule: function (root) {
  9597. var me = this,
  9598. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  9599. if (styles) {
  9600. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  9601. }
  9602. },
  9603. commands: {
  9604. 'background': {
  9605. execCommand: function (cmd, obj) {
  9606. setBackground(obj);
  9607. },
  9608. queryCommandValue: function () {
  9609. var me = this,
  9610. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  9611. return styles ? stringToObj(styles[1]) : null;
  9612. },
  9613. notNeedUndo: true
  9614. }
  9615. }
  9616. }
  9617. });
  9618. /**
  9619. * 图片插入、排版插件
  9620. * @file
  9621. * @since 1.2.6.1
  9622. */
  9623. /**
  9624. * 图片对齐方式
  9625. * @command imagefloat
  9626. * @method execCommand
  9627. * @remind 值center为独占一行居中
  9628. * @param { String } cmd 命令字符串
  9629. * @param { String } align 对齐方式,可传left、right、none、center
  9630. * @remaind center表示图片独占一行
  9631. * @example
  9632. * ```javascript
  9633. * editor.execCommand( 'imagefloat', 'center' );
  9634. * ```
  9635. */
  9636. /**
  9637. * 如果选区所在位置是图片区域
  9638. * @command imagefloat
  9639. * @method queryCommandValue
  9640. * @param { String } cmd 命令字符串
  9641. * @return { String } 返回图片对齐方式
  9642. * @example
  9643. * ```javascript
  9644. * editor.queryCommandValue( 'imagefloat' );
  9645. * ```
  9646. */
  9647. UE.commands['imagefloat'] = {
  9648. execCommand:function (cmd, align) {
  9649. var me = this,
  9650. range = me.selection.getRange();
  9651. if (!range.collapsed) {
  9652. var img = range.getClosedNode();
  9653. if (img && img.tagName == 'IMG') {
  9654. switch (align) {
  9655. case 'left':
  9656. case 'right':
  9657. case 'none':
  9658. var pN = img.parentNode, tmpNode, pre, next;
  9659. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  9660. pN = pN.parentNode;
  9661. }
  9662. tmpNode = pN;
  9663. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  9664. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  9665. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  9666. }) == 1) {
  9667. pre = tmpNode.previousSibling;
  9668. next = tmpNode.nextSibling;
  9669. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  9670. pre.appendChild(tmpNode.firstChild);
  9671. while (next.firstChild) {
  9672. pre.appendChild(next.firstChild);
  9673. }
  9674. domUtils.remove(tmpNode);
  9675. domUtils.remove(next);
  9676. } else {
  9677. domUtils.setStyle(tmpNode, 'text-align', '');
  9678. }
  9679. }
  9680. range.selectNode(img).select();
  9681. }
  9682. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  9683. if(align == 'none'){
  9684. domUtils.removeAttributes(img,'align');
  9685. }
  9686. break;
  9687. case 'center':
  9688. if (me.queryCommandValue('imagefloat') != 'center') {
  9689. pN = img.parentNode;
  9690. domUtils.setStyle(img, 'float', '');
  9691. domUtils.removeAttributes(img,'align');
  9692. tmpNode = img;
  9693. while (pN && domUtils.getChildCount(pN, function (node) {
  9694. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  9695. }) == 1
  9696. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  9697. tmpNode = pN;
  9698. pN = pN.parentNode;
  9699. }
  9700. range.setStartBefore(tmpNode).setCursor(false);
  9701. pN = me.document.createElement('div');
  9702. pN.appendChild(tmpNode);
  9703. domUtils.setStyle(tmpNode, 'float', '');
  9704. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  9705. tmpNode = me.document.getElementById('_img_parent_tmp');
  9706. tmpNode.removeAttribute('id');
  9707. tmpNode = tmpNode.firstChild;
  9708. range.selectNode(tmpNode).select();
  9709. //去掉后边多余的元素
  9710. next = tmpNode.parentNode.nextSibling;
  9711. if (next && domUtils.isEmptyNode(next)) {
  9712. domUtils.remove(next);
  9713. }
  9714. }
  9715. break;
  9716. }
  9717. }
  9718. }
  9719. },
  9720. queryCommandValue:function () {
  9721. var range = this.selection.getRange(),
  9722. startNode, floatStyle;
  9723. if (range.collapsed) {
  9724. return 'none';
  9725. }
  9726. startNode = range.getClosedNode();
  9727. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  9728. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  9729. if (floatStyle == 'none') {
  9730. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  9731. }
  9732. return {
  9733. left:1,
  9734. right:1,
  9735. center:1
  9736. }[floatStyle] ? floatStyle : 'none';
  9737. }
  9738. return 'none';
  9739. },
  9740. queryCommandState:function () {
  9741. var range = this.selection.getRange(),
  9742. startNode;
  9743. if (range.collapsed) return -1;
  9744. startNode = range.getClosedNode();
  9745. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  9746. return 0;
  9747. }
  9748. return -1;
  9749. }
  9750. };
  9751. /**
  9752. * 插入图片
  9753. * @command insertimage
  9754. * @method execCommand
  9755. * @param { String } cmd 命令字符串
  9756. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  9757. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  9758. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  9759. * @example
  9760. * ```javascript
  9761. * editor.execCommand( 'insertimage', {
  9762. * src:'a/b/c.jpg',
  9763. * width:'100',
  9764. * height:'100'
  9765. * } );
  9766. * ```
  9767. * @example
  9768. * ```javascript
  9769. * editor.execCommand( 'insertimage', [{
  9770. * src:'a/b/c.jpg',
  9771. * width:'100',
  9772. * height:'100'
  9773. * },{
  9774. * src:'a/b/d.jpg',
  9775. * width:'100',
  9776. * height:'100'
  9777. * }] );
  9778. * ```
  9779. */
  9780. UE.commands['insertimage'] = {
  9781. execCommand:function (cmd, opt) {
  9782. opt = utils.isArray(opt) ? opt : [opt];
  9783. if (!opt.length) {
  9784. return;
  9785. }
  9786. var me = this,
  9787. range = me.selection.getRange(),
  9788. img = range.getClosedNode();
  9789. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  9790. var first = opt.shift();
  9791. var floatStyle = first['floatStyle'];
  9792. delete first['floatStyle'];
  9793. //// img.style.border = (first.border||0) +"px solid #000";
  9794. //// img.style.margin = (first.margin||0) +"px";
  9795. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  9796. domUtils.setAttributes(img, first);
  9797. me.execCommand('imagefloat', floatStyle);
  9798. if (opt.length > 0) {
  9799. range.setStartAfter(img).setCursor(false, true);
  9800. me.execCommand('insertimage', opt);
  9801. }
  9802. } else {
  9803. var html = [], str = '', ci;
  9804. ci = opt[0];
  9805. if (opt.length == 1) {
  9806. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  9807. (ci.width ? 'width="' + ci.width + '" ' : '') +
  9808. (ci.height ? ' height="' + ci.height + '" ' : '') +
  9809. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  9810. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  9811. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  9812. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  9813. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  9814. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  9815. if (ci['floatStyle'] == 'center') {
  9816. str = '<p style="text-align: center">' + str + '</p>';
  9817. }
  9818. html.push(str);
  9819. } else {
  9820. for (var i = 0; ci = opt[i++];) {
  9821. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  9822. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  9823. (ci.height ? ' height="' + ci.height + '" ' : '') +
  9824. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  9825. (ci.border || '') + '" ' +
  9826. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  9827. html.push(str);
  9828. }
  9829. }
  9830. me.execCommand('insertHtml', html.join(''));
  9831. }
  9832. }
  9833. };
  9834. /**
  9835. * 段落格式
  9836. * @file
  9837. * @since 1.2.6.1
  9838. */
  9839. /**
  9840. * 段落对齐方式
  9841. * @command justify
  9842. * @method execCommand
  9843. * @param { String } cmd 命令字符串
  9844. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  9845. * @example
  9846. * ```javascript
  9847. * editor.execCommand( 'justify', 'center' );
  9848. * ```
  9849. */
  9850. /**
  9851. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  9852. * @command justify
  9853. * @method queryCommandValue
  9854. * @param { String } cmd 命令字符串
  9855. * @return { String } 返回段落对齐方式
  9856. * @example
  9857. * ```javascript
  9858. * editor.queryCommandValue( 'justify' );
  9859. * ```
  9860. */
  9861. UE.plugins['justify']=function(){
  9862. var me=this,
  9863. block = domUtils.isBlockElm,
  9864. defaultValue = {
  9865. left:1,
  9866. right:1,
  9867. center:1,
  9868. justify:1
  9869. },
  9870. doJustify = function (range, style) {
  9871. var bookmark = range.createBookmark(),
  9872. filterFn = function (node) {
  9873. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  9874. };
  9875. range.enlarge(true);
  9876. var bookmark2 = range.createBookmark(),
  9877. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  9878. tmpRange = range.cloneRange(),
  9879. tmpNode;
  9880. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  9881. if (current.nodeType == 3 || !block(current)) {
  9882. tmpRange.setStartBefore(current);
  9883. while (current && current !== bookmark2.end && !block(current)) {
  9884. tmpNode = current;
  9885. current = domUtils.getNextDomNode(current, false, null, function (node) {
  9886. return !block(node);
  9887. });
  9888. }
  9889. tmpRange.setEndAfter(tmpNode);
  9890. var common = tmpRange.getCommonAncestor();
  9891. if (!domUtils.isBody(common) && block(common)) {
  9892. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  9893. current = common;
  9894. } else {
  9895. var p = range.document.createElement('p');
  9896. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  9897. var frag = tmpRange.extractContents();
  9898. p.appendChild(frag);
  9899. tmpRange.insertNode(p);
  9900. current = p;
  9901. }
  9902. current = domUtils.getNextDomNode(current, false, filterFn);
  9903. } else {
  9904. current = domUtils.getNextDomNode(current, true, filterFn);
  9905. }
  9906. }
  9907. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  9908. };
  9909. UE.commands['justify'] = {
  9910. execCommand:function (cmdName, align) {
  9911. var range = this.selection.getRange(),
  9912. txt;
  9913. //闭合时单独处理
  9914. if (range.collapsed) {
  9915. txt = this.document.createTextNode('p');
  9916. range.insertNode(txt);
  9917. }
  9918. doJustify(range, align);
  9919. if (txt) {
  9920. range.setStartBefore(txt).collapse(true);
  9921. domUtils.remove(txt);
  9922. }
  9923. range.select();
  9924. return true;
  9925. },
  9926. queryCommandValue:function () {
  9927. var startNode = this.selection.getStart(),
  9928. value = domUtils.getComputedStyle(startNode, 'text-align');
  9929. return defaultValue[value] ? value : 'left';
  9930. },
  9931. queryCommandState:function () {
  9932. var start = this.selection.getStart(),
  9933. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  9934. return cell? -1:0;
  9935. }
  9936. };
  9937. };
  9938. /**
  9939. * 字体颜色,背景色,字号,字体,下划线,删除线
  9940. * @file
  9941. * @since 1.2.6.1
  9942. */
  9943. /**
  9944. * 字体颜色
  9945. * @command forecolor
  9946. * @method execCommand
  9947. * @param { String } cmd 命令字符串
  9948. * @param { String } value 色值(必须十六进制)
  9949. * @example
  9950. * ```javascript
  9951. * editor.execCommand( 'forecolor', '#000' );
  9952. * ```
  9953. */
  9954. /**
  9955. * 返回选区字体颜色
  9956. * @command forecolor
  9957. * @method queryCommandValue
  9958. * @param { String } cmd 命令字符串
  9959. * @return { String } 返回字体颜色
  9960. * @example
  9961. * ```javascript
  9962. * editor.queryCommandValue( 'forecolor' );
  9963. * ```
  9964. */
  9965. /**
  9966. * 字体背景颜色
  9967. * @command backcolor
  9968. * @method execCommand
  9969. * @param { String } cmd 命令字符串
  9970. * @param { String } value 色值(必须十六进制)
  9971. * @example
  9972. * ```javascript
  9973. * editor.execCommand( 'backcolor', '#000' );
  9974. * ```
  9975. */
  9976. /**
  9977. * 返回选区字体颜色
  9978. * @command backcolor
  9979. * @method queryCommandValue
  9980. * @param { String } cmd 命令字符串
  9981. * @return { String } 返回字体背景颜色
  9982. * @example
  9983. * ```javascript
  9984. * editor.queryCommandValue( 'backcolor' );
  9985. * ```
  9986. */
  9987. /**
  9988. * 字体大小
  9989. * @command fontsize
  9990. * @method execCommand
  9991. * @param { String } cmd 命令字符串
  9992. * @param { String } value 字体大小
  9993. * @example
  9994. * ```javascript
  9995. * editor.execCommand( 'fontsize', '14px' );
  9996. * ```
  9997. */
  9998. /**
  9999. * 返回选区字体大小
  10000. * @command fontsize
  10001. * @method queryCommandValue
  10002. * @param { String } cmd 命令字符串
  10003. * @return { String } 返回字体大小
  10004. * @example
  10005. * ```javascript
  10006. * editor.queryCommandValue( 'fontsize' );
  10007. * ```
  10008. */
  10009. /**
  10010. * 字体样式
  10011. * @command fontfamily
  10012. * @method execCommand
  10013. * @param { String } cmd 命令字符串
  10014. * @param { String } value 字体样式
  10015. * @example
  10016. * ```javascript
  10017. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10018. * ```
  10019. */
  10020. /**
  10021. * 返回选区字体样式
  10022. * @command fontfamily
  10023. * @method queryCommandValue
  10024. * @param { String } cmd 命令字符串
  10025. * @return { String } 返回字体样式
  10026. * @example
  10027. * ```javascript
  10028. * editor.queryCommandValue( 'fontfamily' );
  10029. * ```
  10030. */
  10031. /**
  10032. * 字体下划线,与删除线互斥
  10033. * @command underline
  10034. * @method execCommand
  10035. * @param { String } cmd 命令字符串
  10036. * @example
  10037. * ```javascript
  10038. * editor.execCommand( 'underline' );
  10039. * ```
  10040. */
  10041. /**
  10042. * 字体删除线,与下划线互斥
  10043. * @command strikethrough
  10044. * @method execCommand
  10045. * @param { String } cmd 命令字符串
  10046. * @example
  10047. * ```javascript
  10048. * editor.execCommand( 'strikethrough' );
  10049. * ```
  10050. */
  10051. /**
  10052. * 字体边框
  10053. * @command fontborder
  10054. * @method execCommand
  10055. * @param { String } cmd 命令字符串
  10056. * @example
  10057. * ```javascript
  10058. * editor.execCommand( 'fontborder' );
  10059. * ```
  10060. */
  10061. UE.plugins['font'] = function () {
  10062. var me = this,
  10063. fonts = {
  10064. 'forecolor': 'color',
  10065. 'backcolor': 'background-color',
  10066. 'fontsize': 'font-size',
  10067. 'fontfamily': 'font-family',
  10068. 'underline': 'text-decoration',
  10069. 'strikethrough': 'text-decoration',
  10070. 'fontborder': 'border'
  10071. },
  10072. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10073. needSetChild = {
  10074. 'forecolor': 'color',
  10075. 'backcolor': 'background-color',
  10076. 'fontsize': 'font-size',
  10077. 'fontfamily': 'font-family'
  10078. };
  10079. me.setOpt({
  10080. 'fontfamily': [
  10081. { name: 'songti', val: '宋体,SimSun'},
  10082. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10083. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10084. { name: 'heiti', val: '黑体, SimHei'},
  10085. { name: 'lishu', val: '隶书, SimLi'},
  10086. { name: 'andaleMono', val: 'andale mono'},
  10087. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10088. { name: 'arialBlack', val: 'arial black,avant garde'},
  10089. { name: 'comicSansMs', val: 'comic sans ms'},
  10090. { name: 'impact', val: 'impact,chicago'},
  10091. { name: 'timesNewRoman', val: 'times new roman'}
  10092. ],
  10093. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10094. });
  10095. function mergeWithParent(node){
  10096. var parent;
  10097. while(parent = node.parentNode){
  10098. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10099. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10100. }) == 1) {
  10101. parent.style.cssText += node.style.cssText;
  10102. domUtils.remove(node,true);
  10103. node = parent;
  10104. }else{
  10105. break;
  10106. }
  10107. }
  10108. }
  10109. function mergeChild(rng,cmdName,value){
  10110. if(needSetChild[cmdName]){
  10111. rng.adjustmentBoundary();
  10112. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10113. var start = rng.startContainer.childNodes[rng.startOffset];
  10114. if(start && domUtils.isTagNode(start,'span')){
  10115. var bk = rng.createBookmark();
  10116. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10117. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10118. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10119. return;
  10120. }
  10121. domUtils.removeStyle(span,needSetChild[cmdName]);
  10122. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10123. domUtils.remove(span,true)
  10124. }
  10125. });
  10126. rng.moveToBookmark(bk)
  10127. }
  10128. }
  10129. }
  10130. }
  10131. function mergesibling(rng,cmdName,value) {
  10132. var collapsed = rng.collapsed,
  10133. bk = rng.createBookmark(), common;
  10134. if (collapsed) {
  10135. common = bk.start.parentNode;
  10136. while (dtd.$inline[common.tagName]) {
  10137. common = common.parentNode;
  10138. }
  10139. } else {
  10140. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10141. }
  10142. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10143. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10144. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10145. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10146. domUtils.remove(span, true);
  10147. }else{
  10148. domUtils.removeStyle(span,'border');
  10149. }
  10150. return
  10151. }
  10152. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10153. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10154. }
  10155. if(!(cmdName=='fontborder' && value=='none')){
  10156. var next = span.nextSibling;
  10157. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10158. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10159. span.appendChild(next);
  10160. next = span.nextSibling;
  10161. continue;
  10162. }
  10163. if (next.style.cssText == span.style.cssText) {
  10164. domUtils.moveChild(next, span);
  10165. domUtils.remove(next);
  10166. }
  10167. if (span.nextSibling === next)
  10168. break;
  10169. next = span.nextSibling;
  10170. }
  10171. }
  10172. mergeWithParent(span);
  10173. if(browser.ie && browser.version > 8 ){
  10174. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10175. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10176. if(parent && !/background-color/.test(span.style.cssText)){
  10177. span.style.backgroundColor = parent.style.backgroundColor;
  10178. }
  10179. }
  10180. });
  10181. rng.moveToBookmark(bk);
  10182. mergeChild(rng,cmdName,value)
  10183. }
  10184. me.addInputRule(function (root) {
  10185. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10186. if (node.tagName == 'font') {
  10187. var cssStyle = [];
  10188. for (var p in node.attrs) {
  10189. switch (p) {
  10190. case 'size':
  10191. cssStyle.push('font-size:' +
  10192. ({
  10193. '1':'10',
  10194. '2':'12',
  10195. '3':'16',
  10196. '4':'18',
  10197. '5':'24',
  10198. '6':'32',
  10199. '7':'48'
  10200. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10201. break;
  10202. case 'color':
  10203. cssStyle.push('color:' + node.attrs[p]);
  10204. break;
  10205. case 'face':
  10206. cssStyle.push('font-family:' + node.attrs[p]);
  10207. break;
  10208. case 'style':
  10209. cssStyle.push(node.attrs[p]);
  10210. }
  10211. }
  10212. node.attrs = {
  10213. 'style': cssStyle.join(';')
  10214. };
  10215. } else {
  10216. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10217. node.attrs = {
  10218. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10219. }
  10220. }
  10221. node.tagName = 'span';
  10222. });
  10223. // utils.each(root.getNodesByTagName('span'), function (node) {
  10224. // var val;
  10225. // if(val = node.getAttr('class')){
  10226. // if(/fontstrikethrough/.test(val)){
  10227. // node.setStyle('text-decoration','line-through');
  10228. // if(node.attrs['class']){
  10229. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10230. // }else{
  10231. // node.setAttr('class')
  10232. // }
  10233. // }
  10234. // if(/fontborder/.test(val)){
  10235. // node.setStyle('border','1px solid #000');
  10236. // if(node.attrs['class']){
  10237. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10238. // }else{
  10239. // node.setAttr('class')
  10240. // }
  10241. // }
  10242. // }
  10243. // });
  10244. });
  10245. // me.addOutputRule(function(root){
  10246. // utils.each(root.getNodesByTagName('span'), function (node) {
  10247. // var val;
  10248. // if(val = node.getStyle('text-decoration')){
  10249. // if(/line-through/.test(val)){
  10250. // if(node.attrs['class']){
  10251. // node.attrs['class'] += ' fontstrikethrough';
  10252. // }else{
  10253. // node.setAttr('class','fontstrikethrough')
  10254. // }
  10255. // }
  10256. //
  10257. // node.setStyle('text-decoration')
  10258. // }
  10259. // if(val = node.getStyle('border')){
  10260. // if(/1px/.test(val) && /solid/.test(val)){
  10261. // if(node.attrs['class']){
  10262. // node.attrs['class'] += ' fontborder';
  10263. //
  10264. // }else{
  10265. // node.setAttr('class','fontborder')
  10266. // }
  10267. // }
  10268. // node.setStyle('border')
  10269. //
  10270. // }
  10271. // });
  10272. // });
  10273. for (var p in fonts) {
  10274. (function (cmd, style) {
  10275. UE.commands[cmd] = {
  10276. execCommand: function (cmdName, value) {
  10277. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10278. cmdName == 'fontborder' ? '1px solid #000' :
  10279. 'line-through');
  10280. var me = this,
  10281. range = this.selection.getRange(),
  10282. text;
  10283. if (value == 'default') {
  10284. if (range.collapsed) {
  10285. text = me.document.createTextNode('font');
  10286. range.insertNode(text).select();
  10287. }
  10288. me.execCommand('removeFormat', 'span,a', style);
  10289. if (text) {
  10290. range.setStartBefore(text).collapse(true);
  10291. domUtils.remove(text);
  10292. }
  10293. mergesibling(range,cmdName,value);
  10294. range.select()
  10295. } else {
  10296. if (!range.collapsed) {
  10297. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10298. me.execCommand('removeFormat', 'span,a', style);
  10299. }
  10300. range = me.selection.getRange();
  10301. range.applyInlineStyle('span', {'style': style + ':' + value});
  10302. mergesibling(range, cmdName,value);
  10303. range.select();
  10304. } else {
  10305. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10306. text = me.document.createTextNode('font');
  10307. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10308. //for ie hack when enter
  10309. range.insertNode(text);
  10310. if (needCmd[cmd]) {
  10311. range.selectNode(text).select();
  10312. me.execCommand('removeFormat', 'span,a', style, null);
  10313. span = domUtils.findParentByTagName(text, 'span', true);
  10314. range.setStartBefore(text);
  10315. }
  10316. span && (span.style.cssText += ';' + style + ':' + value);
  10317. range.collapse(true).select();
  10318. } else {
  10319. range.insertNode(text);
  10320. range.selectNode(text).select();
  10321. span = range.document.createElement('span');
  10322. if (needCmd[cmd]) {
  10323. //a标签内的不处理跳过
  10324. if (domUtils.findParentByTagName(text, 'a', true)) {
  10325. range.setStartBefore(text).setCursor();
  10326. domUtils.remove(text);
  10327. return;
  10328. }
  10329. me.execCommand('removeFormat', 'span,a', style);
  10330. }
  10331. span.style.cssText = style + ':' + value;
  10332. text.parentNode.insertBefore(span, text);
  10333. //修复,span套span 但样式不继承的问题
  10334. if (!browser.ie || browser.ie && browser.version == 9) {
  10335. var spanParent = span.parentNode;
  10336. while (!domUtils.isBlockElm(spanParent)) {
  10337. if (spanParent.tagName == 'SPAN') {
  10338. //opera合并style不会加入";"
  10339. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10340. }
  10341. spanParent = spanParent.parentNode;
  10342. }
  10343. }
  10344. if (opera) {
  10345. setTimeout(function () {
  10346. range.setStart(span, 0).collapse(true);
  10347. mergesibling(range, cmdName,value);
  10348. range.select();
  10349. });
  10350. } else {
  10351. range.setStart(span, 0).collapse(true);
  10352. mergesibling(range,cmdName,value);
  10353. range.select();
  10354. }
  10355. //trace:981
  10356. //domUtils.mergeToParent(span)
  10357. }
  10358. domUtils.remove(text);
  10359. }
  10360. }
  10361. return true;
  10362. },
  10363. queryCommandValue: function (cmdName) {
  10364. var startNode = this.selection.getStart();
  10365. //trace:946
  10366. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  10367. var tmpNode = startNode, value;
  10368. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  10369. if (tmpNode.nodeType == 1) {
  10370. value = domUtils.getComputedStyle(tmpNode, style);
  10371. if (value != 'none') {
  10372. return value;
  10373. }
  10374. }
  10375. tmpNode = tmpNode.parentNode;
  10376. }
  10377. return 'none';
  10378. }
  10379. if (cmdName == 'fontborder') {
  10380. var tmp = startNode, val;
  10381. while (tmp && dtd.$inline[tmp.tagName]) {
  10382. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  10383. if (/1px/.test(val) && /solid/.test(val)) {
  10384. return val;
  10385. }
  10386. }
  10387. tmp = tmp.parentNode;
  10388. }
  10389. return ''
  10390. }
  10391. if( cmdName == 'FontSize' ) {
  10392. var styleVal = domUtils.getComputedStyle(startNode, style),
  10393. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  10394. if( tmp ) {
  10395. return Math.floor( tmp[1] ) + tmp[2];
  10396. }
  10397. return styleVal;
  10398. }
  10399. return domUtils.getComputedStyle(startNode, style);
  10400. },
  10401. queryCommandState: function (cmdName) {
  10402. if (!needCmd[cmdName])
  10403. return 0;
  10404. var val = this.queryCommandValue(cmdName);
  10405. if (cmdName == 'fontborder') {
  10406. return /1px/.test(val) && /solid/.test(val)
  10407. } else {
  10408. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  10409. }
  10410. }
  10411. };
  10412. })(p, fonts[p]);
  10413. }
  10414. };
  10415. /**
  10416. * 超链接
  10417. * @file
  10418. * @since 1.2.6.1
  10419. */
  10420. /**
  10421. * 插入超链接
  10422. * @command link
  10423. * @method execCommand
  10424. * @param { String } cmd 命令字符串
  10425. * @param { Object } options 设置自定义属性,例如:url、title、target
  10426. * @example
  10427. * ```javascript
  10428. * editor.execCommand( 'link', '{
  10429. * url:'ueditor.baidu.com',
  10430. * title:'ueditor',
  10431. * target:'_blank'
  10432. * }' );
  10433. * ```
  10434. */
  10435. /**
  10436. * 返回当前选中的第一个超链接节点
  10437. * @command link
  10438. * @method queryCommandValue
  10439. * @param { String } cmd 命令字符串
  10440. * @return { Element } 超链接节点
  10441. * @example
  10442. * ```javascript
  10443. * editor.queryCommandValue( 'link' );
  10444. * ```
  10445. */
  10446. /**
  10447. * 取消超链接
  10448. * @command unlink
  10449. * @method execCommand
  10450. * @param { String } cmd 命令字符串
  10451. * @example
  10452. * ```javascript
  10453. * editor.execCommand( 'unlink');
  10454. * ```
  10455. */
  10456. UE.plugins['link'] = function(){
  10457. function optimize( range ) {
  10458. var start = range.startContainer,end = range.endContainer;
  10459. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  10460. range.setStartBefore( start );
  10461. }
  10462. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  10463. range.setEndAfter( end );
  10464. }
  10465. }
  10466. UE.commands['unlink'] = {
  10467. execCommand : function() {
  10468. var range = this.selection.getRange(),
  10469. bookmark;
  10470. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  10471. return;
  10472. }
  10473. bookmark = range.createBookmark();
  10474. optimize( range );
  10475. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  10476. },
  10477. queryCommandState : function(){
  10478. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  10479. }
  10480. };
  10481. function doLink(range,opt,me){
  10482. var rngClone = range.cloneRange(),
  10483. link = me.queryCommandValue('link');
  10484. optimize( range = range.adjustmentBoundary() );
  10485. var start = range.startContainer;
  10486. if(start.nodeType == 1 && link){
  10487. start = start.childNodes[range.startOffset];
  10488. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  10489. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  10490. }
  10491. }
  10492. if( !rngClone.collapsed || link){
  10493. range.removeInlineStyle( 'a' );
  10494. rngClone = range.cloneRange();
  10495. }
  10496. if ( rngClone.collapsed ) {
  10497. var a = range.document.createElement( 'a'),
  10498. text = '';
  10499. if(opt.textValue){
  10500. text = utils.html(opt.textValue);
  10501. delete opt.textValue;
  10502. }else{
  10503. text = utils.html(opt.href);
  10504. }
  10505. domUtils.setAttributes( a, opt );
  10506. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  10507. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  10508. range.setStartAfter(start).collapse(true);
  10509. }
  10510. a[browser.ie ? 'innerText' : 'textContent'] = text;
  10511. range.insertNode(a).selectNode( a );
  10512. } else {
  10513. range.applyInlineStyle( 'a', opt );
  10514. }
  10515. }
  10516. UE.commands['link'] = {
  10517. execCommand : function( cmdName, opt ) {
  10518. var range;
  10519. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  10520. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  10521. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  10522. doLink(range=this.selection.getRange(),opt,this);
  10523. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  10524. range.collapse().select(true);
  10525. },
  10526. queryCommandValue : function() {
  10527. var range = this.selection.getRange(),
  10528. node;
  10529. if ( range.collapsed ) {
  10530. // node = this.selection.getStart();
  10531. //在ie下getstart()取值偏上了
  10532. node = range.startContainer;
  10533. node = node.nodeType == 1 ? node : node.parentNode;
  10534. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  10535. return node;
  10536. }
  10537. } else {
  10538. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  10539. range.shrinkBoundary();
  10540. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  10541. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  10542. common = range.getCommonAncestor();
  10543. node = domUtils.findParentByTagName( common, 'a', true );
  10544. if ( !node && common.nodeType == 1){
  10545. var as = common.getElementsByTagName( 'a' ),
  10546. ps,pe;
  10547. for ( var i = 0,ci; ci = as[i++]; ) {
  10548. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  10549. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  10550. &&
  10551. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  10552. ) {
  10553. node = ci;
  10554. break;
  10555. }
  10556. }
  10557. }
  10558. return node;
  10559. }
  10560. },
  10561. queryCommandState : function() {
  10562. //判断如果是视频的话连接不可用
  10563. //fix 853
  10564. var img = this.selection.getRange().getClosedNode(),
  10565. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  10566. return flag ? -1 : 0;
  10567. }
  10568. };
  10569. };
  10570. ///import core
  10571. ///import plugins\inserthtml.js
  10572. ///commands 插入框架
  10573. ///commandsName InsertFrame
  10574. ///commandsTitle 插入Iframe
  10575. ///commandsDialog dialogs\insertframe
  10576. UE.plugins['insertframe'] = function() {
  10577. var me =this;
  10578. function deleteIframe(){
  10579. me._iframe && delete me._iframe;
  10580. }
  10581. me.addListener("selectionchange",function(){
  10582. deleteIframe();
  10583. });
  10584. };
  10585. ///import core
  10586. ///commands 涂鸦
  10587. ///commandsName Scrawl
  10588. ///commandsTitle 涂鸦
  10589. ///commandsDialog dialogs\scrawl
  10590. UE.commands['scrawl'] = {
  10591. queryCommandState : function(){
  10592. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  10593. }
  10594. };
  10595. /**
  10596. * 清除格式
  10597. * @file
  10598. * @since 1.2.6.1
  10599. */
  10600. /**
  10601. * 清除文字样式
  10602. * @command removeformat
  10603. * @method execCommand
  10604. * @param { String } cmd 命令字符串
  10605. * @param {String} tags 以逗号隔开的标签。如:strong
  10606. * @param {String} style 样式如:color
  10607. * @param {String} attrs 属性如:width
  10608. * @example
  10609. * ```javascript
  10610. * editor.execCommand( 'removeformat', 'strong','color','width' );
  10611. * ```
  10612. */
  10613. UE.plugins['removeformat'] = function(){
  10614. var me = this;
  10615. me.setOpt({
  10616. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  10617. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  10618. });
  10619. me.commands['removeformat'] = {
  10620. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  10621. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  10622. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  10623. range = new dom.Range( this.document ),
  10624. bookmark,node,parent,
  10625. filter = function( node ) {
  10626. return node.nodeType == 1;
  10627. };
  10628. function isRedundantSpan (node) {
  10629. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  10630. return 0;
  10631. }
  10632. if (browser.ie) {
  10633. //ie 下判断实效,所以只能简单用style来判断
  10634. //return node.style.cssText == '' ? 1 : 0;
  10635. var attrs = node.attributes;
  10636. if ( attrs.length ) {
  10637. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  10638. if ( attrs[i].specified ) {
  10639. return 0;
  10640. }
  10641. }
  10642. return 1;
  10643. }
  10644. }
  10645. return !node.attributes.length;
  10646. }
  10647. function doRemove( range ) {
  10648. var bookmark1 = range.createBookmark();
  10649. if ( range.collapsed ) {
  10650. range.enlarge( true );
  10651. }
  10652. //不能把a标签切了
  10653. if(!notIncludeA){
  10654. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  10655. if(aNode){
  10656. range.setStartBefore(aNode);
  10657. }
  10658. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  10659. if(aNode){
  10660. range.setEndAfter(aNode);
  10661. }
  10662. }
  10663. bookmark = range.createBookmark();
  10664. node = bookmark.start;
  10665. //切开始
  10666. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  10667. domUtils.breakParent( node, parent );
  10668. domUtils.clearEmptySibling( node );
  10669. }
  10670. if ( bookmark.end ) {
  10671. //切结束
  10672. node = bookmark.end;
  10673. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  10674. domUtils.breakParent( node, parent );
  10675. domUtils.clearEmptySibling( node );
  10676. }
  10677. //开始去除样式
  10678. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  10679. next;
  10680. while ( current ) {
  10681. if ( current == bookmark.end ) {
  10682. break;
  10683. }
  10684. next = domUtils.getNextDomNode( current, true, filter );
  10685. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  10686. if ( tagReg.test( current.tagName ) ) {
  10687. if ( style ) {
  10688. domUtils.removeStyle( current, style );
  10689. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  10690. domUtils.remove( current, true );
  10691. }
  10692. } else {
  10693. domUtils.remove( current, true );
  10694. }
  10695. } else {
  10696. //trace:939 不能把list上的样式去掉
  10697. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  10698. domUtils.removeAttributes( current, removeFormatAttributes );
  10699. if ( isRedundantSpan( current ) ){
  10700. domUtils.remove( current, true );
  10701. }
  10702. }
  10703. }
  10704. }
  10705. current = next;
  10706. }
  10707. }
  10708. //trace:1035
  10709. //trace:1096 不能把td上的样式去掉,比如边框
  10710. var pN = bookmark.start.parentNode;
  10711. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  10712. domUtils.removeAttributes( pN,removeFormatAttributes );
  10713. }
  10714. pN = bookmark.end.parentNode;
  10715. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  10716. domUtils.removeAttributes( pN,removeFormatAttributes );
  10717. }
  10718. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  10719. //清除冗余的代码 <b><bookmark></b>
  10720. var node = range.startContainer,
  10721. tmp,
  10722. collapsed = range.collapsed;
  10723. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  10724. tmp = node.parentNode;
  10725. range.setStartBefore(node);
  10726. //trace:937
  10727. //更新结束边界
  10728. if(range.startContainer === range.endContainer){
  10729. range.endOffset--;
  10730. }
  10731. domUtils.remove(node);
  10732. node = tmp;
  10733. }
  10734. if(!collapsed){
  10735. node = range.endContainer;
  10736. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  10737. tmp = node.parentNode;
  10738. range.setEndBefore(node);
  10739. domUtils.remove(node);
  10740. node = tmp;
  10741. }
  10742. }
  10743. }
  10744. range = this.selection.getRange();
  10745. doRemove( range );
  10746. range.select();
  10747. }
  10748. };
  10749. };
  10750. /**
  10751. * 添加引用
  10752. * @file
  10753. * @since 1.2.6.1
  10754. */
  10755. /**
  10756. * 添加引用
  10757. * @command blockquote
  10758. * @method execCommand
  10759. * @param { String } cmd 命令字符串
  10760. * @example
  10761. * ```javascript
  10762. * editor.execCommand( 'blockquote' );
  10763. * ```
  10764. */
  10765. /**
  10766. * 添加引用
  10767. * @command blockquote
  10768. * @method execCommand
  10769. * @param { String } cmd 命令字符串
  10770. * @param { Object } attrs 节点属性
  10771. * @example
  10772. * ```javascript
  10773. * editor.execCommand( 'blockquote',{
  10774. * style: "color: red;"
  10775. * } );
  10776. * ```
  10777. */
  10778. UE.plugins['blockquote'] = function(){
  10779. var me = this;
  10780. function getObj(editor){
  10781. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  10782. }
  10783. me.commands['blockquote'] = {
  10784. execCommand : function( cmdName, attrs ) {
  10785. var range = this.selection.getRange(),
  10786. obj = getObj(this),
  10787. blockquote = dtd.blockquote,
  10788. bookmark = range.createBookmark();
  10789. if ( obj ) {
  10790. var start = range.startContainer,
  10791. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  10792. end = range.endContainer,
  10793. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  10794. //处理一下li
  10795. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  10796. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  10797. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  10798. domUtils.remove(obj,true);
  10799. }else{
  10800. domUtils.breakParent(startBlock,obj);
  10801. }
  10802. if(startBlock !== endBlock){
  10803. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  10804. if(obj){
  10805. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  10806. obj.parentNode && domUtils.remove(obj,true);
  10807. }else{
  10808. domUtils.breakParent(endBlock,obj);
  10809. }
  10810. }
  10811. }
  10812. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  10813. for(var i=0,bi;bi=blockquotes[i++];){
  10814. if(!bi.childNodes.length){
  10815. domUtils.remove(bi);
  10816. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  10817. domUtils.remove(bi,true);
  10818. }
  10819. }
  10820. } else {
  10821. var tmpRange = range.cloneRange(),
  10822. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  10823. preNode = node,
  10824. doEnd = 1;
  10825. //调整开始
  10826. while ( 1 ) {
  10827. if ( domUtils.isBody(node) ) {
  10828. if ( preNode !== node ) {
  10829. if ( range.collapsed ) {
  10830. tmpRange.selectNode( preNode );
  10831. doEnd = 0;
  10832. } else {
  10833. tmpRange.setStartBefore( preNode );
  10834. }
  10835. }else{
  10836. tmpRange.setStart(node,0);
  10837. }
  10838. break;
  10839. }
  10840. if ( !blockquote[node.tagName] ) {
  10841. if ( range.collapsed ) {
  10842. tmpRange.selectNode( preNode );
  10843. } else{
  10844. tmpRange.setStartBefore( preNode);
  10845. }
  10846. break;
  10847. }
  10848. preNode = node;
  10849. node = node.parentNode;
  10850. }
  10851. //调整结束
  10852. if ( doEnd ) {
  10853. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  10854. while ( 1 ) {
  10855. if ( domUtils.isBody( node ) ) {
  10856. if ( preNode !== node ) {
  10857. tmpRange.setEndAfter( preNode );
  10858. } else {
  10859. tmpRange.setEnd( node, node.childNodes.length );
  10860. }
  10861. break;
  10862. }
  10863. if ( !blockquote[node.tagName] ) {
  10864. tmpRange.setEndAfter( preNode );
  10865. break;
  10866. }
  10867. preNode = node;
  10868. node = node.parentNode;
  10869. }
  10870. }
  10871. node = range.document.createElement( 'blockquote' );
  10872. domUtils.setAttributes( node, attrs );
  10873. node.appendChild( tmpRange.extractContents() );
  10874. tmpRange.insertNode( node );
  10875. //去除重复的
  10876. var childs = domUtils.getElementsByTagName(node,'blockquote');
  10877. for(var i=0,ci;ci=childs[i++];){
  10878. if(ci.parentNode){
  10879. domUtils.remove(ci,true);
  10880. }
  10881. }
  10882. }
  10883. range.moveToBookmark( bookmark ).select();
  10884. },
  10885. queryCommandState : function() {
  10886. return getObj(this) ? 1 : 0;
  10887. }
  10888. };
  10889. };
  10890. /**
  10891. * 大小写转换
  10892. * @file
  10893. * @since 1.2.6.1
  10894. */
  10895. /**
  10896. * 把选区内文本变大写,与“tolowercase”命令互斥
  10897. * @command touppercase
  10898. * @method execCommand
  10899. * @param { String } cmd 命令字符串
  10900. * @example
  10901. * ```javascript
  10902. * editor.execCommand( 'touppercase' );
  10903. * ```
  10904. */
  10905. /**
  10906. * 把选区内文本变小写,与“touppercase”命令互斥
  10907. * @command tolowercase
  10908. * @method execCommand
  10909. * @param { String } cmd 命令字符串
  10910. * @example
  10911. * ```javascript
  10912. * editor.execCommand( 'tolowercase' );
  10913. * ```
  10914. */
  10915. UE.commands['touppercase'] =
  10916. UE.commands['tolowercase'] = {
  10917. execCommand:function (cmd) {
  10918. var me = this;
  10919. var rng = me.selection.getRange();
  10920. if(rng.collapsed){
  10921. return rng;
  10922. }
  10923. var bk = rng.createBookmark(),
  10924. bkEnd = bk.end,
  10925. filterFn = function( node ) {
  10926. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  10927. },
  10928. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  10929. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  10930. if ( curNode.nodeType == 3 ) {
  10931. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  10932. }
  10933. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  10934. if(curNode === bkEnd){
  10935. break;
  10936. }
  10937. }
  10938. rng.moveToBookmark(bk).select();
  10939. }
  10940. };
  10941. /**
  10942. * 首行缩进
  10943. * @file
  10944. * @since 1.2.6.1
  10945. */
  10946. /**
  10947. * 缩进
  10948. * @command indent
  10949. * @method execCommand
  10950. * @param { String } cmd 命令字符串
  10951. * @example
  10952. * ```javascript
  10953. * editor.execCommand( 'indent' );
  10954. * ```
  10955. */
  10956. UE.commands['indent'] = {
  10957. execCommand : function() {
  10958. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  10959. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  10960. },
  10961. queryCommandState : function() {
  10962. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  10963. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  10964. }
  10965. };
  10966. /**
  10967. * 打印
  10968. * @file
  10969. * @since 1.2.6.1
  10970. */
  10971. /**
  10972. * 打印
  10973. * @command print
  10974. * @method execCommand
  10975. * @param { String } cmd 命令字符串
  10976. * @example
  10977. * ```javascript
  10978. * editor.execCommand( 'print' );
  10979. * ```
  10980. */
  10981. UE.commands['print'] = {
  10982. execCommand : function(){
  10983. this.window.print();
  10984. },
  10985. notNeedUndo : 1
  10986. };
  10987. /**
  10988. * 全选
  10989. * @file
  10990. * @since 1.2.6.1
  10991. */
  10992. /**
  10993. * 选中所有内容
  10994. * @command selectall
  10995. * @method execCommand
  10996. * @param { String } cmd 命令字符串
  10997. * @example
  10998. * ```javascript
  10999. * editor.execCommand( 'selectall' );
  11000. * ```
  11001. */
  11002. UE.plugins['selectall'] = function(){
  11003. var me = this;
  11004. me.commands['selectall'] = {
  11005. execCommand : function(){
  11006. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11007. var me = this,body = me.body,
  11008. range = me.selection.getRange();
  11009. range.selectNodeContents(body);
  11010. if(domUtils.isEmptyBlock(body)){
  11011. //opera不能自动合并到元素的里边,要手动处理一下
  11012. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11013. range.setStartAtFirst(body.firstChild);
  11014. }
  11015. range.collapse(true);
  11016. }
  11017. range.select(true);
  11018. },
  11019. notNeedUndo : 1
  11020. };
  11021. //快捷键
  11022. me.addshortcutkey({
  11023. "selectAll" : "ctrl+65"
  11024. });
  11025. };
  11026. /**
  11027. * 段落样式
  11028. * @file
  11029. * @since 1.2.6.1
  11030. */
  11031. /**
  11032. * 段落格式
  11033. * @command paragraph
  11034. * @method execCommand
  11035. * @param { String } cmd 命令字符串
  11036. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11037. * @param {Object} attrs 标签的属性
  11038. * @example
  11039. * ```javascript
  11040. * editor.execCommand( 'Paragraph','h1','{
  11041. * class:'test'
  11042. * }' );
  11043. * ```
  11044. */
  11045. /**
  11046. * 返回选区内节点标签名
  11047. * @command paragraph
  11048. * @method queryCommandValue
  11049. * @param { String } cmd 命令字符串
  11050. * @return { String } 节点标签名
  11051. * @example
  11052. * ```javascript
  11053. * editor.queryCommandValue( 'Paragraph' );
  11054. * ```
  11055. */
  11056. UE.plugins['paragraph'] = function() {
  11057. var me = this,
  11058. block = domUtils.isBlockElm,
  11059. notExchange = ['TD','LI','PRE'],
  11060. doParagraph = function(range,style,attrs,sourceCmdName){
  11061. var bookmark = range.createBookmark(),
  11062. filterFn = function( node ) {
  11063. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11064. },
  11065. para;
  11066. range.enlarge( true );
  11067. var bookmark2 = range.createBookmark(),
  11068. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11069. tmpRange = range.cloneRange(),
  11070. tmpNode;
  11071. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11072. if ( current.nodeType == 3 || !block( current ) ) {
  11073. tmpRange.setStartBefore( current );
  11074. while ( current && current !== bookmark2.end && !block( current ) ) {
  11075. tmpNode = current;
  11076. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11077. return !block( node );
  11078. } );
  11079. }
  11080. tmpRange.setEndAfter( tmpNode );
  11081. para = range.document.createElement( style );
  11082. if(attrs){
  11083. domUtils.setAttributes(para,attrs);
  11084. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11085. para.style.cssText = attrs.style;
  11086. }
  11087. }
  11088. para.appendChild( tmpRange.extractContents() );
  11089. //需要内容占位
  11090. if(domUtils.isEmptyNode(para)){
  11091. domUtils.fillChar(range.document,para);
  11092. }
  11093. tmpRange.insertNode( para );
  11094. var parent = para.parentNode;
  11095. //如果para上一级是一个block元素且不是body,td就删除它
  11096. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11097. //存储dir,style
  11098. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11099. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11100. //trace:1070
  11101. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11102. //trace:1030
  11103. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11104. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11105. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11106. }
  11107. //trace:1706 选择的就是h1-6要删除
  11108. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11109. domUtils.setAttributes(parent,attrs);
  11110. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11111. parent.style.cssText = attrs.style;
  11112. }
  11113. domUtils.remove(para,true);
  11114. para = parent;
  11115. }else{
  11116. domUtils.remove( para.parentNode, true );
  11117. }
  11118. }
  11119. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11120. current = parent;
  11121. }else{
  11122. current = para;
  11123. }
  11124. current = domUtils.getNextDomNode( current, false, filterFn );
  11125. } else {
  11126. current = domUtils.getNextDomNode( current, true, filterFn );
  11127. }
  11128. }
  11129. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11130. };
  11131. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11132. me.commands['paragraph'] = {
  11133. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11134. var range = this.selection.getRange();
  11135. //闭合时单独处理
  11136. if(range.collapsed){
  11137. var txt = this.document.createTextNode('p');
  11138. range.insertNode(txt);
  11139. //去掉冗余的fillchar
  11140. if(browser.ie){
  11141. var node = txt.previousSibling;
  11142. if(node && domUtils.isWhitespace(node)){
  11143. domUtils.remove(node);
  11144. }
  11145. node = txt.nextSibling;
  11146. if(node && domUtils.isWhitespace(node)){
  11147. domUtils.remove(node);
  11148. }
  11149. }
  11150. }
  11151. range = doParagraph(range,style,attrs,sourceCmdName);
  11152. if(txt){
  11153. range.setStartBefore(txt).collapse(true);
  11154. pN = txt.parentNode;
  11155. domUtils.remove(txt);
  11156. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11157. domUtils.fillNode(this.document,pN);
  11158. }
  11159. }
  11160. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11161. var child = range.startContainer.childNodes[range.startOffset];
  11162. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11163. range.setStart(child,0).collapse(true);
  11164. }
  11165. }
  11166. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11167. range.select();
  11168. return true;
  11169. },
  11170. queryCommandValue : function() {
  11171. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11172. return node ? node.tagName.toLowerCase() : '';
  11173. }
  11174. };
  11175. };
  11176. /**
  11177. * 设置文字输入的方向的插件
  11178. * @file
  11179. * @since 1.2.6.1
  11180. */
  11181. (function() {
  11182. var block = domUtils.isBlockElm ,
  11183. getObj = function(editor){
  11184. // var startNode = editor.selection.getStart(),
  11185. // parents;
  11186. // if ( startNode ) {
  11187. // //查找所有的是block的父亲节点
  11188. // parents = domUtils.findParents( startNode, true, block, true );
  11189. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11190. // if ( ci.getAttribute( 'dir' ) ) {
  11191. // return ci;
  11192. // }
  11193. // }
  11194. // }
  11195. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n.getAttribute('dir')});
  11196. },
  11197. doDirectionality = function(range,editor,forward){
  11198. var bookmark,
  11199. filterFn = function( node ) {
  11200. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11201. },
  11202. obj = getObj( editor );
  11203. if ( obj && range.collapsed ) {
  11204. obj.setAttribute( 'dir', forward );
  11205. return range;
  11206. }
  11207. bookmark = range.createBookmark();
  11208. range.enlarge( true );
  11209. var bookmark2 = range.createBookmark(),
  11210. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11211. tmpRange = range.cloneRange(),
  11212. tmpNode;
  11213. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11214. if ( current.nodeType == 3 || !block( current ) ) {
  11215. tmpRange.setStartBefore( current );
  11216. while ( current && current !== bookmark2.end && !block( current ) ) {
  11217. tmpNode = current;
  11218. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11219. return !block( node );
  11220. } );
  11221. }
  11222. tmpRange.setEndAfter( tmpNode );
  11223. var common = tmpRange.getCommonAncestor();
  11224. if ( !domUtils.isBody( common ) && block( common ) ) {
  11225. //遍历到了block节点
  11226. common.setAttribute( 'dir', forward );
  11227. current = common;
  11228. } else {
  11229. //没有遍历到,添加一个block节点
  11230. var p = range.document.createElement( 'p' );
  11231. p.setAttribute( 'dir', forward );
  11232. var frag = tmpRange.extractContents();
  11233. p.appendChild( frag );
  11234. tmpRange.insertNode( p );
  11235. current = p;
  11236. }
  11237. current = domUtils.getNextDomNode( current, false, filterFn );
  11238. } else {
  11239. current = domUtils.getNextDomNode( current, true, filterFn );
  11240. }
  11241. }
  11242. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11243. };
  11244. /**
  11245. * 文字输入方向
  11246. * @command directionality
  11247. * @method execCommand
  11248. * @param { String } cmdName 命令字符串
  11249. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11250. * @example
  11251. * ```javascript
  11252. * editor.execCommand( 'directionality', 'ltr');
  11253. * ```
  11254. */
  11255. /**
  11256. * 查询当前选区的文字输入方向
  11257. * @command directionality
  11258. * @method queryCommandValue
  11259. * @param { String } cmdName 命令字符串
  11260. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11261. * @example
  11262. * ```javascript
  11263. * editor.queryCommandValue( 'directionality');
  11264. * ```
  11265. */
  11266. UE.commands['directionality'] = {
  11267. execCommand : function( cmdName,forward ) {
  11268. var range = this.selection.getRange();
  11269. //闭合时单独处理
  11270. if(range.collapsed){
  11271. var txt = this.document.createTextNode('d');
  11272. range.insertNode(txt);
  11273. }
  11274. doDirectionality(range,this,forward);
  11275. if(txt){
  11276. range.setStartBefore(txt).collapse(true);
  11277. domUtils.remove(txt);
  11278. }
  11279. range.select();
  11280. return true;
  11281. },
  11282. queryCommandValue : function() {
  11283. var node = getObj(this);
  11284. return node ? node.getAttribute('dir') : 'ltr';
  11285. }
  11286. };
  11287. })();
  11288. /**
  11289. * 插入分割线插件
  11290. * @file
  11291. * @since 1.2.6.1
  11292. */
  11293. /**
  11294. * 插入分割线
  11295. * @command horizontal
  11296. * @method execCommand
  11297. * @param { String } cmdName 命令字符串
  11298. * @example
  11299. * ```javascript
  11300. * editor.execCommand( 'horizontal' );
  11301. * ```
  11302. */
  11303. UE.plugins['horizontal'] = function(){
  11304. var me = this;
  11305. me.commands['horizontal'] = {
  11306. execCommand : function( cmdName ) {
  11307. var me = this;
  11308. if(me.queryCommandState(cmdName)!==-1){
  11309. me.execCommand('insertHtml','<hr>');
  11310. var range = me.selection.getRange(),
  11311. start = range.startContainer;
  11312. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  11313. var tmp;
  11314. if(tmp = start.childNodes[range.startOffset - 1]){
  11315. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  11316. if(me.options.enterTag == 'p'){
  11317. tmp = me.document.createElement('p');
  11318. range.insertNode(tmp);
  11319. range.setStart(tmp,0).setCursor();
  11320. }else{
  11321. tmp = me.document.createElement('br');
  11322. range.insertNode(tmp);
  11323. range.setStartBefore(tmp).setCursor();
  11324. }
  11325. }
  11326. }
  11327. }
  11328. return true;
  11329. }
  11330. },
  11331. //边界在table里不能加分隔线
  11332. queryCommandState : function() {
  11333. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  11334. }
  11335. };
  11336. // me.addListener('delkeyup',function(){
  11337. // var rng = this.selection.getRange();
  11338. // if(browser.ie && browser.version > 8){
  11339. // rng.txtToElmBoundary(true);
  11340. // if(domUtils.isStartInblock(rng)){
  11341. // var tmpNode = rng.startContainer;
  11342. // var pre = tmpNode.previousSibling;
  11343. // if(pre && domUtils.isTagNode(pre,'hr')){
  11344. // domUtils.remove(pre);
  11345. // rng.select();
  11346. // return;
  11347. // }
  11348. // }
  11349. // }
  11350. // if(domUtils.isBody(rng.startContainer)){
  11351. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  11352. // if(hr && hr.nodeName == 'HR'){
  11353. // var next = hr.nextSibling;
  11354. // if(next){
  11355. // rng.setStart(next,0)
  11356. // }else if(hr.previousSibling){
  11357. // rng.setStartAtLast(hr.previousSibling)
  11358. // }else{
  11359. // var p = this.document.createElement('p');
  11360. // hr.parentNode.insertBefore(p,hr);
  11361. // domUtils.fillNode(this.document,p);
  11362. // rng.setStart(p,0);
  11363. // }
  11364. // domUtils.remove(hr);
  11365. // rng.setCursor(false,true);
  11366. // }
  11367. // }
  11368. // })
  11369. me.addListener('delkeydown',function(name,evt){
  11370. var rng = this.selection.getRange();
  11371. rng.txtToElmBoundary(true);
  11372. if(domUtils.isStartInblock(rng)){
  11373. var tmpNode = rng.startContainer;
  11374. var pre = tmpNode.previousSibling;
  11375. if(pre && domUtils.isTagNode(pre,'hr')){
  11376. domUtils.remove(pre);
  11377. rng.select();
  11378. domUtils.preventDefault(evt);
  11379. return true;
  11380. }
  11381. }
  11382. })
  11383. };
  11384. /**
  11385. * 插入时间和日期
  11386. * @file
  11387. * @since 1.2.6.1
  11388. */
  11389. /**
  11390. * 插入时间,默认格式:12:59:59
  11391. * @command time
  11392. * @method execCommand
  11393. * @param { String } cmd 命令字符串
  11394. * @example
  11395. * ```javascript
  11396. * editor.execCommand( 'time');
  11397. * ```
  11398. */
  11399. /**
  11400. * 插入日期,默认格式:2013-08-30
  11401. * @command date
  11402. * @method execCommand
  11403. * @param { String } cmd 命令字符串
  11404. * @example
  11405. * ```javascript
  11406. * editor.execCommand( 'date');
  11407. * ```
  11408. */
  11409. UE.commands['time'] = UE.commands["date"] = {
  11410. execCommand : function(cmd, format){
  11411. var date = new Date;
  11412. function formatTime(date, format) {
  11413. var hh = ('0' + date.getHours()).slice(-2),
  11414. ii = ('0' + date.getMinutes()).slice(-2),
  11415. ss = ('0' + date.getSeconds()).slice(-2);
  11416. format = format || 'hh:ii:ss';
  11417. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  11418. }
  11419. function formatDate(date, format) {
  11420. var yyyy = ('000' + date.getFullYear()).slice(-4),
  11421. yy = yyyy.slice(-2),
  11422. mm = ('0' + (date.getMonth()+1)).slice(-2),
  11423. dd = ('0' + date.getDate()).slice(-2);
  11424. format = format || 'yyyy-mm-dd';
  11425. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  11426. }
  11427. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  11428. }
  11429. };
  11430. /**
  11431. * 段前段后间距插件
  11432. * @file
  11433. * @since 1.2.6.1
  11434. */
  11435. /**
  11436. * 设置段间距
  11437. * @command rowspacing
  11438. * @method execCommand
  11439. * @param { String } cmd 命令字符串
  11440. * @param { String } value 段间距的值,以px为单位
  11441. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  11442. * @example
  11443. * ```javascript
  11444. * editor.execCommand( 'rowspacing', '10', 'top' );
  11445. * ```
  11446. */
  11447. UE.plugins['rowspacing'] = function(){
  11448. var me = this;
  11449. me.setOpt({
  11450. 'rowspacingtop':['5', '10', '15', '20', '25'],
  11451. 'rowspacingbottom':['5', '10', '15', '20', '25']
  11452. });
  11453. me.commands['rowspacing'] = {
  11454. execCommand : function( cmdName,value,dir ) {
  11455. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  11456. return true;
  11457. },
  11458. queryCommandValue : function(cmdName,dir) {
  11459. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  11460. value;
  11461. //trace:1026
  11462. if(pN){
  11463. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  11464. return !value ? 0 : value;
  11465. }
  11466. return 0;
  11467. }
  11468. };
  11469. };
  11470. /**
  11471. * 设置行内间距
  11472. * @file
  11473. * @since 1.2.6.1
  11474. */
  11475. UE.plugins['lineheight'] = function(){
  11476. var me = this;
  11477. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  11478. /**
  11479. * 行距
  11480. * @command lineheight
  11481. * @method execCommand
  11482. * @param { String } cmdName 命令字符串
  11483. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  11484. * @example
  11485. * ```javascript
  11486. * editor.execCommand( 'lineheight', 1.5);
  11487. * ```
  11488. */
  11489. /**
  11490. * 查询当前选区内容的行高大小
  11491. * @command lineheight
  11492. * @method queryCommandValue
  11493. * @param { String } cmd 命令字符串
  11494. * @return { String } 返回当前行高大小
  11495. * @example
  11496. * ```javascript
  11497. * editor.queryCommandValue( 'lineheight' );
  11498. * ```
  11499. */
  11500. me.commands['lineheight'] = {
  11501. execCommand : function( cmdName,value ) {
  11502. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  11503. return true;
  11504. },
  11505. queryCommandValue : function() {
  11506. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  11507. if(pN){
  11508. var value = domUtils.getComputedStyle(pN,'line-height');
  11509. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  11510. }
  11511. }
  11512. };
  11513. };
  11514. /**
  11515. * 插入代码插件
  11516. * @file
  11517. * @since 1.2.6.1
  11518. */
  11519. UE.plugins['insertcode'] = function() {
  11520. var me = this;
  11521. me.ready(function(){
  11522. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  11523. me.document)
  11524. });
  11525. me.setOpt('insertcode',{
  11526. 'as3':'ActionScript3',
  11527. 'bash':'Bash/Shell',
  11528. 'cpp':'C/C++',
  11529. 'css':'Css',
  11530. 'cf':'CodeFunction',
  11531. 'c#':'C#',
  11532. 'delphi':'Delphi',
  11533. 'diff':'Diff',
  11534. 'erlang':'Erlang',
  11535. 'groovy':'Groovy',
  11536. 'html':'Html',
  11537. 'java':'Java',
  11538. 'jfx':'JavaFx',
  11539. 'js':'Javascript',
  11540. 'pl':'Perl',
  11541. 'php':'Php',
  11542. 'plain':'Plain Text',
  11543. 'ps':'PowerShell',
  11544. 'python':'Python',
  11545. 'ruby':'Ruby',
  11546. 'scala':'Scala',
  11547. 'sql':'Sql',
  11548. 'vb':'Vb',
  11549. 'xml':'Xml'
  11550. });
  11551. /**
  11552. * 插入代码
  11553. * @command insertcode
  11554. * @method execCommand
  11555. * @param { String } cmd 命令字符串
  11556. * @param { String } lang 插入代码的语言
  11557. * @example
  11558. * ```javascript
  11559. * editor.execCommand( 'insertcode', 'javascript' );
  11560. * ```
  11561. */
  11562. /**
  11563. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  11564. * @command insertcode
  11565. * @method queryCommandValue
  11566. * @param { String } cmd 命令字符串
  11567. * @return { String } 返回代码的语言
  11568. * @example
  11569. * ```javascript
  11570. * editor.queryCommandValue( 'insertcode' );
  11571. * ```
  11572. */
  11573. me.commands['insertcode'] = {
  11574. execCommand : function(cmd,lang){
  11575. var me = this,
  11576. rng = me.selection.getRange(),
  11577. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11578. if(pre){
  11579. pre.className = 'brush:'+lang+';toolbar:false;';
  11580. }else{
  11581. var code = '';
  11582. if(rng.collapsed){
  11583. code = browser.ie? (browser.version > 8 ? '' : '&nbsp;'):'<br/>';
  11584. }else{
  11585. var frag = rng.extractContents();
  11586. var div = me.document.createElement('div');
  11587. div.appendChild(frag);
  11588. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  11589. if(browser.ie && browser.version > 8){
  11590. if(node.type =='element'){
  11591. if(node.tagName == 'br'){
  11592. code += '\n'
  11593. }else if(!dtd.$empty[node.tagName]){
  11594. utils.each(node.children,function(cn){
  11595. if(cn.type =='element'){
  11596. if(cn.tagName == 'br'){
  11597. code += '\n'
  11598. }else if(!dtd.$empty[node.tagName]){
  11599. code += cn.innerText();
  11600. }
  11601. }else{
  11602. code += cn.data
  11603. }
  11604. })
  11605. if(!/\n$/.test(code)){
  11606. code += '\n';
  11607. }
  11608. }
  11609. }else{
  11610. code += node.data + '\n'
  11611. }
  11612. if(!node.nextSibling() && /\n$/.test(code)){
  11613. code = code.replace(/\n$/,'');
  11614. }
  11615. }else{
  11616. if(browser.ie){
  11617. if(node.type =='element'){
  11618. if(node.tagName == 'br'){
  11619. code += '<br>'
  11620. }else if(!dtd.$empty[node.tagName]){
  11621. utils.each(node.children,function(cn){
  11622. if(cn.type =='element'){
  11623. if(cn.tagName == 'br'){
  11624. code += '<br>'
  11625. }else if(!dtd.$empty[node.tagName]){
  11626. code += cn.innerText();
  11627. }
  11628. }else{
  11629. code += cn.data
  11630. }
  11631. });
  11632. if(!/br>$/.test(code)){
  11633. code += '<br>';
  11634. }
  11635. }
  11636. }else{
  11637. code += node.data + '<br>'
  11638. }
  11639. if(!node.nextSibling() && /<br>$/.test(code)){
  11640. code = code.replace(/<br>$/,'');
  11641. }
  11642. }else{
  11643. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  11644. if(!/br\/?\s*>$/.test(code)){
  11645. if(!node.nextSibling())
  11646. return;
  11647. code += '<br>'
  11648. }
  11649. }
  11650. }
  11651. });
  11652. }
  11653. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  11654. pre = me.document.getElementById('coder');
  11655. domUtils.removeAttributes(pre,'id');
  11656. var tmpNode = pre.previousSibling;
  11657. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  11658. domUtils.remove(tmpNode)
  11659. }
  11660. var rng = me.selection.getRange();
  11661. if(domUtils.isEmptyBlock(pre)){
  11662. rng.setStart(pre,0).setCursor(false,true)
  11663. }else{
  11664. rng.selectNodeContents(pre).select()
  11665. }
  11666. }
  11667. },
  11668. queryCommandValue : function(){
  11669. var path = this.selection.getStartElementPath();
  11670. var lang = '';
  11671. utils.each(path,function(node){
  11672. if(node.nodeName =='PRE'){
  11673. var match = node.className.match(/brush:([^;]+)/);
  11674. lang = match && match[1] ? match[1] : '';
  11675. return false;
  11676. }
  11677. });
  11678. return lang;
  11679. }
  11680. };
  11681. me.addInputRule(function(root){
  11682. utils.each(root.getNodesByTagName('pre'),function(pre){
  11683. var brs = pre.getNodesByTagName('br');
  11684. if(brs.length){
  11685. browser.ie && browser.version > 8 && utils.each(brs,function(br){
  11686. var txt = UE.uNode.createText('\n');
  11687. br.parentNode.insertBefore(txt,br);
  11688. br.parentNode.removeChild(br);
  11689. });
  11690. return;
  11691. }
  11692. if(browser.ie && browser.version > 8)
  11693. return;
  11694. var code = pre.innerText().split(/\n/);
  11695. pre.innerHTML('');
  11696. utils.each(code,function(c){
  11697. if(c.length){
  11698. pre.appendChild(UE.uNode.createText(c));
  11699. }
  11700. pre.appendChild(UE.uNode.createElement('br'))
  11701. })
  11702. })
  11703. });
  11704. me.addOutputRule(function(root){
  11705. utils.each(root.getNodesByTagName('pre'),function(pre){
  11706. var code = '';
  11707. utils.each(pre.children,function(n){
  11708. if(n.type == 'text'){
  11709. //在ie下文本内容有可能末尾带有\n要去掉
  11710. //trace:3396
  11711. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  11712. }else{
  11713. if(n.tagName == 'br'){
  11714. code += '\n'
  11715. }else{
  11716. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  11717. }
  11718. }
  11719. });
  11720. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  11721. })
  11722. });
  11723. //不需要判断highlight的command列表
  11724. me.notNeedCodeQuery ={
  11725. help:1,
  11726. undo:1,
  11727. redo:1,
  11728. source:1,
  11729. print:1,
  11730. searchreplace:1,
  11731. fullscreen:1,
  11732. preview:1,
  11733. insertparagraph:1,
  11734. elementpath:1,
  11735. insertcode:1,
  11736. inserthtml:1,
  11737. selectall:1
  11738. };
  11739. //将queyCommamndState重置
  11740. var orgQuery = me.queryCommandState;
  11741. me.queryCommandState = function(cmd){
  11742. var me = this;
  11743. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  11744. return -1;
  11745. }
  11746. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  11747. };
  11748. me.addListener('beforeenterkeydown',function(){
  11749. var rng = me.selection.getRange();
  11750. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11751. if(pre){
  11752. me.fireEvent('saveScene');
  11753. if(!rng.collapsed){
  11754. rng.deleteContents();
  11755. }
  11756. if(!browser.ie || browser.ie9above){
  11757. var tmpNode = me.document.createElement('br'),pre;
  11758. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  11759. var next = tmpNode.nextSibling;
  11760. if(!next && (!browser.ie || browser.version > 10)){
  11761. rng.insertNode(tmpNode.cloneNode(false));
  11762. }else{
  11763. rng.setStartAfter(tmpNode);
  11764. }
  11765. pre = tmpNode.previousSibling;
  11766. var tmp;
  11767. while(pre ){
  11768. tmp = pre;
  11769. pre = pre.previousSibling;
  11770. if(!pre || pre.nodeName == 'BR'){
  11771. pre = tmp;
  11772. break;
  11773. }
  11774. }
  11775. if(pre){
  11776. var str = '';
  11777. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  11778. str += pre.nodeValue;
  11779. pre = pre.nextSibling;
  11780. }
  11781. if(pre.nodeName != 'BR'){
  11782. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  11783. if(match && match[1]){
  11784. str += match[1]
  11785. }
  11786. }
  11787. if(str){
  11788. str = me.document.createTextNode(str);
  11789. rng.insertNode(str).setStartAfter(str);
  11790. }
  11791. }
  11792. rng.collapse(true).select(true);
  11793. }else{
  11794. if(browser.version > 8){
  11795. var txt = me.document.createTextNode('\n');
  11796. var start = rng.startContainer;
  11797. if(rng.startOffset == 0){
  11798. var preNode = start.previousSibling;
  11799. if(preNode){
  11800. rng.insertNode(txt);
  11801. var fillchar = me.document.createTextNode(' ');
  11802. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  11803. }
  11804. }else{
  11805. rng.insertNode(txt).setStartAfter(txt);
  11806. var fillchar = me.document.createTextNode(' ');
  11807. start = rng.startContainer.childNodes[rng.startOffset];
  11808. if(start && !/^\n/.test(start.nodeValue)){
  11809. rng.setStartBefore(txt)
  11810. }
  11811. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  11812. }
  11813. }else{
  11814. var tmpNode = me.document.createElement('br');
  11815. rng.insertNode(tmpNode);
  11816. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  11817. rng.setStartAfter(tmpNode);
  11818. pre = tmpNode.previousSibling;
  11819. var tmp;
  11820. while(pre ){
  11821. tmp = pre;
  11822. pre = pre.previousSibling;
  11823. if(!pre || pre.nodeName == 'BR'){
  11824. pre = tmp;
  11825. break;
  11826. }
  11827. }
  11828. if(pre){
  11829. var str = '';
  11830. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  11831. str += pre.nodeValue;
  11832. pre = pre.nextSibling;
  11833. }
  11834. if(pre.nodeName != 'BR'){
  11835. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  11836. if(match && match[1]){
  11837. str += match[1]
  11838. }
  11839. }
  11840. str = me.document.createTextNode(str);
  11841. rng.insertNode(str).setStartAfter(str);
  11842. }
  11843. rng.collapse(true).select();
  11844. }
  11845. }
  11846. me.fireEvent('saveScene');
  11847. return true;
  11848. }
  11849. });
  11850. me.addListener('tabkeydown',function(cmd,evt){
  11851. var rng = me.selection.getRange();
  11852. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11853. if(pre){
  11854. me.fireEvent('saveScene');
  11855. if(evt.shiftKey){
  11856. }else{
  11857. if(!rng.collapsed){
  11858. var bk = rng.createBookmark();
  11859. var start = bk.start.previousSibling;
  11860. while(start){
  11861. if(pre.firstChild === start && !domUtils.isBr(start)){
  11862. pre.insertBefore(me.document.createTextNode(' '),start);
  11863. break;
  11864. }
  11865. if(domUtils.isBr(start)){
  11866. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  11867. break;
  11868. }
  11869. start = start.previousSibling;
  11870. }
  11871. var end = bk.end;
  11872. start = bk.start.nextSibling;
  11873. if(pre.firstChild === bk.start){
  11874. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  11875. }
  11876. while(start && start !== end){
  11877. if(domUtils.isBr(start) && start.nextSibling){
  11878. if(start.nextSibling === end){
  11879. break;
  11880. }
  11881. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  11882. }
  11883. start = start.nextSibling;
  11884. }
  11885. rng.moveToBookmark(bk).select();
  11886. }else{
  11887. var tmpNode = me.document.createTextNode(' ');
  11888. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  11889. }
  11890. }
  11891. me.fireEvent('saveScene');
  11892. return true;
  11893. }
  11894. });
  11895. me.addListener('beforeinserthtml',function(evtName,html){
  11896. var me = this,
  11897. rng = me.selection.getRange(),
  11898. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11899. if(pre){
  11900. if(!rng.collapsed){
  11901. rng.deleteContents()
  11902. }
  11903. var htmlstr = '';
  11904. if(browser.ie && browser.version > 8){
  11905. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  11906. if(node.type =='element'){
  11907. if(node.tagName == 'br'){
  11908. htmlstr += '\n'
  11909. }else if(!dtd.$empty[node.tagName]){
  11910. utils.each(node.children,function(cn){
  11911. if(cn.type =='element'){
  11912. if(cn.tagName == 'br'){
  11913. htmlstr += '\n'
  11914. }else if(!dtd.$empty[node.tagName]){
  11915. htmlstr += cn.innerText();
  11916. }
  11917. }else{
  11918. htmlstr += cn.data
  11919. }
  11920. })
  11921. if(!/\n$/.test(htmlstr)){
  11922. htmlstr += '\n';
  11923. }
  11924. }
  11925. }else{
  11926. htmlstr += node.data + '\n'
  11927. }
  11928. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  11929. htmlstr = htmlstr.replace(/\n$/,'');
  11930. }
  11931. });
  11932. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  11933. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  11934. }else{
  11935. var frag = me.document.createDocumentFragment();
  11936. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  11937. if(node.type =='element'){
  11938. if(node.tagName == 'br'){
  11939. frag.appendChild(me.document.createElement('br'))
  11940. }else if(!dtd.$empty[node.tagName]){
  11941. utils.each(node.children,function(cn){
  11942. if(cn.type =='element'){
  11943. if(cn.tagName == 'br'){
  11944. frag.appendChild(me.document.createElement('br'))
  11945. }else if(!dtd.$empty[node.tagName]){
  11946. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  11947. }
  11948. }else{
  11949. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  11950. }
  11951. })
  11952. if(frag.lastChild.nodeName != 'BR'){
  11953. frag.appendChild(me.document.createElement('br'))
  11954. }
  11955. }
  11956. }else{
  11957. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  11958. }
  11959. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  11960. frag.removeChild(frag.lastChild)
  11961. }
  11962. });
  11963. rng.insertNode(frag).select();
  11964. }
  11965. return true;
  11966. }
  11967. });
  11968. //方向键的处理
  11969. me.addListener('keydown',function(cmd,evt){
  11970. var me = this,keyCode = evt.keyCode || evt.which;
  11971. if(keyCode == 40){
  11972. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  11973. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  11974. var last = pre.lastChild
  11975. while(last && last.nodeName == 'BR'){
  11976. last = last.previousSibling;
  11977. }
  11978. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  11979. me.execCommand('insertparagraph');
  11980. domUtils.preventDefault(evt)
  11981. }
  11982. }
  11983. }
  11984. });
  11985. //trace:3395
  11986. me.addListener('delkeydown',function(type,evt){
  11987. var rng = this.selection.getRange();
  11988. rng.txtToElmBoundary(true);
  11989. var start = rng.startContainer;
  11990. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  11991. var p = me.document.createElement('p');
  11992. domUtils.fillNode(me.document,p);
  11993. start.parentNode.insertBefore(p,start);
  11994. domUtils.remove(start);
  11995. rng.setStart(p,0).setCursor(false,true);
  11996. domUtils.preventDefault(evt);
  11997. return true;
  11998. }
  11999. })
  12000. };
  12001. /**
  12002. * 清空文档插件
  12003. * @file
  12004. * @since 1.2.6.1
  12005. */
  12006. /**
  12007. * 清空文档
  12008. * @command cleardoc
  12009. * @method execCommand
  12010. * @param { String } cmd 命令字符串
  12011. * @example
  12012. * ```javascript
  12013. * //editor 是编辑器实例
  12014. * editor.execCommand('cleardoc');
  12015. * ```
  12016. */
  12017. UE.commands['cleardoc'] = {
  12018. execCommand : function( cmdName) {
  12019. var me = this,
  12020. enterTag = me.options.enterTag,
  12021. range = me.selection.getRange();
  12022. if(enterTag == "br"){
  12023. me.body.innerHTML = "<br/>";
  12024. range.setStart(me.body,0).setCursor();
  12025. }else{
  12026. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12027. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12028. }
  12029. setTimeout(function(){
  12030. me.fireEvent("clearDoc");
  12031. },0);
  12032. }
  12033. };
  12034. /**
  12035. * 锚点插件,为UEditor提供插入锚点支持
  12036. * @file
  12037. * @since 1.2.6.1
  12038. */
  12039. UE.plugin.register('anchor', function (){
  12040. return {
  12041. bindEvents:{
  12042. 'ready':function(){
  12043. utils.cssRule('anchor',
  12044. '.anchorclass{background: url(\''
  12045. + this.options.themePath
  12046. + this.options.theme +'/images/anchor.gif\') no-repeat scroll left center transparent;border: 1px dotted #0000FF;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12047. this.document);
  12048. }
  12049. },
  12050. outputRule: function(root){
  12051. utils.each(root.getNodesByTagName('img'),function(a){
  12052. var val;
  12053. if(val = a.getAttr('anchorname')){
  12054. a.tagName = 'a';
  12055. a.setAttr({
  12056. anchorname : '',
  12057. name : val,
  12058. 'class' : ''
  12059. })
  12060. }
  12061. })
  12062. },
  12063. inputRule:function(root){
  12064. utils.each(root.getNodesByTagName('a'),function(a){
  12065. var val;
  12066. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12067. a.tagName = 'img';
  12068. a.setAttr({
  12069. anchorname :a.getAttr('name'),
  12070. 'class' : 'anchorclass'
  12071. });
  12072. a.setAttr('name')
  12073. }
  12074. })
  12075. },
  12076. commands:{
  12077. /**
  12078. * 插入锚点
  12079. * @command anchor
  12080. * @method execCommand
  12081. * @param { String } cmd 命令字符串
  12082. * @param { String } name 锚点名称字符串
  12083. * @example
  12084. * ```javascript
  12085. * //editor 是编辑器实例
  12086. * editor.execCommand('anchor', 'anchor1');
  12087. * ```
  12088. */
  12089. 'anchor':{
  12090. execCommand:function (cmd, name) {
  12091. var range = this.selection.getRange(),img = range.getClosedNode();
  12092. if (img && img.getAttribute('anchorname')) {
  12093. if (name) {
  12094. img.setAttribute('anchorname', name);
  12095. } else {
  12096. range.setStartBefore(img).setCursor();
  12097. domUtils.remove(img);
  12098. }
  12099. } else {
  12100. if (name) {
  12101. //只在选区的开始插入
  12102. var anchor = this.document.createElement('img');
  12103. range.collapse(true);
  12104. domUtils.setAttributes(anchor,{
  12105. 'anchorname':name,
  12106. 'class':'anchorclass'
  12107. });
  12108. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12109. }
  12110. }
  12111. }
  12112. }
  12113. }
  12114. }
  12115. });
  12116. ///import core
  12117. ///commands 字数统计
  12118. ///commandsName WordCount,wordCount
  12119. ///commandsTitle 字数统计
  12120. /*
  12121. * Created by JetBrains WebStorm.
  12122. * User: taoqili
  12123. * Date: 11-9-7
  12124. * Time: 下午8:18
  12125. * To change this template use File | Settings | File Templates.
  12126. */
  12127. UE.plugins['wordcount'] = function(){
  12128. var me = this;
  12129. me.setOpt('wordCount',true);
  12130. me.addListener('contentchange',function(){
  12131. me.fireEvent('wordcount');
  12132. });
  12133. var timer;
  12134. me.addListener('ready',function(){
  12135. var me = this;
  12136. domUtils.on(me.body,"keyup",function(evt){
  12137. var code = evt.keyCode||evt.which,
  12138. //忽略的按键,ctr,alt,shift,方向键
  12139. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12140. if(code in ignores) return;
  12141. clearTimeout(timer);
  12142. timer = setTimeout(function(){
  12143. me.fireEvent('wordcount');
  12144. },200)
  12145. })
  12146. });
  12147. };
  12148. /**
  12149. * 分页功能插件
  12150. * @file
  12151. * @since 1.2.6.1
  12152. */
  12153. UE.plugins['pagebreak'] = function () {
  12154. var me = this,
  12155. notBreakTags = ['td'];
  12156. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12157. function fillNode(node){
  12158. if(domUtils.isEmptyBlock(node)){
  12159. var firstChild = node.firstChild,tmpNode;
  12160. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12161. tmpNode = firstChild;
  12162. firstChild = firstChild.firstChild;
  12163. }
  12164. !tmpNode && (tmpNode = node);
  12165. domUtils.fillNode(me.document,tmpNode);
  12166. }
  12167. }
  12168. //分页符样式添加
  12169. me.ready(function(){
  12170. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12171. });
  12172. function isHr(node){
  12173. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12174. }
  12175. me.addInputRule(function(root){
  12176. root.traversal(function(node){
  12177. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12178. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12179. node.parentNode.insertBefore(hr,node);
  12180. node.parentNode.removeChild(node)
  12181. }
  12182. })
  12183. });
  12184. me.addOutputRule(function(node){
  12185. utils.each(node.getNodesByTagName('hr'),function(n){
  12186. if(n.getAttr('class') == 'pagebreak'){
  12187. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12188. n.parentNode.insertBefore(txt,n);
  12189. n.parentNode.removeChild(n);
  12190. }
  12191. })
  12192. });
  12193. /**
  12194. * 插入分页符
  12195. * @command pagebreak
  12196. * @method execCommand
  12197. * @param { String } cmd 命令字符串
  12198. * @remind 在表格中插入分页符会把表格切分成两部分
  12199. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12200. * 以便于提交数据到服务器端后处理分页。
  12201. * @example
  12202. * ```javascript
  12203. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12204. * ```
  12205. */
  12206. me.commands['pagebreak'] = {
  12207. execCommand:function () {
  12208. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12209. domUtils.setAttributes(hr,{
  12210. 'class' : 'pagebreak',
  12211. noshade:"noshade",
  12212. size:"5"
  12213. });
  12214. domUtils.unSelectable(hr);
  12215. //table单独处理
  12216. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12217. parents = [], pN;
  12218. if (node) {
  12219. switch (node.tagName) {
  12220. case 'TD':
  12221. pN = node.parentNode;
  12222. if (!pN.previousSibling) {
  12223. var table = domUtils.findParentByTagName(pN, 'table');
  12224. // var tableWrapDiv = table.parentNode;
  12225. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12226. // && tableWrapDiv.tagName == 'DIV'
  12227. // && tableWrapDiv.getAttribute('dropdrag')
  12228. // ){
  12229. // domUtils.remove(tableWrapDiv,true);
  12230. // }
  12231. table.parentNode.insertBefore(hr, table);
  12232. parents = domUtils.findParents(hr, true);
  12233. } else {
  12234. pN.parentNode.insertBefore(hr, pN);
  12235. parents = domUtils.findParents(hr);
  12236. }
  12237. pN = parents[1];
  12238. if (hr !== pN) {
  12239. domUtils.breakParent(hr, pN);
  12240. }
  12241. //table要重写绑定一下拖拽
  12242. me.fireEvent('afteradjusttable',me.document);
  12243. }
  12244. } else {
  12245. if (!range.collapsed) {
  12246. range.deleteContents();
  12247. var start = range.startContainer;
  12248. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12249. range.setStartBefore(start).collapse(true);
  12250. domUtils.remove(start);
  12251. start = range.startContainer;
  12252. }
  12253. }
  12254. range.insertNode(hr);
  12255. var pN = hr.parentNode, nextNode;
  12256. while (!domUtils.isBody(pN)) {
  12257. domUtils.breakParent(hr, pN);
  12258. nextNode = hr.nextSibling;
  12259. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12260. domUtils.remove(nextNode);
  12261. }
  12262. pN = hr.parentNode;
  12263. }
  12264. nextNode = hr.nextSibling;
  12265. var pre = hr.previousSibling;
  12266. if(isHr(pre)){
  12267. domUtils.remove(pre);
  12268. }else{
  12269. pre && fillNode(pre);
  12270. }
  12271. if(!nextNode){
  12272. var p = me.document.createElement('p');
  12273. hr.parentNode.appendChild(p);
  12274. domUtils.fillNode(me.document,p);
  12275. range.setStart(p,0).collapse(true);
  12276. }else{
  12277. if(isHr(nextNode)){
  12278. domUtils.remove(nextNode);
  12279. }else{
  12280. fillNode(nextNode);
  12281. }
  12282. range.setEndAfter(hr).collapse(false);
  12283. }
  12284. range.select(true);
  12285. }
  12286. }
  12287. };
  12288. };
  12289. ///import core
  12290. ///commands 本地图片引导上传
  12291. ///commandsName WordImage
  12292. ///commandsTitle 本地图片引导上传
  12293. ///commandsDialog dialogs\wordimage
  12294. UE.plugin.register('wordimage',function(){
  12295. var me = this,
  12296. images = [];
  12297. return {
  12298. commands : {
  12299. 'wordimage':{
  12300. execCommand:function () {
  12301. var images = domUtils.getElementsByTagName(me.body, "img");
  12302. var urlList = [];
  12303. for (var i = 0, ci; ci = images[i++];) {
  12304. var url = ci.getAttribute("word_img");
  12305. url && urlList.push(url);
  12306. }
  12307. return urlList;
  12308. },
  12309. queryCommandState:function () {
  12310. images = domUtils.getElementsByTagName(me.body, "img");
  12311. for (var i = 0, ci; ci = images[i++];) {
  12312. if (ci.getAttribute("word_img")) {
  12313. return 1;
  12314. }
  12315. }
  12316. return -1;
  12317. },
  12318. notNeedUndo:true
  12319. }
  12320. },
  12321. inputRule : function (root) {
  12322. utils.each(root.getNodesByTagName('img'), function (img) {
  12323. var attrs = img.attrs,
  12324. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  12325. opt = me.options,
  12326. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  12327. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  12328. img.setAttr({
  12329. width:attrs.width,
  12330. height:attrs.height,
  12331. alt:attrs.alt,
  12332. word_img: attrs.src,
  12333. src:src,
  12334. 'style':'background:url(' + ( flag ? opt.themePath + opt.theme + '/images/word.gif' : opt.langPath + opt.lang + '/images/localimage.png') + ') no-repeat center center;border:1px solid #ddd'
  12335. })
  12336. }
  12337. })
  12338. }
  12339. }
  12340. });
  12341. UE.plugins['dragdrop'] = function (){
  12342. var me = this;
  12343. me.ready(function(){
  12344. domUtils.on(this.body,'dragend',function(){
  12345. var rng = me.selection.getRange();
  12346. var node = rng.getClosedNode()||me.selection.getStart();
  12347. if(node && node.tagName == 'IMG'){
  12348. var pre = node.previousSibling,next;
  12349. while(next = node.nextSibling){
  12350. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  12351. domUtils.remove(next)
  12352. }else{
  12353. break;
  12354. }
  12355. }
  12356. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  12357. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  12358. pre.appendChild(node);
  12359. domUtils.moveChild(next,pre);
  12360. domUtils.remove(next);
  12361. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  12362. next.insertBefore(node,next.firstChild);
  12363. }
  12364. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  12365. domUtils.remove(pre)
  12366. }
  12367. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  12368. domUtils.remove(next)
  12369. }
  12370. rng.selectNode(node).select();
  12371. me.fireEvent('saveScene');
  12372. }
  12373. }
  12374. })
  12375. });
  12376. me.addListener('keyup', function(type, evt) {
  12377. var keyCode = evt.keyCode || evt.which;
  12378. if (keyCode == 13) {
  12379. var rng = me.selection.getRange(),node;
  12380. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  12381. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  12382. domUtils.removeStyle(node,'text-align')
  12383. }
  12384. }
  12385. }
  12386. })
  12387. };
  12388. /**
  12389. * undo redo
  12390. * @file
  12391. * @since 1.2.6.1
  12392. */
  12393. /**
  12394. * 撤销上一次执行的命令
  12395. * @command undo
  12396. * @method execCommand
  12397. * @param { String } cmd 命令字符串
  12398. * @example
  12399. * ```javascript
  12400. * editor.execCommand( 'undo' );
  12401. * ```
  12402. */
  12403. /**
  12404. * 重做上一次执行的命令
  12405. * @command redo
  12406. * @method execCommand
  12407. * @param { String } cmd 命令字符串
  12408. * @example
  12409. * ```javascript
  12410. * editor.execCommand( 'redo' );
  12411. * ```
  12412. */
  12413. UE.plugins['undo'] = function () {
  12414. var saveSceneTimer;
  12415. var me = this,
  12416. maxUndoCount = me.options.maxUndoCount || 20,
  12417. maxInputCount = me.options.maxInputCount || 20,
  12418. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  12419. var noNeedFillCharTags = {
  12420. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  12421. };
  12422. var orgState = me.options.autoClearEmptyNode;
  12423. function compareAddr(indexA, indexB) {
  12424. if (indexA.length != indexB.length)
  12425. return 0;
  12426. for (var i = 0, l = indexA.length; i < l; i++) {
  12427. if (indexA[i] != indexB[i])
  12428. return 0
  12429. }
  12430. return 1;
  12431. }
  12432. function compareRangeAddress(rngAddrA, rngAddrB) {
  12433. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  12434. return 0;
  12435. }
  12436. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  12437. return 0;
  12438. }
  12439. return 1;
  12440. }
  12441. function UndoManager() {
  12442. this.list = [];
  12443. this.index = 0;
  12444. this.hasUndo = false;
  12445. this.hasRedo = false;
  12446. this.undo = function () {
  12447. if (this.hasUndo) {
  12448. if (!this.list[this.index - 1] && this.list.length == 1) {
  12449. this.reset();
  12450. return;
  12451. }
  12452. while (this.list[this.index].content == this.list[this.index - 1].content) {
  12453. this.index--;
  12454. if (this.index == 0) {
  12455. return this.restore(0);
  12456. }
  12457. }
  12458. this.restore(--this.index);
  12459. }
  12460. };
  12461. this.redo = function () {
  12462. if (this.hasRedo) {
  12463. while (this.list[this.index].content == this.list[this.index + 1].content) {
  12464. this.index++;
  12465. if (this.index == this.list.length - 1) {
  12466. return this.restore(this.index);
  12467. }
  12468. }
  12469. this.restore(++this.index);
  12470. }
  12471. };
  12472. this.restore = function () {
  12473. var me = this.editor;
  12474. var scene = this.list[this.index];
  12475. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  12476. me.options.autoClearEmptyNode = false;
  12477. me.filterInputRule(root);
  12478. me.options.autoClearEmptyNode = orgState;
  12479. //trace:873
  12480. //去掉展位符
  12481. me.document.body.innerHTML = root.toHtml();
  12482. me.fireEvent('afterscencerestore');
  12483. //处理undo后空格不展位的问题
  12484. if (browser.ie) {
  12485. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  12486. if(domUtils.isEmptyNode(node)){
  12487. domUtils.fillNode(me.document, node);
  12488. }
  12489. })
  12490. }
  12491. try{
  12492. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  12493. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  12494. }catch(e){}
  12495. this.update();
  12496. this.clearKey();
  12497. //不能把自己reset了
  12498. me.fireEvent('reset', true);
  12499. };
  12500. this.getScene = function () {
  12501. var me = this.editor;
  12502. var rng = me.selection.getRange(),
  12503. rngAddress = rng.createAddress(false,true);
  12504. me.fireEvent('beforegetscene');
  12505. var root = UE.htmlparser(me.body.innerHTML);
  12506. me.options.autoClearEmptyNode = false;
  12507. me.filterOutputRule(root);
  12508. me.options.autoClearEmptyNode = orgState;
  12509. var cont = root.toHtml();
  12510. //trace:3461
  12511. //这个会引起回退时导致空格丢失的情况
  12512. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  12513. me.fireEvent('aftergetscene');
  12514. return {
  12515. address:rngAddress,
  12516. content:cont
  12517. }
  12518. };
  12519. this.save = function (notCompareRange,notSetCursor) {
  12520. clearTimeout(saveSceneTimer);
  12521. var currentScene = this.getScene(notSetCursor),
  12522. lastScene = this.list[this.index];
  12523. //内容相同位置相同不存
  12524. if (lastScene && lastScene.content == currentScene.content &&
  12525. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  12526. ) {
  12527. return;
  12528. }
  12529. this.list = this.list.slice(0, this.index + 1);
  12530. this.list.push(currentScene);
  12531. //如果大于最大数量了,就把最前的剔除
  12532. if (this.list.length > maxUndoCount) {
  12533. this.list.shift();
  12534. }
  12535. this.index = this.list.length - 1;
  12536. this.clearKey();
  12537. //跟新undo/redo状态
  12538. this.update();
  12539. };
  12540. this.update = function () {
  12541. this.hasRedo = !!this.list[this.index + 1];
  12542. this.hasUndo = !!this.list[this.index - 1];
  12543. };
  12544. this.reset = function () {
  12545. this.list = [];
  12546. this.index = 0;
  12547. this.hasUndo = false;
  12548. this.hasRedo = false;
  12549. this.clearKey();
  12550. };
  12551. this.clearKey = function () {
  12552. keycont = 0;
  12553. lastKeyCode = null;
  12554. };
  12555. }
  12556. me.undoManger = new UndoManager();
  12557. me.undoManger.editor = me;
  12558. function saveScene() {
  12559. this.undoManger.save();
  12560. }
  12561. me.addListener('saveScene', function () {
  12562. var args = Array.prototype.splice.call(arguments,1);
  12563. this.undoManger.save.apply(this.undoManger,args);
  12564. });
  12565. // me.addListener('beforeexeccommand', saveScene);
  12566. // me.addListener('afterexeccommand', saveScene);
  12567. me.addListener('reset', function (type, exclude) {
  12568. if (!exclude) {
  12569. this.undoManger.reset();
  12570. }
  12571. });
  12572. me.commands['redo'] = me.commands['undo'] = {
  12573. execCommand:function (cmdName) {
  12574. this.undoManger[cmdName]();
  12575. },
  12576. queryCommandState:function (cmdName) {
  12577. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  12578. },
  12579. notNeedUndo:1
  12580. };
  12581. var keys = {
  12582. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  12583. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  12584. 37:1, 38:1, 39:1, 40:1
  12585. },
  12586. keycont = 0,
  12587. lastKeyCode;
  12588. //输入法状态下不计算字符数
  12589. var inputType = false;
  12590. me.addListener('ready', function () {
  12591. domUtils.on(this.body, 'compositionstart', function () {
  12592. inputType = true;
  12593. });
  12594. domUtils.on(this.body, 'compositionend', function () {
  12595. inputType = false;
  12596. })
  12597. });
  12598. //快捷键
  12599. me.addshortcutkey({
  12600. "Undo":"ctrl+90", //undo
  12601. "Redo":"ctrl+89" //redo
  12602. });
  12603. var isCollapsed = true;
  12604. me.addListener('keydown', function (type, evt) {
  12605. var me = this;
  12606. var keyCode = evt.keyCode || evt.which;
  12607. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  12608. if (inputType)
  12609. return;
  12610. if(!me.selection.getRange().collapsed){
  12611. me.undoManger.save(false,true);
  12612. isCollapsed = false;
  12613. return;
  12614. }
  12615. if (me.undoManger.list.length == 0) {
  12616. me.undoManger.save(true);
  12617. }
  12618. clearTimeout(saveSceneTimer);
  12619. function save(cont){
  12620. if (cont.selection.getRange().collapsed)
  12621. cont.fireEvent('contentchange');
  12622. cont.undoManger.save(false,true);
  12623. cont.fireEvent('selectionchange');
  12624. }
  12625. saveSceneTimer = setTimeout(function(){
  12626. if(inputType){
  12627. var interalTimer = setInterval(function(){
  12628. if(!inputType){
  12629. save(me);
  12630. clearInterval(interalTimer)
  12631. }
  12632. },300)
  12633. return;
  12634. }
  12635. save(me);
  12636. },200);
  12637. lastKeyCode = keyCode;
  12638. keycont++;
  12639. if (keycont >= maxInputCount ) {
  12640. save(me)
  12641. }
  12642. }
  12643. });
  12644. me.addListener('keyup', function (type, evt) {
  12645. var keyCode = evt.keyCode || evt.which;
  12646. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  12647. if (inputType)
  12648. return;
  12649. if(!isCollapsed){
  12650. this.undoManger.save(false,true);
  12651. isCollapsed = true;
  12652. }
  12653. }
  12654. });
  12655. //扩展实例,添加关闭和开启命令undo
  12656. me.stopCmdUndo = function(){
  12657. me.__hasEnterExecCommand = true;
  12658. };
  12659. me.startCmdUndo = function(){
  12660. me.__hasEnterExecCommand = false;
  12661. }
  12662. };
  12663. ///import core
  12664. ///import plugins/inserthtml.js
  12665. ///import plugins/undo.js
  12666. ///import plugins/serialize.js
  12667. ///commands 粘贴
  12668. ///commandsName PastePlain
  12669. ///commandsTitle 纯文本粘贴模式
  12670. /*
  12671. ** @description 粘贴
  12672. * @author zhanyi
  12673. */
  12674. UE.plugins['paste'] = function () {
  12675. function getClipboardData(callback) {
  12676. var doc = this.document;
  12677. if (doc.getElementById('baidu_pastebin')) {
  12678. return;
  12679. }
  12680. var range = this.selection.getRange(),
  12681. bk = range.createBookmark(),
  12682. //创建剪贴的容器div
  12683. pastebin = doc.createElement('div');
  12684. pastebin.id = 'baidu_pastebin';
  12685. // Safari 要求div必须有内容,才能粘贴内容进来
  12686. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  12687. doc.body.appendChild(pastebin);
  12688. //trace:717 隐藏的span不能得到top
  12689. //bk.start.innerHTML = '&nbsp;';
  12690. bk.start.style.display = '';
  12691. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  12692. //要在现在光标平行的位置加入,否则会出现跳动的问题
  12693. domUtils.getXY(bk.start).y + 'px';
  12694. range.selectNodeContents(pastebin).select(true);
  12695. setTimeout(function () {
  12696. if (browser.webkit) {
  12697. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  12698. if (domUtils.isEmptyNode(pi)) {
  12699. domUtils.remove(pi);
  12700. } else {
  12701. pastebin = pi;
  12702. break;
  12703. }
  12704. }
  12705. }
  12706. try {
  12707. pastebin.parentNode.removeChild(pastebin);
  12708. } catch (e) {
  12709. }
  12710. range.moveToBookmark(bk).select(true);
  12711. callback(pastebin);
  12712. }, 0);
  12713. }
  12714. var me = this;
  12715. var txtContent, htmlContent, address;
  12716. function filter(div) {
  12717. var html;
  12718. if (div.firstChild) {
  12719. //去掉cut中添加的边界值
  12720. var nodes = domUtils.getElementsByTagName(div, 'span');
  12721. for (var i = 0, ni; ni = nodes[i++];) {
  12722. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  12723. domUtils.remove(ni);
  12724. }
  12725. }
  12726. if (browser.webkit) {
  12727. var brs = div.querySelectorAll('div br');
  12728. for (var i = 0, bi; bi = brs[i++];) {
  12729. var pN = bi.parentNode;
  12730. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  12731. pN.innerHTML = '<p><br/></p>';
  12732. domUtils.remove(pN);
  12733. }
  12734. }
  12735. var divs = div.querySelectorAll('#baidu_pastebin');
  12736. for (var i = 0, di; di = divs[i++];) {
  12737. var tmpP = me.document.createElement('p');
  12738. di.parentNode.insertBefore(tmpP, di);
  12739. while (di.firstChild) {
  12740. tmpP.appendChild(di.firstChild);
  12741. }
  12742. domUtils.remove(di);
  12743. }
  12744. var metas = div.querySelectorAll('meta');
  12745. for (var i = 0, ci; ci = metas[i++];) {
  12746. domUtils.remove(ci);
  12747. }
  12748. var brs = div.querySelectorAll('br');
  12749. for (i = 0; ci = brs[i++];) {
  12750. if (/^apple-/i.test(ci.className)) {
  12751. domUtils.remove(ci);
  12752. }
  12753. }
  12754. }
  12755. if (browser.gecko) {
  12756. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  12757. for (i = 0; ci = dirtyNodes[i++];) {
  12758. ci.removeAttribute('_moz_dirty');
  12759. }
  12760. }
  12761. if (!browser.ie) {
  12762. var spans = div.querySelectorAll('span.Apple-style-span');
  12763. for (var i = 0, ci; ci = spans[i++];) {
  12764. domUtils.remove(ci, true);
  12765. }
  12766. }
  12767. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  12768. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  12769. //过滤word粘贴过来的冗余属性
  12770. html = UE.filterWord(html);
  12771. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  12772. var root = UE.htmlparser(html);
  12773. //如果给了过滤规则就先进行过滤
  12774. if (me.options.filterRules) {
  12775. UE.filterNode(root, me.options.filterRules);
  12776. }
  12777. //执行默认的处理
  12778. me.filterInputRule(root);
  12779. //针对chrome的处理
  12780. if (browser.webkit) {
  12781. var br = root.lastChild();
  12782. if (br && br.type == 'element' && br.tagName == 'br') {
  12783. root.removeChild(br)
  12784. }
  12785. utils.each(me.body.querySelectorAll('div'), function (node) {
  12786. if (domUtils.isEmptyBlock(node)) {
  12787. domUtils.remove(node,true)
  12788. }
  12789. })
  12790. }
  12791. html = {'html': root.toHtml()};
  12792. me.fireEvent('beforepaste', html, root);
  12793. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  12794. if(!html.html){
  12795. return;
  12796. }
  12797. root = UE.htmlparser(html.html,true);
  12798. //如果开启了纯文本模式
  12799. if (me.queryCommandState('pasteplain') === 1) {
  12800. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  12801. } else {
  12802. //文本模式
  12803. UE.filterNode(root, me.options.filterTxtRules);
  12804. txtContent = root.toHtml();
  12805. //完全模式
  12806. htmlContent = html.html;
  12807. address = me.selection.getRange().createAddress(true);
  12808. me.execCommand('insertHtml', htmlContent, true);
  12809. }
  12810. me.fireEvent("afterpaste", html);
  12811. }
  12812. }
  12813. me.addListener('pasteTransfer', function (cmd, plainType) {
  12814. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  12815. var range = me.selection.getRange();
  12816. range.moveToAddress(address, true);
  12817. if (!range.collapsed) {
  12818. while (!domUtils.isBody(range.startContainer)
  12819. ) {
  12820. var start = range.startContainer;
  12821. if(start.nodeType == 1){
  12822. start = start.childNodes[range.startOffset];
  12823. if(!start){
  12824. range.setStartBefore(range.startContainer);
  12825. continue;
  12826. }
  12827. var pre = start.previousSibling;
  12828. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12829. range.setStartBefore(pre)
  12830. }
  12831. }
  12832. if(range.startOffset == 0){
  12833. range.setStartBefore(range.startContainer);
  12834. }else{
  12835. break;
  12836. }
  12837. }
  12838. while (!domUtils.isBody(range.endContainer)
  12839. ) {
  12840. var end = range.endContainer;
  12841. if(end.nodeType == 1){
  12842. end = end.childNodes[range.endOffset];
  12843. if(!end){
  12844. range.setEndAfter(range.endContainer);
  12845. continue;
  12846. }
  12847. var next = end.nextSibling;
  12848. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  12849. range.setEndAfter(next)
  12850. }
  12851. }
  12852. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  12853. range.setEndAfter(range.endContainer);
  12854. }else{
  12855. break;
  12856. }
  12857. }
  12858. }
  12859. range.deleteContents();
  12860. range.select(true);
  12861. me.__hasEnterExecCommand = true;
  12862. var html = htmlContent;
  12863. if (plainType === 2) {
  12864. html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  12865. tagName = tagName.toLowerCase();
  12866. if ({img: 1}[tagName]) {
  12867. return a;
  12868. }
  12869. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  12870. if ({
  12871. 'src': 1,
  12872. 'href': 1,
  12873. 'name': 1
  12874. }[atr.toLowerCase()]) {
  12875. return atr + '=' + val + ' '
  12876. }
  12877. return ''
  12878. });
  12879. if ({
  12880. 'span': 1,
  12881. 'div': 1
  12882. }[tagName]) {
  12883. return ''
  12884. } else {
  12885. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  12886. }
  12887. });
  12888. } else if (plainType) {
  12889. html = txtContent;
  12890. }
  12891. me.execCommand('inserthtml', html, true);
  12892. me.__hasEnterExecCommand = false;
  12893. var rng = me.selection.getRange();
  12894. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  12895. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  12896. ) {
  12897. rng.setStartBefore(rng.startContainer);
  12898. }
  12899. var tmpAddress = rng.createAddress(true);
  12900. address.endAddress = tmpAddress.startAddress;
  12901. }
  12902. });
  12903. me.addListener('ready', function () {
  12904. domUtils.on(me.body, 'cut', function () {
  12905. var range = me.selection.getRange();
  12906. if (!range.collapsed && me.undoManger) {
  12907. me.undoManger.save();
  12908. }
  12909. });
  12910. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  12911. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  12912. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  12913. return;
  12914. }
  12915. getClipboardData.call(me, function (div) {
  12916. filter(div);
  12917. });
  12918. });
  12919. });
  12920. };
  12921. /**
  12922. * 有序列表,无序列表插件
  12923. * @file
  12924. * @since 1.2.6.1
  12925. */
  12926. UE.plugins['list'] = function () {
  12927. var me = this,
  12928. notExchange = {
  12929. 'TD':1,
  12930. 'PRE':1,
  12931. 'BLOCKQUOTE':1
  12932. };
  12933. var customStyle = {
  12934. 'cn' : 'cn-1-',
  12935. 'cn1' : 'cn-2-',
  12936. 'cn2' : 'cn-3-',
  12937. 'num': 'num-1-',
  12938. 'num1' : 'num-2-',
  12939. 'num2' : 'num-3-',
  12940. 'dash' : 'dash',
  12941. 'dot':'dot'
  12942. };
  12943. me.setOpt( {
  12944. 'autoTransWordToList':false,
  12945. 'insertorderedlist':{
  12946. 'num':'',
  12947. 'num1':'',
  12948. 'num2':'',
  12949. 'cn':'',
  12950. 'cn1':'',
  12951. 'cn2':'',
  12952. 'decimal':'',
  12953. 'lower-alpha':'',
  12954. 'lower-roman':'',
  12955. 'upper-alpha':'',
  12956. 'upper-roman':''
  12957. },
  12958. 'insertunorderedlist':{
  12959. 'circle':'',
  12960. 'disc':'',
  12961. 'square':'',
  12962. 'dash' : '',
  12963. 'dot':''
  12964. },
  12965. listDefaultPaddingLeft : '30',
  12966. listiconpath : 'http://bs.baidu.com/listicon/',
  12967. maxListLevel : -1//-1不限制
  12968. } );
  12969. function listToArray(list){
  12970. var arr = [];
  12971. for(var p in list){
  12972. arr.push(p)
  12973. }
  12974. return arr;
  12975. }
  12976. var listStyle = {
  12977. 'OL':listToArray(me.options.insertorderedlist),
  12978. 'UL':listToArray(me.options.insertunorderedlist)
  12979. };
  12980. var liiconpath = me.options.listiconpath;
  12981. //根据用户配置,调整customStyle
  12982. for(var s in customStyle){
  12983. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  12984. delete customStyle[s];
  12985. }
  12986. }
  12987. me.ready(function () {
  12988. var customCss = [];
  12989. for(var p in customStyle){
  12990. if(p == 'dash' || p == 'dot'){
  12991. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  12992. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  12993. }else{
  12994. for(var i= 0;i<99;i++){
  12995. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  12996. }
  12997. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  12998. }
  12999. switch(p){
  13000. case 'cn':
  13001. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13002. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13003. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13004. break;
  13005. case 'cn1':
  13006. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13007. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13008. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13009. break;
  13010. case 'cn2':
  13011. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13012. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13013. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13014. break;
  13015. case 'num':
  13016. case 'num1':
  13017. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13018. break;
  13019. case 'num2':
  13020. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13021. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13022. break;
  13023. case 'dash':
  13024. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13025. break;
  13026. case 'dot':
  13027. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13028. }
  13029. }
  13030. customCss.push('.list-paddingleft-1{padding-left:0}');
  13031. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13032. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13033. //如果不给宽度会在自定应样式里出现滚动条
  13034. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13035. });
  13036. //单独处理剪切的问题
  13037. me.ready(function(){
  13038. domUtils.on(me.body,'cut',function(){
  13039. setTimeout(function(){
  13040. var rng = me.selection.getRange(),li;
  13041. //trace:3416
  13042. if(!rng.collapsed){
  13043. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13044. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13045. var pn = li.parentNode,node;
  13046. if(node = pn.previousSibling){
  13047. domUtils.remove(pn);
  13048. rng.setStartAtLast(node).collapse(true);
  13049. rng.select(true);
  13050. }else if(node = pn.nextSibling){
  13051. domUtils.remove(pn);
  13052. rng.setStartAtFirst(node).collapse(true);
  13053. rng.select(true);
  13054. }else{
  13055. var tmpNode = me.document.createElement('p');
  13056. domUtils.fillNode(me.document,tmpNode);
  13057. pn.parentNode.insertBefore(tmpNode,pn);
  13058. domUtils.remove(pn);
  13059. rng.setStart(tmpNode,0).collapse(true);
  13060. rng.select(true);
  13061. }
  13062. }
  13063. }
  13064. }
  13065. })
  13066. })
  13067. });
  13068. function getStyle(node){
  13069. var cls = node.className;
  13070. if(domUtils.hasClass(node,/custom_/)){
  13071. return cls.match(/custom_(\w+)/)[1]
  13072. }
  13073. return domUtils.getStyle(node, 'list-style-type')
  13074. }
  13075. me.addListener('beforepaste',function(type,html){
  13076. var me = this,
  13077. rng = me.selection.getRange(),li;
  13078. var root = UE.htmlparser(html.html,true);
  13079. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13080. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13081. utils.each(root.getNodesByTagName(tagName),function(n){
  13082. n.tagName = list.tagName;
  13083. n.setAttr();
  13084. if(n.parentNode === root){
  13085. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13086. }else{
  13087. var className = n.parentNode.getAttr('class');
  13088. if(className && /custom_/.test(className)){
  13089. type = className.match(/custom_(\w+)/)[1]
  13090. }else{
  13091. type = n.parentNode.getStyle('list-style-type');
  13092. }
  13093. if(!type){
  13094. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13095. }
  13096. }
  13097. var index = utils.indexOf(listStyle[list.tagName], type);
  13098. if(n.parentNode !== root)
  13099. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13100. var currentStyle = listStyle[list.tagName][index];
  13101. if(customStyle[currentStyle]){
  13102. n.setAttr('class', 'custom_' + currentStyle)
  13103. }else{
  13104. n.setStyle('list-style-type',currentStyle)
  13105. }
  13106. })
  13107. }
  13108. html.html = root.toHtml();
  13109. });
  13110. //进入编辑器的li要套p标签
  13111. me.addInputRule(function(root){
  13112. utils.each(root.getNodesByTagName('li'),function(li){
  13113. var tmpP = UE.uNode.createElement('p');
  13114. for(var i= 0,ci;ci=li.children[i];){
  13115. if(ci.type == 'text' || dtd.p[ci.tagName]){
  13116. tmpP.appendChild(ci);
  13117. }else{
  13118. if(tmpP.firstChild()){
  13119. li.insertBefore(tmpP,ci);
  13120. tmpP = UE.uNode.createElement('p');
  13121. i = i + 2;
  13122. }else{
  13123. i++;
  13124. }
  13125. }
  13126. }
  13127. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  13128. li.appendChild(tmpP);
  13129. }
  13130. //trace:3357
  13131. //p不能为空
  13132. if (!tmpP.firstChild()) {
  13133. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  13134. }
  13135. //去掉末尾的空白
  13136. var p = li.firstChild();
  13137. var lastChild = p.lastChild();
  13138. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  13139. p.removeChild(lastChild)
  13140. }
  13141. });
  13142. if(me.options.autoTransWordToList){
  13143. var orderlisttype = {
  13144. 'num1':/^\d+\)/,
  13145. 'decimal':/^\d+\./,
  13146. 'lower-alpha':/^[a-z]+\)/,
  13147. 'upper-alpha':/^[A-Z]+\./,
  13148. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  13149. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  13150. },
  13151. unorderlisttype = {
  13152. 'square':'n'
  13153. };
  13154. function checkListType(content,container){
  13155. var span = container.firstChild();
  13156. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  13157. for(var p in unorderlisttype){
  13158. if(unorderlisttype[p] == span.data){
  13159. return p
  13160. }
  13161. }
  13162. return 'disc'
  13163. }
  13164. for(var p in orderlisttype){
  13165. if(orderlisttype[p].test(content)){
  13166. return p;
  13167. }
  13168. }
  13169. }
  13170. utils.each(root.getNodesByTagName('p'),function(node){
  13171. if(node.getAttr('class') != 'MsoListParagraph'){
  13172. return
  13173. }
  13174. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  13175. node.setStyle('margin','');
  13176. node.setStyle('margin-left','');
  13177. node.setAttr('class','');
  13178. function appendLi(list,p,type){
  13179. if(list.tagName == 'ol'){
  13180. if(browser.ie){
  13181. var first = p.firstChild();
  13182. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  13183. p.removeChild(first);
  13184. }
  13185. }else{
  13186. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  13187. }
  13188. }else{
  13189. p.removeChild(p.firstChild())
  13190. }
  13191. var li = UE.uNode.createElement('li');
  13192. li.appendChild(p);
  13193. list.appendChild(li);
  13194. }
  13195. var tmp = node,type,cacheNode = node;
  13196. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  13197. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  13198. if(customStyle[type]){
  13199. list.setAttr('class','custom_'+type)
  13200. }else{
  13201. list.setStyle('list-style-type',type)
  13202. }
  13203. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  13204. tmp = node.nextSibling();
  13205. if(!tmp){
  13206. node.parentNode.insertBefore(list,node)
  13207. }
  13208. appendLi(list,node,type);
  13209. node = tmp;
  13210. }
  13211. if(!list.parentNode && node && node.parentNode){
  13212. node.parentNode.insertBefore(list,node)
  13213. }
  13214. }
  13215. var span = cacheNode.firstChild();
  13216. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  13217. span.parentNode.removeChild(span)
  13218. }
  13219. })
  13220. }
  13221. });
  13222. //调整索引标签
  13223. me.addListener('contentchange',function(){
  13224. adjustListStyle(me.document)
  13225. });
  13226. function adjustListStyle(doc,ignore){
  13227. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  13228. if(!domUtils.inDoc(node,doc))
  13229. return;
  13230. var parent = node.parentNode;
  13231. if(parent.tagName == node.tagName){
  13232. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  13233. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  13234. if(nodeStyleType == parentStyleType){
  13235. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  13236. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  13237. setListStyle(node,listStyle[node.tagName][styleIndex])
  13238. }
  13239. }
  13240. var index = 0,type = 2;
  13241. if( domUtils.hasClass(node,/custom_/)){
  13242. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  13243. type = 1;
  13244. }
  13245. }else{
  13246. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  13247. type = 3;
  13248. }
  13249. }
  13250. var style = domUtils.getStyle(node, 'list-style-type');
  13251. style && (node.style.cssText = 'list-style-type:' + style);
  13252. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  13253. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  13254. li.style.cssText && (li.style.cssText = '');
  13255. if(!li.firstChild){
  13256. domUtils.remove(li);
  13257. return;
  13258. }
  13259. if(li.parentNode !== node){
  13260. return;
  13261. }
  13262. index++;
  13263. if(domUtils.hasClass(node,/custom_/) ){
  13264. var paddingLeft = 1,currentStyle = getStyle(node);
  13265. if(node.tagName == 'OL'){
  13266. if(currentStyle){
  13267. switch(currentStyle){
  13268. case 'cn' :
  13269. case 'cn1':
  13270. case 'cn2':
  13271. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  13272. paddingLeft = 2
  13273. }else if(index > 20){
  13274. paddingLeft = 3
  13275. }
  13276. break;
  13277. case 'num2' :
  13278. if(index > 9){
  13279. paddingLeft = 2
  13280. }
  13281. }
  13282. }
  13283. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  13284. }else{
  13285. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  13286. }
  13287. }else{
  13288. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  13289. }
  13290. var className = li.getAttribute('class');
  13291. if(className !== null && !className.replace(/\s/g,'')){
  13292. domUtils.removeAttributes(li,'class')
  13293. }
  13294. });
  13295. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  13296. })
  13297. }
  13298. function adjustList(list, tag, style,ignoreEmpty) {
  13299. var nextList = list.nextSibling;
  13300. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  13301. domUtils.moveChild(nextList, list);
  13302. if (nextList.childNodes.length == 0) {
  13303. domUtils.remove(nextList);
  13304. }
  13305. }
  13306. if(nextList && domUtils.isFillChar(nextList)){
  13307. domUtils.remove(nextList);
  13308. }
  13309. var preList = list.previousSibling;
  13310. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  13311. domUtils.moveChild(list, preList);
  13312. }
  13313. if(preList && domUtils.isFillChar(preList)){
  13314. domUtils.remove(preList);
  13315. }
  13316. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  13317. if(getStyle(list)){
  13318. adjustListStyle(list.ownerDocument,true)
  13319. }
  13320. }
  13321. function setListStyle(list,style){
  13322. if(customStyle[style]){
  13323. list.className = 'custom_' + style;
  13324. }
  13325. try{
  13326. domUtils.setStyle(list, 'list-style-type', style);
  13327. }catch(e){}
  13328. }
  13329. function clearEmptySibling(node) {
  13330. var tmpNode = node.previousSibling;
  13331. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  13332. domUtils.remove(tmpNode);
  13333. }
  13334. tmpNode = node.nextSibling;
  13335. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  13336. domUtils.remove(tmpNode);
  13337. }
  13338. }
  13339. me.addListener('keydown', function (type, evt) {
  13340. function preventAndSave() {
  13341. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  13342. me.fireEvent('contentchange');
  13343. me.undoManger && me.undoManger.save();
  13344. }
  13345. function findList(node,filterFn){
  13346. while(node && !domUtils.isBody(node)){
  13347. if(filterFn(node)){
  13348. return null
  13349. }
  13350. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  13351. return node;
  13352. }
  13353. node = node.parentNode;
  13354. }
  13355. return null;
  13356. }
  13357. var keyCode = evt.keyCode || evt.which;
  13358. if (keyCode == 13 && !evt.shiftKey) {//回车
  13359. var rng = me.selection.getRange(),
  13360. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  13361. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  13362. if(parent && parent.tagName != 'PRE' && !li){
  13363. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  13364. if(/^\s*1\s*\.[^\d]/.test(html)){
  13365. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  13366. rng.setStartAtLast(parent).collapse(true).select();
  13367. me.__hasEnterExecCommand = true;
  13368. me.execCommand('insertorderedlist');
  13369. me.__hasEnterExecCommand = false;
  13370. }
  13371. }
  13372. var range = me.selection.getRange(),
  13373. start = findList(range.startContainer,function (node) {
  13374. return node.tagName == 'TABLE';
  13375. }),
  13376. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  13377. return node.tagName == 'TABLE';
  13378. });
  13379. if (start && end && start === end) {
  13380. if (!range.collapsed) {
  13381. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13382. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  13383. if (start && end && start === end) {
  13384. range.deleteContents();
  13385. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13386. if (li && domUtils.isEmptyBlock(li)) {
  13387. pre = li.previousSibling;
  13388. next = li.nextSibling;
  13389. p = me.document.createElement('p');
  13390. domUtils.fillNode(me.document, p);
  13391. parentList = li.parentNode;
  13392. if (pre && next) {
  13393. range.setStart(next, 0).collapse(true).select(true);
  13394. domUtils.remove(li);
  13395. } else {
  13396. if (!pre && !next || !pre) {
  13397. parentList.parentNode.insertBefore(p, parentList);
  13398. } else {
  13399. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  13400. }
  13401. domUtils.remove(li);
  13402. if (!parentList.firstChild) {
  13403. domUtils.remove(parentList);
  13404. }
  13405. range.setStart(p, 0).setCursor();
  13406. }
  13407. preventAndSave();
  13408. return;
  13409. }
  13410. } else {
  13411. var tmpRange = range.cloneRange(),
  13412. bk = tmpRange.collapse(false).createBookmark();
  13413. range.deleteContents();
  13414. tmpRange.moveToBookmark(bk);
  13415. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  13416. clearEmptySibling(li);
  13417. tmpRange.select();
  13418. preventAndSave();
  13419. return;
  13420. }
  13421. }
  13422. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13423. if (li) {
  13424. if (domUtils.isEmptyBlock(li)) {
  13425. bk = range.createBookmark();
  13426. var parentList = li.parentNode;
  13427. if (li !== parentList.lastChild) {
  13428. domUtils.breakParent(li, parentList);
  13429. clearEmptySibling(li);
  13430. } else {
  13431. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  13432. if (domUtils.isEmptyNode(parentList)) {
  13433. domUtils.remove(parentList);
  13434. }
  13435. }
  13436. //嵌套不处理
  13437. if (!dtd.$list[li.parentNode.tagName]) {
  13438. if (!domUtils.isBlockElm(li.firstChild)) {
  13439. p = me.document.createElement('p');
  13440. li.parentNode.insertBefore(p, li);
  13441. while (li.firstChild) {
  13442. p.appendChild(li.firstChild);
  13443. }
  13444. domUtils.remove(li);
  13445. } else {
  13446. domUtils.remove(li, true);
  13447. }
  13448. }
  13449. range.moveToBookmark(bk).select();
  13450. } else {
  13451. var first = li.firstChild;
  13452. if (!first || !domUtils.isBlockElm(first)) {
  13453. var p = me.document.createElement('p');
  13454. !li.firstChild && domUtils.fillNode(me.document, p);
  13455. while (li.firstChild) {
  13456. p.appendChild(li.firstChild);
  13457. }
  13458. li.appendChild(p);
  13459. first = p;
  13460. }
  13461. var span = me.document.createElement('span');
  13462. range.insertNode(span);
  13463. domUtils.breakParent(span, li);
  13464. var nextLi = span.nextSibling;
  13465. first = nextLi.firstChild;
  13466. if (!first) {
  13467. p = me.document.createElement('p');
  13468. domUtils.fillNode(me.document, p);
  13469. nextLi.appendChild(p);
  13470. first = p;
  13471. }
  13472. if (domUtils.isEmptyNode(first)) {
  13473. first.innerHTML = '';
  13474. domUtils.fillNode(me.document, first);
  13475. }
  13476. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  13477. domUtils.remove(span);
  13478. var pre = nextLi.previousSibling;
  13479. if (pre && domUtils.isEmptyBlock(pre)) {
  13480. pre.innerHTML = '<p></p>';
  13481. domUtils.fillNode(me.document, pre.firstChild);
  13482. }
  13483. }
  13484. // }
  13485. preventAndSave();
  13486. }
  13487. }
  13488. }
  13489. if (keyCode == 8) {
  13490. //修中ie中li下的问题
  13491. range = me.selection.getRange();
  13492. if (range.collapsed && domUtils.isStartInblock(range)) {
  13493. tmpRange = range.cloneRange().trimBoundary();
  13494. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13495. //要在li的最左边,才能处理
  13496. if (li && domUtils.isStartInblock(tmpRange)) {
  13497. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  13498. if (start && start !== li.firstChild) {
  13499. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  13500. domUtils.breakParent(start,parentList);
  13501. clearEmptySibling(start);
  13502. me.fireEvent('contentchange');
  13503. range.setStart(start,0).setCursor(false,true);
  13504. me.fireEvent('saveScene');
  13505. domUtils.preventDefault(evt);
  13506. return;
  13507. }
  13508. if (li && (pre = li.previousSibling)) {
  13509. if (keyCode == 46 && li.childNodes.length) {
  13510. return;
  13511. }
  13512. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  13513. if (dtd.$list[pre.tagName]) {
  13514. pre = pre.lastChild;
  13515. }
  13516. me.undoManger && me.undoManger.save();
  13517. first = li.firstChild;
  13518. if (domUtils.isBlockElm(first)) {
  13519. if (domUtils.isEmptyNode(first)) {
  13520. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  13521. pre.appendChild(first);
  13522. range.setStart(first, 0).setCursor(false, true);
  13523. //first不是唯一的节点
  13524. while (li.firstChild) {
  13525. pre.appendChild(li.firstChild);
  13526. }
  13527. } else {
  13528. span = me.document.createElement('span');
  13529. range.insertNode(span);
  13530. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  13531. if (domUtils.isEmptyBlock(pre)) {
  13532. pre.innerHTML = '';
  13533. }
  13534. domUtils.moveChild(li, pre);
  13535. range.setStartBefore(span).collapse(true).select(true);
  13536. domUtils.remove(span);
  13537. }
  13538. } else {
  13539. if (domUtils.isEmptyNode(li)) {
  13540. var p = me.document.createElement('p');
  13541. pre.appendChild(p);
  13542. range.setStart(p, 0).setCursor();
  13543. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  13544. } else {
  13545. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  13546. while (li.firstChild) {
  13547. pre.appendChild(li.firstChild);
  13548. }
  13549. }
  13550. }
  13551. domUtils.remove(li);
  13552. me.fireEvent('contentchange');
  13553. me.fireEvent('saveScene');
  13554. domUtils.preventDefault(evt);
  13555. return;
  13556. }
  13557. //trace:980
  13558. if (li && !li.previousSibling) {
  13559. var parentList = li.parentNode;
  13560. var bk = range.createBookmark();
  13561. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  13562. parentList.parentNode.insertBefore(li,parentList);
  13563. if(domUtils.isEmptyNode(parentList)){
  13564. domUtils.remove(parentList)
  13565. }
  13566. }else{
  13567. while(li.firstChild){
  13568. parentList.parentNode.insertBefore(li.firstChild,parentList);
  13569. }
  13570. domUtils.remove(li);
  13571. if(domUtils.isEmptyNode(parentList)){
  13572. domUtils.remove(parentList)
  13573. }
  13574. }
  13575. range.moveToBookmark(bk).setCursor(false,true);
  13576. me.fireEvent('contentchange');
  13577. me.fireEvent('saveScene');
  13578. domUtils.preventDefault(evt);
  13579. return;
  13580. }
  13581. }
  13582. }
  13583. }
  13584. });
  13585. me.addListener('keyup',function(type, evt){
  13586. var keyCode = evt.keyCode || evt.which;
  13587. if (keyCode == 8) {
  13588. var rng = me.selection.getRange(),list;
  13589. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  13590. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  13591. }
  13592. }
  13593. });
  13594. //处理tab键
  13595. me.addListener('tabkeydown',function(){
  13596. var range = me.selection.getRange();
  13597. //控制级数
  13598. function checkLevel(li){
  13599. if(me.options.maxListLevel != -1){
  13600. var level = li.parentNode,levelNum = 0;
  13601. while(/[ou]l/i.test(level.tagName)){
  13602. levelNum++;
  13603. level = level.parentNode;
  13604. }
  13605. if(levelNum >= me.options.maxListLevel){
  13606. return true;
  13607. }
  13608. }
  13609. }
  13610. //只以开始为准
  13611. //todo 后续改进
  13612. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13613. if(li){
  13614. var bk;
  13615. if(range.collapsed){
  13616. if(checkLevel(li))
  13617. return true;
  13618. var parentLi = li.parentNode,
  13619. list = me.document.createElement(parentLi.tagName),
  13620. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  13621. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13622. var currentStyle = listStyle[list.tagName][index];
  13623. setListStyle(list,currentStyle);
  13624. if(domUtils.isStartInblock(range)){
  13625. me.fireEvent('saveScene');
  13626. bk = range.createBookmark();
  13627. parentLi.insertBefore(list, li);
  13628. list.appendChild(li);
  13629. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  13630. me.fireEvent('contentchange');
  13631. range.moveToBookmark(bk).select(true);
  13632. return true;
  13633. }
  13634. }else{
  13635. me.fireEvent('saveScene');
  13636. bk = range.createBookmark();
  13637. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  13638. if(domUtils.isTagNode(ci,'ol ul')){
  13639. closeList = ci;
  13640. break;
  13641. }
  13642. }
  13643. var current = li;
  13644. if(bk.end){
  13645. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  13646. if(checkLevel(current)){
  13647. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  13648. continue;
  13649. }
  13650. var parentLi = current.parentNode,
  13651. list = me.document.createElement(parentLi.tagName),
  13652. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  13653. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13654. var currentStyle = listStyle[list.tagName][currentIndex];
  13655. setListStyle(list,currentStyle);
  13656. parentLi.insertBefore(list, current);
  13657. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  13658. li = current.nextSibling;
  13659. list.appendChild(current);
  13660. if(!li || domUtils.isTagNode(li,'ol ul')){
  13661. if(li){
  13662. while(li = li.firstChild){
  13663. if(li.tagName == 'LI'){
  13664. break;
  13665. }
  13666. }
  13667. }else{
  13668. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  13669. }
  13670. break;
  13671. }
  13672. current = li;
  13673. }
  13674. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  13675. current = li;
  13676. }
  13677. }
  13678. me.fireEvent('contentchange');
  13679. range.moveToBookmark(bk).select();
  13680. return true;
  13681. }
  13682. }
  13683. });
  13684. function getLi(start){
  13685. while(start && !domUtils.isBody(start)){
  13686. if(start.nodeName == 'TABLE'){
  13687. return null;
  13688. }
  13689. if(start.nodeName == 'LI'){
  13690. return start
  13691. }
  13692. start = start.parentNode;
  13693. }
  13694. }
  13695. /**
  13696. * 有序列表,与“insertunorderedlist”命令互斥
  13697. * @command insertorderedlist
  13698. * @method execCommand
  13699. * @param { String } command 命令字符串
  13700. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  13701. * @example
  13702. * ```javascript
  13703. * editor.execCommand( 'insertunorderedlist','decimal');
  13704. * ```
  13705. */
  13706. /**
  13707. * 查询当前选区内容是否有序列表
  13708. * @command insertorderedlist
  13709. * @method queryCommandState
  13710. * @param { String } cmd 命令字符串
  13711. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  13712. * @example
  13713. * ```javascript
  13714. * editor.queryCommandState( 'insertorderedlist' );
  13715. * ```
  13716. */
  13717. /**
  13718. * 查询当前选区内容是否有序列表
  13719. * @command insertorderedlist
  13720. * @method queryCommandValue
  13721. * @param { String } cmd 命令字符串
  13722. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  13723. * @example
  13724. * ```javascript
  13725. * editor.queryCommandValue( 'insertorderedlist' );
  13726. * ```
  13727. */
  13728. /**
  13729. * 无序列表,与“insertorderedlist”命令互斥
  13730. * @command insertunorderedlist
  13731. * @method execCommand
  13732. * @param { String } command 命令字符串
  13733. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  13734. * @example
  13735. * ```javascript
  13736. * editor.execCommand( 'insertunorderedlist','circle');
  13737. * ```
  13738. */
  13739. /**
  13740. * 查询当前是否有word文档粘贴进来的图片
  13741. * @command insertunorderedlist
  13742. * @method insertunorderedlist
  13743. * @param { String } command 命令字符串
  13744. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  13745. * @example
  13746. * ```javascript
  13747. * editor.queryCommandState( 'insertunorderedlist' );
  13748. * ```
  13749. */
  13750. /**
  13751. * 查询当前选区内容是否有序列表
  13752. * @command insertunorderedlist
  13753. * @method queryCommandValue
  13754. * @param { String } command 命令字符串
  13755. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  13756. * @example
  13757. * ```javascript
  13758. * editor.queryCommandValue( 'insertunorderedlist' );
  13759. * ```
  13760. */
  13761. me.commands['insertorderedlist'] =
  13762. me.commands['insertunorderedlist'] = {
  13763. execCommand:function (command, style) {
  13764. if (!style) {
  13765. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  13766. }
  13767. var me = this,
  13768. range = this.selection.getRange(),
  13769. filterFn = function (node) {
  13770. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  13771. },
  13772. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  13773. frag = me.document.createDocumentFragment();
  13774. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  13775. //range.shrinkBoundary();//.adjustmentBoundary();
  13776. range.adjustmentBoundary().shrinkBoundary();
  13777. var bko = range.createBookmark(true),
  13778. start = getLi(me.document.getElementById(bko.start)),
  13779. modifyStart = 0,
  13780. end = getLi(me.document.getElementById(bko.end)),
  13781. modifyEnd = 0,
  13782. startParent, endParent,
  13783. list, tmp;
  13784. if (start || end) {
  13785. start && (startParent = start.parentNode);
  13786. if (!bko.end) {
  13787. end = start;
  13788. }
  13789. end && (endParent = end.parentNode);
  13790. if (startParent === endParent) {
  13791. while (start !== end) {
  13792. tmp = start;
  13793. start = start.nextSibling;
  13794. if (!domUtils.isBlockElm(tmp.firstChild)) {
  13795. var p = me.document.createElement('p');
  13796. while (tmp.firstChild) {
  13797. p.appendChild(tmp.firstChild);
  13798. }
  13799. tmp.appendChild(p);
  13800. }
  13801. frag.appendChild(tmp);
  13802. }
  13803. tmp = me.document.createElement('span');
  13804. startParent.insertBefore(tmp, end);
  13805. if (!domUtils.isBlockElm(end.firstChild)) {
  13806. p = me.document.createElement('p');
  13807. while (end.firstChild) {
  13808. p.appendChild(end.firstChild);
  13809. }
  13810. end.appendChild(p);
  13811. }
  13812. frag.appendChild(end);
  13813. domUtils.breakParent(tmp, startParent);
  13814. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  13815. domUtils.remove(tmp.previousSibling);
  13816. }
  13817. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  13818. domUtils.remove(tmp.nextSibling)
  13819. }
  13820. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  13821. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  13822. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  13823. if(domUtils.isTagNode(ci,'ol ul')){
  13824. // 删除时,子列表不处理
  13825. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  13826. // while(li.firstChild){
  13827. // tmpFrag.appendChild(li.firstChild);
  13828. // }
  13829. //
  13830. // });
  13831. tmpFrag.appendChild(ci);
  13832. }else{
  13833. while (ci.firstChild) {
  13834. tmpFrag.appendChild(ci.firstChild);
  13835. domUtils.remove(ci);
  13836. }
  13837. }
  13838. }
  13839. tmp.parentNode.insertBefore(tmpFrag, tmp);
  13840. } else {
  13841. list = me.document.createElement(tag);
  13842. setListStyle(list,style);
  13843. list.appendChild(frag);
  13844. tmp.parentNode.insertBefore(list, tmp);
  13845. }
  13846. domUtils.remove(tmp);
  13847. list && adjustList(list, tag, style);
  13848. range.moveToBookmark(bko).select();
  13849. return;
  13850. }
  13851. //开始
  13852. if (start) {
  13853. while (start) {
  13854. tmp = start.nextSibling;
  13855. if (domUtils.isTagNode(start, 'ol ul')) {
  13856. frag.appendChild(start);
  13857. } else {
  13858. var tmpfrag = me.document.createDocumentFragment(),
  13859. hasBlock = 0;
  13860. while (start.firstChild) {
  13861. if (domUtils.isBlockElm(start.firstChild)) {
  13862. hasBlock = 1;
  13863. }
  13864. tmpfrag.appendChild(start.firstChild);
  13865. }
  13866. if (!hasBlock) {
  13867. var tmpP = me.document.createElement('p');
  13868. tmpP.appendChild(tmpfrag);
  13869. frag.appendChild(tmpP);
  13870. } else {
  13871. frag.appendChild(tmpfrag);
  13872. }
  13873. domUtils.remove(start);
  13874. }
  13875. start = tmp;
  13876. }
  13877. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  13878. if (domUtils.isEmptyNode(startParent)) {
  13879. range.setStartBefore(startParent);
  13880. domUtils.remove(startParent);
  13881. } else {
  13882. range.setStartAfter(startParent);
  13883. }
  13884. modifyStart = 1;
  13885. }
  13886. if (end && domUtils.inDoc(endParent, me.document)) {
  13887. //结束
  13888. start = endParent.firstChild;
  13889. while (start && start !== end) {
  13890. tmp = start.nextSibling;
  13891. if (domUtils.isTagNode(start, 'ol ul')) {
  13892. frag.appendChild(start);
  13893. } else {
  13894. tmpfrag = me.document.createDocumentFragment();
  13895. hasBlock = 0;
  13896. while (start.firstChild) {
  13897. if (domUtils.isBlockElm(start.firstChild)) {
  13898. hasBlock = 1;
  13899. }
  13900. tmpfrag.appendChild(start.firstChild);
  13901. }
  13902. if (!hasBlock) {
  13903. tmpP = me.document.createElement('p');
  13904. tmpP.appendChild(tmpfrag);
  13905. frag.appendChild(tmpP);
  13906. } else {
  13907. frag.appendChild(tmpfrag);
  13908. }
  13909. domUtils.remove(start);
  13910. }
  13911. start = tmp;
  13912. }
  13913. var tmpDiv = domUtils.createElement(me.document, 'div', {
  13914. 'tmpDiv':1
  13915. });
  13916. domUtils.moveChild(end, tmpDiv);
  13917. frag.appendChild(tmpDiv);
  13918. domUtils.remove(end);
  13919. endParent.parentNode.insertBefore(frag, endParent);
  13920. range.setEndBefore(endParent);
  13921. if (domUtils.isEmptyNode(endParent)) {
  13922. domUtils.remove(endParent);
  13923. }
  13924. modifyEnd = 1;
  13925. }
  13926. }
  13927. if (!modifyStart) {
  13928. range.setStartBefore(me.document.getElementById(bko.start));
  13929. }
  13930. if (bko.end && !modifyEnd) {
  13931. range.setEndAfter(me.document.getElementById(bko.end));
  13932. }
  13933. range.enlarge(true, function (node) {
  13934. return notExchange[node.tagName];
  13935. });
  13936. frag = me.document.createDocumentFragment();
  13937. var bk = range.createBookmark(),
  13938. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  13939. tmpRange = range.cloneRange(),
  13940. tmpNode,
  13941. block = domUtils.isBlockElm;
  13942. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  13943. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  13944. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  13945. while (current.firstChild) {
  13946. frag.appendChild(current.firstChild);
  13947. }
  13948. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  13949. domUtils.remove(current);
  13950. current = tmpNode;
  13951. continue;
  13952. }
  13953. tmpNode = current;
  13954. tmpRange.setStartBefore(current);
  13955. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  13956. tmpNode = current;
  13957. current = domUtils.getNextDomNode(current, false, null, function (node) {
  13958. return !notExchange[node.tagName];
  13959. });
  13960. }
  13961. if (current && block(current)) {
  13962. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  13963. if (tmp && domUtils.isBookmarkNode(tmp)) {
  13964. current = domUtils.getNextDomNode(tmp, false, filterFn);
  13965. tmpNode = tmp;
  13966. }
  13967. }
  13968. tmpRange.setEndAfter(tmpNode);
  13969. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  13970. var li = range.document.createElement('li');
  13971. li.appendChild(tmpRange.extractContents());
  13972. if(domUtils.isEmptyNode(li)){
  13973. var tmpNode = range.document.createElement('p');
  13974. while(li.firstChild){
  13975. tmpNode.appendChild(li.firstChild)
  13976. }
  13977. li.appendChild(tmpNode);
  13978. }
  13979. frag.appendChild(li);
  13980. } else {
  13981. current = domUtils.getNextDomNode(current, true, filterFn);
  13982. }
  13983. }
  13984. range.moveToBookmark(bk).collapse(true);
  13985. list = me.document.createElement(tag);
  13986. setListStyle(list,style);
  13987. list.appendChild(frag);
  13988. range.insertNode(list);
  13989. //当前list上下看能否合并
  13990. adjustList(list, tag, style);
  13991. //去掉冗余的tmpDiv
  13992. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  13993. if (ci.getAttribute('tmpDiv')) {
  13994. domUtils.remove(ci, true)
  13995. }
  13996. }
  13997. range.moveToBookmark(bko).select();
  13998. },
  13999. queryCommandState:function (command) {
  14000. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14001. var path = this.selection.getStartElementPath();
  14002. for(var i= 0,ci;ci = path[i++];){
  14003. if(ci.nodeName == 'TABLE'){
  14004. return 0
  14005. }
  14006. if(tag == ci.nodeName.toLowerCase()){
  14007. return 1
  14008. };
  14009. }
  14010. return 0;
  14011. },
  14012. queryCommandValue:function (command) {
  14013. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14014. var path = this.selection.getStartElementPath(),
  14015. node;
  14016. for(var i= 0,ci;ci = path[i++];){
  14017. if(ci.nodeName == 'TABLE'){
  14018. node = null;
  14019. break;
  14020. }
  14021. if(tag == ci.nodeName.toLowerCase()){
  14022. node = ci;
  14023. break;
  14024. };
  14025. }
  14026. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14027. }
  14028. };
  14029. };
  14030. /**
  14031. * 源码编辑插件
  14032. * @file
  14033. * @since 1.2.6.1
  14034. */
  14035. (function (){
  14036. var sourceEditors = {
  14037. textarea: function (editor, holder){
  14038. var textarea = holder.ownerDocument.createElement('textarea');
  14039. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14040. // todo: IE下只有onresize属性可用... 很纠结
  14041. if (browser.ie && browser.version < 8) {
  14042. textarea.style.width = holder.offsetWidth + 'px';
  14043. textarea.style.height = holder.offsetHeight + 'px';
  14044. holder.onresize = function (){
  14045. textarea.style.width = holder.offsetWidth + 'px';
  14046. textarea.style.height = holder.offsetHeight + 'px';
  14047. };
  14048. }
  14049. holder.appendChild(textarea);
  14050. return {
  14051. setContent: function (content){
  14052. textarea.value = content;
  14053. },
  14054. getContent: function (){
  14055. return textarea.value;
  14056. },
  14057. select: function (){
  14058. var range;
  14059. if (browser.ie) {
  14060. range = textarea.createTextRange();
  14061. range.collapse(true);
  14062. range.select();
  14063. } else {
  14064. //todo: chrome下无法设置焦点
  14065. textarea.setSelectionRange(0, 0);
  14066. textarea.focus();
  14067. }
  14068. },
  14069. dispose: function (){
  14070. holder.removeChild(textarea);
  14071. // todo
  14072. holder.onresize = null;
  14073. textarea = null;
  14074. holder = null;
  14075. }
  14076. };
  14077. },
  14078. codemirror: function (editor, holder){
  14079. var codeEditor = window.CodeMirror(holder, {
  14080. mode: "text/html",
  14081. tabMode: "indent",
  14082. lineNumbers: true,
  14083. lineWrapping:true
  14084. });
  14085. var dom = codeEditor.getWrapperElement();
  14086. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  14087. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  14088. codeEditor.refresh();
  14089. return {
  14090. getCodeMirror:function(){
  14091. return codeEditor;
  14092. },
  14093. setContent: function (content){
  14094. codeEditor.setValue(content);
  14095. },
  14096. getContent: function (){
  14097. return codeEditor.getValue();
  14098. },
  14099. select: function (){
  14100. codeEditor.focus();
  14101. },
  14102. dispose: function (){
  14103. holder.removeChild(dom);
  14104. dom = null;
  14105. codeEditor = null;
  14106. }
  14107. };
  14108. }
  14109. };
  14110. UE.plugins['source'] = function (){
  14111. var me = this;
  14112. var opt = this.options;
  14113. var sourceMode = false;
  14114. var sourceEditor;
  14115. var orgSetContent;
  14116. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  14117. me.setOpt({
  14118. sourceEditorFirst:false
  14119. });
  14120. function createSourceEditor(holder){
  14121. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  14122. }
  14123. var bakCssText;
  14124. //解决在源码模式下getContent不能得到最新的内容问题
  14125. var oldGetContent,
  14126. bakAddress;
  14127. /**
  14128. * 切换源码模式和编辑模式
  14129. * @command source
  14130. * @method execCommand
  14131. * @param { String } cmd 命令字符串
  14132. * @example
  14133. * ```javascript
  14134. * editor.execCommand( 'source');
  14135. * ```
  14136. */
  14137. /**
  14138. * 查询当前编辑区域的状态是源码模式还是可视化模式
  14139. * @command source
  14140. * @method queryCommandState
  14141. * @param { String } cmd 命令字符串
  14142. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  14143. * @example
  14144. * ```javascript
  14145. * editor.queryCommandState( 'source' );
  14146. * ```
  14147. */
  14148. me.commands['source'] = {
  14149. execCommand: function (){
  14150. sourceMode = !sourceMode;
  14151. if (sourceMode) {
  14152. bakAddress = me.selection.getRange().createAddress(false,true);
  14153. me.undoManger && me.undoManger.save(true);
  14154. if(browser.gecko){
  14155. me.body.contentEditable = false;
  14156. }
  14157. bakCssText = me.iframe.style.cssText;
  14158. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  14159. me.fireEvent('beforegetcontent');
  14160. var root = UE.htmlparser(me.body.innerHTML);
  14161. me.filterOutputRule(root);
  14162. root.traversal(function (node) {
  14163. if (node.type == 'element') {
  14164. switch (node.tagName) {
  14165. case 'td':
  14166. case 'th':
  14167. case 'caption':
  14168. if(node.children && node.children.length == 1){
  14169. if(node.firstChild().tagName == 'br' ){
  14170. node.removeChild(node.firstChild())
  14171. }
  14172. };
  14173. break;
  14174. case 'pre':
  14175. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  14176. }
  14177. }
  14178. });
  14179. me.fireEvent('aftergetcontent');
  14180. var content = root.toHtml(true);
  14181. sourceEditor = createSourceEditor(me.iframe.parentNode);
  14182. sourceEditor.setContent(content);
  14183. orgSetContent = me.setContent;
  14184. me.setContent = function(html){
  14185. //这里暂时不触发事件,防止报错
  14186. var root = UE.htmlparser(html);
  14187. me.filterInputRule(root);
  14188. html = root.toHtml();
  14189. sourceEditor.setContent(html);
  14190. };
  14191. setTimeout(function (){
  14192. sourceEditor.select();
  14193. me.addListener('fullscreenchanged', function(){
  14194. try{
  14195. sourceEditor.getCodeMirror().refresh()
  14196. }catch(e){}
  14197. });
  14198. });
  14199. //重置getContent,源码模式下取值也能是最新的数据
  14200. oldGetContent = me.getContent;
  14201. me.getContent = function (){
  14202. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  14203. };
  14204. } else {
  14205. me.iframe.style.cssText = bakCssText;
  14206. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  14207. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  14208. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  14209. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  14210. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  14211. }
  14212. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  14213. });
  14214. me.setContent = orgSetContent;
  14215. me.setContent(cont);
  14216. sourceEditor.dispose();
  14217. sourceEditor = null;
  14218. //还原getContent方法
  14219. me.getContent = oldGetContent;
  14220. var first = me.body.firstChild;
  14221. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  14222. if(!first){
  14223. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  14224. first = me.body.firstChild;
  14225. }
  14226. //要在ifm为显示时ff才能取到selection,否则报错
  14227. //这里不能比较位置了
  14228. me.undoManger && me.undoManger.save(true);
  14229. if(browser.gecko){
  14230. var input = document.createElement('input');
  14231. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  14232. document.body.appendChild(input);
  14233. me.body.contentEditable = false;
  14234. setTimeout(function(){
  14235. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  14236. input.focus();
  14237. setTimeout(function(){
  14238. me.body.contentEditable = true;
  14239. me.selection.getRange().moveToAddress(bakAddress).select(true);
  14240. domUtils.remove(input);
  14241. });
  14242. });
  14243. }else{
  14244. //ie下有可能报错,比如在代码顶头的情况
  14245. try{
  14246. me.selection.getRange().moveToAddress(bakAddress).select(true);
  14247. }catch(e){}
  14248. }
  14249. }
  14250. this.fireEvent('sourcemodechanged', sourceMode);
  14251. },
  14252. queryCommandState: function (){
  14253. return sourceMode|0;
  14254. },
  14255. notNeedUndo : 1
  14256. };
  14257. var oldQueryCommandState = me.queryCommandState;
  14258. me.queryCommandState = function (cmdName){
  14259. cmdName = cmdName.toLowerCase();
  14260. if (sourceMode) {
  14261. //源码模式下可以开启的命令
  14262. return cmdName in {
  14263. 'source' : 1,
  14264. 'fullscreen' : 1
  14265. } ? 1 : -1
  14266. }
  14267. return oldQueryCommandState.apply(this, arguments);
  14268. };
  14269. if(opt.sourceEditor == "codemirror"){
  14270. me.addListener("ready",function(){
  14271. utils.loadFile(document,{
  14272. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  14273. tag : "script",
  14274. type : "text/javascript",
  14275. defer : "defer"
  14276. },function(){
  14277. if(opt.sourceEditorFirst){
  14278. setTimeout(function(){
  14279. me.execCommand("source");
  14280. },0);
  14281. }
  14282. });
  14283. utils.loadFile(document,{
  14284. tag : "link",
  14285. rel : "stylesheet",
  14286. type : "text/css",
  14287. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  14288. });
  14289. });
  14290. }
  14291. };
  14292. })();
  14293. ///import core
  14294. ///import plugins/undo.js
  14295. ///commands 设置回车标签p或br
  14296. ///commandsName EnterKey
  14297. ///commandsTitle 设置回车标签p或br
  14298. /*
  14299. * @description 处理回车
  14300. * @author zhanyi
  14301. */
  14302. UE.plugins['enterkey'] = function() {
  14303. var hTag,
  14304. me = this,
  14305. tag = me.options.enterTag;
  14306. me.addListener('keyup', function(type, evt) {
  14307. var keyCode = evt.keyCode || evt.which;
  14308. if (keyCode == 13) {
  14309. var range = me.selection.getRange(),
  14310. start = range.startContainer,
  14311. doSave;
  14312. //修正在h1-h6里边回车后不能嵌套p的问题
  14313. if (!browser.ie) {
  14314. if (/h\d/i.test(hTag)) {
  14315. if (browser.gecko) {
  14316. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  14317. if (!h) {
  14318. me.document.execCommand('formatBlock', false, '<p>');
  14319. doSave = 1;
  14320. }
  14321. } else {
  14322. //chrome remove div
  14323. if (start.nodeType == 1) {
  14324. var tmp = me.document.createTextNode(''),div;
  14325. range.insertNode(tmp);
  14326. div = domUtils.findParentByTagName(tmp, 'div', true);
  14327. if (div) {
  14328. var p = me.document.createElement('p');
  14329. while (div.firstChild) {
  14330. p.appendChild(div.firstChild);
  14331. }
  14332. div.parentNode.insertBefore(p, div);
  14333. domUtils.remove(div);
  14334. range.setStartBefore(tmp).setCursor();
  14335. doSave = 1;
  14336. }
  14337. domUtils.remove(tmp);
  14338. }
  14339. }
  14340. if (me.undoManger && doSave) {
  14341. me.undoManger.save();
  14342. }
  14343. }
  14344. //没有站位符,会出现多行的问题
  14345. browser.opera && range.select();
  14346. }else{
  14347. me.fireEvent('saveScene',true,true)
  14348. }
  14349. }
  14350. });
  14351. me.addListener('keydown', function(type, evt) {
  14352. var keyCode = evt.keyCode || evt.which;
  14353. if (keyCode == 13) {//回车
  14354. if(me.fireEvent('beforeenterkeydown')){
  14355. domUtils.preventDefault(evt);
  14356. return;
  14357. }
  14358. me.fireEvent('saveScene',true,true);
  14359. hTag = '';
  14360. var range = me.selection.getRange();
  14361. if (!range.collapsed) {
  14362. //跨td不能删
  14363. var start = range.startContainer,
  14364. end = range.endContainer,
  14365. startTd = domUtils.findParentByTagName(start, 'td', true),
  14366. endTd = domUtils.findParentByTagName(end, 'td', true);
  14367. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  14368. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  14369. return;
  14370. }
  14371. }
  14372. if (tag == 'p') {
  14373. if (!browser.ie) {
  14374. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  14375. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  14376. //trace:2431
  14377. if (!start && !browser.opera) {
  14378. me.document.execCommand('formatBlock', false, '<p>');
  14379. if (browser.gecko) {
  14380. range = me.selection.getRange();
  14381. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14382. start && domUtils.removeDirtyAttr(start);
  14383. }
  14384. } else {
  14385. hTag = start.tagName;
  14386. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  14387. }
  14388. }
  14389. } else {
  14390. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  14391. if (!range.collapsed) {
  14392. range.deleteContents();
  14393. start = range.startContainer;
  14394. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  14395. while (start.nodeType == 1) {
  14396. if (dtd.$empty[start.tagName]) {
  14397. range.setStartBefore(start).setCursor();
  14398. if (me.undoManger) {
  14399. me.undoManger.save();
  14400. }
  14401. return false;
  14402. }
  14403. if (!start.firstChild) {
  14404. var br = range.document.createElement('br');
  14405. start.appendChild(br);
  14406. range.setStart(start, 0).setCursor();
  14407. if (me.undoManger) {
  14408. me.undoManger.save();
  14409. }
  14410. return false;
  14411. }
  14412. start = start.firstChild;
  14413. }
  14414. if (start === range.startContainer.childNodes[range.startOffset]) {
  14415. br = range.document.createElement('br');
  14416. range.insertNode(br).setCursor();
  14417. } else {
  14418. range.setStart(start, 0).setCursor();
  14419. }
  14420. } else {
  14421. br = range.document.createElement('br');
  14422. range.insertNode(br).setStartAfter(br).setCursor();
  14423. }
  14424. } else {
  14425. br = range.document.createElement('br');
  14426. range.insertNode(br);
  14427. var parent = br.parentNode;
  14428. if (parent.lastChild === br) {
  14429. br.parentNode.insertBefore(br.cloneNode(true), br);
  14430. range.setStartBefore(br);
  14431. } else {
  14432. range.setStartAfter(br);
  14433. }
  14434. range.setCursor();
  14435. }
  14436. }
  14437. }
  14438. });
  14439. };
  14440. /*
  14441. * 处理特殊键的兼容性问题
  14442. */
  14443. UE.plugins['keystrokes'] = function() {
  14444. var me = this;
  14445. var collapsed = true;
  14446. me.addListener('keydown', function(type, evt) {
  14447. var keyCode = evt.keyCode || evt.which,
  14448. rng = me.selection.getRange();
  14449. //处理全选的情况
  14450. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  14451. || keyCode >= 48 && keyCode <= 57 ||
  14452. keyCode >= 96 && keyCode <= 111 || {
  14453. 13:1,
  14454. 8:1,
  14455. 46:1
  14456. }[keyCode])
  14457. ){
  14458. var tmpNode = rng.startContainer;
  14459. if(domUtils.isFillChar(tmpNode)){
  14460. rng.setStartBefore(tmpNode)
  14461. }
  14462. tmpNode = rng.endContainer;
  14463. if(domUtils.isFillChar(tmpNode)){
  14464. rng.setEndAfter(tmpNode)
  14465. }
  14466. rng.txtToElmBoundary();
  14467. //结束边界可能放到了br的前边,要把br包含进来
  14468. // x[xxx]<br/>
  14469. if(rng.endContainer && rng.endContainer.nodeType == 1){
  14470. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  14471. if(tmpNode && domUtils.isBr(tmpNode)){
  14472. rng.setEndAfter(tmpNode);
  14473. }
  14474. }
  14475. if(rng.startOffset == 0){
  14476. tmpNode = rng.startContainer;
  14477. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  14478. tmpNode = rng.endContainer;
  14479. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  14480. me.fireEvent('saveScene');
  14481. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  14482. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  14483. me._selectionChange();
  14484. return;
  14485. }
  14486. }
  14487. }
  14488. }
  14489. //处理backspace
  14490. if (keyCode == 8) {
  14491. rng = me.selection.getRange();
  14492. collapsed = rng.collapsed;
  14493. if(me.fireEvent('delkeydown',evt)){
  14494. return;
  14495. }
  14496. var start,end;
  14497. //避免按两次删除才能生效的问题
  14498. if(rng.collapsed && rng.inFillChar()){
  14499. start = rng.startContainer;
  14500. if(domUtils.isFillChar(start)){
  14501. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  14502. domUtils.remove(start)
  14503. }else{
  14504. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  14505. rng.startOffset--;
  14506. rng.collapse(true).select(true)
  14507. }
  14508. }
  14509. //解决选中control元素不能删除的问题
  14510. if (start = rng.getClosedNode()) {
  14511. me.fireEvent('saveScene');
  14512. rng.setStartBefore(start);
  14513. domUtils.remove(start);
  14514. rng.setCursor();
  14515. me.fireEvent('saveScene');
  14516. domUtils.preventDefault(evt);
  14517. return;
  14518. }
  14519. //阻止在table上的删除
  14520. if (!browser.ie) {
  14521. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  14522. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  14523. if (start && !end || !start && end || start !== end) {
  14524. evt.preventDefault();
  14525. return;
  14526. }
  14527. }
  14528. }
  14529. //处理tab键的逻辑
  14530. if (keyCode == 9) {
  14531. //不处理以下标签
  14532. var excludeTagNameForTabKey = {
  14533. 'ol' : 1,
  14534. 'ul' : 1,
  14535. 'table':1
  14536. };
  14537. //处理组件里的tab按下事件
  14538. if(me.fireEvent('tabkeydown',evt)){
  14539. domUtils.preventDefault(evt);
  14540. return;
  14541. }
  14542. var range = me.selection.getRange();
  14543. me.fireEvent('saveScene');
  14544. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  14545. txt += tabNode;
  14546. }
  14547. var span = me.document.createElement('span');
  14548. span.innerHTML = txt + domUtils.fillChar;
  14549. if (range.collapsed) {
  14550. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  14551. } else {
  14552. var filterFn = function(node) {
  14553. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  14554. };
  14555. //普通的情况
  14556. start = domUtils.findParent(range.startContainer, filterFn,true);
  14557. end = domUtils.findParent(range.endContainer, filterFn,true);
  14558. if (start && end && start === end) {
  14559. range.deleteContents();
  14560. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  14561. } else {
  14562. var bookmark = range.createBookmark();
  14563. range.enlarge(true);
  14564. var bookmark2 = range.createBookmark(),
  14565. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  14566. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  14567. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  14568. current = domUtils.getNextDomNode(current, false, filterFn);
  14569. }
  14570. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  14571. }
  14572. }
  14573. domUtils.preventDefault(evt)
  14574. }
  14575. //trace:1634
  14576. //ff的del键在容器空的时候,也会删除
  14577. if(browser.gecko && keyCode == 46){
  14578. range = me.selection.getRange();
  14579. if(range.collapsed){
  14580. start = range.startContainer;
  14581. if(domUtils.isEmptyBlock(start)){
  14582. var parent = start.parentNode;
  14583. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  14584. start = parent;
  14585. parent = parent.parentNode;
  14586. }
  14587. if(start === parent.lastChild)
  14588. evt.preventDefault();
  14589. return;
  14590. }
  14591. }
  14592. }
  14593. });
  14594. me.addListener('keyup', function(type, evt) {
  14595. var keyCode = evt.keyCode || evt.which,
  14596. rng,me = this;
  14597. if(keyCode == 8){
  14598. if(me.fireEvent('delkeyup')){
  14599. return;
  14600. }
  14601. rng = me.selection.getRange();
  14602. if(rng.collapsed){
  14603. var tmpNode,
  14604. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  14605. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  14606. if(domUtils.isEmptyBlock(tmpNode)){
  14607. var pre = tmpNode.previousSibling;
  14608. if(pre && pre.nodeName != 'TABLE'){
  14609. domUtils.remove(tmpNode);
  14610. rng.setStartAtLast(pre).setCursor(false,true);
  14611. return;
  14612. }else{
  14613. var next = tmpNode.nextSibling;
  14614. if(next && next.nodeName != 'TABLE'){
  14615. domUtils.remove(tmpNode);
  14616. rng.setStartAtFirst(next).setCursor(false,true);
  14617. return;
  14618. }
  14619. }
  14620. }
  14621. }
  14622. //处理当删除到body时,要重新给p标签展位
  14623. if(domUtils.isBody(rng.startContainer)){
  14624. var tmpNode = domUtils.createElement(me.document,'p',{
  14625. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  14626. });
  14627. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  14628. }
  14629. }
  14630. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  14631. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  14632. if(browser.ie){
  14633. var span = rng.document.createElement('span');
  14634. rng.insertNode(span).setStartBefore(span).collapse(true);
  14635. rng.select();
  14636. domUtils.remove(span)
  14637. }else{
  14638. rng.select()
  14639. }
  14640. }
  14641. }
  14642. })
  14643. };
  14644. ///import core
  14645. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  14646. ///commandsName FixImgClick
  14647. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  14648. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  14649. UE.plugins['fiximgclick'] = (function () {
  14650. function Scale() {
  14651. this.editor = null;
  14652. this.resizer = null;
  14653. this.cover = null;
  14654. this.doc = document;
  14655. this.prePos = {x: 0, y: 0};
  14656. this.startPos = {x: 0, y: 0};
  14657. }
  14658. (function () {
  14659. var rect = [
  14660. //[left, top, width, height]
  14661. [0, 0, -1, -1],
  14662. [0, 0, 0, -1],
  14663. [0, 0, 1, -1],
  14664. [0, 0, -1, 0],
  14665. [0, 0, 1, 0],
  14666. [0, 0, -1, 1],
  14667. [0, 0, 0, 1],
  14668. [0, 0, 1, 1]
  14669. ];
  14670. Scale.prototype = {
  14671. init: function (editor) {
  14672. var me = this;
  14673. me.editor = editor;
  14674. me.startPos = this.prePos = {x: 0, y: 0};
  14675. me.dragId = -1;
  14676. var hands = [],
  14677. cover = me.cover = document.createElement('div'),
  14678. resizer = me.resizer = document.createElement('div');
  14679. cover.id = me.editor.ui.id + '_imagescale_cover';
  14680. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  14681. domUtils.on(cover, 'mousedown click', function () {
  14682. me.hide();
  14683. });
  14684. for (i = 0; i < 8; i++) {
  14685. hands.push('<span class="edui-editor-scale-hand' + i + '"></span>');
  14686. }
  14687. resizer.id = me.editor.ui.id + '_imagescale';
  14688. resizer.className = 'edui-editor-scale';
  14689. resizer.innerHTML = hands.join('');
  14690. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  14691. me.editor.ui.getDom().appendChild(cover);
  14692. me.editor.ui.getDom().appendChild(resizer);
  14693. me.initStyle();
  14694. me.initEvents();
  14695. },
  14696. initStyle: function () {
  14697. utils.cssRule('imagescale', '.edui-editor-scale{position:absolute;border:1px solid #38B2CE;}' +
  14698. '.edui-editor-scale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  14699. + '.edui-editor-scale .edui-editor-scale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  14700. + '.edui-editor-scale .edui-editor-scale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  14701. + '.edui-editor-scale .edui-editor-scale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  14702. + '.edui-editor-scale .edui-editor-scale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  14703. + '.edui-editor-scale .edui-editor-scale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  14704. + '.edui-editor-scale .edui-editor-scale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  14705. + '.edui-editor-scale .edui-editor-scale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  14706. + '.edui-editor-scale .edui-editor-scale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  14707. },
  14708. initEvents: function () {
  14709. var me = this;
  14710. me.startPos.x = me.startPos.y = 0;
  14711. me.isDraging = false;
  14712. },
  14713. _eventHandler: function (e) {
  14714. var me = this;
  14715. switch (e.type) {
  14716. case 'mousedown':
  14717. var hand = e.target || e.srcElement, hand;
  14718. if (hand.className.indexOf('edui-editor-scale-hand') != -1 && me.dragId == -1) {
  14719. me.dragId = hand.className.slice(-1);
  14720. me.startPos.x = me.prePos.x = e.clientX;
  14721. me.startPos.y = me.prePos.y = e.clientY;
  14722. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  14723. }
  14724. break;
  14725. case 'mousemove':
  14726. if (me.dragId != -1) {
  14727. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  14728. me.prePos.x = e.clientX;
  14729. me.prePos.y = e.clientY;
  14730. me.updateTargetElement();
  14731. }
  14732. break;
  14733. case 'mouseup':
  14734. if (me.dragId != -1) {
  14735. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  14736. me.updateTargetElement();
  14737. if (me.target.parentNode) me.attachTo(me.target);
  14738. me.dragId = -1;
  14739. }
  14740. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  14741. me.editor.fireEvent('contentchange');
  14742. break;
  14743. default:
  14744. break;
  14745. }
  14746. },
  14747. updateTargetElement: function () {
  14748. var me = this,
  14749. targetPos;
  14750. domUtils.setStyles(me.target, {
  14751. 'width': me.resizer.style.width,
  14752. 'height': me.resizer.style.height
  14753. });
  14754. me.attachTo(me.target);
  14755. },
  14756. updateContainerStyle: function (dir, offset) {
  14757. var me = this,
  14758. dom = me.resizer, tmp;
  14759. if (rect[dir][0] != 0) {
  14760. tmp = parseInt(dom.style.left) + offset.x;
  14761. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  14762. }
  14763. if (rect[dir][1] != 0) {
  14764. tmp = parseInt(dom.style.top) + offset.y;
  14765. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  14766. }
  14767. if (rect[dir][2] != 0) {
  14768. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  14769. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  14770. }
  14771. if (rect[dir][3] != 0) {
  14772. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  14773. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  14774. }
  14775. },
  14776. _validScaledProp: function (prop, value) {
  14777. var ele = this.resizer,
  14778. wrap = document;
  14779. value = isNaN(value) ? 0 : value;
  14780. switch (prop) {
  14781. case 'left':
  14782. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  14783. case 'top':
  14784. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  14785. case 'width':
  14786. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  14787. case 'height':
  14788. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  14789. }
  14790. },
  14791. hideCover: function () {
  14792. this.cover.style.display = 'none';
  14793. },
  14794. showCover: function () {
  14795. var me = this,
  14796. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  14797. iframePos = domUtils.getXY(me.editor.iframe);
  14798. domUtils.setStyles(me.cover, {
  14799. 'width': me.editor.iframe.offsetWidth + 'px',
  14800. 'height': me.editor.iframe.offsetHeight + 'px',
  14801. 'top': iframePos.y - editorPos.y + 'px',
  14802. 'left': iframePos.x - editorPos.x + 'px',
  14803. 'position': 'absolute',
  14804. 'display': ''
  14805. })
  14806. },
  14807. show: function (targetObj) {
  14808. var me = this;
  14809. me.resizer.style.display = 'block';
  14810. if(targetObj) me.attachTo(targetObj);
  14811. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  14812. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  14813. me.showCover();
  14814. me.editor.fireEvent('afterscaleshow', me);
  14815. me.editor.fireEvent('saveScene');
  14816. },
  14817. hide: function () {
  14818. var me = this;
  14819. me.hideCover();
  14820. me.resizer.style.display = 'none';
  14821. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  14822. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  14823. me.editor.fireEvent('afterscalehide', me);
  14824. },
  14825. proxy: function( fn, context ) {
  14826. return function(e) {
  14827. return fn.apply( context || this, arguments);
  14828. };
  14829. },
  14830. attachTo: function (targetObj) {
  14831. var me = this,
  14832. target = me.target = targetObj,
  14833. resizer = this.resizer,
  14834. imgPos = domUtils.getXY(target),
  14835. iframePos = domUtils.getXY(me.editor.iframe),
  14836. editorPos = domUtils.getXY(resizer.parentNode);
  14837. domUtils.setStyles(resizer, {
  14838. 'width': target.width + 'px',
  14839. 'height': target.height + 'px',
  14840. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  14841. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  14842. });
  14843. }
  14844. }
  14845. })();
  14846. return function () {
  14847. var me = this,
  14848. imageScale;
  14849. me.setOpt('imageScaleEnabled', true);
  14850. if ( !browser.ie && me.options.imageScaleEnabled) {
  14851. me.addListener('click', function (type, e) {
  14852. var range = me.selection.getRange(),
  14853. img = range.getClosedNode();
  14854. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  14855. if (!imageScale) {
  14856. imageScale = new Scale();
  14857. imageScale.init(me);
  14858. me.ui.getDom().appendChild(imageScale.resizer);
  14859. var _keyDownHandler = function (e) {
  14860. imageScale.hide();
  14861. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  14862. }, _mouseDownHandler = function (e) {
  14863. var ele = e.target || e.srcElement;
  14864. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-scale') == -1)) {
  14865. _keyDownHandler(e);
  14866. }
  14867. }, timer;
  14868. me.addListener('afterscaleshow', function (e) {
  14869. me.addListener('beforekeydown', _keyDownHandler);
  14870. me.addListener('beforemousedown', _mouseDownHandler);
  14871. domUtils.on(document, 'keydown', _keyDownHandler);
  14872. domUtils.on(document,'mousedown', _mouseDownHandler);
  14873. me.selection.getNative().removeAllRanges();
  14874. });
  14875. me.addListener('afterscalehide', function (e) {
  14876. me.removeListener('beforekeydown', _keyDownHandler);
  14877. me.removeListener('beforemousedown', _mouseDownHandler);
  14878. domUtils.un(document, 'keydown', _keyDownHandler);
  14879. domUtils.un(document,'mousedown', _mouseDownHandler);
  14880. var target = imageScale.target;
  14881. if (target.parentNode) {
  14882. me.selection.getRange().selectNode(target).select();
  14883. }
  14884. });
  14885. //TODO 有iframe的情况,mousedown不能往下传。。
  14886. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  14887. me.selection.getNative().removeAllRanges();
  14888. var ele = e.target || e.srcElement;
  14889. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  14890. timer = setTimeout(function () {
  14891. imageScale.hide();
  14892. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  14893. }, 200);
  14894. }
  14895. });
  14896. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  14897. var ele = e.target || e.srcElement;
  14898. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  14899. clearTimeout(timer);
  14900. }
  14901. });
  14902. }
  14903. imageScale.show(img);
  14904. } else {
  14905. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  14906. }
  14907. });
  14908. }
  14909. if (browser.webkit) {
  14910. me.addListener('click', function (type, e) {
  14911. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  14912. var range = new dom.Range(me.document);
  14913. range.selectNode(e.target).select();
  14914. }
  14915. });
  14916. }
  14917. }
  14918. })();
  14919. ///import core
  14920. ///commands 为非ie浏览器自动添加a标签
  14921. ///commandsName AutoLink
  14922. ///commandsTitle 自动增加链接
  14923. /*
  14924. * @description 为非ie浏览器自动添加a标签
  14925. * @author zhanyi
  14926. */
  14927. UE.plugin.register('autolink',function(){
  14928. var cont = 0;
  14929. return !browser.ie ? {
  14930. bindEvents:{
  14931. 'reset' : function(){
  14932. cont = 0;
  14933. },
  14934. 'keydown':function(type, evt) {
  14935. var me = this;
  14936. var keyCode = evt.keyCode || evt.which;
  14937. if (keyCode == 32 || keyCode == 13) {
  14938. var sel = me.selection.getNative(),
  14939. range = sel.getRangeAt(0).cloneRange(),
  14940. offset,
  14941. charCode;
  14942. var start = range.startContainer;
  14943. while (start.nodeType == 1 && range.startOffset > 0) {
  14944. start = range.startContainer.childNodes[range.startOffset - 1];
  14945. if (!start){
  14946. break;
  14947. }
  14948. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  14949. range.collapse(true);
  14950. start = range.startContainer;
  14951. }
  14952. do{
  14953. if (range.startOffset == 0) {
  14954. start = range.startContainer.previousSibling;
  14955. while (start && start.nodeType == 1) {
  14956. start = start.lastChild;
  14957. }
  14958. if (!start || domUtils.isFillChar(start)){
  14959. break;
  14960. }
  14961. offset = start.nodeValue.length;
  14962. } else {
  14963. start = range.startContainer;
  14964. offset = range.startOffset;
  14965. }
  14966. range.setStart(start, offset - 1);
  14967. charCode = range.toString().charCodeAt(0);
  14968. } while (charCode != 160 && charCode != 32);
  14969. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  14970. while(range.toString().length){
  14971. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  14972. break;
  14973. }
  14974. try{
  14975. range.setStart(range.startContainer,range.startOffset+1);
  14976. }catch(e){
  14977. //trace:2121
  14978. var start = range.startContainer;
  14979. while(!(next = start.nextSibling)){
  14980. if(domUtils.isBody(start)){
  14981. return;
  14982. }
  14983. start = start.parentNode;
  14984. }
  14985. range.setStart(next,0);
  14986. }
  14987. }
  14988. //range的开始边界已经在a标签里的不再处理
  14989. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  14990. return;
  14991. }
  14992. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  14993. me.undoManger && me.undoManger.save();
  14994. a.appendChild(range.extractContents());
  14995. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  14996. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  14997. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  14998. a.setAttribute('_src',utils.html(href));
  14999. a.href = utils.html(href);
  15000. range.insertNode(a);
  15001. a.parentNode.insertBefore(text, a.nextSibling);
  15002. range.setStart(text, 0);
  15003. range.collapse(true);
  15004. sel.removeAllRanges();
  15005. sel.addRange(range);
  15006. me.undoManger && me.undoManger.save();
  15007. }
  15008. }
  15009. }
  15010. }
  15011. }:{}
  15012. },function(){
  15013. var keyCodes = {
  15014. 37:1, 38:1, 39:1, 40:1,
  15015. 13:1,32:1
  15016. };
  15017. function checkIsCludeLink(node){
  15018. if(node.nodeType == 3){
  15019. return null
  15020. }
  15021. if(node.nodeName == 'A'){
  15022. return node;
  15023. }
  15024. var lastChild = node.lastChild;
  15025. while(lastChild){
  15026. if(lastChild.nodeName == 'A'){
  15027. return lastChild;
  15028. }
  15029. if(lastChild.nodeType == 3){
  15030. if(domUtils.isWhitespace(lastChild)){
  15031. lastChild = lastChild.previousSibling;
  15032. continue;
  15033. }
  15034. return null
  15035. }
  15036. lastChild = lastChild.lastChild;
  15037. }
  15038. }
  15039. browser.ie && this.addListener('keyup',function(cmd,evt){
  15040. var me = this,keyCode = evt.keyCode;
  15041. if(keyCodes[keyCode]){
  15042. var rng = me.selection.getRange();
  15043. var start = rng.startContainer;
  15044. if(keyCode == 13){
  15045. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15046. start = start.parentNode;
  15047. }
  15048. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15049. var pre = start.previousSibling;
  15050. if(pre && pre.nodeType == 1){
  15051. var pre = checkIsCludeLink(pre);
  15052. if(pre && !pre.getAttribute('_href')){
  15053. domUtils.remove(pre,true);
  15054. }
  15055. }
  15056. }
  15057. }else if(keyCode == 32 ){
  15058. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15059. start = start.previousSibling;
  15060. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15061. domUtils.remove(start,true);
  15062. }
  15063. }
  15064. }else {
  15065. start = domUtils.findParentByTagName(start,'a',true);
  15066. if(start && !start.getAttribute('_href')){
  15067. var bk = rng.createBookmark();
  15068. domUtils.remove(start,true);
  15069. rng.moveToBookmark(bk).select(true)
  15070. }
  15071. }
  15072. }
  15073. });
  15074. }
  15075. );
  15076. ///import core
  15077. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  15078. ///commandsName AutoHeight,autoHeightEnabled
  15079. ///commandsTitle 自动增高
  15080. /*
  15081. * @description 自动伸展
  15082. * @author zhanyi
  15083. */
  15084. UE.plugins['autoheight'] = function () {
  15085. var me = this;
  15086. //提供开关,就算加载也可以关闭
  15087. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  15088. if (!me.autoHeightEnabled) {
  15089. return;
  15090. }
  15091. var bakOverflow,
  15092. lastHeight = 0,
  15093. options = me.options,
  15094. currentHeight,
  15095. timer;
  15096. function adjustHeight() {
  15097. var me = this;
  15098. clearTimeout(timer);
  15099. if(isFullscreen)return;
  15100. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  15101. timer = setTimeout(function(){
  15102. var node = me.body.lastChild;
  15103. while(node && node.nodeType != 1){
  15104. node = node.previousSibling;
  15105. }
  15106. if(node && node.nodeType == 1){
  15107. node.style.clear = 'both';
  15108. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  15109. if (currentHeight != lastHeight) {
  15110. me.setHeight(currentHeight,true);
  15111. lastHeight = currentHeight;
  15112. }
  15113. domUtils.removeStyle(node,'clear');
  15114. }
  15115. },50)
  15116. }
  15117. }
  15118. var isFullscreen;
  15119. me.addListener('fullscreenchanged',function(cmd,f){
  15120. isFullscreen = f
  15121. });
  15122. me.addListener('destroy', function () {
  15123. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  15124. });
  15125. me.enableAutoHeight = function () {
  15126. var me = this;
  15127. if (!me.autoHeightEnabled) {
  15128. return;
  15129. }
  15130. var doc = me.document;
  15131. me.autoHeightEnabled = true;
  15132. bakOverflow = doc.body.style.overflowY;
  15133. doc.body.style.overflowY = 'hidden';
  15134. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  15135. //ff不给事件算得不对
  15136. setTimeout(function () {
  15137. adjustHeight.call(me);
  15138. }, browser.gecko ? 100 : 0);
  15139. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  15140. };
  15141. me.disableAutoHeight = function () {
  15142. me.body.style.overflowY = bakOverflow || '';
  15143. me.removeListener('contentchange', adjustHeight);
  15144. me.removeListener('keyup', adjustHeight);
  15145. me.removeListener('mouseup', adjustHeight);
  15146. me.autoHeightEnabled = false;
  15147. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  15148. };
  15149. me.addListener('ready', function () {
  15150. me.enableAutoHeight();
  15151. //trace:1764
  15152. var timer;
  15153. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  15154. clearTimeout(timer);
  15155. timer = setTimeout(function () {
  15156. //trace:3681
  15157. adjustHeight.call(me);
  15158. }, 100);
  15159. });
  15160. });
  15161. };
  15162. ///import core
  15163. ///commands 悬浮工具栏
  15164. ///commandsName AutoFloat,autoFloatEnabled
  15165. ///commandsTitle 悬浮工具栏
  15166. /*
  15167. * modified by chengchao01
  15168. *
  15169. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  15170. */
  15171. UE.plugins['autofloat'] = function() {
  15172. var me = this,
  15173. lang = me.getLang();
  15174. me.setOpt({
  15175. topOffset:0
  15176. });
  15177. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  15178. topOffset = me.options.topOffset;
  15179. //如果不固定toolbar的位置,则直接退出
  15180. if(!optsAutoFloatEnabled){
  15181. return;
  15182. }
  15183. var uiUtils = UE.ui.uiUtils,
  15184. LteIE6 = browser.ie && browser.version <= 6,
  15185. quirks = browser.quirks;
  15186. function checkHasUI(){
  15187. if(!UE.ui){
  15188. alert(lang.autofloatMsg);
  15189. return 0;
  15190. }
  15191. return 1;
  15192. }
  15193. function fixIE6FixedPos(){
  15194. var docStyle = document.body.style;
  15195. docStyle.backgroundImage = 'url("about:blank")';
  15196. docStyle.backgroundAttachment = 'fixed';
  15197. }
  15198. var bakCssText,
  15199. placeHolder = document.createElement('div'),
  15200. toolbarBox,orgTop,
  15201. getPosition,
  15202. flag =true; //ie7模式下需要偏移
  15203. function setFloating(){
  15204. var toobarBoxPos = domUtils.getXY(toolbarBox),
  15205. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  15206. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  15207. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  15208. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  15209. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  15210. if (LteIE6 || (quirks && browser.ie)) {
  15211. if(toolbarBox.style.position != 'absolute'){
  15212. toolbarBox.style.position = 'absolute';
  15213. }
  15214. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  15215. } else {
  15216. if (browser.ie7Compat && flag) {
  15217. flag = false;
  15218. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  15219. }
  15220. if(toolbarBox.style.position != 'fixed'){
  15221. toolbarBox.style.position = 'fixed';
  15222. toolbarBox.style.top = topOffset +"px";
  15223. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  15224. }
  15225. }
  15226. }
  15227. function unsetFloating(){
  15228. flag = true;
  15229. if(placeHolder.parentNode){
  15230. placeHolder.parentNode.removeChild(placeHolder);
  15231. }
  15232. toolbarBox.style.cssText = bakCssText;
  15233. }
  15234. function updateFloating(){
  15235. var rect3 = getPosition(me.container);
  15236. var offset=me.options.toolbarTopOffset||0;
  15237. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  15238. setFloating();
  15239. }else{
  15240. unsetFloating();
  15241. }
  15242. }
  15243. var defer_updateFloating = utils.defer(function(){
  15244. updateFloating();
  15245. },browser.ie ? 200 : 100,true);
  15246. me.addListener('destroy',function(){
  15247. domUtils.un(window, ['scroll','resize'], updateFloating);
  15248. me.removeListener('keydown', defer_updateFloating);
  15249. });
  15250. me.addListener('ready', function(){
  15251. if(checkHasUI(me)){
  15252. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  15253. if(!me.ui){
  15254. return;
  15255. }
  15256. getPosition = uiUtils.getClientRect;
  15257. toolbarBox = me.ui.getDom('toolbarbox');
  15258. orgTop = getPosition(toolbarBox).top;
  15259. bakCssText = toolbarBox.style.cssText;
  15260. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  15261. if(LteIE6){
  15262. fixIE6FixedPos();
  15263. }
  15264. domUtils.on(window, ['scroll','resize'], updateFloating);
  15265. me.addListener('keydown', defer_updateFloating);
  15266. me.addListener('beforefullscreenchange', function (t, enabled){
  15267. if (enabled) {
  15268. unsetFloating();
  15269. }
  15270. });
  15271. me.addListener('fullscreenchanged', function (t, enabled){
  15272. if (!enabled) {
  15273. updateFloating();
  15274. }
  15275. });
  15276. me.addListener('sourcemodechanged', function (t, enabled){
  15277. setTimeout(function (){
  15278. updateFloating();
  15279. },0);
  15280. });
  15281. me.addListener("clearDoc",function(){
  15282. setTimeout(function(){
  15283. updateFloating();
  15284. },0);
  15285. })
  15286. }
  15287. });
  15288. };
  15289. /**
  15290. * 纯文本粘贴插件
  15291. * @file
  15292. * @since 1.2.6.1
  15293. */
  15294. UE.plugins['pasteplain'] = function(){
  15295. var me = this;
  15296. me.setOpt({
  15297. 'pasteplain':false,
  15298. 'filterTxtRules' : function(){
  15299. function transP(node){
  15300. node.tagName = 'p';
  15301. node.setStyle();
  15302. }
  15303. function removeNode(node){
  15304. node.parentNode.removeChild(node,true)
  15305. }
  15306. return {
  15307. //直接删除及其字节点内容
  15308. '-' : 'script style object iframe embed input select',
  15309. 'p': {$:{}},
  15310. 'br':{$:{}},
  15311. div: function (node) {
  15312. var tmpNode, p = UE.uNode.createElement('p');
  15313. while (tmpNode = node.firstChild()) {
  15314. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  15315. p.appendChild(tmpNode);
  15316. } else {
  15317. if (p.firstChild()) {
  15318. node.parentNode.insertBefore(p, node);
  15319. p = UE.uNode.createElement('p');
  15320. } else {
  15321. node.parentNode.insertBefore(tmpNode, node);
  15322. }
  15323. }
  15324. }
  15325. if (p.firstChild()) {
  15326. node.parentNode.insertBefore(p, node);
  15327. }
  15328. node.parentNode.removeChild(node);
  15329. },
  15330. ol: removeNode,
  15331. ul: removeNode,
  15332. dl:removeNode,
  15333. dt:removeNode,
  15334. dd:removeNode,
  15335. 'li':removeNode,
  15336. 'caption':transP,
  15337. 'th':transP,
  15338. 'tr':transP,
  15339. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  15340. 'td':function(node){
  15341. //没有内容的td直接删掉
  15342. var txt = !!node.innerText();
  15343. if(txt){
  15344. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  15345. }
  15346. node.parentNode.removeChild(node,node.innerText())
  15347. }
  15348. }
  15349. }()
  15350. });
  15351. //暂时这里支持一下老版本的属性
  15352. var pasteplain = me.options.pasteplain;
  15353. /**
  15354. * 启用或取消纯文本粘贴模式
  15355. * @command pasteplain
  15356. * @method execCommand
  15357. * @param { String } cmd 命令字符串
  15358. * @example
  15359. * ```javascript
  15360. * editor.queryCommandState( 'pasteplain' );
  15361. * ```
  15362. */
  15363. /**
  15364. * 查询当前是否处于纯文本粘贴模式
  15365. * @command pasteplain
  15366. * @method queryCommandState
  15367. * @param { String } cmd 命令字符串
  15368. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  15369. * @example
  15370. * ```javascript
  15371. * editor.queryCommandState( 'pasteplain' );
  15372. * ```
  15373. */
  15374. me.commands['pasteplain'] = {
  15375. queryCommandState: function (){
  15376. return pasteplain ? 1 : 0;
  15377. },
  15378. execCommand: function (){
  15379. pasteplain = !pasteplain|0;
  15380. },
  15381. notNeedUndo : 1
  15382. };
  15383. };
  15384. /**
  15385. * video插件, 为UEditor提供视频插入支持
  15386. * @file
  15387. * @since 1.2.6.1
  15388. */
  15389. UE.plugins['video'] = function (){
  15390. var me =this;
  15391. /*
  15392. * 创建插入视频字符窜
  15393. * @param url 视频地址
  15394. * @param width 视频宽度
  15395. * @param height 视频高度
  15396. * @param align 视频对齐
  15397. * @param toEmbed 是否以flash代替显示
  15398. * @param addParagraph 是否需要添加P 标签
  15399. */
  15400. function creatInsertStr(url,width,height,id,align,classname,type){
  15401. var str;
  15402. switch (type){
  15403. case 'image':
  15404. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname + '"' +
  15405. ' src="' + me.options.UEDITOR_HOME_URL+'themes/default/images/spacer.gif" style="background:url('+me.options.UEDITOR_HOME_URL+'themes/default/images/videologo.gif) no-repeat center center; border:1px solid gray;'+(align ? 'float:' + align + ';': '')+'" />'
  15406. break;
  15407. case 'embed':
  15408. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  15409. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  15410. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  15411. break;
  15412. case 'video':
  15413. var ext = url.substr(url.lastIndexOf('.') + 1);
  15414. if(ext == 'ogv') ext = 'ogg';
  15415. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + '" ' + (align ? ' style="float:' + align + '"': '') +
  15416. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  15417. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  15418. break;
  15419. }
  15420. return str;
  15421. }
  15422. function switchImgAndVideo(root,img2video){
  15423. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  15424. var className = node.getAttr('class');
  15425. if(className && className.indexOf('edui-faked-video') != -1){
  15426. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  15427. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  15428. }
  15429. if(className && className.indexOf('edui-upload-video') != -1){
  15430. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  15431. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  15432. }
  15433. })
  15434. }
  15435. me.addOutputRule(function(root){
  15436. switchImgAndVideo(root,true)
  15437. });
  15438. me.addInputRule(function(root){
  15439. switchImgAndVideo(root)
  15440. });
  15441. /**
  15442. * 插入视频
  15443. * @command insertvideo
  15444. * @method execCommand
  15445. * @param { String } cmd 命令字符串
  15446. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  15447. * @example
  15448. * ```javascript
  15449. *
  15450. * var videoAttr = {
  15451. * //视频地址
  15452. * url: 'http://www.youku.com/xxx',
  15453. * //视频宽高值, 单位px
  15454. * width: 200,
  15455. * height: 100
  15456. * };
  15457. *
  15458. * //editor 是编辑器实例
  15459. * //向编辑器插入单个视频
  15460. * editor.execCommand( 'insertvideo', videoAttr );
  15461. * ```
  15462. */
  15463. /**
  15464. * 插入视频
  15465. * @command insertvideo
  15466. * @method execCommand
  15467. * @param { String } cmd 命令字符串
  15468. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  15469. * @example
  15470. * ```javascript
  15471. *
  15472. * var videoAttr1 = {
  15473. * //视频地址
  15474. * url: 'http://www.youku.com/xxx',
  15475. * //视频宽高值, 单位px
  15476. * width: 200,
  15477. * height: 100
  15478. * },
  15479. * videoAttr2 = {
  15480. * //视频地址
  15481. * url: 'http://www.youku.com/xxx',
  15482. * //视频宽高值, 单位px
  15483. * width: 200,
  15484. * height: 100
  15485. * }
  15486. *
  15487. * //editor 是编辑器实例
  15488. * //该方法将会向编辑器内插入两个视频
  15489. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  15490. * ```
  15491. */
  15492. /**
  15493. * 查询当前光标所在处是否是一个视频
  15494. * @command insertvideo
  15495. * @method queryCommandState
  15496. * @param { String } cmd 需要查询的命令字符串
  15497. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  15498. * @example
  15499. * ```javascript
  15500. *
  15501. * //editor 是编辑器实例
  15502. * editor.queryCommandState( 'insertvideo' );
  15503. * ```
  15504. */
  15505. me.commands["insertvideo"] = {
  15506. execCommand: function (cmd, videoObjs, type){
  15507. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  15508. var html = [],id = 'tmpVedio', cl;
  15509. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  15510. vi = videoObjs[i];
  15511. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  15512. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  15513. }
  15514. me.execCommand("inserthtml",html.join(""),true);
  15515. var rng = this.selection.getRange();
  15516. for(var i= 0,len=videoObjs.length;i<len;i++){
  15517. var img = this.document.getElementById('tmpVedio'+i);
  15518. domUtils.removeAttributes(img,'id');
  15519. rng.selectNode(img).select();
  15520. me.execCommand('imagefloat',videoObjs[i].align)
  15521. }
  15522. },
  15523. queryCommandState : function(){
  15524. var img = me.selection.getRange().getClosedNode(),
  15525. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  15526. return flag ? 1 : 0;
  15527. }
  15528. };
  15529. };
  15530. /**
  15531. * Created with JetBrains WebStorm.
  15532. * User: taoqili
  15533. * Date: 13-1-18
  15534. * Time: 上午11:09
  15535. * To change this template use File | Settings | File Templates.
  15536. */
  15537. /**
  15538. * UE表格操作类
  15539. * @param table
  15540. * @constructor
  15541. */
  15542. (function () {
  15543. var UETable = UE.UETable = function (table) {
  15544. this.table = table;
  15545. this.indexTable = [];
  15546. this.selectedTds = [];
  15547. this.cellsRange = {};
  15548. this.update(table);
  15549. };
  15550. //===以下为静态工具方法===
  15551. UETable.removeSelectedClass = function (cells) {
  15552. utils.each(cells, function (cell) {
  15553. domUtils.removeClasses(cell, "selectTdClass");
  15554. })
  15555. };
  15556. UETable.addSelectedClass = function (cells) {
  15557. utils.each(cells, function (cell) {
  15558. domUtils.addClass(cell, "selectTdClass");
  15559. })
  15560. };
  15561. UETable.isEmptyBlock = function (node) {
  15562. var reg = new RegExp(domUtils.fillChar, 'g');
  15563. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  15564. return 0;
  15565. }
  15566. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  15567. if (node.getElementsByTagName(i).length) {
  15568. return 0;
  15569. }
  15570. }
  15571. return 1;
  15572. };
  15573. UETable.getWidth = function (cell) {
  15574. if (!cell)return 0;
  15575. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  15576. };
  15577. /**
  15578. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  15579. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  15580. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  15581. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  15582. */
  15583. UETable.getTableCellAlignState = function ( cells ) {
  15584. !utils.isArray( cells ) && ( cells = [cells] );
  15585. var result = {},
  15586. status = ['align', 'valign'],
  15587. tempStatus = null,
  15588. isSame = true;//状态是否相同
  15589. utils.each( cells, function( cellNode ){
  15590. utils.each( status, function( currentState ){
  15591. tempStatus = cellNode.getAttribute( currentState );
  15592. if( !result[ currentState ] && tempStatus ) {
  15593. result[ currentState ] = tempStatus;
  15594. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  15595. isSame = false;
  15596. return false;
  15597. }
  15598. } );
  15599. return isSame;
  15600. });
  15601. return isSame ? result : null;
  15602. };
  15603. /**
  15604. * 根据当前选区获取相关的table信息
  15605. * @return {Object}
  15606. */
  15607. UETable.getTableItemsByRange = function (editor) {
  15608. var start = editor.selection.getStart();
  15609. //ff下会选中bookmark
  15610. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 ) {
  15611. start = start.nextSibling;
  15612. }
  15613. //在table或者td边缘有可能存在选中tr的情况
  15614. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  15615. tr = cell && cell.parentNode,
  15616. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  15617. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  15618. return {
  15619. cell:cell,
  15620. tr:tr,
  15621. table:table,
  15622. caption:caption
  15623. }
  15624. };
  15625. UETable.getUETableBySelected = function (editor) {
  15626. var table = UETable.getTableItemsByRange(editor).table;
  15627. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  15628. return table.ueTable;
  15629. }
  15630. return null;
  15631. };
  15632. UETable.getDefaultValue = function (editor, table) {
  15633. var borderMap = {
  15634. thin:'0px',
  15635. medium:'1px',
  15636. thick:'2px'
  15637. },
  15638. tableBorder, tdPadding, tdBorder, tmpValue;
  15639. if (!table) {
  15640. table = editor.document.createElement('table');
  15641. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  15642. editor.body.appendChild(table);
  15643. var td = table.getElementsByTagName('td')[0];
  15644. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  15645. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15646. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  15647. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15648. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  15649. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15650. domUtils.remove(table);
  15651. return {
  15652. tableBorder:tableBorder,
  15653. tdPadding:tdPadding,
  15654. tdBorder:tdBorder
  15655. };
  15656. } else {
  15657. td = table.getElementsByTagName('td')[0];
  15658. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  15659. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15660. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  15661. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15662. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  15663. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15664. return {
  15665. tableBorder:tableBorder,
  15666. tdPadding:tdPadding,
  15667. tdBorder:tdBorder
  15668. };
  15669. }
  15670. };
  15671. /**
  15672. * 根据当前点击的td或者table获取索引对象
  15673. * @param tdOrTable
  15674. */
  15675. UETable.getUETable = function (tdOrTable) {
  15676. var tag = tdOrTable.tagName.toLowerCase();
  15677. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  15678. if (!tdOrTable.ueTable) {
  15679. tdOrTable.ueTable = new UETable(tdOrTable);
  15680. }
  15681. return tdOrTable.ueTable;
  15682. };
  15683. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  15684. if (!cell || utils.isString(cell)) {
  15685. return this.table.ownerDocument.createElement(cell || 'td');
  15686. }
  15687. var flag = domUtils.hasClass(cell, "selectTdClass");
  15688. flag && domUtils.removeClasses(cell, "selectTdClass");
  15689. var tmpCell = cell.cloneNode(true);
  15690. if (ignoreMerge) {
  15691. tmpCell.rowSpan = tmpCell.colSpan = 1;
  15692. }
  15693. //去掉宽高
  15694. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  15695. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  15696. tmpCell.style.borderLeftStyle = "";
  15697. tmpCell.style.borderTopStyle = "";
  15698. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  15699. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  15700. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  15701. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  15702. flag && domUtils.addClass(cell, "selectTdClass");
  15703. return tmpCell;
  15704. }
  15705. UETable.prototype = {
  15706. getMaxRows:function () {
  15707. var rows = this.table.rows, maxLen = 1;
  15708. for (var i = 0, row; row = rows[i]; i++) {
  15709. var currentMax = 1;
  15710. for (var j = 0, cj; cj = row.cells[j++];) {
  15711. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  15712. }
  15713. maxLen = Math.max(currentMax + i, maxLen);
  15714. }
  15715. return maxLen;
  15716. },
  15717. /**
  15718. * 获取当前表格的最大列数
  15719. */
  15720. getMaxCols:function () {
  15721. var rows = this.table.rows, maxLen = 0, cellRows = {};
  15722. for (var i = 0, row; row = rows[i]; i++) {
  15723. var cellsNum = 0;
  15724. for (var j = 0, cj; cj = row.cells[j++];) {
  15725. cellsNum += (cj.colSpan || 1);
  15726. if (cj.rowSpan && cj.rowSpan > 1) {
  15727. for (var k = 1; k < cj.rowSpan; k++) {
  15728. if (!cellRows['row_' + (i + k)]) {
  15729. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  15730. } else {
  15731. cellRows['row_' + (i + k)]++
  15732. }
  15733. }
  15734. }
  15735. }
  15736. cellsNum += cellRows['row_' + i] || 0;
  15737. maxLen = Math.max(cellsNum, maxLen);
  15738. }
  15739. return maxLen;
  15740. },
  15741. getCellColIndex:function (cell) {
  15742. },
  15743. /**
  15744. * 获取当前cell旁边的单元格,
  15745. * @param cell
  15746. * @param right
  15747. */
  15748. getHSideCell:function (cell, right) {
  15749. try {
  15750. var cellInfo = this.getCellInfo(cell),
  15751. previewRowIndex, previewColIndex;
  15752. var len = this.selectedTds.length,
  15753. range = this.cellsRange;
  15754. //首行或者首列没有前置单元格
  15755. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  15756. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  15757. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  15758. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  15759. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  15760. } catch (e) {
  15761. showError(e);
  15762. }
  15763. },
  15764. getTabNextCell:function (cell, preRowIndex) {
  15765. var cellInfo = this.getCellInfo(cell),
  15766. rowIndex = preRowIndex || cellInfo.rowIndex,
  15767. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  15768. nextCell;
  15769. try {
  15770. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  15771. } catch (e) {
  15772. try {
  15773. rowIndex = rowIndex * 1 + 1;
  15774. colIndex = 0;
  15775. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  15776. } catch (e) {
  15777. }
  15778. }
  15779. return nextCell;
  15780. },
  15781. /**
  15782. * 获取视觉上的后置单元格
  15783. * @param cell
  15784. * @param bottom
  15785. */
  15786. getVSideCell:function (cell, bottom, ignoreRange) {
  15787. try {
  15788. var cellInfo = this.getCellInfo(cell),
  15789. nextRowIndex, nextColIndex;
  15790. var len = this.selectedTds.length && !ignoreRange,
  15791. range = this.cellsRange;
  15792. //末行或者末列没有后置单元格
  15793. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  15794. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  15795. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  15796. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  15797. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  15798. } catch (e) {
  15799. showError(e);
  15800. }
  15801. },
  15802. /**
  15803. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  15804. */
  15805. getSameEndPosCells:function (cell, xOrY) {
  15806. try {
  15807. var flag = (xOrY.toLowerCase() === "x"),
  15808. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  15809. rows = this.table.rows,
  15810. cells = null, returns = [];
  15811. for (var i = 0; i < this.rowsNum; i++) {
  15812. cells = rows[i].cells;
  15813. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  15814. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  15815. //对应行的td已经被上面行rowSpan了
  15816. if (tmpEnd > end && flag) break;
  15817. if (cell == tmpCell || end == tmpEnd) {
  15818. //只获取单一的单元格
  15819. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  15820. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  15821. returns.push(tmpCell);
  15822. }
  15823. if (flag) break;
  15824. }
  15825. }
  15826. }
  15827. return returns;
  15828. } catch (e) {
  15829. showError(e);
  15830. }
  15831. },
  15832. setCellContent:function (cell, content) {
  15833. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  15834. },
  15835. cloneCell:UETable.cloneCell,
  15836. /**
  15837. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  15838. */
  15839. getSameStartPosXCells:function (cell) {
  15840. try {
  15841. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  15842. rows = this.table.rows, cells , returns = [];
  15843. for (var i = 0; i < this.rowsNum; i++) {
  15844. cells = rows[i].cells;
  15845. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  15846. var tmpStart = domUtils.getXY(tmpCell).x;
  15847. if (tmpStart > start) break;
  15848. if (tmpStart == start && tmpCell.colSpan == 1) {
  15849. returns.push(tmpCell);
  15850. break;
  15851. }
  15852. }
  15853. }
  15854. return returns;
  15855. } catch (e) {
  15856. showError(e);
  15857. }
  15858. },
  15859. /**
  15860. * 更新table对应的索引表
  15861. */
  15862. update:function (table) {
  15863. this.table = table || this.table;
  15864. this.selectedTds = [];
  15865. this.cellsRange = {};
  15866. this.indexTable = [];
  15867. var rows = this.table.rows,
  15868. rowsNum = this.getMaxRows(),
  15869. dNum = rowsNum - rows.length,
  15870. colsNum = this.getMaxCols();
  15871. while (dNum--) {
  15872. this.table.insertRow(rows.length);
  15873. }
  15874. this.rowsNum = rowsNum;
  15875. this.colsNum = colsNum;
  15876. for (var i = 0, len = rows.length; i < len; i++) {
  15877. this.indexTable[i] = new Array(colsNum);
  15878. }
  15879. //填充索引表
  15880. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  15881. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  15882. //修正整行被rowSpan时导致的行数计算错误
  15883. if (cell.rowSpan > rowsNum) {
  15884. cell.rowSpan = rowsNum;
  15885. }
  15886. var colIndex = cellIndex,
  15887. rowSpan = cell.rowSpan || 1,
  15888. colSpan = cell.colSpan || 1;
  15889. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  15890. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  15891. for (var j = 0; j < rowSpan; j++) {
  15892. for (var k = 0; k < colSpan; k++) {
  15893. this.indexTable[rowIndex + j][colIndex + k] = {
  15894. rowIndex:rowIndex,
  15895. cellIndex:cellIndex,
  15896. colIndex:colIndex,
  15897. rowSpan:rowSpan,
  15898. colSpan:colSpan
  15899. }
  15900. }
  15901. }
  15902. }
  15903. }
  15904. //修复残缺td
  15905. for (j = 0; j < rowsNum; j++) {
  15906. for (k = 0; k < colsNum; k++) {
  15907. if (this.indexTable[j][k] === undefined) {
  15908. row = rows[j];
  15909. cell = row.cells[row.cells.length - 1];
  15910. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  15911. this.setCellContent(cell);
  15912. if (cell.colSpan !== 1)cell.colSpan = 1;
  15913. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  15914. row.appendChild(cell);
  15915. this.indexTable[j][k] = {
  15916. rowIndex:j,
  15917. cellIndex:cell.cellIndex,
  15918. colIndex:k,
  15919. rowSpan:1,
  15920. colSpan:1
  15921. }
  15922. }
  15923. }
  15924. }
  15925. //当框选后删除行或者列后撤销,需要重建选区。
  15926. var tds = domUtils.getElementsByTagName(this.table, "td"),
  15927. selectTds = [];
  15928. utils.each(tds, function (td) {
  15929. if (domUtils.hasClass(td, "selectTdClass")) {
  15930. selectTds.push(td);
  15931. }
  15932. });
  15933. if (selectTds.length) {
  15934. var start = selectTds[0],
  15935. end = selectTds[selectTds.length - 1],
  15936. startInfo = this.getCellInfo(start),
  15937. endInfo = this.getCellInfo(end);
  15938. this.selectedTds = selectTds;
  15939. this.cellsRange = {
  15940. beginRowIndex:startInfo.rowIndex,
  15941. beginColIndex:startInfo.colIndex,
  15942. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  15943. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  15944. };
  15945. }
  15946. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  15947. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  15948. domUtils.addClass(this.table.rows[0], "firstRow");
  15949. for(var i = 1; i< this.table.rows.length; i++) {
  15950. domUtils.removeClasses(this.table.rows[i], "firstRow");
  15951. }
  15952. }
  15953. },
  15954. /**
  15955. * 获取单元格的索引信息
  15956. */
  15957. getCellInfo:function (cell) {
  15958. if (!cell) return;
  15959. var cellIndex = cell.cellIndex,
  15960. rowIndex = cell.parentNode.rowIndex,
  15961. rowInfo = this.indexTable[rowIndex],
  15962. numCols = this.colsNum;
  15963. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  15964. var cellInfo = rowInfo[colIndex];
  15965. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  15966. return cellInfo;
  15967. }
  15968. }
  15969. },
  15970. /**
  15971. * 根据行列号获取单元格
  15972. */
  15973. getCell:function (rowIndex, cellIndex) {
  15974. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  15975. },
  15976. /**
  15977. * 删除单元格
  15978. */
  15979. deleteCell:function (cell, rowIndex) {
  15980. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  15981. var row = this.table.rows[rowIndex];
  15982. row.deleteCell(cell.cellIndex);
  15983. },
  15984. /**
  15985. * 根据始末两个单元格获取被框选的所有单元格范围
  15986. */
  15987. getCellsRange:function (cellA, cellB) {
  15988. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  15989. var tmpBeginRowIndex = beginRowIndex,
  15990. tmpBeginColIndex = beginColIndex,
  15991. tmpEndRowIndex = endRowIndex,
  15992. tmpEndColIndex = endColIndex,
  15993. cellInfo, colIndex, rowIndex;
  15994. // 通过indexTable检查是否存在超出TableRange上边界的情况
  15995. if (beginRowIndex > 0) {
  15996. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  15997. cellInfo = me.indexTable[beginRowIndex][colIndex];
  15998. rowIndex = cellInfo.rowIndex;
  15999. if (rowIndex < beginRowIndex) {
  16000. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16001. }
  16002. }
  16003. }
  16004. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16005. if (endColIndex < me.colsNum) {
  16006. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16007. cellInfo = me.indexTable[rowIndex][endColIndex];
  16008. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16009. if (colIndex > endColIndex) {
  16010. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16011. }
  16012. }
  16013. }
  16014. // 检查是否有超出TableRange下边界的情况
  16015. if (endRowIndex < me.rowsNum) {
  16016. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16017. cellInfo = me.indexTable[endRowIndex][colIndex];
  16018. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16019. if (rowIndex > endRowIndex) {
  16020. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16021. }
  16022. }
  16023. }
  16024. // 检查是否有超出TableRange左边界的情况
  16025. if (beginColIndex > 0) {
  16026. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16027. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16028. colIndex = cellInfo.colIndex;
  16029. if (colIndex < beginColIndex) {
  16030. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16031. }
  16032. }
  16033. }
  16034. //递归调用直至所有完成所有框选单元格的扩展
  16035. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16036. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16037. } else {
  16038. // 不需要扩展TableRange的情况
  16039. return {
  16040. beginRowIndex:beginRowIndex,
  16041. beginColIndex:beginColIndex,
  16042. endRowIndex:endRowIndex,
  16043. endColIndex:endColIndex
  16044. };
  16045. }
  16046. }
  16047. try {
  16048. var me = this,
  16049. cellAInfo = me.getCellInfo(cellA);
  16050. if (cellA === cellB) {
  16051. return {
  16052. beginRowIndex:cellAInfo.rowIndex,
  16053. beginColIndex:cellAInfo.colIndex,
  16054. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16055. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16056. };
  16057. }
  16058. var cellBInfo = me.getCellInfo(cellB);
  16059. // 计算TableRange的四个边
  16060. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16061. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16062. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16063. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16064. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16065. } catch (e) {
  16066. //throw e;
  16067. }
  16068. },
  16069. /**
  16070. * 依据cellsRange获取对应的单元格集合
  16071. */
  16072. getCells:function (range) {
  16073. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16074. this.clearSelected();
  16075. var beginRowIndex = range.beginRowIndex,
  16076. beginColIndex = range.beginColIndex,
  16077. endRowIndex = range.endRowIndex,
  16078. endColIndex = range.endColIndex,
  16079. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16080. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16081. for (var j = beginColIndex; j <= endColIndex; j++) {
  16082. cellInfo = this.indexTable[i][j];
  16083. rowIndex = cellInfo.rowIndex;
  16084. colIndex = cellInfo.colIndex;
  16085. // 如果Cells里已经包含了此Cell则跳过
  16086. var key = rowIndex + '|' + colIndex;
  16087. if (tdHash[key]) continue;
  16088. tdHash[key] = 1;
  16089. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16090. return null;
  16091. }
  16092. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16093. }
  16094. }
  16095. return returnTds;
  16096. },
  16097. /**
  16098. * 清理已经选中的单元格
  16099. */
  16100. clearSelected:function () {
  16101. UETable.removeSelectedClass(this.selectedTds);
  16102. this.selectedTds = [];
  16103. this.cellsRange = {};
  16104. },
  16105. /**
  16106. * 根据range设置已经选中的单元格
  16107. */
  16108. setSelected:function (range) {
  16109. var cells = this.getCells(range);
  16110. UETable.addSelectedClass(cells);
  16111. this.selectedTds = cells;
  16112. this.cellsRange = range;
  16113. },
  16114. isFullRow:function () {
  16115. var range = this.cellsRange;
  16116. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16117. },
  16118. isFullCol:function () {
  16119. var range = this.cellsRange,
  16120. table = this.table,
  16121. ths = table.getElementsByTagName("th"),
  16122. rows = range.endRowIndex - range.beginRowIndex + 1;
  16123. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16124. },
  16125. /**
  16126. * 获取视觉上的前置单元格,默认是左边,top传入时
  16127. * @param cell
  16128. * @param top
  16129. */
  16130. getNextCell:function (cell, bottom, ignoreRange) {
  16131. try {
  16132. var cellInfo = this.getCellInfo(cell),
  16133. nextRowIndex, nextColIndex;
  16134. var len = this.selectedTds.length && !ignoreRange,
  16135. range = this.cellsRange;
  16136. //末行或者末列没有后置单元格
  16137. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16138. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16139. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16140. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16141. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16142. } catch (e) {
  16143. showError(e);
  16144. }
  16145. },
  16146. getPreviewCell:function (cell, top) {
  16147. try {
  16148. var cellInfo = this.getCellInfo(cell),
  16149. previewRowIndex, previewColIndex;
  16150. var len = this.selectedTds.length,
  16151. range = this.cellsRange;
  16152. //首行或者首列没有前置单元格
  16153. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16154. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  16155. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  16156. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16157. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  16158. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16159. } catch (e) {
  16160. showError(e);
  16161. }
  16162. },
  16163. /**
  16164. * 移动单元格中的内容
  16165. */
  16166. moveContent:function (cellTo, cellFrom) {
  16167. if (UETable.isEmptyBlock(cellFrom)) return;
  16168. if (UETable.isEmptyBlock(cellTo)) {
  16169. cellTo.innerHTML = cellFrom.innerHTML;
  16170. return;
  16171. }
  16172. var child = cellTo.lastChild;
  16173. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  16174. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  16175. }
  16176. while (child = cellFrom.firstChild) {
  16177. cellTo.appendChild(child);
  16178. }
  16179. },
  16180. /**
  16181. * 向右合并单元格
  16182. */
  16183. mergeRight:function (cell) {
  16184. var cellInfo = this.getCellInfo(cell),
  16185. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  16186. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  16187. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  16188. //合并
  16189. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  16190. //被合并的单元格不应存在宽度属性
  16191. cell.removeAttribute("width");
  16192. //移动内容
  16193. this.moveContent(cell, rightCell);
  16194. //删掉被合并的Cell
  16195. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  16196. this.update();
  16197. },
  16198. /**
  16199. * 向下合并单元格
  16200. */
  16201. mergeDown:function (cell) {
  16202. var cellInfo = this.getCellInfo(cell),
  16203. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  16204. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  16205. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  16206. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  16207. cell.removeAttribute("height");
  16208. this.moveContent(cell, downCell);
  16209. this.deleteCell(downCell, downCellInfo.rowIndex);
  16210. this.update();
  16211. },
  16212. /**
  16213. * 合并整个range中的内容
  16214. */
  16215. mergeRange:function () {
  16216. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  16217. var range = this.cellsRange,
  16218. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  16219. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  16220. var index = this.indexTable,
  16221. info = this.getCellInfo(leftTopCell);
  16222. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  16223. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  16224. }
  16225. // 删除剩余的Cells
  16226. var cells = this.getCells(range);
  16227. for(var i= 0,ci;ci=cells[i++];){
  16228. if (ci !== leftTopCell) {
  16229. this.moveContent(leftTopCell, ci);
  16230. this.deleteCell(ci);
  16231. }
  16232. }
  16233. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  16234. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  16235. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  16236. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  16237. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  16238. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  16239. leftTopCell.colSpan = 1;
  16240. }
  16241. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  16242. var rowIndex = leftTopCell.parentNode.rowIndex;
  16243. //解决IE下的表格操作问题
  16244. if( this.table.deleteRow ) {
  16245. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  16246. this.table.deleteRow(curIndex);
  16247. }
  16248. } else {
  16249. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  16250. var row = this.table.rows[rowIndex + 1];
  16251. row.parentNode.removeChild(row);
  16252. }
  16253. }
  16254. leftTopCell.rowSpan = 1;
  16255. }
  16256. this.update();
  16257. },
  16258. /**
  16259. * 插入一行单元格
  16260. */
  16261. insertRow:function (rowIndex, sourceCell) {
  16262. var numCols = this.colsNum,
  16263. table = this.table,
  16264. row = table.insertRow(rowIndex), cell,
  16265. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  16266. function replaceTdToTh(colIndex, cell, tableRow) {
  16267. if (colIndex == 0) {
  16268. var tr = tableRow.nextSibling || tableRow.previousSibling,
  16269. th = tr.cells[colIndex];
  16270. if (th.tagName == 'TH') {
  16271. th = cell.ownerDocument.createElement("th");
  16272. th.appendChild(cell.firstChild);
  16273. tableRow.insertBefore(th, cell);
  16274. domUtils.remove(cell)
  16275. }
  16276. }else{
  16277. if (cell.tagName == 'TH') {
  16278. var td = cell.ownerDocument.createElement("td");
  16279. td.appendChild(cell.firstChild);
  16280. tableRow.insertBefore(td, cell);
  16281. domUtils.remove(cell)
  16282. }
  16283. }
  16284. }
  16285. //首行直接插入,无需考虑部分单元格被rowspan的情况
  16286. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  16287. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  16288. cell = this.cloneCell(sourceCell, true);
  16289. this.setCellContent(cell);
  16290. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16291. row.appendChild(cell);
  16292. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  16293. }
  16294. } else {
  16295. var infoRow = this.indexTable[rowIndex],
  16296. cellIndex = 0;
  16297. for (colIndex = 0; colIndex < numCols; colIndex++) {
  16298. var cellInfo = infoRow[colIndex];
  16299. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  16300. if (cellInfo.rowIndex < rowIndex) {
  16301. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16302. cell.rowSpan = cellInfo.rowSpan + 1;
  16303. } else {
  16304. cell = this.cloneCell(sourceCell, true);
  16305. this.setCellContent(cell);
  16306. row.appendChild(cell);
  16307. }
  16308. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  16309. }
  16310. }
  16311. //框选时插入不触发contentchange,需要手动更新索引。
  16312. this.update();
  16313. return row;
  16314. },
  16315. /**
  16316. * 删除一行单元格
  16317. * @param rowIndex
  16318. */
  16319. deleteRow:function (rowIndex) {
  16320. var row = this.table.rows[rowIndex],
  16321. infoRow = this.indexTable[rowIndex],
  16322. colsNum = this.colsNum,
  16323. count = 0; //处理计数
  16324. for (var colIndex = 0; colIndex < colsNum;) {
  16325. var cellInfo = infoRow[colIndex],
  16326. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16327. if (cell.rowSpan > 1) {
  16328. if (cellInfo.rowIndex == rowIndex) {
  16329. var clone = cell.cloneNode(true);
  16330. clone.rowSpan = cell.rowSpan - 1;
  16331. clone.innerHTML = "";
  16332. cell.rowSpan = 1;
  16333. var nextRowIndex = rowIndex + 1,
  16334. nextRow = this.table.rows[nextRowIndex],
  16335. insertCellIndex,
  16336. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  16337. if (preMerged < colIndex) {
  16338. insertCellIndex = colIndex - preMerged - 1;
  16339. //nextRow.insertCell(insertCellIndex);
  16340. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  16341. } else {
  16342. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  16343. }
  16344. count += 1;
  16345. //cell.parentNode.removeChild(cell);
  16346. }
  16347. }
  16348. colIndex += cell.colSpan || 1;
  16349. }
  16350. var deleteTds = [], cacheMap = {};
  16351. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  16352. var tmpRowIndex = infoRow[colIndex].rowIndex,
  16353. tmpCellIndex = infoRow[colIndex].cellIndex,
  16354. key = tmpRowIndex + "_" + tmpCellIndex;
  16355. if (cacheMap[key])continue;
  16356. cacheMap[key] = 1;
  16357. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  16358. deleteTds.push(cell);
  16359. }
  16360. var mergeTds = [];
  16361. utils.each(deleteTds, function (td) {
  16362. if (td.rowSpan == 1) {
  16363. td.parentNode.removeChild(td);
  16364. } else {
  16365. mergeTds.push(td);
  16366. }
  16367. });
  16368. utils.each(mergeTds, function (td) {
  16369. td.rowSpan--;
  16370. });
  16371. row.parentNode.removeChild(row);
  16372. //浏览器方法本身存在bug,采用自定义方法删除
  16373. //this.table.deleteRow(rowIndex);
  16374. this.update();
  16375. },
  16376. insertCol:function (colIndex, sourceCell, defaultValue) {
  16377. var rowsNum = this.rowsNum,
  16378. rowIndex = 0,
  16379. tableRow, cell,
  16380. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  16381. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  16382. function replaceTdToTh(rowIndex, cell, tableRow) {
  16383. if (rowIndex == 0) {
  16384. var th = cell.nextSibling || cell.previousSibling;
  16385. if (th.tagName == 'TH') {
  16386. th = cell.ownerDocument.createElement("th");
  16387. th.appendChild(cell.firstChild);
  16388. tableRow.insertBefore(th, cell);
  16389. domUtils.remove(cell)
  16390. }
  16391. }else{
  16392. if (cell.tagName == 'TH') {
  16393. var td = cell.ownerDocument.createElement("td");
  16394. td.appendChild(cell.firstChild);
  16395. tableRow.insertBefore(td, cell);
  16396. domUtils.remove(cell)
  16397. }
  16398. }
  16399. }
  16400. var preCell;
  16401. if (colIndex == 0 || colIndex == this.colsNum) {
  16402. for (; rowIndex < rowsNum; rowIndex++) {
  16403. tableRow = this.table.rows[rowIndex];
  16404. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  16405. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  16406. this.setCellContent(cell);
  16407. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16408. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  16409. if (!colIndex) {
  16410. tableRow.insertBefore(cell, tableRow.cells[0]);
  16411. } else {
  16412. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  16413. }
  16414. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  16415. }
  16416. } else {
  16417. for (; rowIndex < rowsNum; rowIndex++) {
  16418. var cellInfo = this.indexTable[rowIndex][colIndex];
  16419. if (cellInfo.colIndex < colIndex) {
  16420. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16421. cell.colSpan = cellInfo.colSpan + 1;
  16422. } else {
  16423. tableRow = this.table.rows[rowIndex];
  16424. preCell = tableRow.cells[cellInfo.cellIndex];
  16425. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  16426. this.setCellContent(cell);
  16427. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16428. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  16429. //防止IE下报错
  16430. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  16431. }
  16432. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  16433. }
  16434. }
  16435. //框选时插入不触发contentchange,需要手动更新索引
  16436. this.update();
  16437. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  16438. },
  16439. updateWidth:function (width, defaultValue) {
  16440. var table = this.table,
  16441. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  16442. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  16443. table.setAttribute("width", tmpWidth);
  16444. return;
  16445. }
  16446. var tds = domUtils.getElementsByTagName(this.table, "td th");
  16447. utils.each(tds, function (td) {
  16448. td.setAttribute("width", width);
  16449. })
  16450. },
  16451. deleteCol:function (colIndex) {
  16452. var indexTable = this.indexTable,
  16453. tableRows = this.table.rows,
  16454. backTableWidth = this.table.getAttribute("width"),
  16455. backTdWidth = 0,
  16456. rowsNum = this.rowsNum,
  16457. cacheMap = {};
  16458. for (var rowIndex = 0; rowIndex < rowsNum;) {
  16459. var infoRow = indexTable[rowIndex],
  16460. cellInfo = infoRow[colIndex],
  16461. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  16462. // 跳过已经处理过的Cell
  16463. if (cacheMap[key])continue;
  16464. cacheMap[key] = 1;
  16465. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16466. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  16467. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  16468. if (cell.colSpan > 1) {
  16469. cell.colSpan--;
  16470. } else {
  16471. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  16472. }
  16473. rowIndex += cellInfo.rowSpan || 1;
  16474. }
  16475. this.table.setAttribute("width", backTableWidth - backTdWidth);
  16476. this.update();
  16477. },
  16478. splitToCells:function (cell) {
  16479. var me = this,
  16480. cells = this.splitToRows(cell);
  16481. utils.each(cells, function (cell) {
  16482. me.splitToCols(cell);
  16483. })
  16484. },
  16485. splitToRows:function (cell) {
  16486. var cellInfo = this.getCellInfo(cell),
  16487. rowIndex = cellInfo.rowIndex,
  16488. colIndex = cellInfo.colIndex,
  16489. results = [];
  16490. // 修改Cell的rowSpan
  16491. cell.rowSpan = 1;
  16492. results.push(cell);
  16493. // 补齐单元格
  16494. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  16495. if (i == rowIndex)continue;
  16496. var tableRow = this.table.rows[i],
  16497. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  16498. tmpCell.colSpan = cellInfo.colSpan;
  16499. this.setCellContent(tmpCell);
  16500. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16501. tmpCell.setAttribute('align', cell.getAttribute('align'));
  16502. if (cell.style.cssText) {
  16503. tmpCell.style.cssText = cell.style.cssText;
  16504. }
  16505. results.push(tmpCell);
  16506. }
  16507. this.update();
  16508. return results;
  16509. },
  16510. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  16511. var indexRow = this.indexTable[rowIndex],
  16512. num = 0;
  16513. for (var i = 0; i < colIndex;) {
  16514. var colSpan = indexRow[i].colSpan,
  16515. tmpRowIndex = indexRow[i].rowIndex;
  16516. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  16517. i += colSpan;
  16518. }
  16519. return num;
  16520. },
  16521. splitToCols:function (cell) {
  16522. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  16523. cellInfo = this.getCellInfo(cell),
  16524. rowIndex = cellInfo.rowIndex,
  16525. colIndex = cellInfo.colIndex,
  16526. results = [];
  16527. // 修改Cell的rowSpan
  16528. cell.colSpan = 1;
  16529. cell.setAttribute("width", backWidth);
  16530. results.push(cell);
  16531. // 补齐单元格
  16532. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  16533. if (j == colIndex)continue;
  16534. var tableRow = this.table.rows[rowIndex],
  16535. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  16536. tmpCell.rowSpan = cellInfo.rowSpan;
  16537. this.setCellContent(tmpCell);
  16538. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16539. tmpCell.setAttribute('align', cell.getAttribute('align'));
  16540. tmpCell.setAttribute('width', backWidth);
  16541. if (cell.style.cssText) {
  16542. tmpCell.style.cssText = cell.style.cssText;
  16543. }
  16544. //处理th的情况
  16545. if (cell.tagName == 'TH') {
  16546. var th = cell.ownerDocument.createElement('th');
  16547. th.appendChild(tmpCell.firstChild);
  16548. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16549. th.rowSpan = tmpCell.rowSpan;
  16550. tableRow.insertBefore(th, tmpCell);
  16551. domUtils.remove(tmpCell);
  16552. }
  16553. results.push(tmpCell);
  16554. }
  16555. this.update();
  16556. return results;
  16557. },
  16558. isLastCell:function (cell, rowsNum, colsNum) {
  16559. rowsNum = rowsNum || this.rowsNum;
  16560. colsNum = colsNum || this.colsNum;
  16561. var cellInfo = this.getCellInfo(cell);
  16562. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  16563. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  16564. },
  16565. getLastCell:function (cells) {
  16566. cells = cells || this.table.getElementsByTagName("td");
  16567. var firstInfo = this.getCellInfo(cells[0]);
  16568. var me = this, last = cells[0],
  16569. tr = last.parentNode,
  16570. cellsNum = 0, cols = 0, rows;
  16571. utils.each(cells, function (cell) {
  16572. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  16573. cellsNum += cell.rowSpan * cell.colSpan || 1;
  16574. });
  16575. rows = cellsNum / cols;
  16576. utils.each(cells, function (cell) {
  16577. if (me.isLastCell(cell, rows, cols)) {
  16578. last = cell;
  16579. return false;
  16580. }
  16581. });
  16582. return last;
  16583. },
  16584. selectRow:function (rowIndex) {
  16585. var indexRow = this.indexTable[rowIndex],
  16586. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  16587. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  16588. range = this.getCellsRange(start, end);
  16589. this.setSelected(range);
  16590. },
  16591. selectTable:function () {
  16592. var tds = this.table.getElementsByTagName("td"),
  16593. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  16594. this.setSelected(range);
  16595. },
  16596. setBackground:function (cells, value) {
  16597. if (typeof value === "string") {
  16598. utils.each(cells, function (cell) {
  16599. cell.style.backgroundColor = value;
  16600. })
  16601. } else if (typeof value === "object") {
  16602. value = utils.extend({
  16603. repeat:true,
  16604. colorList:["#ddd", "#fff"]
  16605. }, value);
  16606. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  16607. count = 0,
  16608. colors = value.colorList,
  16609. getColor = function (list, index, repeat) {
  16610. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  16611. };
  16612. for (var i = 0, cell; cell = cells[i++];) {
  16613. var cellInfo = this.getCellInfo(cell);
  16614. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  16615. }
  16616. }
  16617. },
  16618. removeBackground:function (cells) {
  16619. utils.each(cells, function (cell) {
  16620. cell.style.backgroundColor = "";
  16621. })
  16622. }
  16623. };
  16624. function showError(e) {
  16625. }
  16626. })();
  16627. /**
  16628. * Created with JetBrains PhpStorm.
  16629. * User: taoqili
  16630. * Date: 13-2-20
  16631. * Time: 下午6:25
  16632. * To change this template use File | Settings | File Templates.
  16633. */
  16634. ;
  16635. (function () {
  16636. var UT = UE.UETable,
  16637. getTableItemsByRange = function (editor) {
  16638. return UT.getTableItemsByRange(editor);
  16639. },
  16640. getUETableBySelected = function (editor) {
  16641. return UT.getUETableBySelected(editor)
  16642. },
  16643. getDefaultValue = function (editor, table) {
  16644. return UT.getDefaultValue(editor, table);
  16645. },
  16646. getUETable = function (tdOrTable) {
  16647. return UT.getUETable(tdOrTable);
  16648. };
  16649. UE.commands['inserttable'] = {
  16650. queryCommandState: function () {
  16651. return getTableItemsByRange(this).table ? -1 : 0;
  16652. },
  16653. execCommand: function (cmd, opt) {
  16654. function createTable(opt, tdWidth) {
  16655. var html = [],
  16656. rowsNum = opt.numRows,
  16657. colsNum = opt.numCols;
  16658. for (var r = 0; r < rowsNum; r++) {
  16659. html.push('<tr>');
  16660. for (var c = 0; c < colsNum; c++) {
  16661. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie ? domUtils.fillChar : '<br/>') + '</td>')
  16662. }
  16663. html.push('</tr>')
  16664. }
  16665. //禁止指定table-width
  16666. return '<table><tbody>' + html.join('') + '</tbody></table>'
  16667. }
  16668. if (!opt) {
  16669. opt = utils.extend({}, {
  16670. numCols: this.options.defaultCols,
  16671. numRows: this.options.defaultRows,
  16672. tdvalign: this.options.tdvalign
  16673. })
  16674. }
  16675. var me = this;
  16676. var range = this.selection.getRange(),
  16677. start = range.startContainer,
  16678. firstParentBlock = domUtils.findParent(start, function (node) {
  16679. return domUtils.isBlockElm(node);
  16680. }, true) || me.body;
  16681. var defaultValue = getDefaultValue(me),
  16682. tableWidth = firstParentBlock.offsetWidth,
  16683. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  16684. //todo其他属性
  16685. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  16686. me.execCommand("inserthtml", createTable(opt, tdWidth));
  16687. }
  16688. };
  16689. UE.commands['insertparagraphbeforetable'] = {
  16690. queryCommandState: function () {
  16691. return getTableItemsByRange(this).cell ? 0 : -1;
  16692. },
  16693. execCommand: function () {
  16694. var table = getTableItemsByRange(this).table;
  16695. if (table) {
  16696. var p = this.document.createElement("p");
  16697. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  16698. table.parentNode.insertBefore(p, table);
  16699. this.selection.getRange().setStart(p, 0).setCursor();
  16700. }
  16701. }
  16702. };
  16703. UE.commands['deletetable'] = {
  16704. queryCommandState: function () {
  16705. var rng = this.selection.getRange();
  16706. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  16707. },
  16708. execCommand: function (cmd, table) {
  16709. var rng = this.selection.getRange();
  16710. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  16711. if (table) {
  16712. var next = table.nextSibling;
  16713. if (!next) {
  16714. next = domUtils.createElement(this.document, 'p', {
  16715. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  16716. });
  16717. table.parentNode.insertBefore(next, table);
  16718. }
  16719. domUtils.remove(table);
  16720. rng = this.selection.getRange();
  16721. if (next.nodeType == 3) {
  16722. rng.setStartBefore(next)
  16723. } else {
  16724. rng.setStart(next, 0)
  16725. }
  16726. rng.setCursor(false, true)
  16727. this.fireEvent("tablehasdeleted")
  16728. }
  16729. }
  16730. };
  16731. UE.commands['cellalign'] = {
  16732. queryCommandState: function () {
  16733. return getSelectedArr(this).length ? 0 : -1
  16734. },
  16735. execCommand: function (cmd, align) {
  16736. var selectedTds = getSelectedArr(this);
  16737. if (selectedTds.length) {
  16738. for (var i = 0, ci; ci = selectedTds[i++];) {
  16739. ci.setAttribute('align', align);
  16740. }
  16741. }
  16742. }
  16743. };
  16744. UE.commands['cellvalign'] = {
  16745. queryCommandState: function () {
  16746. return getSelectedArr(this).length ? 0 : -1;
  16747. },
  16748. execCommand: function (cmd, valign) {
  16749. var selectedTds = getSelectedArr(this);
  16750. if (selectedTds.length) {
  16751. for (var i = 0, ci; ci = selectedTds[i++];) {
  16752. ci.setAttribute('vAlign', valign);
  16753. }
  16754. }
  16755. }
  16756. };
  16757. UE.commands['insertcaption'] = {
  16758. queryCommandState: function () {
  16759. var table = getTableItemsByRange(this).table;
  16760. if (table) {
  16761. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  16762. }
  16763. return -1;
  16764. },
  16765. execCommand: function () {
  16766. var table = getTableItemsByRange(this).table;
  16767. if (table) {
  16768. var caption = this.document.createElement('caption');
  16769. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  16770. table.insertBefore(caption, table.firstChild);
  16771. var range = this.selection.getRange();
  16772. range.setStart(caption, 0).setCursor();
  16773. }
  16774. }
  16775. };
  16776. UE.commands['deletecaption'] = {
  16777. queryCommandState: function () {
  16778. var rng = this.selection.getRange(),
  16779. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  16780. if (table) {
  16781. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  16782. }
  16783. return -1;
  16784. },
  16785. execCommand: function () {
  16786. var rng = this.selection.getRange(),
  16787. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  16788. if (table) {
  16789. domUtils.remove(table.getElementsByTagName('caption')[0]);
  16790. var range = this.selection.getRange();
  16791. range.setStart(table.rows[0].cells[0], 0).setCursor();
  16792. }
  16793. }
  16794. };
  16795. UE.commands['inserttitle'] = {
  16796. queryCommandState: function () {
  16797. var table = getTableItemsByRange(this).table;
  16798. if (table) {
  16799. var firstRow = table.rows[0];
  16800. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  16801. }
  16802. return -1;
  16803. },
  16804. execCommand: function () {
  16805. var table = getTableItemsByRange(this).table;
  16806. if (table) {
  16807. getUETable(table).insertRow(0, 'th');
  16808. }
  16809. var th = table.getElementsByTagName('th')[0];
  16810. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  16811. }
  16812. };
  16813. UE.commands['deletetitle'] = {
  16814. queryCommandState: function () {
  16815. var table = getTableItemsByRange(this).table;
  16816. if (table) {
  16817. var firstRow = table.rows[0];
  16818. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  16819. }
  16820. return -1;
  16821. },
  16822. execCommand: function () {
  16823. var table = getTableItemsByRange(this).table;
  16824. if (table) {
  16825. domUtils.remove(table.rows[0])
  16826. }
  16827. var td = table.getElementsByTagName('td')[0];
  16828. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  16829. }
  16830. };
  16831. UE.commands['inserttitlecol'] = {
  16832. queryCommandState: function () {
  16833. var table = getTableItemsByRange(this).table;
  16834. if (table) {
  16835. var lastRow = table.rows[table.rows.length-1];
  16836. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  16837. }
  16838. return -1;
  16839. },
  16840. execCommand: function (cmd) {
  16841. var table = getTableItemsByRange(this).table;
  16842. if (table) {
  16843. getUETable(table).insertCol(0, 'th');
  16844. }
  16845. resetTdWidth(table, this);
  16846. var th = table.getElementsByTagName('th')[0];
  16847. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  16848. }
  16849. };
  16850. UE.commands['deletetitlecol'] = {
  16851. queryCommandState: function () {
  16852. var table = getTableItemsByRange(this).table;
  16853. if (table) {
  16854. var lastRow = table.rows[table.rows.length-1];
  16855. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  16856. }
  16857. return -1;
  16858. },
  16859. execCommand: function () {
  16860. var table = getTableItemsByRange(this).table;
  16861. if (table) {
  16862. for(var i = 0; i< table.rows.length; i++ ){
  16863. domUtils.remove(table.rows[i].children[0])
  16864. }
  16865. }
  16866. resetTdWidth(table, this);
  16867. var td = table.getElementsByTagName('td')[0];
  16868. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  16869. }
  16870. };
  16871. UE.commands["mergeright"] = {
  16872. queryCommandState: function (cmd) {
  16873. var tableItems = getTableItemsByRange(this);
  16874. if (!tableItems.cell) return -1;
  16875. var ut = getUETable(tableItems.table);
  16876. if (ut.selectedTds.length) return -1;
  16877. var cellInfo = ut.getCellInfo(tableItems.cell),
  16878. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  16879. if (rightColIndex >= ut.colsNum) return -1;
  16880. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex];
  16881. return (rightCellInfo.rowIndex == cellInfo.rowIndex
  16882. && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  16883. },
  16884. execCommand: function (cmd) {
  16885. var rng = this.selection.getRange(),
  16886. bk = rng.createBookmark(true);
  16887. var cell = getTableItemsByRange(this).cell,
  16888. ut = getUETable(cell);
  16889. ut.mergeRight(cell);
  16890. rng.moveToBookmark(bk).select();
  16891. }
  16892. };
  16893. UE.commands["mergedown"] = {
  16894. queryCommandState: function (cmd) {
  16895. var tableItems = getTableItemsByRange(this),
  16896. cell = tableItems.cell;
  16897. if (!cell || cell.tagName == "TH") return -1;
  16898. var ut = getUETable(tableItems.table);
  16899. if (ut.selectedTds.length)return -1;
  16900. var cellInfo = ut.getCellInfo(tableItems.cell),
  16901. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  16902. // 如果处于最下边则不能f向右合并
  16903. if (downRowIndex >= ut.rowsNum) return -1;
  16904. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex];
  16905. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  16906. return (downCellInfo.colIndex == cellInfo.colIndex
  16907. && downCellInfo.colSpan == cellInfo.colSpan) && tableItems.cell.tagName !== 'TH' ? 0 : -1;
  16908. },
  16909. execCommand: function () {
  16910. var rng = this.selection.getRange(),
  16911. bk = rng.createBookmark(true);
  16912. var cell = getTableItemsByRange(this).cell,
  16913. ut = getUETable(cell);
  16914. ut.mergeDown(cell);
  16915. rng.moveToBookmark(bk).select();
  16916. }
  16917. };
  16918. UE.commands["mergecells"] = {
  16919. queryCommandState: function () {
  16920. return getUETableBySelected(this) ? 0 : -1;
  16921. },
  16922. execCommand: function () {
  16923. var ut = getUETableBySelected(this);
  16924. if (ut && ut.selectedTds.length) {
  16925. var cell = ut.selectedTds[0];
  16926. ut.mergeRange();
  16927. var rng = this.selection.getRange();
  16928. if (domUtils.isEmptyBlock(cell)) {
  16929. rng.setStart(cell, 0).collapse(true)
  16930. } else {
  16931. rng.selectNodeContents(cell)
  16932. }
  16933. rng.select();
  16934. }
  16935. }
  16936. };
  16937. UE.commands["insertrow"] = {
  16938. queryCommandState: function () {
  16939. var tableItems = getTableItemsByRange(this),
  16940. cell = tableItems.cell;
  16941. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  16942. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  16943. },
  16944. execCommand: function () {
  16945. var rng = this.selection.getRange(),
  16946. bk = rng.createBookmark(true);
  16947. var tableItems = getTableItemsByRange(this),
  16948. cell = tableItems.cell,
  16949. table = tableItems.table,
  16950. ut = getUETable(table),
  16951. cellInfo = ut.getCellInfo(cell);
  16952. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  16953. if (!ut.selectedTds.length) {
  16954. ut.insertRow(cellInfo.rowIndex, cell);
  16955. } else {
  16956. var range = ut.cellsRange;
  16957. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  16958. ut.insertRow(range.beginRowIndex, cell);
  16959. }
  16960. }
  16961. rng.moveToBookmark(bk).select();
  16962. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  16963. }
  16964. };
  16965. //后插入行
  16966. UE.commands["insertrownext"] = {
  16967. queryCommandState: function () {
  16968. var tableItems = getTableItemsByRange(this),
  16969. cell = tableItems.cell;
  16970. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  16971. },
  16972. execCommand: function () {
  16973. var rng = this.selection.getRange(),
  16974. bk = rng.createBookmark(true);
  16975. var tableItems = getTableItemsByRange(this),
  16976. cell = tableItems.cell,
  16977. table = tableItems.table,
  16978. ut = getUETable(table),
  16979. cellInfo = ut.getCellInfo(cell);
  16980. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  16981. if (!ut.selectedTds.length) {
  16982. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  16983. } else {
  16984. var range = ut.cellsRange;
  16985. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  16986. ut.insertRow(range.endRowIndex + 1, cell);
  16987. }
  16988. }
  16989. rng.moveToBookmark(bk).select();
  16990. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  16991. }
  16992. };
  16993. UE.commands["deleterow"] = {
  16994. queryCommandState: function () {
  16995. var tableItems = getTableItemsByRange(this);
  16996. if (!tableItems.cell) {
  16997. return -1;
  16998. }
  16999. },
  17000. execCommand: function () {
  17001. var cell = getTableItemsByRange(this).cell,
  17002. ut = getUETable(cell),
  17003. cellsRange = ut.cellsRange,
  17004. cellInfo = ut.getCellInfo(cell),
  17005. preCell = ut.getVSideCell(cell),
  17006. nextCell = ut.getVSideCell(cell, true),
  17007. rng = this.selection.getRange();
  17008. if (utils.isEmptyObject(cellsRange)) {
  17009. ut.deleteRow(cellInfo.rowIndex);
  17010. } else {
  17011. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17012. ut.deleteRow(cellsRange.beginRowIndex);
  17013. }
  17014. }
  17015. var table = ut.table;
  17016. if (!table.getElementsByTagName('td').length) {
  17017. var nextSibling = table.nextSibling;
  17018. domUtils.remove(table);
  17019. if (nextSibling) {
  17020. rng.setStart(nextSibling, 0).setCursor(false, true);
  17021. }
  17022. } else {
  17023. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17024. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17025. } else {
  17026. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17027. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17028. }
  17029. }
  17030. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17031. }
  17032. };
  17033. UE.commands["insertcol"] = {
  17034. queryCommandState: function (cmd) {
  17035. var tableItems = getTableItemsByRange(this),
  17036. cell = tableItems.cell;
  17037. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17038. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17039. },
  17040. execCommand: function (cmd) {
  17041. var rng = this.selection.getRange(),
  17042. bk = rng.createBookmark(true);
  17043. if (this.queryCommandState(cmd) == -1)return;
  17044. var cell = getTableItemsByRange(this).cell,
  17045. ut = getUETable(cell),
  17046. cellInfo = ut.getCellInfo(cell);
  17047. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17048. if (!ut.selectedTds.length) {
  17049. ut.insertCol(cellInfo.colIndex, cell);
  17050. } else {
  17051. var range = ut.cellsRange;
  17052. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17053. ut.insertCol(range.beginColIndex, cell);
  17054. }
  17055. }
  17056. rng.moveToBookmark(bk).select(true);
  17057. }
  17058. };
  17059. UE.commands["insertcolnext"] = {
  17060. queryCommandState: function () {
  17061. var tableItems = getTableItemsByRange(this),
  17062. cell = tableItems.cell;
  17063. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17064. },
  17065. execCommand: function () {
  17066. var rng = this.selection.getRange(),
  17067. bk = rng.createBookmark(true);
  17068. var cell = getTableItemsByRange(this).cell,
  17069. ut = getUETable(cell),
  17070. cellInfo = ut.getCellInfo(cell);
  17071. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17072. if (!ut.selectedTds.length) {
  17073. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17074. } else {
  17075. var range = ut.cellsRange;
  17076. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17077. ut.insertCol(range.endColIndex + 1, cell);
  17078. }
  17079. }
  17080. rng.moveToBookmark(bk).select();
  17081. }
  17082. };
  17083. UE.commands["deletecol"] = {
  17084. queryCommandState: function () {
  17085. var tableItems = getTableItemsByRange(this);
  17086. if (!tableItems.cell) return -1;
  17087. },
  17088. execCommand: function () {
  17089. var cell = getTableItemsByRange(this).cell,
  17090. ut = getUETable(cell),
  17091. range = ut.cellsRange,
  17092. cellInfo = ut.getCellInfo(cell),
  17093. preCell = ut.getHSideCell(cell),
  17094. nextCell = ut.getHSideCell(cell, true);
  17095. if (utils.isEmptyObject(range)) {
  17096. ut.deleteCol(cellInfo.colIndex);
  17097. } else {
  17098. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17099. ut.deleteCol(range.beginColIndex);
  17100. }
  17101. }
  17102. var table = ut.table,
  17103. rng = this.selection.getRange();
  17104. if (!table.getElementsByTagName('td').length) {
  17105. var nextSibling = table.nextSibling;
  17106. domUtils.remove(table);
  17107. if (nextSibling) {
  17108. rng.setStart(nextSibling, 0).setCursor(false, true);
  17109. }
  17110. } else {
  17111. if (domUtils.inDoc(cell, this.document)) {
  17112. rng.setStart(cell, 0).setCursor(false, true);
  17113. } else {
  17114. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17115. rng.selectNodeContents(nextCell).setCursor(false, true);
  17116. } else {
  17117. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17118. rng.selectNodeContents(preCell).setCursor(true, true);
  17119. }
  17120. }
  17121. }
  17122. }
  17123. }
  17124. };
  17125. UE.commands["splittocells"] = {
  17126. queryCommandState: function () {
  17127. var tableItems = getTableItemsByRange(this),
  17128. cell = tableItems.cell;
  17129. if (!cell) return -1;
  17130. var ut = getUETable(tableItems.table);
  17131. if (ut.selectedTds.length > 0) return -1;
  17132. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17133. },
  17134. execCommand: function () {
  17135. var rng = this.selection.getRange(),
  17136. bk = rng.createBookmark(true);
  17137. var cell = getTableItemsByRange(this).cell,
  17138. ut = getUETable(cell);
  17139. ut.splitToCells(cell);
  17140. rng.moveToBookmark(bk).select();
  17141. }
  17142. };
  17143. UE.commands["splittorows"] = {
  17144. queryCommandState: function () {
  17145. var tableItems = getTableItemsByRange(this),
  17146. cell = tableItems.cell;
  17147. if (!cell) return -1;
  17148. var ut = getUETable(tableItems.table);
  17149. if (ut.selectedTds.length > 0) return -1;
  17150. return cell && cell.rowSpan > 1 ? 0 : -1;
  17151. },
  17152. execCommand: function () {
  17153. var rng = this.selection.getRange(),
  17154. bk = rng.createBookmark(true);
  17155. var cell = getTableItemsByRange(this).cell,
  17156. ut = getUETable(cell);
  17157. ut.splitToRows(cell);
  17158. rng.moveToBookmark(bk).select();
  17159. }
  17160. };
  17161. UE.commands["splittocols"] = {
  17162. queryCommandState: function () {
  17163. var tableItems = getTableItemsByRange(this),
  17164. cell = tableItems.cell;
  17165. if (!cell) return -1;
  17166. var ut = getUETable(tableItems.table);
  17167. if (ut.selectedTds.length > 0) return -1;
  17168. return cell && cell.colSpan > 1 ? 0 : -1;
  17169. },
  17170. execCommand: function () {
  17171. var rng = this.selection.getRange(),
  17172. bk = rng.createBookmark(true);
  17173. var cell = getTableItemsByRange(this).cell,
  17174. ut = getUETable(cell);
  17175. ut.splitToCols(cell);
  17176. rng.moveToBookmark(bk).select();
  17177. }
  17178. };
  17179. UE.commands["adaptbytext"] =
  17180. UE.commands["adaptbywindow"] = {
  17181. queryCommandState: function () {
  17182. return getTableItemsByRange(this).table ? 0 : -1
  17183. },
  17184. execCommand: function (cmd) {
  17185. var tableItems = getTableItemsByRange(this),
  17186. table = tableItems.table;
  17187. if (table) {
  17188. if (cmd == 'adaptbywindow') {
  17189. resetTdWidth(table, this);
  17190. } else {
  17191. var cells = domUtils.getElementsByTagName(table, "td th");
  17192. utils.each(cells, function (cell) {
  17193. cell.removeAttribute("width");
  17194. });
  17195. table.removeAttribute("width");
  17196. }
  17197. }
  17198. }
  17199. };
  17200. //平均分配各列
  17201. UE.commands['averagedistributecol'] = {
  17202. queryCommandState: function () {
  17203. var ut = getUETableBySelected(this);
  17204. if (!ut) return -1;
  17205. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  17206. },
  17207. execCommand: function (cmd) {
  17208. var me = this,
  17209. ut = getUETableBySelected(me);
  17210. function getAverageWidth() {
  17211. var tb = ut.table,
  17212. averageWidth, sumWidth = 0, colsNum = 0,
  17213. tbAttr = getDefaultValue(me, tb);
  17214. if (ut.isFullRow()) {
  17215. sumWidth = tb.offsetWidth;
  17216. colsNum = ut.colsNum;
  17217. } else {
  17218. var begin = ut.cellsRange.beginColIndex,
  17219. end = ut.cellsRange.endColIndex,
  17220. node;
  17221. for (var i = begin; i <= end;) {
  17222. node = ut.selectedTds[i];
  17223. sumWidth += node.offsetWidth;
  17224. i += node.colSpan;
  17225. colsNum += 1;
  17226. }
  17227. }
  17228. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  17229. return averageWidth;
  17230. }
  17231. function setAverageWidth(averageWidth) {
  17232. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  17233. node.setAttribute("width", "");
  17234. });
  17235. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  17236. utils.each(cells, function (node) {
  17237. if (node.colSpan == 1) {
  17238. node.setAttribute("width", averageWidth);
  17239. }
  17240. });
  17241. }
  17242. if (ut && ut.selectedTds.length) {
  17243. setAverageWidth(getAverageWidth());
  17244. }
  17245. }
  17246. };
  17247. //平均分配各行
  17248. UE.commands['averagedistributerow'] = {
  17249. queryCommandState: function () {
  17250. var ut = getUETableBySelected(this);
  17251. if (!ut) return -1;
  17252. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  17253. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  17254. },
  17255. execCommand: function (cmd) {
  17256. var me = this,
  17257. ut = getUETableBySelected(me);
  17258. function getAverageHeight() {
  17259. var averageHeight, rowNum, sumHeight = 0,
  17260. tb = ut.table,
  17261. tbAttr = getDefaultValue(me, tb),
  17262. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  17263. if (ut.isFullCol()) {
  17264. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  17265. thArr = domUtils.getElementsByTagName(tb, "th"),
  17266. captionHeight, thHeight;
  17267. if (captionArr.length > 0) {
  17268. captionHeight = captionArr[0].offsetHeight;
  17269. }
  17270. if (thArr.length > 0) {
  17271. thHeight = thArr[0].offsetHeight;
  17272. }
  17273. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  17274. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  17275. } else {
  17276. var begin = ut.cellsRange.beginRowIndex,
  17277. end = ut.cellsRange.endRowIndex,
  17278. count = 0,
  17279. trs = domUtils.getElementsByTagName(tb, "tr");
  17280. for (var i = begin; i <= end; i++) {
  17281. sumHeight += trs[i].offsetHeight;
  17282. count += 1;
  17283. }
  17284. rowNum = count;
  17285. }
  17286. //ie8下是混杂模式
  17287. if (browser.ie && browser.version < 9) {
  17288. averageHeight = Math.ceil(sumHeight / rowNum);
  17289. } else {
  17290. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  17291. }
  17292. return averageHeight;
  17293. }
  17294. function setAverageHeight(averageHeight) {
  17295. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  17296. utils.each(cells, function (node) {
  17297. if (node.rowSpan == 1) {
  17298. node.setAttribute("height", averageHeight);
  17299. }
  17300. });
  17301. }
  17302. if (ut && ut.selectedTds.length) {
  17303. setAverageHeight(getAverageHeight());
  17304. }
  17305. }
  17306. };
  17307. //单元格对齐方式
  17308. UE.commands['cellalignment'] = {
  17309. queryCommandState: function () {
  17310. return getTableItemsByRange(this).table ? 0 : -1
  17311. },
  17312. execCommand: function (cmd, data) {
  17313. var me = this,
  17314. ut = getUETableBySelected(me);
  17315. if (!ut) {
  17316. var start = me.selection.getStart(),
  17317. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  17318. if (!/caption/ig.test(cell.tagName)) {
  17319. domUtils.setAttributes(cell, data);
  17320. } else {
  17321. cell.style.textAlign = data.align;
  17322. cell.style.verticalAlign = data.vAlign;
  17323. }
  17324. me.selection.getRange().setCursor(true);
  17325. } else {
  17326. utils.each(ut.selectedTds, function (cell) {
  17327. domUtils.setAttributes(cell, data);
  17328. });
  17329. }
  17330. },
  17331. /**
  17332. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  17333. * @see UE.UETable.getTableCellAlignState
  17334. */
  17335. queryCommandValue: function (cmd) {
  17336. var activeMenuCell = getTableItemsByRange( this).cell;
  17337. if( !activeMenuCell ) {
  17338. activeMenuCell = getSelectedArr(this)[0];
  17339. }
  17340. if (!activeMenuCell) {
  17341. return null;
  17342. } else {
  17343. //获取同时选中的其他单元格
  17344. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  17345. !cells.length && ( cells = activeMenuCell );
  17346. return UE.UETable.getTableCellAlignState(cells);
  17347. }
  17348. }
  17349. };
  17350. //表格对齐方式
  17351. UE.commands['tablealignment'] = {
  17352. queryCommandState: function () {
  17353. if (browser.ie && browser.version < 8) {
  17354. return -1;
  17355. }
  17356. return getTableItemsByRange(this).table ? 0 : -1
  17357. },
  17358. execCommand: function (cmd, value) {
  17359. var me = this,
  17360. start = me.selection.getStart(),
  17361. table = start && domUtils.findParentByTagName(start, ["table"], true);
  17362. if (table) {
  17363. table.setAttribute("align",value);
  17364. }
  17365. }
  17366. };
  17367. //表格属性
  17368. UE.commands['edittable'] = {
  17369. queryCommandState: function () {
  17370. return getTableItemsByRange(this).table ? 0 : -1
  17371. },
  17372. execCommand: function (cmd, color) {
  17373. var rng = this.selection.getRange(),
  17374. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17375. if (table) {
  17376. var arr = domUtils.getElementsByTagName(table, "td").concat(
  17377. domUtils.getElementsByTagName(table, "th"),
  17378. domUtils.getElementsByTagName(table, "caption")
  17379. );
  17380. utils.each(arr, function (node) {
  17381. node.style.borderColor = color;
  17382. });
  17383. }
  17384. }
  17385. };
  17386. //单元格属性
  17387. UE.commands['edittd'] = {
  17388. queryCommandState: function () {
  17389. return getTableItemsByRange(this).table ? 0 : -1
  17390. },
  17391. execCommand: function (cmd, bkColor) {
  17392. var me = this,
  17393. ut = getUETableBySelected(me);
  17394. if (!ut) {
  17395. var start = me.selection.getStart(),
  17396. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  17397. if (cell) {
  17398. cell.style.backgroundColor = bkColor;
  17399. }
  17400. } else {
  17401. utils.each(ut.selectedTds, function (cell) {
  17402. cell.style.backgroundColor = bkColor;
  17403. });
  17404. }
  17405. }
  17406. };
  17407. UE.commands["settablebackground"] = {
  17408. queryCommandState: function () {
  17409. return getSelectedArr(this).length > 1 ? 0 : -1;
  17410. },
  17411. execCommand: function (cmd, value) {
  17412. var cells, ut;
  17413. cells = getSelectedArr(this);
  17414. ut = getUETable(cells[0]);
  17415. ut.setBackground(cells, value);
  17416. }
  17417. };
  17418. UE.commands["cleartablebackground"] = {
  17419. queryCommandState: function () {
  17420. var cells = getSelectedArr(this);
  17421. if (!cells.length)return -1;
  17422. for (var i = 0, cell; cell = cells[i++];) {
  17423. if (cell.style.backgroundColor !== "") return 0;
  17424. }
  17425. return -1;
  17426. },
  17427. execCommand: function () {
  17428. var cells = getSelectedArr(this),
  17429. ut = getUETable(cells[0]);
  17430. ut.removeBackground(cells);
  17431. }
  17432. };
  17433. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  17434. queryCommandState: function (cmd) {
  17435. var table = getTableItemsByRange(this).table;
  17436. if (!table) return -1;
  17437. var interlaced = table.getAttribute("interlaced");
  17438. if (cmd == "interlacetable") {
  17439. //TODO 待定
  17440. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  17441. return (interlaced === "enabled") ? -1 : 0;
  17442. } else {
  17443. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  17444. }
  17445. },
  17446. execCommand: function (cmd, classList) {
  17447. var table = getTableItemsByRange(this).table;
  17448. if (cmd == "interlacetable") {
  17449. table.setAttribute("interlaced", "enabled");
  17450. this.fireEvent("interlacetable", table, classList);
  17451. } else {
  17452. table.setAttribute("interlaced", "disabled");
  17453. this.fireEvent("uninterlacetable", table);
  17454. }
  17455. }
  17456. };
  17457. UE.commands["setbordervisible"] = {
  17458. queryCommandState: function (cmd) {
  17459. var table = getTableItemsByRange(this).table;
  17460. if (!table) return -1;
  17461. return 0;
  17462. },
  17463. execCommand: function () {
  17464. var table = getTableItemsByRange(this).table;
  17465. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  17466. td.style.borderWidth = '1px';
  17467. td.style.borderStyle = 'solid';
  17468. })
  17469. }
  17470. };
  17471. function resetTdWidth(table, editor) {
  17472. var tds = domUtils.getElementsByTagName(table,'td th');
  17473. utils.each(tds, function (td) {
  17474. td.removeAttribute("width");
  17475. });
  17476. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  17477. var tdsWidths = [];
  17478. setTimeout(function () {
  17479. utils.each(tds, function (td) {
  17480. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  17481. })
  17482. utils.each(tds, function (td,i) {
  17483. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  17484. })
  17485. }, 0);
  17486. }
  17487. function getTableWidth(editor, needIEHack, defaultValue) {
  17488. var body = editor.body;
  17489. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  17490. }
  17491. function getSelectedArr(editor) {
  17492. var cell = getTableItemsByRange(editor).cell;
  17493. if (cell) {
  17494. var ut = getUETable(cell);
  17495. return ut.selectedTds.length ? ut.selectedTds : [cell];
  17496. } else {
  17497. return [];
  17498. }
  17499. }
  17500. })();
  17501. /**
  17502. * Created with JetBrains PhpStorm.
  17503. * User: taoqili
  17504. * Date: 12-10-12
  17505. * Time: 上午10:05
  17506. * To change this template use File | Settings | File Templates.
  17507. */
  17508. UE.plugins['table'] = function () {
  17509. var me = this,
  17510. tabTimer = null,
  17511. //拖动计时器
  17512. tableDragTimer = null,
  17513. //双击计时器
  17514. tableResizeTimer = null,
  17515. //单元格最小宽度
  17516. cellMinWidth = 5,
  17517. isInResizeBuffer = false,
  17518. //单元格边框大小
  17519. cellBorderWidth = 5,
  17520. //鼠标偏移距离
  17521. offsetOfTableCell = 10,
  17522. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  17523. singleClickState = 0,
  17524. userActionStatus = null,
  17525. //双击允许的时间范围
  17526. dblclickTime = 360,
  17527. UT = UE.UETable,
  17528. getUETable = function (tdOrTable) {
  17529. return UT.getUETable(tdOrTable);
  17530. },
  17531. getUETableBySelected = function (editor) {
  17532. return UT.getUETableBySelected(editor);
  17533. },
  17534. getDefaultValue = function (editor, table) {
  17535. return UT.getDefaultValue(editor, table);
  17536. },
  17537. removeSelectedClass = function (cells) {
  17538. return UT.removeSelectedClass(cells);
  17539. };
  17540. function showError(e) {
  17541. // throw e;
  17542. }
  17543. me.ready(function(){
  17544. var me = this;
  17545. var orgGetText = me.selection.getText;
  17546. me.selection.getText = function(){
  17547. var table = getUETableBySelected(me);
  17548. if(table){
  17549. var str = '';
  17550. utils.each(table.selectedTds,function(td){
  17551. str += td[browser.ie?'innerText':'textContent'];
  17552. })
  17553. return str;
  17554. }else{
  17555. return orgGetText.call(me.selection)
  17556. }
  17557. }
  17558. })
  17559. //处理拖动及框选相关方法
  17560. var startTd = null, //鼠标按下时的锚点td
  17561. currentTd = null, //当前鼠标经过时的td
  17562. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  17563. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  17564. dragButton = null,
  17565. dragOver = false,
  17566. dragLine = null, //模拟的拖动线
  17567. dragTd = null; //发生拖动的目标td
  17568. var mousedown = false,
  17569. //todo 判断混乱模式
  17570. needIEHack = true;
  17571. me.setOpt({
  17572. 'maxColNum':20,
  17573. 'maxRowNum':100,
  17574. 'defaultCols':5,
  17575. 'defaultRows':5,
  17576. 'tdvalign':'top',
  17577. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  17578. 'tableDragable':false,
  17579. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  17580. });
  17581. me.getUETable = getUETable;
  17582. var commands = {
  17583. 'deletetable':1,
  17584. 'inserttable':1,
  17585. 'cellvalign':1,
  17586. 'insertcaption':1,
  17587. 'deletecaption':1,
  17588. 'inserttitle':1,
  17589. 'deletetitle':1,
  17590. "mergeright":1,
  17591. "mergedown":1,
  17592. "mergecells":1,
  17593. "insertrow":1,
  17594. "insertrownext":1,
  17595. "deleterow":1,
  17596. "insertcol":1,
  17597. "insertcolnext":1,
  17598. "deletecol":1,
  17599. "splittocells":1,
  17600. "splittorows":1,
  17601. "splittocols":1,
  17602. "adaptbytext":1,
  17603. "adaptbywindow":1,
  17604. "adaptbycustomer":1,
  17605. "insertparagraph":1,
  17606. "insertparagraphbeforetable":1,
  17607. "averagedistributecol":1,
  17608. "averagedistributerow":1
  17609. };
  17610. me.ready(function () {
  17611. utils.cssRule('table',
  17612. //选中的td上的样式
  17613. '.selectTdClass{background-color:#edf5fa !important}' +
  17614. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  17615. //插入的表格的默认样式
  17616. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  17617. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  17618. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  17619. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  17620. 'table tr.firstRow th{border-top-width:2px;}' +
  17621. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  17622. 'td p{margin:0;padding:0;}', me.document);
  17623. var tableCopyList, isFullCol, isFullRow;
  17624. //注册del/backspace事件
  17625. me.addListener('keydown', function (cmd, evt) {
  17626. var me = this;
  17627. var keyCode = evt.keyCode || evt.which;
  17628. if (keyCode == 8) {
  17629. var ut = getUETableBySelected(me);
  17630. if (ut && ut.selectedTds.length) {
  17631. if (ut.isFullCol()) {
  17632. me.execCommand('deletecol')
  17633. } else if (ut.isFullRow()) {
  17634. me.execCommand('deleterow')
  17635. } else {
  17636. me.fireEvent('delcells');
  17637. }
  17638. domUtils.preventDefault(evt);
  17639. }
  17640. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  17641. range = me.selection.getRange();
  17642. if (range.collapsed && caption && isEmptyBlock(caption)) {
  17643. me.fireEvent('saveScene');
  17644. var table = caption.parentNode;
  17645. domUtils.remove(caption);
  17646. if (table) {
  17647. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  17648. }
  17649. me.fireEvent('saveScene');
  17650. }
  17651. }
  17652. if (keyCode == 46) {
  17653. ut = getUETableBySelected(me);
  17654. if (ut) {
  17655. me.fireEvent('saveScene');
  17656. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  17657. domUtils.fillNode(me.document, ci)
  17658. }
  17659. me.fireEvent('saveScene');
  17660. domUtils.preventDefault(evt);
  17661. }
  17662. }
  17663. if (keyCode == 13) {
  17664. var rng = me.selection.getRange(),
  17665. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  17666. if (caption) {
  17667. var table = domUtils.findParentByTagName(caption, 'table');
  17668. if (!rng.collapsed) {
  17669. rng.deleteContents();
  17670. me.fireEvent('saveScene');
  17671. } else {
  17672. if (caption) {
  17673. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  17674. }
  17675. }
  17676. domUtils.preventDefault(evt);
  17677. return;
  17678. }
  17679. if (rng.collapsed) {
  17680. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17681. if (table) {
  17682. var cell = table.rows[0].cells[0],
  17683. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  17684. preNode = table.previousSibling;
  17685. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  17686. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  17687. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  17688. me.execCommand('insertparagraphbeforetable');
  17689. domUtils.preventDefault(evt);
  17690. }
  17691. }
  17692. }
  17693. }
  17694. }
  17695. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  17696. tableCopyList = null;
  17697. var ut = getUETableBySelected(me);
  17698. if (ut) {
  17699. var tds = ut.selectedTds;
  17700. isFullCol = ut.isFullCol();
  17701. isFullRow = ut.isFullRow();
  17702. tableCopyList = [
  17703. [ut.cloneCell(tds[0],null,true)]
  17704. ];
  17705. for (var i = 1, ci; ci = tds[i]; i++) {
  17706. if (ci.parentNode !== tds[i - 1].parentNode) {
  17707. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  17708. } else {
  17709. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  17710. }
  17711. }
  17712. }
  17713. }
  17714. });
  17715. me.addListener("tablehasdeleted",function(){
  17716. toggleDraggableState(this, false, "", null);
  17717. if (dragButton)domUtils.remove(dragButton);
  17718. });
  17719. me.addListener('beforepaste', function (cmd, html) {
  17720. var me = this;
  17721. var rng = me.selection.getRange();
  17722. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  17723. var div = me.document.createElement("div");
  17724. div.innerHTML = html.html;
  17725. //trace:3729
  17726. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  17727. return;
  17728. }
  17729. var table = getUETableBySelected(me);
  17730. if (tableCopyList) {
  17731. me.fireEvent('saveScene');
  17732. var rng = me.selection.getRange();
  17733. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  17734. if (td) {
  17735. var ut = getUETable(td);
  17736. if (isFullRow) {
  17737. var rowIndex = ut.getCellInfo(td).rowIndex;
  17738. if (td.tagName == 'TH') {
  17739. rowIndex++;
  17740. }
  17741. for (var i = 0, ci; ci = tableCopyList[i++];) {
  17742. var tr = ut.insertRow(rowIndex++, "td");
  17743. for (var j = 0, cj; cj = ci[j]; j++) {
  17744. var cell = tr.cells[j];
  17745. if (!cell) {
  17746. cell = tr.insertCell(j)
  17747. }
  17748. cell.innerHTML = cj.innerHTML;
  17749. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  17750. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  17751. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  17752. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  17753. }
  17754. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  17755. if (!ci[j])
  17756. break;
  17757. cj.innerHTML = ci[j].innerHTML;
  17758. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  17759. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  17760. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  17761. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  17762. }
  17763. }
  17764. } else {
  17765. if (isFullCol) {
  17766. cellInfo = ut.getCellInfo(td);
  17767. var maxColNum = 0;
  17768. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  17769. maxColNum += cj.colSpan || 1;
  17770. }
  17771. me.__hasEnterExecCommand = true;
  17772. for (i = 0; i < maxColNum; i++) {
  17773. me.execCommand('insertcol');
  17774. }
  17775. me.__hasEnterExecCommand = false;
  17776. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  17777. if (td.tagName == 'TH') {
  17778. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  17779. }
  17780. }
  17781. for (var i = 0, ci; ci = tableCopyList[i++];) {
  17782. tmpNode = td;
  17783. for (var j = 0, cj; cj = ci[j++];) {
  17784. if (td) {
  17785. td.innerHTML = cj.innerHTML;
  17786. //todo 定制处理
  17787. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  17788. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  17789. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  17790. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  17791. preNode = td;
  17792. td = td.nextSibling;
  17793. } else {
  17794. var cloneTd = cj.cloneNode(true);
  17795. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  17796. preNode.parentNode.appendChild(cloneTd)
  17797. }
  17798. }
  17799. td = ut.getNextCell(tmpNode, true, true);
  17800. if (!tableCopyList[i])
  17801. break;
  17802. if (!td) {
  17803. var cellInfo = ut.getCellInfo(tmpNode);
  17804. ut.table.insertRow(ut.table.rows.length);
  17805. ut.update();
  17806. td = ut.getVSideCell(tmpNode, true);
  17807. }
  17808. }
  17809. }
  17810. ut.update();
  17811. } else {
  17812. table = me.document.createElement('table');
  17813. for (var i = 0, ci; ci = tableCopyList[i++];) {
  17814. var tr = table.insertRow(table.rows.length);
  17815. for (var j = 0, cj; cj = ci[j++];) {
  17816. cloneTd = UT.cloneCell(cj,null,true);
  17817. domUtils.removeAttributes(cloneTd, ['class']);
  17818. tr.appendChild(cloneTd)
  17819. }
  17820. if (j == 2 && cloneTd.rowSpan > 1) {
  17821. cloneTd.rowSpan = 1;
  17822. }
  17823. }
  17824. var defaultValue = getDefaultValue(me),
  17825. width = me.body.offsetWidth -
  17826. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  17827. me.execCommand('insertHTML', '<table ' +
  17828. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  17829. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  17830. }
  17831. me.fireEvent('contentchange');
  17832. me.fireEvent('saveScene');
  17833. html.html = '';
  17834. return true;
  17835. } else {
  17836. var div = me.document.createElement("div"), tables;
  17837. div.innerHTML = html.html;
  17838. tables = div.getElementsByTagName("table");
  17839. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  17840. utils.each(tables, function (t) {
  17841. domUtils.remove(t)
  17842. });
  17843. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  17844. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  17845. }
  17846. } else {
  17847. utils.each(tables, function (table) {
  17848. removeStyleSize(table, true);
  17849. domUtils.removeAttributes(table, ['style', 'border']);
  17850. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  17851. if (isEmptyBlock(td)) {
  17852. domUtils.fillNode(me.document, td);
  17853. }
  17854. removeStyleSize(td, true);
  17855. // domUtils.removeAttributes(td, ['style'])
  17856. });
  17857. });
  17858. }
  17859. html.html = div.innerHTML;
  17860. }
  17861. });
  17862. me.addListener('afterpaste', function () {
  17863. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  17864. if (table.offsetWidth > me.body.offsetWidth) {
  17865. var defaultValue = getDefaultValue(me, table);
  17866. table.style.width = me.body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0) + 'px'
  17867. }
  17868. })
  17869. });
  17870. me.addListener('blur', function () {
  17871. tableCopyList = null;
  17872. });
  17873. var timer;
  17874. me.addListener('keydown', function () {
  17875. clearTimeout(timer);
  17876. timer = setTimeout(function () {
  17877. var rng = me.selection.getRange(),
  17878. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  17879. if (cell) {
  17880. var table = cell.parentNode.parentNode.parentNode;
  17881. if (table.offsetWidth > table.getAttribute("width")) {
  17882. cell.style.wordBreak = "break-all";
  17883. }
  17884. }
  17885. }, 100);
  17886. });
  17887. me.addListener("selectionchange", function () {
  17888. toggleDraggableState(me, false, "", null);
  17889. });
  17890. //内容变化时触发索引更新
  17891. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  17892. me.addListener("contentchange", function () {
  17893. var me = this;
  17894. //尽可能排除一些不需要更新的状况
  17895. hideDragLine(me);
  17896. if (getUETableBySelected(me))return;
  17897. var rng = me.selection.getRange();
  17898. var start = rng.startContainer;
  17899. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  17900. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  17901. if (me.fireEvent("excludetable", table) === true) return;
  17902. table.ueTable = new UT(table);
  17903. //trace:3742
  17904. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  17905. //
  17906. // if (domUtils.isEmptyBlock(td) && td !== start) {
  17907. // domUtils.fillNode(me.document, td);
  17908. // if (browser.ie && browser.version == 6) {
  17909. // td.innerHTML = '&nbsp;'
  17910. // }
  17911. // }
  17912. // });
  17913. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  17914. // if (domUtils.isEmptyBlock(th) && th !== start) {
  17915. // domUtils.fillNode(me.document, th);
  17916. // if (browser.ie && browser.version == 6) {
  17917. // th.innerHTML = '&nbsp;'
  17918. // }
  17919. // }
  17920. // });
  17921. table.onmouseover = function () {
  17922. me.fireEvent('tablemouseover', table);
  17923. };
  17924. table.onmousemove = function () {
  17925. me.fireEvent('tablemousemove', table);
  17926. me.options.tableDragable && toggleDragButton(true, this, me);
  17927. utils.defer(function(){
  17928. me.fireEvent('contentchange',50)
  17929. },true)
  17930. };
  17931. table.onmouseout = function () {
  17932. me.fireEvent('tablemouseout', table);
  17933. toggleDraggableState(me, false, "", null);
  17934. hideDragLine(me);
  17935. };
  17936. table.onclick = function (evt) {
  17937. evt = me.window.event || evt;
  17938. var target = getParentTdOrTh(evt.target || evt.srcElement);
  17939. if (!target)return;
  17940. var ut = getUETable(target),
  17941. table = ut.table,
  17942. cellInfo = ut.getCellInfo(target),
  17943. cellsRange,
  17944. rng = me.selection.getRange();
  17945. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  17946. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  17947. // ut.setSelected(cellsRange);
  17948. // return;
  17949. // }
  17950. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  17951. //
  17952. // return;
  17953. // }
  17954. if (inTableSide(table, target, evt, true)) {
  17955. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  17956. if (evt.shiftKey && ut.selectedTds.length) {
  17957. if (ut.selectedTds[0] !== endTdCol) {
  17958. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  17959. ut.setSelected(cellsRange);
  17960. } else {
  17961. rng && rng.selectNodeContents(endTdCol).select();
  17962. }
  17963. } else {
  17964. if (target !== endTdCol) {
  17965. cellsRange = ut.getCellsRange(target, endTdCol);
  17966. ut.setSelected(cellsRange);
  17967. } else {
  17968. rng && rng.selectNodeContents(endTdCol).select();
  17969. }
  17970. }
  17971. return;
  17972. }
  17973. if (inTableSide(table, target, evt)) {
  17974. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  17975. if (evt.shiftKey && ut.selectedTds.length) {
  17976. if (ut.selectedTds[0] !== endTdRow) {
  17977. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  17978. ut.setSelected(cellsRange);
  17979. } else {
  17980. rng && rng.selectNodeContents(endTdRow).select();
  17981. }
  17982. } else {
  17983. if (target !== endTdRow) {
  17984. cellsRange = ut.getCellsRange(target, endTdRow);
  17985. ut.setSelected(cellsRange);
  17986. } else {
  17987. rng && rng.selectNodeContents(endTdRow).select();
  17988. }
  17989. }
  17990. }
  17991. };
  17992. });
  17993. switchBorderColor(me, true);
  17994. });
  17995. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  17996. domUtils.on(me.document, "mouseout", function (evt) {
  17997. var target = evt.target || evt.srcElement;
  17998. if (target.tagName == "TABLE") {
  17999. toggleDraggableState(me, false, "", null);
  18000. }
  18001. });
  18002. /**
  18003. * 表格隔行变色
  18004. */
  18005. me.addListener("interlacetable",function(type,table,classList){
  18006. if(!table) return;
  18007. var me = this,
  18008. rows = table.rows,
  18009. len = rows.length,
  18010. getClass = function(list,index,repeat){
  18011. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18012. };
  18013. for(var i = 0;i<len;i++){
  18014. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18015. }
  18016. });
  18017. me.addListener("uninterlacetable",function(type,table){
  18018. if(!table) return;
  18019. var me = this,
  18020. rows = table.rows,
  18021. classList = me.options.classList,
  18022. len = rows.length;
  18023. for(var i = 0;i<len;i++){
  18024. domUtils.removeClasses( rows[i], classList );
  18025. }
  18026. });
  18027. me.addListener("mousedown", mouseDownEvent);
  18028. me.addListener("mouseup", mouseUpEvent);
  18029. //拖动的时候不出发mouseup
  18030. domUtils.on( me.body, 'dragstart', function( evt ){
  18031. mouseUpEvent.call( me, 'dragstart', evt );
  18032. });
  18033. var currentRowIndex = 0;
  18034. me.addListener("mousedown", function () {
  18035. currentRowIndex = 0;
  18036. });
  18037. me.addListener('tabkeydown', function () {
  18038. var range = this.selection.getRange(),
  18039. common = range.getCommonAncestor(true, true),
  18040. table = domUtils.findParentByTagName(common, 'table');
  18041. if (table) {
  18042. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18043. var cell = domUtils.getElementsByTagName(table, 'th td');
  18044. if (cell && cell.length) {
  18045. range.setStart(cell[0], 0).setCursor(false, true)
  18046. }
  18047. } else {
  18048. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18049. ua = getUETable(cell);
  18050. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18051. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18052. if (nextCell) {
  18053. if (isEmptyBlock(nextCell)) {
  18054. range.setStart(nextCell, 0).setCursor(false, true)
  18055. } else {
  18056. range.selectNodeContents(nextCell).select()
  18057. }
  18058. } else {
  18059. me.fireEvent('saveScene');
  18060. me.__hasEnterExecCommand = true;
  18061. this.execCommand('insertrownext');
  18062. me.__hasEnterExecCommand = false;
  18063. range = this.selection.getRange();
  18064. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18065. me.fireEvent('saveScene');
  18066. }
  18067. }
  18068. return true;
  18069. }
  18070. });
  18071. browser.ie && me.addListener('selectionchange', function () {
  18072. toggleDraggableState(this, false, "", null);
  18073. });
  18074. me.addListener("keydown", function (type, evt) {
  18075. var me = this;
  18076. //处理在表格的最后一个输入tab产生新的表格
  18077. var keyCode = evt.keyCode || evt.which;
  18078. if (keyCode == 8 || keyCode == 46) {
  18079. return;
  18080. }
  18081. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18082. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18083. var ut = getUETableBySelected(me);
  18084. if (!ut) return;
  18085. notCtrlKey && ut.clearSelected();
  18086. });
  18087. me.addListener("beforegetcontent", function () {
  18088. switchBorderColor(this, false);
  18089. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18090. if (domUtils.isEmptyNode(ci)) {
  18091. ci.innerHTML = '&nbsp;'
  18092. }
  18093. });
  18094. });
  18095. me.addListener("aftergetcontent", function () {
  18096. switchBorderColor(this, true);
  18097. });
  18098. me.addListener("getAllHtml", function () {
  18099. removeSelectedClass(me.document.getElementsByTagName("td"));
  18100. });
  18101. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18102. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18103. if (!fullscreen) {
  18104. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18105. tables = domUtils.getElementsByTagName(this.body, "table");
  18106. utils.each(tables, function (table) {
  18107. if (table.offsetWidth < me.body.offsetWidth) return false;
  18108. var tds = domUtils.getElementsByTagName(table, "td"),
  18109. backWidths = [];
  18110. utils.each(tds, function (td) {
  18111. backWidths.push(td.offsetWidth);
  18112. });
  18113. for (var i = 0, td; td = tds[i]; i++) {
  18114. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18115. }
  18116. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18117. });
  18118. }
  18119. });
  18120. //重写execCommand命令,用于处理框选时的处理
  18121. var oldExecCommand = me.execCommand;
  18122. me.execCommand = function (cmd, datatat) {
  18123. var me = this,
  18124. args = arguments;
  18125. cmd = cmd.toLowerCase();
  18126. var ut = getUETableBySelected(me), tds,
  18127. range = new dom.Range(me.document),
  18128. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18129. result;
  18130. if (!cmdFun) return;
  18131. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18132. me.__hasEnterExecCommand = true;
  18133. me.fireEvent("beforeexeccommand", cmd);
  18134. tds = ut.selectedTds;
  18135. var lastState = -2, lastValue = -2, value, state;
  18136. for (var i = 0, td; td = tds[i]; i++) {
  18137. if (isEmptyBlock(td)) {
  18138. range.setStart(td, 0).setCursor(false, true)
  18139. } else {
  18140. range.selectNode(td).select(true);
  18141. }
  18142. state = me.queryCommandState(cmd);
  18143. value = me.queryCommandValue(cmd);
  18144. if (state != -1) {
  18145. if (lastState !== state || lastValue !== value) {
  18146. me._ignoreContentChange = true;
  18147. result = oldExecCommand.apply(me, arguments);
  18148. me._ignoreContentChange = false;
  18149. }
  18150. lastState = me.queryCommandState(cmd);
  18151. lastValue = me.queryCommandValue(cmd);
  18152. if (domUtils.isEmptyBlock(td)) {
  18153. domUtils.fillNode(me.document, td)
  18154. }
  18155. }
  18156. }
  18157. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  18158. me.fireEvent('contentchange');
  18159. me.fireEvent("afterexeccommand", cmd);
  18160. me.__hasEnterExecCommand = false;
  18161. me._selectionChange();
  18162. } else {
  18163. result = oldExecCommand.apply(me, arguments);
  18164. }
  18165. return result;
  18166. };
  18167. });
  18168. /**
  18169. * 删除obj的宽高style,改成属性宽高
  18170. * @param obj
  18171. * @param replaceToProperty
  18172. */
  18173. function removeStyleSize(obj, replaceToProperty) {
  18174. removeStyle(obj, "width", true);
  18175. removeStyle(obj, "height", true);
  18176. }
  18177. function removeStyle(obj, styleName, replaceToProperty) {
  18178. if (obj.style[styleName]) {
  18179. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  18180. obj.style[styleName] = "";
  18181. }
  18182. }
  18183. function getParentTdOrTh(ele) {
  18184. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  18185. var td;
  18186. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  18187. return null;
  18188. }
  18189. function isEmptyBlock(node) {
  18190. var reg = new RegExp(domUtils.fillChar, 'g');
  18191. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  18192. return 0;
  18193. }
  18194. for (var n in dtd.$isNotEmpty) {
  18195. if (node.getElementsByTagName(n).length) {
  18196. return 0;
  18197. }
  18198. }
  18199. return 1;
  18200. }
  18201. function mouseCoords(evt) {
  18202. if (evt.pageX || evt.pageY) {
  18203. return { x:evt.pageX, y:evt.pageY };
  18204. }
  18205. return {
  18206. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  18207. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  18208. };
  18209. }
  18210. function mouseMoveEvent(evt) {
  18211. if( isEditorDisabled() ) {
  18212. return;
  18213. }
  18214. try {
  18215. //普通状态下鼠标移动
  18216. var target = getParentTdOrTh(evt.target || evt.srcElement),
  18217. pos;
  18218. //区分用户的行为是拖动还是双击
  18219. if( isInResizeBuffer ) {
  18220. me.body.style.webkitUserSelect = 'none';
  18221. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  18222. clearTableDragTimer();
  18223. isInResizeBuffer = false;
  18224. singleClickState = 0;
  18225. //drag action
  18226. tableBorderDrag(evt);
  18227. }
  18228. }
  18229. //修改单元格大小时的鼠标移动
  18230. if (onDrag && dragTd) {
  18231. singleClickState = 0;
  18232. me.body.style.webkitUserSelect = 'none';
  18233. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  18234. pos = mouseCoords(evt);
  18235. toggleDraggableState(me, true, onDrag, pos, target);
  18236. if (onDrag == "h") {
  18237. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  18238. } else if (onDrag == "v") {
  18239. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  18240. }
  18241. return;
  18242. }
  18243. //当鼠标处于table上时,修改移动过程中的光标状态
  18244. if (target) {
  18245. //针对使用table作为容器的组件不触发拖拽效果
  18246. if (me.fireEvent('excludetable', target) === true)
  18247. return;
  18248. pos = mouseCoords(evt);
  18249. var state = getRelation(target, pos),
  18250. table = domUtils.findParentByTagName(target, "table", true);
  18251. if (inTableSide(table, target, evt, true)) {
  18252. if (me.fireEvent("excludetable", table) === true) return;
  18253. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  18254. } else if (inTableSide(table, target, evt)) {
  18255. if (me.fireEvent("excludetable", table) === true) return;
  18256. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  18257. } else {
  18258. me.body.style.cursor = "text";
  18259. var curCell = target;
  18260. if (/\d/.test(state)) {
  18261. state = state.replace(/\d/, '');
  18262. target = getUETable(target).getPreviewCell(target, state == "v");
  18263. }
  18264. //位于第一行的顶部或者第一列的左边时不可拖动
  18265. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  18266. }
  18267. } else {
  18268. toggleDragButton(false, table, me);
  18269. }
  18270. } catch (e) {
  18271. showError(e);
  18272. }
  18273. }
  18274. var dragButtonTimer;
  18275. function toggleDragButton(show, table, editor) {
  18276. if (!show) {
  18277. if (dragOver)return;
  18278. dragButtonTimer = setTimeout(function () {
  18279. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  18280. }, 2000);
  18281. } else {
  18282. createDragButton(table, editor);
  18283. }
  18284. }
  18285. function createDragButton(table, editor) {
  18286. var pos = domUtils.getXY(table),
  18287. doc = table.ownerDocument;
  18288. if (dragButton && dragButton.parentNode)return dragButton;
  18289. dragButton = doc.createElement("div");
  18290. dragButton.contentEditable = false;
  18291. dragButton.innerHTML = "";
  18292. dragButton.style.cssText = "width:15px;height:15px;background-image:url(" + editor.options.UEDITOR_HOME_URL + "dialogs/table/dragicon.png);position: absolute;cursor:move;top:" + (pos.y - 15) + "px;left:" + (pos.x) + "px;";
  18293. domUtils.unSelectable(dragButton);
  18294. dragButton.onmouseover = function (evt) {
  18295. dragOver = true;
  18296. };
  18297. dragButton.onmouseout = function (evt) {
  18298. dragOver = false;
  18299. };
  18300. domUtils.on(dragButton, 'click', function (type, evt) {
  18301. doClick(evt, this);
  18302. });
  18303. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  18304. doDblClick(evt);
  18305. });
  18306. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  18307. domUtils.preventDefault(evt);
  18308. });
  18309. var timer;
  18310. function doClick(evt, button) {
  18311. // 部分浏览器下需要清理
  18312. clearTimeout(timer);
  18313. timer = setTimeout(function () {
  18314. editor.fireEvent("tableClicked", table, button);
  18315. }, 300);
  18316. }
  18317. function doDblClick(evt) {
  18318. clearTimeout(timer);
  18319. var ut = getUETable(table),
  18320. start = table.rows[0].cells[0],
  18321. end = ut.getLastCell(),
  18322. range = ut.getCellsRange(start, end);
  18323. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  18324. ut.setSelected(range);
  18325. }
  18326. doc.body.appendChild(dragButton);
  18327. }
  18328. // function inPosition(table, pos) {
  18329. // var tablePos = domUtils.getXY(table),
  18330. // width = table.offsetWidth,
  18331. // height = table.offsetHeight;
  18332. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  18333. // return "topLeft";
  18334. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  18335. // return "bottomRight";
  18336. // }
  18337. // }
  18338. function inTableSide(table, cell, evt, top) {
  18339. var pos = mouseCoords(evt),
  18340. state = getRelation(cell, pos);
  18341. if (top) {
  18342. var caption = table.getElementsByTagName("caption")[0],
  18343. capHeight = caption ? caption.offsetHeight : 0;
  18344. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  18345. } else {
  18346. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  18347. }
  18348. }
  18349. /**
  18350. * 获取拖动时允许的X轴坐标
  18351. * @param dragTd
  18352. * @param evt
  18353. */
  18354. function getPermissionX(dragTd, evt) {
  18355. var ut = getUETable(dragTd);
  18356. if (ut) {
  18357. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  18358. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  18359. mouseX = mouseCoords(evt).x,
  18360. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  18361. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  18362. left += cellMinWidth;
  18363. right -= cellMinWidth;
  18364. return mouseX < left ? left : mouseX > right ? right : mouseX;
  18365. }
  18366. }
  18367. /**
  18368. * 获取拖动时允许的Y轴坐标
  18369. */
  18370. function getPermissionY(dragTd, evt) {
  18371. try {
  18372. var top = domUtils.getXY(dragTd).y,
  18373. mousePosY = mouseCoords(evt).y;
  18374. return mousePosY < top ? top : mousePosY;
  18375. } catch (e) {
  18376. showError(e);
  18377. }
  18378. }
  18379. /**
  18380. * 移动状态切换
  18381. */
  18382. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  18383. try {
  18384. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  18385. if (browser.ie) {
  18386. if (dir && !mousedown && !getUETableBySelected(editor)) {
  18387. getDragLine(editor, editor.document);
  18388. showDragLineAt(dir, cell);
  18389. } else {
  18390. hideDragLine(editor)
  18391. }
  18392. }
  18393. onBorder = draggable;
  18394. } catch (e) {
  18395. showError(e);
  18396. }
  18397. }
  18398. /**
  18399. * 获取与UETable相关的resize line
  18400. * @param uetable UETable对象
  18401. */
  18402. function getResizeLineByUETable() {
  18403. var lineId = '_UETableResizeLine',
  18404. line = this.document.getElementById( lineId );
  18405. if( !line ) {
  18406. line = this.document.createElement("div");
  18407. line.id = lineId;
  18408. line.contnetEditable = false;
  18409. line.setAttribute("unselectable", "on");
  18410. var styles = {
  18411. width: 2*cellBorderWidth + 1 + 'px',
  18412. position: 'absolute',
  18413. 'z-index': 100000,
  18414. cursor: 'col-resize',
  18415. background: 'red',
  18416. display: 'none'
  18417. };
  18418. //切换状态
  18419. line.onmouseout = function(){
  18420. this.style.display = 'none';
  18421. };
  18422. utils.extend( line.style, styles );
  18423. this.document.body.appendChild( line );
  18424. }
  18425. return line;
  18426. }
  18427. /**
  18428. * 更新resize-line
  18429. */
  18430. function updateResizeLine( cell, uetable ) {
  18431. var line = getResizeLineByUETable.call( this ),
  18432. table = uetable.table,
  18433. styles = {
  18434. top: domUtils.getXY( table ).y + 'px',
  18435. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  18436. display: 'block',
  18437. height: table.offsetHeight + 'px'
  18438. };
  18439. utils.extend( line.style, styles );
  18440. }
  18441. /**
  18442. * 显示resize-line
  18443. */
  18444. function showResizeLine( cell ) {
  18445. var uetable = getUETable( cell );
  18446. updateResizeLine.call( this, cell, uetable );
  18447. }
  18448. /**
  18449. * 获取鼠标与当前单元格的相对位置
  18450. * @param ele
  18451. * @param mousePos
  18452. */
  18453. function getRelation(ele, mousePos) {
  18454. var elePos = domUtils.getXY(ele);
  18455. if( !elePos ) {
  18456. return '';
  18457. }
  18458. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  18459. return "h";
  18460. }
  18461. if (mousePos.x - elePos.x < cellBorderWidth) {
  18462. return 'h1'
  18463. }
  18464. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  18465. return "v";
  18466. }
  18467. if (mousePos.y - elePos.y < cellBorderWidth) {
  18468. return 'v1'
  18469. }
  18470. return '';
  18471. }
  18472. function mouseDownEvent(type, evt) {
  18473. if( isEditorDisabled() ) {
  18474. return ;
  18475. }
  18476. userActionStatus = {
  18477. x: evt.clientX,
  18478. y: evt.clientY
  18479. };
  18480. //右键菜单单独处理
  18481. if (evt.button == 2) {
  18482. var ut = getUETableBySelected(me),
  18483. flag = false;
  18484. if (ut) {
  18485. var td = getTargetTd(me, evt);
  18486. utils.each(ut.selectedTds, function (ti) {
  18487. if (ti === td) {
  18488. flag = true;
  18489. }
  18490. });
  18491. if (!flag) {
  18492. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  18493. ut.clearSelected()
  18494. } else {
  18495. td = ut.selectedTds[0];
  18496. setTimeout(function () {
  18497. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  18498. }, 0);
  18499. }
  18500. }
  18501. } else {
  18502. tableClickHander( evt );
  18503. }
  18504. }
  18505. //清除表格的计时器
  18506. function clearTableTimer() {
  18507. tabTimer && clearTimeout( tabTimer );
  18508. tabTimer = null;
  18509. }
  18510. //双击收缩
  18511. function tableDbclickHandler(evt) {
  18512. singleClickState = 0;
  18513. evt = evt || me.window.event;
  18514. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18515. if (target) {
  18516. var h;
  18517. if (h = getRelation(target, mouseCoords(evt))) {
  18518. hideDragLine( me );
  18519. if (h == 'h1') {
  18520. h = 'h';
  18521. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  18522. me.execCommand('adaptbywindow');
  18523. } else {
  18524. target = getUETable(target).getPreviewCell(target);
  18525. if (target) {
  18526. var rng = me.selection.getRange();
  18527. rng.selectNodeContents(target).setCursor(true, true)
  18528. }
  18529. }
  18530. }
  18531. if (h == 'h') {
  18532. var ut = getUETable(target),
  18533. table = ut.table,
  18534. cells = getCellsByMoveBorder( target, table, true );
  18535. cells = extractArray( cells, 'left' );
  18536. ut.width = ut.offsetWidth;
  18537. var oldWidth = [],
  18538. newWidth = [];
  18539. utils.each( cells, function( cell ){
  18540. oldWidth.push( cell.offsetWidth );
  18541. } );
  18542. utils.each( cells, function( cell ){
  18543. cell.removeAttribute("width");
  18544. } );
  18545. window.setTimeout( function(){
  18546. //是否允许改变
  18547. var changeable = true;
  18548. utils.each( cells, function( cell, index ){
  18549. var width = cell.offsetWidth;
  18550. if( width > oldWidth[index] ) {
  18551. changeable = false;
  18552. return false;
  18553. }
  18554. newWidth.push( width );
  18555. } );
  18556. var change = changeable ? newWidth : oldWidth;
  18557. utils.each( cells, function( cell, index ){
  18558. cell.width = change[index] - getTabcellSpace();
  18559. } );
  18560. }, 0 );
  18561. // minWidth -= cellMinWidth;
  18562. //
  18563. // table.removeAttribute("width");
  18564. // utils.each(cells, function (cell) {
  18565. // cell.style.width = "";
  18566. // cell.width -= minWidth;
  18567. // });
  18568. }
  18569. }
  18570. }
  18571. }
  18572. function tableClickHander( evt ) {
  18573. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  18574. //trace:3113
  18575. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  18576. utils.each(me.document.getElementsByTagName('table'), function (t) {
  18577. t.ueTable = null;
  18578. });
  18579. startTd = getTargetTd(me, evt);
  18580. if( !startTd ) return;
  18581. var table = domUtils.findParentByTagName(startTd, "table", true);
  18582. ut = getUETable(table);
  18583. ut && ut.clearSelected();
  18584. //判断当前鼠标状态
  18585. if (!onBorder) {
  18586. me.document.body.style.webkitUserSelect = '';
  18587. mousedown = true;
  18588. me.addListener('mouseover', mouseOverEvent);
  18589. } else {
  18590. //边框上的动作处理
  18591. borderActionHandler( evt );
  18592. }
  18593. }
  18594. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  18595. function borderActionHandler( evt ) {
  18596. if ( browser.ie ) {
  18597. evt = reconstruct(evt );
  18598. }
  18599. clearTableDragTimer();
  18600. //是否正在等待resize的缓冲中
  18601. isInResizeBuffer = true;
  18602. tableDragTimer = setTimeout(function(){
  18603. tableBorderDrag( evt );
  18604. }, dblclickTime);
  18605. }
  18606. function extractArray( originArr, key ) {
  18607. var result = [],
  18608. tmp = null;
  18609. for( var i = 0, len = originArr.length; i<len; i++ ) {
  18610. tmp = originArr[ i ][ key ];
  18611. if( tmp ) {
  18612. result.push( tmp );
  18613. }
  18614. }
  18615. return result;
  18616. }
  18617. function clearTableDragTimer() {
  18618. tableDragTimer && clearTimeout(tableDragTimer);
  18619. tableDragTimer = null;
  18620. }
  18621. function reconstruct( obj ) {
  18622. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  18623. newObj = {};
  18624. if( obj ) {
  18625. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  18626. val=obj[ key ];
  18627. val && (newObj[ key ] = val);
  18628. }
  18629. }
  18630. return newObj;
  18631. }
  18632. //边框拖动
  18633. function tableBorderDrag( evt ) {
  18634. isInResizeBuffer = false;
  18635. if( !startTd ) return;
  18636. var state = Math.abs( userActionStatus.x - evt.clientX ) >= Math.abs( userActionStatus.y - evt.clientY ) ? 'h' : 'v';
  18637. // var state = getRelation(startTd, mouseCoords(evt));
  18638. if (/\d/.test(state)) {
  18639. state = state.replace(/\d/, '');
  18640. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  18641. }
  18642. hideDragLine(me);
  18643. getDragLine(me, me.document);
  18644. me.fireEvent('saveScene');
  18645. showDragLineAt(state, startTd);
  18646. mousedown = true;
  18647. //拖动开始
  18648. onDrag = state;
  18649. dragTd = startTd;
  18650. }
  18651. function mouseUpEvent(type, evt) {
  18652. if( isEditorDisabled() ) {
  18653. return ;
  18654. }
  18655. clearTableDragTimer();
  18656. isInResizeBuffer = false;
  18657. if( onBorder ) {
  18658. singleClickState = ++singleClickState % 3;
  18659. userActionStatus = {
  18660. x: evt.clientX,
  18661. y: evt.clientY
  18662. };
  18663. tableResizeTimer = setTimeout(function(){
  18664. singleClickState > 0 && singleClickState--;
  18665. }, dblclickTime );
  18666. if( singleClickState === 2 ) {
  18667. singleClickState = 0;
  18668. tableDbclickHandler(evt);
  18669. return;
  18670. }
  18671. }
  18672. if (evt.button == 2)return;
  18673. var me = this;
  18674. //清除表格上原生跨选问题
  18675. var range = me.selection.getRange(),
  18676. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  18677. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  18678. if (start || end) {
  18679. if (start === end) {
  18680. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  18681. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  18682. if (start !== end) {
  18683. me.selection.clearRange()
  18684. }
  18685. } else {
  18686. me.selection.clearRange()
  18687. }
  18688. }
  18689. mousedown = false;
  18690. me.document.body.style.webkitUserSelect = '';
  18691. //拖拽状态下的mouseUP
  18692. if ( onDrag && dragTd ) {
  18693. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  18694. singleClickState = 0;
  18695. dragLine = me.document.getElementById('ue_tableDragLine');
  18696. var dragTdPos = domUtils.getXY(dragTd),
  18697. dragLinePos = domUtils.getXY(dragLine);
  18698. switch (onDrag) {
  18699. case "h":
  18700. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  18701. break;
  18702. case "v":
  18703. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  18704. break;
  18705. default:
  18706. }
  18707. onDrag = "";
  18708. dragTd = null;
  18709. hideDragLine(me);
  18710. me.fireEvent('saveScene');
  18711. return;
  18712. }
  18713. //正常状态下的mouseup
  18714. if (!startTd) {
  18715. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  18716. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  18717. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  18718. if (me.fireEvent("excludetable", target) === true) return;
  18719. range = new dom.Range(me.document);
  18720. range.setStart(target, 0).setCursor(false, true);
  18721. }
  18722. } else {
  18723. var ut = getUETable(startTd),
  18724. cell = ut ? ut.selectedTds[0] : null;
  18725. if (cell) {
  18726. range = new dom.Range(me.document);
  18727. if (domUtils.isEmptyBlock(cell)) {
  18728. range.setStart(cell, 0).setCursor(false, true);
  18729. } else {
  18730. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  18731. }
  18732. } else {
  18733. range = me.selection.getRange().shrinkBoundary();
  18734. if (!range.collapsed) {
  18735. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  18736. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  18737. //在table里边的不能清除
  18738. if (start && !end || !start && end || start && end && start !== end) {
  18739. range.setCursor(false, true);
  18740. }
  18741. }
  18742. }
  18743. startTd = null;
  18744. me.removeListener('mouseover', mouseOverEvent);
  18745. }
  18746. me._selectionChange(250, evt);
  18747. }
  18748. function mouseOverEvent(type, evt) {
  18749. if( isEditorDisabled() ) {
  18750. return;
  18751. }
  18752. var me = this,
  18753. tar = evt.target || evt.srcElement;
  18754. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  18755. //需要判断两个TD是否位于同一个表格内
  18756. if (startTd && currentTd &&
  18757. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  18758. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  18759. var ut = getUETable(currentTd);
  18760. if (startTd != currentTd) {
  18761. me.document.body.style.webkitUserSelect = 'none';
  18762. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  18763. var range = ut.getCellsRange(startTd, currentTd);
  18764. ut.setSelected(range);
  18765. } else {
  18766. me.document.body.style.webkitUserSelect = '';
  18767. ut.clearSelected();
  18768. }
  18769. }
  18770. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  18771. }
  18772. function setCellHeight(cell, height, backHeight) {
  18773. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  18774. tmpHeight = backHeight + height;
  18775. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  18776. if (cell.style.height) cell.style.height = "";
  18777. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  18778. }
  18779. function getWidth(cell) {
  18780. if (!cell)return 0;
  18781. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  18782. }
  18783. function changeColWidth(cell, changeValue) {
  18784. var ut = getUETable(cell);
  18785. if (ut) {
  18786. //根据当前移动的边框获取相关的单元格
  18787. var table = ut.table,
  18788. cells = getCellsByMoveBorder( cell, table );
  18789. table.style.width = "";
  18790. table.removeAttribute("width");
  18791. //修正改变量
  18792. changeValue = correctChangeValue( changeValue, cell, cells );
  18793. if (cell.nextSibling) {
  18794. var i=0;
  18795. utils.each( cells, function( cellGroup ){
  18796. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  18797. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  18798. } );
  18799. } else {
  18800. utils.each( cells, function( cellGroup ){
  18801. cellGroup.left.width -= -changeValue;
  18802. } );
  18803. }
  18804. }
  18805. }
  18806. function isEditorDisabled() {
  18807. return me.body.contentEditable === "false";
  18808. }
  18809. function changeRowHeight(td, changeValue) {
  18810. if (Math.abs(changeValue) < 10) return;
  18811. var ut = getUETable(td);
  18812. if (ut) {
  18813. var cells = ut.getSameEndPosCells(td, "y"),
  18814. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  18815. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  18816. for (var i = 0, cell; cell = cells[i++];) {
  18817. setCellHeight(cell, changeValue, backHeight);
  18818. }
  18819. }
  18820. }
  18821. /**
  18822. * 获取调整单元格大小的相关单元格
  18823. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  18824. */
  18825. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  18826. if( !table ) {
  18827. table = domUtils.findParentByTagName( cell, 'table' );
  18828. }
  18829. if( !table ) {
  18830. return null;
  18831. }
  18832. //获取到该单元格所在行的序列号
  18833. var index = domUtils.getNodeIndex( cell ),
  18834. temp = cell,
  18835. rows = table.rows,
  18836. colIndex = 0;
  18837. while( temp ) {
  18838. //获取到当前单元格在未发生单元格合并时的序列
  18839. if( temp.nodeType === 1 ) {
  18840. colIndex += (temp.colSpan || 1);
  18841. }
  18842. temp = temp.previousSibling;
  18843. }
  18844. temp = null;
  18845. //记录想关的单元格
  18846. var borderCells = [];
  18847. utils.each(rows, function( tabRow ){
  18848. var cells = tabRow.cells,
  18849. currIndex = 0;
  18850. utils.each( cells, function( tabCell ){
  18851. currIndex += (tabCell.colSpan || 1);
  18852. if( currIndex === colIndex ) {
  18853. borderCells.push({
  18854. left: tabCell,
  18855. right: tabCell.nextSibling || null
  18856. });
  18857. return false;
  18858. } else if( currIndex > colIndex ) {
  18859. if( isContainMergeCell ) {
  18860. borderCells.push({
  18861. left: tabCell
  18862. });
  18863. }
  18864. return false;
  18865. }
  18866. } );
  18867. });
  18868. return borderCells;
  18869. }
  18870. /**
  18871. * 通过给定的单元格集合获取最小的单元格width
  18872. */
  18873. function getMinWidthByTableCells( cells ) {
  18874. var minWidth = Number.MAX_VALUE;
  18875. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  18876. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  18877. }
  18878. return minWidth;
  18879. }
  18880. function correctChangeValue( changeValue, relatedCell, cells ) {
  18881. //为单元格的paading预留空间
  18882. changeValue -= getTabcellSpace();
  18883. if( changeValue < 0 ) {
  18884. return 0;
  18885. }
  18886. changeValue -= getTableCellWidth( relatedCell );
  18887. //确定方向
  18888. var direction = changeValue < 0 ? 'left':'right';
  18889. changeValue = Math.abs(changeValue);
  18890. //只关心非最后一个单元格就可以
  18891. utils.each( cells, function( cellGroup ){
  18892. var curCell = cellGroup[direction];
  18893. //为单元格保留最小空间
  18894. if( curCell ) {
  18895. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  18896. }
  18897. } );
  18898. //修正越界
  18899. changeValue = changeValue < 0 ? 0 : changeValue;
  18900. return direction === 'left' ? -changeValue : changeValue;
  18901. }
  18902. function getTableCellWidth( cell ) {
  18903. var width = 0,
  18904. //偏移纠正量
  18905. offset = 0,
  18906. width = cell.offsetWidth - getTabcellSpace();
  18907. //最后一个节点纠正一下
  18908. if( !cell.nextSibling ) {
  18909. width -= getTableCellOffset( cell );
  18910. }
  18911. width = width < 0 ? 0 : width;
  18912. try {
  18913. cell.width = width;
  18914. } catch(e) {
  18915. }
  18916. return width;
  18917. }
  18918. /**
  18919. * 获取单元格所在表格的最末单元格的偏移量
  18920. */
  18921. function getTableCellOffset( cell ) {
  18922. tab = domUtils.findParentByTagName( cell, "table", false);
  18923. if( tab.offsetVal === undefined ) {
  18924. var prev = cell.previousSibling;
  18925. if( prev ) {
  18926. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  18927. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  18928. } else {
  18929. tab.offsetVal = 0;
  18930. }
  18931. }
  18932. return tab.offsetVal;
  18933. }
  18934. function getTabcellSpace() {
  18935. if( UT.tabcellSpace === undefined ) {
  18936. var cell = null,
  18937. tab = me.document.createElement("table"),
  18938. tbody = me.document.createElement("tbody"),
  18939. trow = me.document.createElement("tr"),
  18940. tabcell = me.document.createElement("td"),
  18941. mirror = null;
  18942. tabcell.style.cssText = 'border: 0;';
  18943. tabcell.width = 1;
  18944. trow.appendChild( tabcell );
  18945. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  18946. tbody.appendChild( trow );
  18947. tab.appendChild( tbody );
  18948. tab.style.cssText = "visibility: hidden;";
  18949. me.body.appendChild( tab );
  18950. UT.paddingSpace = tabcell.offsetWidth - 1;
  18951. var tmpTabWidth = tab.offsetWidth;
  18952. tabcell.style.cssText = '';
  18953. mirror.style.cssText = '';
  18954. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  18955. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  18956. me.body.removeChild( tab );
  18957. }
  18958. getTabcellSpace = function(){ return UT.tabcellSpace; };
  18959. return UT.tabcellSpace;
  18960. }
  18961. function getDragLine(editor, doc) {
  18962. if (mousedown)return;
  18963. dragLine = editor.document.createElement("div");
  18964. domUtils.setAttributes(dragLine, {
  18965. id:"ue_tableDragLine",
  18966. unselectable:'on',
  18967. contenteditable:false,
  18968. 'onresizestart':'return false',
  18969. 'ondragstart':'return false',
  18970. 'onselectstart':'return false',
  18971. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  18972. });
  18973. editor.body.appendChild(dragLine);
  18974. }
  18975. function hideDragLine(editor) {
  18976. if (mousedown)return;
  18977. var line;
  18978. while (line = editor.document.getElementById('ue_tableDragLine')) {
  18979. domUtils.remove(line)
  18980. }
  18981. }
  18982. /**
  18983. * 依据state(v|h)在cell位置显示横线
  18984. * @param state
  18985. * @param cell
  18986. */
  18987. function showDragLineAt(state, cell) {
  18988. if (!cell) return;
  18989. var table = domUtils.findParentByTagName(cell, "table"),
  18990. caption = table.getElementsByTagName('caption'),
  18991. width = table.offsetWidth,
  18992. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  18993. tablePos = domUtils.getXY(table),
  18994. cellPos = domUtils.getXY(cell), css;
  18995. switch (state) {
  18996. case "h":
  18997. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  18998. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  18999. break;
  19000. case "v":
  19001. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19002. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19003. dragLine.style.cssText = css + 'px;overflow:hidden;position: absolute;display:block;background-color:blue;height:1px;border:0;color:blue;opacity:.2;filter:alpha(opacity=20)';
  19004. break;
  19005. default:
  19006. }
  19007. }
  19008. /**
  19009. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19010. * @param editor
  19011. * @param flag
  19012. */
  19013. function switchBorderColor(editor, flag) {
  19014. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19015. for (var i = 0, node; node = tableArr[i++];) {
  19016. var td = domUtils.getElementsByTagName(node, "td");
  19017. if (td[0]) {
  19018. if (flag) {
  19019. color = (td[0].style.borderColor).replace(/\s/g, "");
  19020. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19021. domUtils.addClass(node, "noBorderTable")
  19022. } else {
  19023. domUtils.removeClasses(node, "noBorderTable")
  19024. }
  19025. }
  19026. }
  19027. }
  19028. function getTableWidth(editor, needIEHack, defaultValue) {
  19029. var body = editor.body;
  19030. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19031. }
  19032. /**
  19033. * 获取当前拖动的单元格
  19034. */
  19035. function getTargetTd(editor, evt) {
  19036. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19037. dir = null;
  19038. if( !target ) {
  19039. return null;
  19040. }
  19041. dir = getRelation( target, mouseCoords( evt ) );
  19042. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19043. if( !target ) {
  19044. return null;
  19045. }
  19046. if( dir === 'h1' && target.previousSibling ) {
  19047. var position = domUtils.getXY( target),
  19048. cellWidth = target.offsetWidth;
  19049. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19050. target = target.previousSibling;
  19051. }
  19052. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19053. var position = domUtils.getXY( target),
  19054. cellHeight = target.offsetHeight;
  19055. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19056. target = target.parentNode.previousSibling.firstChild;
  19057. }
  19058. }
  19059. //排除了非td内部以及用于代码高亮部分的td
  19060. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19061. }
  19062. };
  19063. /**
  19064. * Created with JetBrains PhpStorm.
  19065. * User: Jinqn
  19066. * Date: 13-10-12
  19067. * Time: 上午10:20
  19068. * To change this template use File | Settings | File Templates.
  19069. */
  19070. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19071. var table = this.table,
  19072. rows = table.rows,
  19073. trArray = [],
  19074. flag = rows[0].cells[0].tagName === "TH",
  19075. lastRowIndex = 0;
  19076. if(this.selectedTds.length){
  19077. var range = this.cellsRange,
  19078. len = range.endRowIndex + 1;
  19079. for (var i = range.beginRowIndex; i < len; i++) {
  19080. trArray[i] = rows[i];
  19081. }
  19082. trArray.splice(0,range.beginRowIndex);
  19083. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19084. }else{
  19085. for (var i = 0,len = rows.length; i < len; i++) {
  19086. trArray[i] = rows[i];
  19087. }
  19088. }
  19089. var Fn = {
  19090. 'reversecurrent': function(td1,td2){
  19091. return 1;
  19092. },
  19093. 'orderbyasc': function(td1,td2){
  19094. var value1 = td1.innerText||td1.textContent,
  19095. value2 = td2.innerText||td2.textContent;
  19096. return value1.localeCompare(value2);
  19097. },
  19098. 'reversebyasc': function(td1,td2){
  19099. var value1 = td1.innerHTML,
  19100. value2 = td2.innerHTML;
  19101. return value2.localeCompare(value1);
  19102. },
  19103. 'orderbynum': function(td1,td2){
  19104. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19105. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19106. if(value1) value1 = +value1[0];
  19107. if(value2) value2 = +value2[0];
  19108. return (value1||0) - (value2||0);
  19109. },
  19110. 'reversebynum': function(td1,td2){
  19111. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19112. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19113. if(value1) value1 = +value1[0];
  19114. if(value2) value2 = +value2[0];
  19115. return (value2||0) - (value1||0);
  19116. }
  19117. };
  19118. //对表格设置排序的标记data-sort-type
  19119. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19120. //th不参与排序
  19121. flag && trArray.splice(0, 1);
  19122. trArray = utils.sort(trArray,function (tr1, tr2) {
  19123. var result;
  19124. if (compareFn && typeof compareFn === "function") {
  19125. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19126. } else if (compareFn && typeof compareFn === "number") {
  19127. result = 1;
  19128. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  19129. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19130. } else {
  19131. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19132. }
  19133. return result;
  19134. });
  19135. var fragment = table.ownerDocument.createDocumentFragment();
  19136. for (var j = 0, len = trArray.length; j < len; j++) {
  19137. fragment.appendChild(trArray[j]);
  19138. }
  19139. var tbody = table.getElementsByTagName("tbody")[0];
  19140. if(!lastRowIndex){
  19141. tbody.appendChild(fragment);
  19142. }else{
  19143. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  19144. }
  19145. };
  19146. UE.plugins['tablesort'] = function () {
  19147. var me = this,
  19148. UT = UE.UETable,
  19149. getUETable = function (tdOrTable) {
  19150. return UT.getUETable(tdOrTable);
  19151. },
  19152. getTableItemsByRange = function (editor) {
  19153. return UT.getTableItemsByRange(editor);
  19154. };
  19155. me.ready(function () {
  19156. //添加表格可排序的样式
  19157. utils.cssRule('tablesort',
  19158. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  19159. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  19160. me.document);
  19161. //做单元格合并操作时,清除可排序标识
  19162. me.addListener("afterexeccommand", function (type, cmd) {
  19163. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  19164. this.execCommand('disablesort');
  19165. }
  19166. });
  19167. });
  19168. //表格排序
  19169. UE.commands['sorttable'] = {
  19170. queryCommandState: function () {
  19171. var me = this,
  19172. tableItems = getTableItemsByRange(me);
  19173. if (!tableItems.cell) return -1;
  19174. var table = tableItems.table,
  19175. cells = table.getElementsByTagName("td");
  19176. for (var i = 0, cell; cell = cells[i++];) {
  19177. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  19178. }
  19179. return 0;
  19180. },
  19181. execCommand: function (cmd, fn) {
  19182. var me = this,
  19183. range = me.selection.getRange(),
  19184. bk = range.createBookmark(true),
  19185. tableItems = getTableItemsByRange(me),
  19186. cell = tableItems.cell,
  19187. ut = getUETable(tableItems.table),
  19188. cellInfo = ut.getCellInfo(cell);
  19189. ut.sortTable(cellInfo.cellIndex, fn);
  19190. range.moveToBookmark(bk);
  19191. try{
  19192. range.select();
  19193. }catch(e){}
  19194. }
  19195. };
  19196. //设置表格可排序,清除表格可排序
  19197. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  19198. queryCommandState: function (cmd) {
  19199. var table = getTableItemsByRange(this).table;
  19200. if(table && cmd=='enablesort') {
  19201. var cells = domUtils.getElementsByTagName(table, 'th td');
  19202. for(var i = 0; i<cells.length; i++) {
  19203. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  19204. }
  19205. }
  19206. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  19207. },
  19208. execCommand: function (cmd) {
  19209. var table = getTableItemsByRange(this).table;
  19210. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  19211. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  19212. }
  19213. };
  19214. };
  19215. ///import core
  19216. ///commands 右键菜单
  19217. ///commandsName ContextMenu
  19218. ///commandsTitle 右键菜单
  19219. /*
  19220. * 右键菜单
  19221. * @function
  19222. * @name baidu.editor.plugins.contextmenu
  19223. * @author zhanyi
  19224. */
  19225. UE.plugins['contextmenu'] = function () {
  19226. var me = this,
  19227. lang = me.getLang( "contextMenu" ),
  19228. menu,
  19229. items = me.options.contextMenu || [
  19230. {label:lang['selectall'], cmdName:'selectall'},
  19231. {
  19232. label:lang.cleardoc,
  19233. cmdName:'cleardoc',
  19234. exec:function () {
  19235. if ( confirm( lang.confirmclear ) ) {
  19236. this.execCommand( 'cleardoc' );
  19237. }
  19238. }
  19239. },
  19240. '-',
  19241. {
  19242. label:lang.unlink,
  19243. cmdName:'unlink'
  19244. },
  19245. '-',
  19246. {
  19247. group:lang.paragraph,
  19248. icon:'justifyjustify',
  19249. subMenu:[
  19250. {
  19251. label:lang.justifyleft,
  19252. cmdName:'justify',
  19253. value:'left'
  19254. },
  19255. {
  19256. label:lang.justifyright,
  19257. cmdName:'justify',
  19258. value:'right'
  19259. },
  19260. {
  19261. label:lang.justifycenter,
  19262. cmdName:'justify',
  19263. value:'center'
  19264. },
  19265. {
  19266. label:lang.justifyjustify,
  19267. cmdName:'justify',
  19268. value:'justify'
  19269. }
  19270. ]
  19271. },
  19272. '-',
  19273. {
  19274. group:lang.table,
  19275. icon:'table',
  19276. subMenu:[
  19277. {
  19278. label:lang.inserttable,
  19279. cmdName:'inserttable'
  19280. },
  19281. {
  19282. label:lang.deletetable,
  19283. cmdName:'deletetable'
  19284. },
  19285. '-',
  19286. {
  19287. label:lang.deleterow,
  19288. cmdName:'deleterow'
  19289. },
  19290. {
  19291. label:lang.deletecol,
  19292. cmdName:'deletecol'
  19293. },
  19294. {
  19295. label:lang.insertcol,
  19296. cmdName:'insertcol'
  19297. },
  19298. {
  19299. label:lang.insertcolnext,
  19300. cmdName:'insertcolnext'
  19301. },
  19302. {
  19303. label:lang.insertrow,
  19304. cmdName:'insertrow'
  19305. },
  19306. {
  19307. label:lang.insertrownext,
  19308. cmdName:'insertrownext'
  19309. },
  19310. '-',
  19311. {
  19312. label:lang.insertcaption,
  19313. cmdName:'insertcaption'
  19314. },
  19315. {
  19316. label:lang.deletecaption,
  19317. cmdName:'deletecaption'
  19318. },
  19319. {
  19320. label:lang.inserttitle,
  19321. cmdName:'inserttitle'
  19322. },
  19323. {
  19324. label:lang.deletetitle,
  19325. cmdName:'deletetitle'
  19326. },
  19327. {
  19328. label:lang.inserttitlecol,
  19329. cmdName:'inserttitlecol'
  19330. },
  19331. {
  19332. label:lang.deletetitlecol,
  19333. cmdName:'deletetitlecol'
  19334. },
  19335. '-',
  19336. {
  19337. label:lang.mergecells,
  19338. cmdName:'mergecells'
  19339. },
  19340. {
  19341. label:lang.mergeright,
  19342. cmdName:'mergeright'
  19343. },
  19344. {
  19345. label:lang.mergedown,
  19346. cmdName:'mergedown'
  19347. },
  19348. '-',
  19349. {
  19350. label:lang.splittorows,
  19351. cmdName:'splittorows'
  19352. },
  19353. {
  19354. label:lang.splittocols,
  19355. cmdName:'splittocols'
  19356. },
  19357. {
  19358. label:lang.splittocells,
  19359. cmdName:'splittocells'
  19360. },
  19361. '-',
  19362. {
  19363. label:lang.averageDiseRow,
  19364. cmdName:'averagedistributerow'
  19365. },
  19366. {
  19367. label:lang.averageDisCol,
  19368. cmdName:'averagedistributecol'
  19369. },
  19370. '-',
  19371. {
  19372. label:lang.edittd,
  19373. cmdName:'edittd',
  19374. exec:function () {
  19375. if ( UE.ui['edittd'] ) {
  19376. new UE.ui['edittd']( this );
  19377. }
  19378. this.getDialog('edittd').open();
  19379. }
  19380. },
  19381. {
  19382. label:lang.edittable,
  19383. cmdName:'edittable',
  19384. exec:function () {
  19385. if ( UE.ui['edittable'] ) {
  19386. new UE.ui['edittable']( this );
  19387. }
  19388. this.getDialog('edittable').open();
  19389. }
  19390. },
  19391. {
  19392. label:lang.setbordervisible,
  19393. cmdName:'setbordervisible'
  19394. }
  19395. ]
  19396. },
  19397. {
  19398. group:lang.tablesort,
  19399. icon:'tablesort',
  19400. subMenu:[
  19401. {
  19402. label:lang.enablesort,
  19403. cmdName:'enablesort'
  19404. },
  19405. {
  19406. label:lang.disablesort,
  19407. cmdName:'disablesort'
  19408. },
  19409. '-',
  19410. {
  19411. label:lang.reversecurrent,
  19412. cmdName:'sorttable',
  19413. value:'reversecurrent'
  19414. },
  19415. {
  19416. label:lang.orderbyasc,
  19417. cmdName:'sorttable',
  19418. value:'orderbyasc'
  19419. },
  19420. {
  19421. label:lang.reversebyasc,
  19422. cmdName:'sorttable',
  19423. value:'reversebyasc'
  19424. },
  19425. {
  19426. label:lang.orderbynum,
  19427. cmdName:'sorttable',
  19428. value:'orderbynum'
  19429. },
  19430. {
  19431. label:lang.reversebynum,
  19432. cmdName:'sorttable',
  19433. value:'reversebynum'
  19434. }
  19435. ]
  19436. },
  19437. {
  19438. group:lang.borderbk,
  19439. icon:'borderBack',
  19440. subMenu:[
  19441. {
  19442. label:lang.setcolor,
  19443. cmdName:"interlacetable",
  19444. exec:function(){
  19445. this.execCommand("interlacetable");
  19446. }
  19447. },
  19448. {
  19449. label:lang.unsetcolor,
  19450. cmdName:"uninterlacetable",
  19451. exec:function(){
  19452. this.execCommand("uninterlacetable");
  19453. }
  19454. },
  19455. {
  19456. label:lang.setbackground,
  19457. cmdName:"settablebackground",
  19458. exec:function(){
  19459. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  19460. }
  19461. },
  19462. {
  19463. label:lang.unsetbackground,
  19464. cmdName:"cleartablebackground",
  19465. exec:function(){
  19466. this.execCommand("cleartablebackground");
  19467. }
  19468. },
  19469. {
  19470. label:lang.redandblue,
  19471. cmdName:"settablebackground",
  19472. exec:function(){
  19473. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  19474. }
  19475. },
  19476. {
  19477. label:lang.threecolorgradient,
  19478. cmdName:"settablebackground",
  19479. exec:function(){
  19480. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  19481. }
  19482. }
  19483. ]
  19484. },
  19485. {
  19486. group:lang.aligntd,
  19487. icon:'aligntd',
  19488. subMenu:[
  19489. {
  19490. cmdName:'cellalignment',
  19491. value:{align:'left',vAlign:'top'}
  19492. },
  19493. {
  19494. cmdName:'cellalignment',
  19495. value:{align:'center',vAlign:'top'}
  19496. },
  19497. {
  19498. cmdName:'cellalignment',
  19499. value:{align:'right',vAlign:'top'}
  19500. },
  19501. {
  19502. cmdName:'cellalignment',
  19503. value:{align:'left',vAlign:'middle'}
  19504. },
  19505. {
  19506. cmdName:'cellalignment',
  19507. value:{align:'center',vAlign:'middle'}
  19508. },
  19509. {
  19510. cmdName:'cellalignment',
  19511. value:{align:'right',vAlign:'middle'}
  19512. },
  19513. {
  19514. cmdName:'cellalignment',
  19515. value:{align:'left',vAlign:'bottom'}
  19516. },
  19517. {
  19518. cmdName:'cellalignment',
  19519. value:{align:'center',vAlign:'bottom'}
  19520. },
  19521. {
  19522. cmdName:'cellalignment',
  19523. value:{align:'right',vAlign:'bottom'}
  19524. }
  19525. ]
  19526. },
  19527. {
  19528. group:lang.aligntable,
  19529. icon:'aligntable',
  19530. subMenu:[
  19531. {
  19532. cmdName:'tablealignment',
  19533. className: 'left',
  19534. label:lang.tableleft,
  19535. value:"left"
  19536. },
  19537. {
  19538. cmdName:'tablealignment',
  19539. className: 'center',
  19540. label:lang.tablecenter,
  19541. value:"center"
  19542. },
  19543. {
  19544. cmdName:'tablealignment',
  19545. className: 'right',
  19546. label:lang.tableright,
  19547. value:"right"
  19548. }
  19549. ]
  19550. },
  19551. '-',
  19552. {
  19553. label:lang.insertparagraphbefore,
  19554. cmdName:'insertparagraph',
  19555. value:true
  19556. },
  19557. {
  19558. label:lang.insertparagraphafter,
  19559. cmdName:'insertparagraph'
  19560. },
  19561. {
  19562. label:lang['copy'],
  19563. cmdName:'copy',
  19564. exec:function () {
  19565. alert( lang.copymsg );
  19566. },
  19567. query:function () {
  19568. return 0;
  19569. }
  19570. },
  19571. {
  19572. label:lang['paste'],
  19573. cmdName:'paste',
  19574. exec:function () {
  19575. alert( lang.pastemsg );
  19576. },
  19577. query:function () {
  19578. return 0;
  19579. }
  19580. }
  19581. ];
  19582. if ( !items.length ) {
  19583. return;
  19584. }
  19585. var uiUtils = UE.ui.uiUtils;
  19586. me.addListener( 'contextmenu', function ( type, evt ) {
  19587. var offset = uiUtils.getViewportOffsetByEvent( evt );
  19588. me.fireEvent( 'beforeselectionchange' );
  19589. if ( menu ) {
  19590. menu.destroy();
  19591. }
  19592. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  19593. var last;
  19594. (function ( item ) {
  19595. if ( item == '-' ) {
  19596. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  19597. contextItems.push( '-' );
  19598. }
  19599. } else if ( item.hasOwnProperty( "group" ) ) {
  19600. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  19601. (function ( subItem ) {
  19602. if ( subItem == '-' ) {
  19603. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  19604. subMenu.push( '-' );
  19605. }else{
  19606. subMenu.splice(subMenu.length-1);
  19607. }
  19608. } else {
  19609. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  19610. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  19611. subMenu.push( {
  19612. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  19613. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  19614. onclick:subItem.exec ? function () {
  19615. subItem.exec.call( me );
  19616. } : function () {
  19617. me.execCommand( subItem.cmdName, subItem.value );
  19618. }
  19619. } );
  19620. }
  19621. }
  19622. })( cj );
  19623. }
  19624. if ( subMenu.length ) {
  19625. function getLabel(){
  19626. switch (item.icon){
  19627. case "table":
  19628. return me.getLang( "contextMenu.table" );
  19629. case "justifyjustify":
  19630. return me.getLang( "contextMenu.paragraph" );
  19631. case "aligntd":
  19632. return me.getLang("contextMenu.aligntd");
  19633. case "aligntable":
  19634. return me.getLang("contextMenu.aligntable");
  19635. case "tablesort":
  19636. return lang.tablesort;
  19637. case "borderBack":
  19638. return lang.borderbk;
  19639. default :
  19640. return '';
  19641. }
  19642. }
  19643. contextItems.push( {
  19644. //todo 修正成自动获取方式
  19645. 'label':getLabel(),
  19646. className:'edui-for-' + item.icon,
  19647. 'subMenu':{
  19648. items:subMenu,
  19649. editor:me
  19650. }
  19651. } );
  19652. }
  19653. } else {
  19654. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  19655. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  19656. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  19657. contextItems.push( {
  19658. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  19659. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  19660. onclick:item.exec ? function () {
  19661. item.exec.call( me );
  19662. } : function () {
  19663. me.execCommand( item.cmdName, item.value );
  19664. }
  19665. } );
  19666. }
  19667. }
  19668. })( ti );
  19669. }
  19670. if ( contextItems[contextItems.length - 1] == '-' ) {
  19671. contextItems.pop();
  19672. }
  19673. menu = new UE.ui.Menu( {
  19674. items:contextItems,
  19675. className:"edui-contextmenu",
  19676. editor:me
  19677. } );
  19678. menu.render();
  19679. menu.showAt( offset );
  19680. me.fireEvent("aftershowcontextmenu",menu);
  19681. domUtils.preventDefault( evt );
  19682. if ( browser.ie ) {
  19683. var ieRange;
  19684. try {
  19685. ieRange = me.selection.getNative().createRange();
  19686. } catch ( e ) {
  19687. return;
  19688. }
  19689. if ( ieRange.item ) {
  19690. var range = new dom.Range( me.document );
  19691. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  19692. }
  19693. }
  19694. } );
  19695. };
  19696. ///import core
  19697. ///commands 弹出菜单
  19698. // commandsName popupmenu
  19699. ///commandsTitle 弹出菜单
  19700. /*
  19701. * 弹出菜单
  19702. * @function
  19703. * @name baidu.editor.plugins.popupmenu
  19704. * @author xuheng
  19705. */
  19706. UE.plugins['shortcutmenu'] = function () {
  19707. var me = this,
  19708. menu,
  19709. items = me.options.shortcutMenu || [];
  19710. if (!items.length) {
  19711. return;
  19712. }
  19713. me.addListener ('contextmenu mouseup' , function (type , e) {
  19714. var me = this,
  19715. customEvt = {
  19716. type : type ,
  19717. target : e.target || e.srcElement ,
  19718. screenX : e.screenX ,
  19719. screenY : e.screenY ,
  19720. clientX : e.clientX ,
  19721. clientY : e.clientY
  19722. };
  19723. setTimeout (function () {
  19724. var rng = me.selection.getRange ();
  19725. if (rng.collapsed === false || type == "contextmenu") {
  19726. if (!menu) {
  19727. menu = new baidu.editor.ui.ShortCutMenu ({
  19728. editor : me ,
  19729. items : items ,
  19730. theme : me.options.theme ,
  19731. className : 'edui-shortcutmenu'
  19732. });
  19733. menu.render ();
  19734. me.fireEvent ("afterrendershortcutmenu" , menu);
  19735. }
  19736. menu.show (customEvt , !!UE.plugins['contextmenu']);
  19737. }
  19738. });
  19739. if (type == 'contextmenu') {
  19740. domUtils.preventDefault (e);
  19741. if (browser.ie9below) {
  19742. var ieRange;
  19743. try {
  19744. ieRange = me.selection.getNative().createRange();
  19745. } catch (e) {
  19746. return;
  19747. }
  19748. if (ieRange.item) {
  19749. var range = new dom.Range (me.document);
  19750. range.selectNode (ieRange.item (0)).select (true , true);
  19751. }
  19752. }
  19753. }
  19754. });
  19755. me.addListener ('keydown' , function (type) {
  19756. if (type == "keydown") {
  19757. menu && !menu.isHidden && menu.hide ();
  19758. }
  19759. });
  19760. };
  19761. /**
  19762. * B、I、sub、super命令支持
  19763. * @file
  19764. * @since 1.2.6.1
  19765. */
  19766. UE.plugins['basestyle'] = function(){
  19767. /**
  19768. * 字体加粗
  19769. * @command bold
  19770. * @param { String } cmd 命令字符串
  19771. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  19772. * @method execCommand
  19773. * @example
  19774. * ```javascript
  19775. * //editor是编辑器实例
  19776. * //对当前选中的文本内容执行加粗操作
  19777. * //第一次执行, 文本内容加粗
  19778. * editor.execCommand( 'bold' );
  19779. *
  19780. * //第二次执行, 文本内容取消加粗
  19781. * editor.execCommand( 'bold' );
  19782. * ```
  19783. */
  19784. /**
  19785. * 字体倾斜
  19786. * @command italic
  19787. * @method execCommand
  19788. * @param { String } cmd 命令字符串
  19789. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  19790. * @example
  19791. * ```javascript
  19792. * //editor是编辑器实例
  19793. * //对当前选中的文本内容执行斜体操作
  19794. * //第一次操作, 文本内容将变成斜体
  19795. * editor.execCommand( 'italic' );
  19796. *
  19797. * //再次对同一文本内容执行, 则文本内容将恢复正常
  19798. * editor.execCommand( 'italic' );
  19799. * ```
  19800. */
  19801. /**
  19802. * 下标文本,与“superscript”命令互斥
  19803. * @command subscript
  19804. * @method execCommand
  19805. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  19806. * @param { String } cmd 命令字符串
  19807. * @example
  19808. * ```javascript
  19809. * //editor是编辑器实例
  19810. * //对当前选中的文本内容执行下标操作
  19811. * //第一次操作, 文本内容将变成下标文本
  19812. * editor.execCommand( 'subscript' );
  19813. *
  19814. * //再次对同一文本内容执行, 则文本内容将恢复正常
  19815. * editor.execCommand( 'subscript' );
  19816. * ```
  19817. */
  19818. /**
  19819. * 上标文本,与“subscript”命令互斥
  19820. * @command superscript
  19821. * @method execCommand
  19822. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  19823. * @param { String } cmd 命令字符串
  19824. * @example
  19825. * ```javascript
  19826. * //editor是编辑器实例
  19827. * //对当前选中的文本内容执行上标操作
  19828. * //第一次操作, 文本内容将变成上标文本
  19829. * editor.execCommand( 'superscript' );
  19830. *
  19831. * //再次对同一文本内容执行, 则文本内容将恢复正常
  19832. * editor.execCommand( 'superscript' );
  19833. * ```
  19834. */
  19835. var basestyles = {
  19836. 'bold':['strong','b'],
  19837. 'italic':['em','i'],
  19838. 'subscript':['sub'],
  19839. 'superscript':['sup']
  19840. },
  19841. getObj = function(editor,tagNames){
  19842. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  19843. },
  19844. me = this;
  19845. //添加快捷键
  19846. me.addshortcutkey({
  19847. "Bold" : "ctrl+66",//^B
  19848. "Italic" : "ctrl+73", //^I
  19849. "Underline" : "ctrl+85"//^U
  19850. });
  19851. me.addInputRule(function(root){
  19852. utils.each(root.getNodesByTagName('b i'),function(node){
  19853. switch (node.tagName){
  19854. case 'b':
  19855. node.tagName = 'strong';
  19856. break;
  19857. case 'i':
  19858. node.tagName = 'em';
  19859. }
  19860. });
  19861. });
  19862. for ( var style in basestyles ) {
  19863. (function( cmd, tagNames ) {
  19864. me.commands[cmd] = {
  19865. execCommand : function( cmdName ) {
  19866. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  19867. if ( range.collapsed ) {
  19868. if ( obj ) {
  19869. var tmpText = me.document.createTextNode('');
  19870. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  19871. range.setStartBefore(tmpText);
  19872. domUtils.remove(tmpText);
  19873. } else {
  19874. var tmpNode = range.document.createElement( tagNames[0] );
  19875. if(cmdName == 'superscript' || cmdName == 'subscript'){
  19876. tmpText = me.document.createTextNode('');
  19877. range.insertNode(tmpText)
  19878. .removeInlineStyle(['sub','sup'])
  19879. .setStartBefore(tmpText)
  19880. .collapse(true);
  19881. }
  19882. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  19883. }
  19884. range.collapse( true );
  19885. } else {
  19886. if(cmdName == 'superscript' || cmdName == 'subscript'){
  19887. if(!obj || obj.tagName.toLowerCase() != cmdName){
  19888. range.removeInlineStyle(['sub','sup']);
  19889. }
  19890. }
  19891. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  19892. }
  19893. range.select();
  19894. },
  19895. queryCommandState : function() {
  19896. return getObj(this,tagNames) ? 1 : 0;
  19897. }
  19898. };
  19899. })( style, basestyles[style] );
  19900. }
  19901. };
  19902. /**
  19903. * 选取路径命令
  19904. * @file
  19905. */
  19906. UE.plugins['elementpath'] = function(){
  19907. var currentLevel,
  19908. tagNames,
  19909. me = this;
  19910. me.setOpt('elementPathEnabled',true);
  19911. if(!me.options.elementPathEnabled){
  19912. return;
  19913. }
  19914. me.commands['elementpath'] = {
  19915. execCommand : function( cmdName, level ) {
  19916. var start = tagNames[level],
  19917. range = me.selection.getRange();
  19918. currentLevel = level*1;
  19919. range.selectNode(start).select();
  19920. },
  19921. queryCommandValue : function() {
  19922. //产生一个副本,不能修改原来的startElementPath;
  19923. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  19924. names = [];
  19925. tagNames = parents;
  19926. for(var i=0,ci;ci=parents[i];i++){
  19927. if(ci.nodeType == 3) {
  19928. continue;
  19929. }
  19930. var name = ci.tagName.toLowerCase();
  19931. if(name == 'img' && ci.getAttribute('anchorname')){
  19932. name = 'anchor';
  19933. }
  19934. names[i] = name;
  19935. if(currentLevel == i){
  19936. currentLevel = -1;
  19937. break;
  19938. }
  19939. }
  19940. return names;
  19941. }
  19942. };
  19943. };
  19944. /**
  19945. * 格式刷,只格式inline的
  19946. * @file
  19947. * @since 1.2.6.1
  19948. */
  19949. /**
  19950. * 格式刷
  19951. * @command formatmatch
  19952. * @method execCommand
  19953. * @remind 该操作不能复制段落格式
  19954. * @param { String } cmd 命令字符串
  19955. * @example
  19956. * ```javascript
  19957. * //editor是编辑器实例
  19958. * //获取格式刷
  19959. * editor.execCommand( 'formatmatch' );
  19960. * ```
  19961. */
  19962. UE.plugins['formatmatch'] = function(){
  19963. var me = this,
  19964. list = [],img,
  19965. flag = 0;
  19966. me.addListener('reset',function(){
  19967. list = [];
  19968. flag = 0;
  19969. });
  19970. function addList(type,evt){
  19971. if(browser.webkit){
  19972. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  19973. }
  19974. function addFormat(range){
  19975. if(text){
  19976. range.selectNode(text);
  19977. }
  19978. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  19979. }
  19980. me.undoManger && me.undoManger.save();
  19981. var range = me.selection.getRange(),
  19982. imgT = target || range.getClosedNode();
  19983. if(img && imgT && imgT.tagName == 'IMG'){
  19984. //trace:964
  19985. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  19986. img = null;
  19987. }else{
  19988. if(!img){
  19989. var collapsed = range.collapsed;
  19990. if(collapsed){
  19991. var text = me.document.createTextNode('match');
  19992. range.insertNode(text).select();
  19993. }
  19994. me.__hasEnterExecCommand = true;
  19995. //不能把block上的属性干掉
  19996. //trace:1553
  19997. var removeFormatAttributes = me.options.removeFormatAttributes;
  19998. me.options.removeFormatAttributes = '';
  19999. me.execCommand('removeformat');
  20000. me.options.removeFormatAttributes = removeFormatAttributes;
  20001. me.__hasEnterExecCommand = false;
  20002. //trace:969
  20003. range = me.selection.getRange();
  20004. if(list.length){
  20005. addFormat(range);
  20006. }
  20007. if(text){
  20008. range.setStartBefore(text).collapse(true);
  20009. }
  20010. range.select();
  20011. text && domUtils.remove(text);
  20012. }
  20013. }
  20014. me.undoManger && me.undoManger.save();
  20015. me.removeListener('mouseup',addList);
  20016. flag = 0;
  20017. }
  20018. me.commands['formatmatch'] = {
  20019. execCommand : function( cmdName ) {
  20020. if(flag){
  20021. flag = 0;
  20022. list = [];
  20023. me.removeListener('mouseup',addList);
  20024. return;
  20025. }
  20026. var range = me.selection.getRange();
  20027. img = range.getClosedNode();
  20028. if(!img || img.tagName != 'IMG'){
  20029. range.collapse(true).shrinkBoundary();
  20030. var start = range.startContainer;
  20031. list = domUtils.findParents(start,true,function(node){
  20032. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20033. });
  20034. //a不能加入格式刷, 并且克隆节点
  20035. for(var i=0,ci;ci=list[i];i++){
  20036. if(ci.tagName == 'A'){
  20037. list.splice(i,1);
  20038. break;
  20039. }
  20040. }
  20041. }
  20042. me.addListener('mouseup',addList);
  20043. flag = 1;
  20044. },
  20045. queryCommandState : function() {
  20046. return flag;
  20047. },
  20048. notNeedUndo : 1
  20049. };
  20050. };
  20051. ///import core
  20052. ///commands 查找替换
  20053. ///commandsName SearchReplace
  20054. ///commandsTitle 查询替换
  20055. ///commandsDialog dialogs\searchreplace
  20056. /*
  20057. * @description 查找替换
  20058. * @author zhanyi
  20059. */
  20060. UE.plugin.register('searchreplace',function(){
  20061. var me = this;
  20062. function findTextInString(textContent,opt,currentIndex){
  20063. var str = opt.searchStr;
  20064. if(opt.dir == -1){
  20065. textContent = textContent.split('').reverse().join('');
  20066. str = str.split('').reverse().join('');
  20067. currentIndex = textContent.length - currentIndex;
  20068. }
  20069. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20070. while(match = reg.exec(textContent)){
  20071. if(match.index >= currentIndex){
  20072. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20073. }
  20074. }
  20075. return -1
  20076. }
  20077. function findTextBlockElm(node,currentIndex,opt){
  20078. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20079. if(domUtils.isBody(node)){
  20080. node = node.firstChild;
  20081. }
  20082. var first = 1;
  20083. while(node){
  20084. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20085. index = findTextInString(textContent,opt,currentIndex );
  20086. first = 0;
  20087. if(index!=-1){
  20088. return {
  20089. 'node':node,
  20090. 'index':index
  20091. }
  20092. }
  20093. node = domUtils[methodName](node);
  20094. if(node){
  20095. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20096. }
  20097. }
  20098. }
  20099. function findNTextInBlockElm(node,index,str){
  20100. var currentIndex = 0,
  20101. currentNode = node.firstChild,
  20102. currentNodeLength = 0,
  20103. result;
  20104. while(currentNode){
  20105. if(currentNode.nodeType == 3){
  20106. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20107. currentIndex += currentNodeLength;
  20108. if(currentIndex >= index){
  20109. return {
  20110. 'node':currentNode,
  20111. 'index': currentNodeLength - (currentIndex - index)
  20112. }
  20113. }
  20114. }else if(!dtd.$empty[currentNode.tagName]){
  20115. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  20116. currentIndex += currentNodeLength;
  20117. if(currentIndex >= index){
  20118. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  20119. if(result){
  20120. return result;
  20121. }
  20122. }
  20123. }
  20124. currentNode = domUtils.getNextDomNode(currentNode);
  20125. }
  20126. }
  20127. function searchReplace(me,opt){
  20128. var rng = me.selection.getRange(),
  20129. startBlockNode,
  20130. searchStr = opt.searchStr,
  20131. span = me.document.createElement('span');
  20132. span.innerHTML = '$$ueditor_searchreplace_key$$';
  20133. //判断是不是第一次选中
  20134. if(!rng.collapsed){
  20135. rng.select();
  20136. var rngText = me.selection.getText();
  20137. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  20138. if(opt.replaceStr != undefined){
  20139. replaceText(rng,opt.replaceStr);
  20140. rng.select();
  20141. return true;
  20142. }else{
  20143. rng.collapse(opt.dir == -1)
  20144. }
  20145. }
  20146. }
  20147. rng.insertNode(span);
  20148. rng.enlargeToBlockElm(true);
  20149. startBlockNode = rng.startContainer;
  20150. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  20151. rng.setStartBefore(span);
  20152. domUtils.remove(span);
  20153. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  20154. if(result){
  20155. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  20156. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  20157. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  20158. if(opt.replaceStr !== undefined){
  20159. replaceText(rng,opt.replaceStr)
  20160. }
  20161. rng.select();
  20162. return true;
  20163. }else{
  20164. rng.setCursor()
  20165. }
  20166. }
  20167. function replaceText(rng,str){
  20168. me.fireEvent('saveScene');
  20169. str = me.document.createTextNode(str);
  20170. rng.deleteContents().insertNode(str);
  20171. me.fireEvent('saveScene');
  20172. }
  20173. return {
  20174. commands:{
  20175. 'searchreplace':{
  20176. execCommand:function(cmdName,opt){
  20177. utils.extend(opt,{
  20178. all : false,
  20179. casesensitive : false,
  20180. dir : 1
  20181. },true);
  20182. var num = 0;
  20183. if(opt.all){
  20184. var rng = me.selection.getRange(),
  20185. first = me.body.firstChild;
  20186. if(first && first.nodeType == 1){
  20187. rng.setStart(first,0)
  20188. }else if(first.nodeType == 3){
  20189. rng.setStartBefore(first)
  20190. }
  20191. rng.collapse(true).select(true);
  20192. while(searchReplace(this,opt)){
  20193. num++;
  20194. }
  20195. }else{
  20196. if(searchReplace(this,opt)){
  20197. num++
  20198. }
  20199. }
  20200. return num;
  20201. },
  20202. notNeedUndo:1
  20203. }
  20204. }
  20205. }
  20206. });
  20207. /**
  20208. * 自定义样式
  20209. * @file
  20210. * @since 1.2.6.1
  20211. */
  20212. /**
  20213. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  20214. * @command customstyle
  20215. * @method execCommand
  20216. * @param { String } cmd 命令字符串
  20217. * @example
  20218. * ```javascript
  20219. * editor.execCommand( 'customstyle' );
  20220. * ```
  20221. */
  20222. UE.plugins['customstyle'] = function() {
  20223. var me = this;
  20224. me.setOpt({ 'customstyle':[
  20225. {tag:'h1',name:'tc', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'},
  20226. {tag:'h1',name:'tl', style:'font-size:32px;font-weight:bold;border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:left;margin:0 0 10px 0;'},
  20227. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  20228. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  20229. ]});
  20230. me.commands['customstyle'] = {
  20231. execCommand : function(cmdName, obj) {
  20232. var me = this,
  20233. tagName = obj.tag,
  20234. node = domUtils.findParent(me.selection.getStart(), function(node) {
  20235. return node.getAttribute('label');
  20236. }, true),
  20237. range,bk,tmpObj = {};
  20238. for (var p in obj) {
  20239. if(obj[p]!==undefined)
  20240. tmpObj[p] = obj[p];
  20241. }
  20242. delete tmpObj.tag;
  20243. if (node && node.getAttribute('label') == obj.label) {
  20244. range = this.selection.getRange();
  20245. bk = range.createBookmark();
  20246. if (range.collapsed) {
  20247. //trace:1732 删掉自定义标签,要有p来回填站位
  20248. if(dtd.$block[node.tagName]){
  20249. var fillNode = me.document.createElement('p');
  20250. domUtils.moveChild(node, fillNode);
  20251. node.parentNode.insertBefore(fillNode, node);
  20252. domUtils.remove(node);
  20253. }else{
  20254. domUtils.remove(node,true);
  20255. }
  20256. } else {
  20257. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  20258. nodes = domUtils.getElementsByTagName(common, tagName);
  20259. if(new RegExp(tagName,'i').test(common.tagName)){
  20260. nodes.push(common);
  20261. }
  20262. for (var i = 0,ni; ni = nodes[i++];) {
  20263. if (ni.getAttribute('label') == obj.label) {
  20264. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  20265. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  20266. &&
  20267. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  20268. )
  20269. if (dtd.$block[tagName]) {
  20270. var fillNode = me.document.createElement('p');
  20271. domUtils.moveChild(ni, fillNode);
  20272. ni.parentNode.insertBefore(fillNode, ni);
  20273. }
  20274. domUtils.remove(ni, true);
  20275. }
  20276. }
  20277. node = domUtils.findParent(common, function(node) {
  20278. return node.getAttribute('label') == obj.label;
  20279. }, true);
  20280. if (node) {
  20281. domUtils.remove(node, true);
  20282. }
  20283. }
  20284. range.moveToBookmark(bk).select();
  20285. } else {
  20286. if (dtd.$block[tagName]) {
  20287. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  20288. range = me.selection.getRange();
  20289. if (!range.collapsed) {
  20290. range.collapse();
  20291. node = domUtils.findParent(me.selection.getStart(), function(node) {
  20292. return node.getAttribute('label') == obj.label;
  20293. }, true);
  20294. var pNode = me.document.createElement('p');
  20295. domUtils.insertAfter(node, pNode);
  20296. domUtils.fillNode(me.document, pNode);
  20297. range.setStart(pNode, 0).setCursor();
  20298. }
  20299. } else {
  20300. range = me.selection.getRange();
  20301. if (range.collapsed) {
  20302. node = me.document.createElement(tagName);
  20303. domUtils.setAttributes(node, tmpObj);
  20304. range.insertNode(node).setStart(node, 0).setCursor();
  20305. return;
  20306. }
  20307. bk = range.createBookmark();
  20308. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  20309. }
  20310. }
  20311. },
  20312. queryCommandValue : function() {
  20313. var parent = domUtils.filterNodeList(
  20314. this.selection.getStartElementPath(),
  20315. function(node){return node.getAttribute('label')}
  20316. );
  20317. return parent ? parent.getAttribute('label') : '';
  20318. }
  20319. };
  20320. //当去掉customstyle是,如果是块元素,用p代替
  20321. me.addListener('keyup', function(type, evt) {
  20322. var keyCode = evt.keyCode || evt.which;
  20323. if (keyCode == 32 || keyCode == 13) {
  20324. var range = me.selection.getRange();
  20325. if (range.collapsed) {
  20326. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  20327. return node.getAttribute('label');
  20328. }, true);
  20329. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  20330. var p = me.document.createElement('p');
  20331. domUtils.insertAfter(node, p);
  20332. domUtils.fillNode(me.document, p);
  20333. domUtils.remove(node);
  20334. range.setStart(p, 0).setCursor();
  20335. }
  20336. }
  20337. }
  20338. });
  20339. };
  20340. ///import core
  20341. ///commands 远程图片抓取
  20342. ///commandsName catchRemoteImage,catchremoteimageenable
  20343. ///commandsTitle 远程图片抓取
  20344. /*
  20345. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  20346. *
  20347. */
  20348. UE.plugins['catchremoteimage'] = function () {
  20349. if (this.options.catchRemoteImageEnable===false){
  20350. return;
  20351. }
  20352. var me = this;
  20353. this.setOpt({
  20354. localDomain:["127.0.0.1","localhost","img.baidu.com"],
  20355. separater:'ue_separate_ue',
  20356. catchFieldName:"upfile",
  20357. catchRemoteImageEnable:true
  20358. });
  20359. var ajax = UE.ajax,
  20360. localDomain = me.options.localDomain ,
  20361. catcherUrl = me.options.catcherUrl,
  20362. separater = me.options.separater;
  20363. function catchremoteimage(imgs, callbacks) {
  20364. var submitStr = imgs.join(separater);
  20365. var tmpOption = {
  20366. timeout:60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  20367. onsuccess:callbacks["success"],
  20368. onerror:callbacks["error"]
  20369. };
  20370. tmpOption[me.options.catchFieldName] = submitStr;
  20371. ajax.request(catcherUrl, tmpOption);
  20372. }
  20373. me.addListener("afterpaste", function () {
  20374. me.fireEvent("catchRemoteImage");
  20375. });
  20376. me.addListener("catchRemoteImage", function () {
  20377. var remoteImages = [];
  20378. var imgs = domUtils.getElementsByTagName(me.document, "img");
  20379. var test = function (src,urls) {
  20380. for (var j = 0, url; url = urls[j++];) {
  20381. if (src.indexOf(url) !== -1) {
  20382. return true;
  20383. }
  20384. }
  20385. return false;
  20386. };
  20387. for (var i = 0, ci; ci = imgs[i++];) {
  20388. if (ci.getAttribute("word_img")){
  20389. continue;
  20390. }
  20391. var src = ci.getAttribute("_src") || ci.src || "";
  20392. if (/^(https?|ftp):/i.test(src) && !test(src,localDomain)) {
  20393. remoteImages.push(src);
  20394. }
  20395. }
  20396. if (remoteImages.length) {
  20397. catchremoteimage(remoteImages, {
  20398. //成功抓取
  20399. success:function (xhr) {
  20400. try {
  20401. var info = eval("(" + xhr.responseText + ")");
  20402. } catch (e) {
  20403. return;
  20404. }
  20405. var srcUrls = info.srcUrl.split(separater),
  20406. urls = info.url.split(separater);
  20407. for (var i = 0, ci; ci = imgs[i++];) {
  20408. var src = ci.getAttribute("_src") || ci.src || "";
  20409. for (var j = 0, cj; cj = srcUrls[j++];) {
  20410. var url = urls[j - 1];
  20411. if (src == cj && url != "error") { //抓取失败时不做替换处理
  20412. //地址修正
  20413. var newSrc = me.options.catcherPath + url;
  20414. domUtils.setAttributes(ci, {
  20415. "src":newSrc,
  20416. "_src":newSrc
  20417. });
  20418. break;
  20419. }
  20420. }
  20421. }
  20422. me.fireEvent('catchremotesuccess')
  20423. },
  20424. //回调失败,本次请求超时
  20425. error:function () {
  20426. me.fireEvent("catchremoteerror");
  20427. }
  20428. });
  20429. }
  20430. });
  20431. };
  20432. ///import core
  20433. ///import plugins\inserthtml.js
  20434. ///import plugins\image.js
  20435. ///commandsName snapscreen
  20436. ///commandsTitle 截屏
  20437. /*
  20438. * 截屏插件
  20439. */
  20440. UE.plugins['snapscreen'] = function(){
  20441. var me = this,
  20442. doc,
  20443. snapplugin;
  20444. me.setOpt({
  20445. snapscreenServerPort: location.port //屏幕截图的server端端口
  20446. ,snapscreenImgAlign: '' //截图的图片默认的排版方式
  20447. ,snapscreenHost: location.hostname //屏幕截图的server端文件所在的网站地址或者ip,请不要加http://
  20448. });
  20449. me.commands['snapscreen'] = {
  20450. execCommand: function(){
  20451. var me = this,lang = me.getLang("snapScreen_plugin");
  20452. if(!snapplugin){
  20453. var container = me.container;
  20454. doc = container.ownerDocument || container.document;
  20455. snapplugin = doc.createElement("object");
  20456. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  20457. return;
  20458. }
  20459. snapplugin.style.cssText = "position:absolute;left:-9999px;";
  20460. snapplugin.setAttribute("width","0");
  20461. snapplugin.setAttribute("height","0");
  20462. container.appendChild(snapplugin);
  20463. }
  20464. var editorOptions = me.options;
  20465. var onSuccess = function(rs){
  20466. try{
  20467. rs = eval("("+ rs +")");
  20468. }catch(e){
  20469. alert(lang.callBackErrorMsg);
  20470. return;
  20471. }
  20472. if(rs.state != 'SUCCESS'){
  20473. alert(rs.state);
  20474. return;
  20475. }
  20476. me.execCommand('insertimage', {
  20477. src: editorOptions.snapscreenPath + rs.url,
  20478. floatStyle: editorOptions.snapscreenImgAlign,
  20479. _src:editorOptions.snapscreenPath + rs.url
  20480. });
  20481. };
  20482. var onStartUpload = function(){
  20483. //开始截图上传
  20484. };
  20485. var onError = function(){
  20486. alert(lang.uploadErrorMsg);
  20487. };
  20488. try{
  20489. var port = editorOptions.snapscreenServerPort + '';
  20490. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.split( editorOptions.snapscreenHost );
  20491. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl[1] || editorOptions.snapscreenServerUrl[0];
  20492. if( editorOptions.snapscreenServerUrl.indexOf(":"+port) === 0 ) {
  20493. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.substring( port.length+1 );
  20494. }
  20495. var ret =snapplugin.saveSnapshot(editorOptions.snapscreenHost, editorOptions.snapscreenServerUrl, port);
  20496. onSuccess(ret);
  20497. }catch(e){
  20498. me.ui._dialogs['snapscreenDialog'].open();
  20499. }
  20500. }
  20501. };
  20502. }
  20503. /**
  20504. * 插入段落
  20505. * @file
  20506. * @since 1.2.6.1
  20507. */
  20508. /**
  20509. * 插入段落
  20510. * @command insertparagraph
  20511. * @method execCommand
  20512. * @param { String } cmd 命令字符串
  20513. * @example
  20514. * ```javascript
  20515. * //editor是编辑器实例
  20516. * editor.execCommand( 'insertparagraph' );
  20517. * ```
  20518. */
  20519. UE.commands['insertparagraph'] = {
  20520. execCommand : function( cmdName,front) {
  20521. var me = this,
  20522. range = me.selection.getRange(),
  20523. start = range.startContainer,tmpNode;
  20524. while(start ){
  20525. if(domUtils.isBody(start)){
  20526. break;
  20527. }
  20528. tmpNode = start;
  20529. start = start.parentNode;
  20530. }
  20531. if(tmpNode){
  20532. var p = me.document.createElement('p');
  20533. if(front){
  20534. tmpNode.parentNode.insertBefore(p,tmpNode)
  20535. }else{
  20536. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  20537. }
  20538. domUtils.fillNode(me.document,p);
  20539. range.setStart(p,0).setCursor(false,true);
  20540. }
  20541. }
  20542. };
  20543. /**
  20544. * 百度应用
  20545. * @file
  20546. * @since 1.2.6.1
  20547. */
  20548. /**
  20549. * 插入百度应用
  20550. * @command webapp
  20551. * @method execCommand
  20552. * @remind 需要百度APPKey
  20553. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  20554. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  20555. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  20556. * @example
  20557. * ```javascript
  20558. * //editor是编辑器实例
  20559. * //在编辑器里插入一个“植物大战僵尸”的APP
  20560. * editor.execCommand( 'webapp' , {
  20561. * title: '植物大战僵尸',
  20562. * width: 560,
  20563. * height: 465,
  20564. * logo: '应用展示的图片',
  20565. * url: '百度应用的地址'
  20566. * } );
  20567. * ```
  20568. */
  20569. //UE.plugins['webapp'] = function () {
  20570. // var me = this;
  20571. // function createInsertStr( obj, toIframe, addParagraph ) {
  20572. // return !toIframe ?
  20573. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  20574. // ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" style="background:url(' + obj.logo+') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" />' +
  20575. // (addParagraph ? '</p>' : '')
  20576. // :
  20577. // '<iframe class="edui-faked-webapp" title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = '+obj.logo+'></iframe>';
  20578. // }
  20579. //
  20580. // function switchImgAndIframe( img2frame ) {
  20581. // var tmpdiv,
  20582. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  20583. // for ( var i = 0, node; node = nodes[i++]; ) {
  20584. // if ( node.className != "edui-faked-webapp" ){
  20585. // continue;
  20586. // }
  20587. // tmpdiv = me.document.createElement( "div" );
  20588. // tmpdiv.innerHTML = createInsertStr( img2frame ? {url:node.getAttribute( "_url" ), width:node.width, height:node.height,title:node.title,logo:node.style.backgroundImage.replace("url(","").replace(")","")} : {url:node.getAttribute( "src", 2 ),title:node.title, width:node.width, height:node.height,logo:node.getAttribute("logo_url")}, img2frame ? true : false,false );
  20589. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  20590. // }
  20591. // }
  20592. //
  20593. // me.addListener( "beforegetcontent", function () {
  20594. // switchImgAndIframe( true );
  20595. // } );
  20596. // me.addListener( 'aftersetcontent', function () {
  20597. // switchImgAndIframe( false );
  20598. // } );
  20599. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  20600. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  20601. // return;
  20602. // }
  20603. // switchImgAndIframe( false );
  20604. // } );
  20605. //
  20606. // me.commands['webapp'] = {
  20607. // execCommand:function ( cmd, obj ) {
  20608. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  20609. // }
  20610. // };
  20611. //};
  20612. UE.plugin.register('webapp', function (){
  20613. var me = this;
  20614. function createInsertStr(obj,toEmbed){
  20615. return !toEmbed ?
  20616. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  20617. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  20618. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  20619. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  20620. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  20621. '/>'
  20622. :
  20623. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  20624. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  20625. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  20626. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  20627. }
  20628. return {
  20629. outputRule: function(root){
  20630. utils.each(root.getNodesByTagName('img'),function(node){
  20631. var html;
  20632. if(node.getAttr('class') == 'edui-faked-webapp'){
  20633. html = createInsertStr({
  20634. title:node.getAttr('title'),
  20635. 'width':node.getAttr('width'),
  20636. 'height':node.getAttr('height'),
  20637. 'align':node.getAttr('align'),
  20638. 'cssfloat':node.getStyle('float'),
  20639. 'url':node.getAttr("_url"),
  20640. 'logo':node.getAttr('_logo_url')
  20641. },true);
  20642. var embed = UE.uNode.createElement(html);
  20643. node.parentNode.replaceChild(embed,node);
  20644. }
  20645. })
  20646. },
  20647. inputRule:function(root){
  20648. utils.each(root.getNodesByTagName('iframe'),function(node){
  20649. if(node.getAttr('class') == 'edui-faked-webapp'){
  20650. var img = UE.uNode.createElement(createInsertStr({
  20651. title:node.getAttr('title'),
  20652. 'width':node.getAttr('width'),
  20653. 'height':node.getAttr('height'),
  20654. 'align':node.getAttr('align'),
  20655. 'cssfloat':node.getStyle('float'),
  20656. 'url':node.getAttr("src"),
  20657. 'logo':node.getAttr('logo_url')
  20658. }));
  20659. node.parentNode.replaceChild(img,node);
  20660. }
  20661. })
  20662. },
  20663. commands:{
  20664. /**
  20665. * 插入百度应用
  20666. * @command webapp
  20667. * @method execCommand
  20668. * @remind 需要百度APPKey
  20669. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  20670. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  20671. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  20672. * @example
  20673. * ```javascript
  20674. * //editor是编辑器实例
  20675. * //在编辑器里插入一个“植物大战僵尸”的APP
  20676. * editor.execCommand( 'webapp' , {
  20677. * title: '植物大战僵尸',
  20678. * width: 560,
  20679. * height: 465,
  20680. * logo: '应用展示的图片',
  20681. * url: '百度应用的地址'
  20682. * } );
  20683. * ```
  20684. */
  20685. 'webapp':{
  20686. execCommand:function (cmd, obj) {
  20687. var me = this,
  20688. str = createInsertStr(utils.extend(obj,{
  20689. align:'none'
  20690. }), false);
  20691. me.execCommand("inserthtml",str);
  20692. },
  20693. queryCommandState:function () {
  20694. var me = this,
  20695. img = me.selection.getRange().getClosedNode(),
  20696. flag = img && (img.className == "edui-faked-webapp");
  20697. return flag ? 1 : 0;
  20698. }
  20699. }
  20700. }
  20701. }
  20702. });
  20703. ///import core
  20704. ///import plugins\inserthtml.js
  20705. ///import plugins\cleardoc.js
  20706. ///commands 模板
  20707. ///commandsName template
  20708. ///commandsTitle 模板
  20709. ///commandsDialog dialogs\template
  20710. UE.plugins['template'] = function () {
  20711. UE.commands['template'] = {
  20712. execCommand:function (cmd, obj) {
  20713. obj.html && this.execCommand("inserthtml", obj.html);
  20714. }
  20715. };
  20716. this.addListener("click", function (type, evt) {
  20717. var el = evt.target || evt.srcElement,
  20718. range = this.selection.getRange();
  20719. var tnode = domUtils.findParent(el, function (node) {
  20720. if (node.className && domUtils.hasClass(node, "ue_t")) {
  20721. return node;
  20722. }
  20723. }, true);
  20724. tnode && range.selectNode(tnode).shrinkBoundary().select();
  20725. });
  20726. this.addListener("keydown", function (type, evt) {
  20727. var range = this.selection.getRange();
  20728. if (!range.collapsed) {
  20729. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  20730. var tnode = domUtils.findParent(range.startContainer, function (node) {
  20731. if (node.className && domUtils.hasClass(node, "ue_t")) {
  20732. return node;
  20733. }
  20734. }, true);
  20735. if (tnode) {
  20736. domUtils.removeClasses(tnode, ["ue_t"]);
  20737. }
  20738. }
  20739. }
  20740. });
  20741. };
  20742. /**
  20743. * 插入音乐命令
  20744. * @file
  20745. */
  20746. UE.plugin.register('music', function (){
  20747. var me = this;
  20748. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  20749. return !toEmbed ?
  20750. '<img ' +
  20751. (align && !cssfloat? 'align="' + align + '"' : '') +
  20752. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  20753. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  20754. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  20755. :
  20756. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  20757. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  20758. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  20759. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  20760. }
  20761. return {
  20762. outputRule: function(root){
  20763. utils.each(root.getNodesByTagName('img'),function(node){
  20764. var html;
  20765. if(node.getAttr('class') == 'edui-faked-music'){
  20766. var cssfloat = node.getStyle('float');
  20767. var align = node.getAttr('align');
  20768. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  20769. var embed = UE.uNode.createElement(html);
  20770. node.parentNode.replaceChild(embed,node);
  20771. }
  20772. })
  20773. },
  20774. inputRule:function(root){
  20775. utils.each(root.getNodesByTagName('embed'),function(node){
  20776. if(node.getAttr('class') == 'edui-faked-music'){
  20777. var cssfloat = node.getStyle('float');
  20778. var align = node.getAttr('align');
  20779. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  20780. var img = UE.uNode.createElement(html);
  20781. node.parentNode.replaceChild(img,node);
  20782. }
  20783. })
  20784. },
  20785. commands:{
  20786. /**
  20787. * 插入音乐
  20788. * @command music
  20789. * @method execCommand
  20790. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  20791. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  20792. * @example
  20793. * ```javascript
  20794. * //editor是编辑器实例
  20795. * //在编辑器里插入一个“植物大战僵尸”的APP
  20796. * editor.execCommand( 'music' , {
  20797. * width: 400,
  20798. * height: 95,
  20799. * align: "center",
  20800. * url: "音乐地址"
  20801. * } );
  20802. * ```
  20803. */
  20804. 'music':{
  20805. execCommand:function (cmd, musicObj) {
  20806. var me = this,
  20807. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  20808. me.execCommand("inserthtml",str);
  20809. },
  20810. queryCommandState:function () {
  20811. var me = this,
  20812. img = me.selection.getRange().getClosedNode(),
  20813. flag = img && (img.className == "edui-faked-music");
  20814. return flag ? 1 : 0;
  20815. }
  20816. }
  20817. }
  20818. }
  20819. });
  20820. /**
  20821. * @description
  20822. * 1.拖放文件到编辑区域,自动上传并插入到选区
  20823. * 2.插入粘贴板的图片,自动上传并插入到选区
  20824. * @author Jinqn
  20825. * @date 2013-10-14
  20826. */
  20827. UE.plugin.register('autoupload', function (){
  20828. var me = this;
  20829. var sendAndInsertImage = function (file, editor) {
  20830. //模拟数据
  20831. var fd = new FormData();
  20832. fd.append(editor.options.imageFieldName || 'upfile', file, file.name || ('blob.' + file.type.substr('image/'.length)));
  20833. fd.append('type', 'ajax');
  20834. var xhr = new XMLHttpRequest();
  20835. xhr.open("post", me.options.imageUrl, true);
  20836. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  20837. xhr.addEventListener('load', function (e) {
  20838. try{
  20839. var json = (new Function("return " + e.target.response))(),
  20840. picLink = me.options.imagePath + json.url;
  20841. editor.execCommand('insertimage', {
  20842. src: picLink,
  20843. _src: picLink
  20844. });
  20845. }catch(er){ }
  20846. });
  20847. xhr.send(fd);
  20848. };
  20849. function getPasteImage(e){
  20850. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  20851. }
  20852. function getDropImage(e){
  20853. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  20854. }
  20855. return {
  20856. bindEvents:{
  20857. //插入粘贴板的图片,拖放插入图片
  20858. 'ready':function(e){
  20859. if(window.FormData && window.FileReader) {
  20860. domUtils.on(me.body, 'paste drop', function(e){
  20861. var hasImg = false,
  20862. items;
  20863. //获取粘贴板文件列表或者拖放文件列表
  20864. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  20865. if(items){
  20866. var len = items.length,
  20867. file;
  20868. while (len--){
  20869. file = items[len];
  20870. if(file.getAsFile) file = file.getAsFile();
  20871. if(file && file.size > 0 && /image\/\w+/i.test(file.type) ) {
  20872. sendAndInsertImage(file, me);
  20873. hasImg = true;
  20874. }
  20875. }
  20876. hasImg && e.preventDefault();
  20877. }
  20878. });
  20879. //取消拖放图片时出现的文字光标位置提示
  20880. domUtils.on(me.body, 'dragover', function (e) {
  20881. if(e.dataTransfer.types[0] == 'Files') {
  20882. e.preventDefault();
  20883. }
  20884. });
  20885. }
  20886. }
  20887. }
  20888. }
  20889. });
  20890. UE.plugin.register('autosave', function (){
  20891. var me = this,
  20892. //无限循环保护
  20893. lastSaveTime = new Date(),
  20894. //最小保存间隔时间
  20895. MIN_TIME = 20,
  20896. //auto save key
  20897. saveKey = null;
  20898. //存储媒介封装
  20899. var LocalStorage = UE.LocalStorage = ( function () {
  20900. var storage = window.localStorage || getUserData() || null,
  20901. LOCAL_FILE = "localStorage";
  20902. return {
  20903. saveLocalData: function ( key, data ) {
  20904. if ( storage && data) {
  20905. storage.setItem( key, data );
  20906. return true;
  20907. }
  20908. return false;
  20909. },
  20910. getLocalData: function ( key ) {
  20911. if ( storage ) {
  20912. return storage.getItem( key );
  20913. }
  20914. return null;
  20915. },
  20916. removeItem: function ( key ) {
  20917. storage && storage.removeItem( key );
  20918. }
  20919. };
  20920. function getUserData () {
  20921. var container = document.createElement( "div" );
  20922. container.style.display = "none";
  20923. if( !container.addBehavior ) {
  20924. return null;
  20925. }
  20926. container.addBehavior("#default#userdata");
  20927. return {
  20928. getItem: function ( key ) {
  20929. var result = null;
  20930. try {
  20931. document.body.appendChild( container );
  20932. container.load( LOCAL_FILE );
  20933. result = container.getAttribute( key );
  20934. document.body.removeChild( container );
  20935. } catch ( e ) {
  20936. }
  20937. return result;
  20938. },
  20939. setItem: function ( key, value ) {
  20940. document.body.appendChild( container );
  20941. container.setAttribute( key, value );
  20942. container.save( LOCAL_FILE );
  20943. document.body.removeChild( container );
  20944. },
  20945. // 暂时没有用到
  20946. // clear: function () {
  20947. //
  20948. // var expiresTime = new Date();
  20949. // expiresTime.setFullYear( expiresTime.getFullYear() - 1 );
  20950. // document.body.appendChild( container );
  20951. // container.expires = expiresTime.toUTCString();
  20952. // container.save( LOCAL_FILE );
  20953. // document.body.removeChild( container );
  20954. //
  20955. // },
  20956. removeItem: function ( key ) {
  20957. document.body.appendChild( container );
  20958. container.removeAttribute( key );
  20959. container.save( LOCAL_FILE );
  20960. document.body.removeChild( container );
  20961. }
  20962. };
  20963. }
  20964. } )();
  20965. function save ( editor ) {
  20966. var saveData = null;
  20967. if ( new Date() - lastSaveTime < MIN_TIME ) {
  20968. return;
  20969. }
  20970. if ( !editor.hasContents() ) {
  20971. //这里不能调用命令来删除, 会造成事件死循环
  20972. saveKey && LocalStorage.removeItem( saveKey );
  20973. return;
  20974. }
  20975. lastSaveTime = new Date();
  20976. editor._saveFlag = null;
  20977. saveData = me.body.innerHTML;
  20978. if ( editor.fireEvent( "beforeautosave", {
  20979. content: saveData
  20980. } ) === false ) {
  20981. return;
  20982. }
  20983. LocalStorage.saveLocalData( saveKey, saveData );
  20984. editor.fireEvent( "afterautosave", {
  20985. content: saveData
  20986. } );
  20987. }
  20988. return {
  20989. defaultOptions: {
  20990. //默认间隔时间
  20991. saveInterval: 500
  20992. },
  20993. bindEvents:{
  20994. 'ready':function(){
  20995. var _suffix = "-drafts-data",
  20996. key = null;
  20997. if ( me.key ) {
  20998. key = me.key + _suffix;
  20999. } else {
  21000. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21001. }
  21002. //页面地址+编辑器ID 保持唯一
  21003. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21004. },
  21005. 'contentchange': function () {
  21006. if ( !saveKey ) {
  21007. return;
  21008. }
  21009. if ( me._saveFlag ) {
  21010. window.clearTimeout( me._saveFlag );
  21011. }
  21012. if ( me.options.saveInterval > 0 ) {
  21013. me._saveFlag = window.setTimeout( function () {
  21014. save( me );
  21015. }, me.options.saveInterval );
  21016. } else {
  21017. save(me);
  21018. }
  21019. }
  21020. },
  21021. commands:{
  21022. 'clearlocaldata':{
  21023. execCommand:function (cmd, name) {
  21024. if ( saveKey && LocalStorage.getLocalData( saveKey ) ) {
  21025. LocalStorage.removeItem( saveKey )
  21026. }
  21027. },
  21028. notNeedUndo: true,
  21029. ignoreContentChange:true
  21030. },
  21031. 'getlocaldata':{
  21032. execCommand:function (cmd, name) {
  21033. return saveKey ? LocalStorage.getLocalData( saveKey ) || '' : '';
  21034. },
  21035. notNeedUndo: true,
  21036. ignoreContentChange:true
  21037. },
  21038. 'drafts':{
  21039. execCommand:function (cmd, name) {
  21040. if ( saveKey ) {
  21041. me.body.innerHTML = LocalStorage.getLocalData( saveKey ) || '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>';
  21042. me.focus(true);
  21043. }
  21044. },
  21045. queryCommandState: function () {
  21046. return saveKey ? ( LocalStorage.getLocalData( saveKey ) === null ? -1 : 0 ) : -1;
  21047. },
  21048. notNeedUndo: true,
  21049. ignoreContentChange:true
  21050. }
  21051. }
  21052. }
  21053. });
  21054. UE.plugin.register('charts', function (){
  21055. var me = this;
  21056. return {
  21057. bindEvents: {
  21058. 'chartserror': function () {
  21059. }
  21060. },
  21061. commands:{
  21062. 'charts': {
  21063. execCommand: function ( cmd, data ) {
  21064. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  21065. flagText = [],
  21066. config = {};
  21067. if ( !tableNode ) {
  21068. return false;
  21069. }
  21070. if ( !validData( tableNode ) ) {
  21071. me.fireEvent( "chartserror" );
  21072. return false;
  21073. }
  21074. config.title = data.title || '';
  21075. config.subTitle = data.subTitle || '';
  21076. config.xTitle = data.xTitle || '';
  21077. config.yTitle = data.yTitle || '';
  21078. config.suffix = data.suffix || '';
  21079. config.tip = data.tip || '';
  21080. //数据对齐方式
  21081. config.dataFormat = data.tableDataFormat || '';
  21082. //图表类型
  21083. config.chartType = data.chartType || 0;
  21084. for ( var key in config ) {
  21085. if ( !config.hasOwnProperty( key ) ) {
  21086. continue;
  21087. }
  21088. flagText.push( key+":"+config[ key ] );
  21089. }
  21090. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  21091. domUtils.addClass( tableNode, "edui-charts-table" );
  21092. },
  21093. queryCommandState: function ( cmd, name ) {
  21094. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  21095. return tableNode && validData( tableNode ) ? 0 : -1;
  21096. }
  21097. }
  21098. },
  21099. inputRule:function(root){
  21100. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  21101. if ( tableNode.getAttr("data-chart") !== undefined ) {
  21102. tableNode.setAttr("style");
  21103. }
  21104. })
  21105. },
  21106. outputRule:function(root){
  21107. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  21108. if ( tableNode.getAttr("data-chart") !== undefined ) {
  21109. tableNode.setAttr("style", "display: none;");
  21110. }
  21111. })
  21112. }
  21113. }
  21114. function validData ( table ) {
  21115. var firstRows = null,
  21116. cellCount = 0;
  21117. //行数不够
  21118. if ( table.rows.length < 2 ) {
  21119. return false;
  21120. }
  21121. //列数不够
  21122. if ( table.rows[0].cells.length < 2 ) {
  21123. return false;
  21124. }
  21125. //第一行所有cell必须是th
  21126. firstRows = table.rows[ 0 ].cells;
  21127. cellCount = firstRows.length;
  21128. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  21129. if ( cell.tagName.toLowerCase() !== 'th' ) {
  21130. return false;
  21131. }
  21132. }
  21133. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  21134. //每行单元格数不匹配, 返回false
  21135. if ( row.cells.length != cellCount ) {
  21136. return false;
  21137. }
  21138. //第一列不是th也返回false
  21139. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  21140. return false;
  21141. }
  21142. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  21143. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  21144. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  21145. //必须是数字
  21146. if ( !/^\d*\.?\d+$/.test( value ) ) {
  21147. return false;
  21148. }
  21149. }
  21150. }
  21151. return true;
  21152. }
  21153. });
  21154. /**
  21155. * 目录大纲支持插件
  21156. * @file
  21157. * @since 1.3.0
  21158. */
  21159. UE.plugin.register('section', function (){
  21160. /* 目录节点对象 */
  21161. function Section(option){
  21162. this.tag = '';
  21163. this.level = -1,
  21164. this.dom = null;
  21165. this.nextSection = null;
  21166. this.previousSection = null;
  21167. this.parentSection = null;
  21168. this.startAddress = [];
  21169. this.endAddress = [];
  21170. this.children = [];
  21171. }
  21172. function getSection(option) {
  21173. var section = new Section();
  21174. return utils.extend(section, option);
  21175. }
  21176. function getNodeFromAddress(startAddress, root) {
  21177. var current = root;
  21178. for(var i = 0;i < startAddress.length; i++) {
  21179. if(!current.childNodes) return null;
  21180. current = current.childNodes[startAddress[i]];
  21181. }
  21182. return current;
  21183. }
  21184. var me = this;
  21185. return {
  21186. bindMultiEvents:{
  21187. type: 'aftersetcontent afterscencerestore',
  21188. handler: function(){
  21189. me.fireEvent('updateSections');
  21190. }
  21191. },
  21192. bindEvents:{
  21193. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  21194. 'ready': function (){
  21195. me.fireEvent('updateSections');
  21196. domUtils.on(me.body, 'drop paste', function(){
  21197. me.fireEvent('updateSections');
  21198. });
  21199. },
  21200. /* 执行paragraph命令之后 */
  21201. 'afterexeccommand': function (type, cmd) {
  21202. if(cmd == 'paragraph') {
  21203. me.fireEvent('updateSections');
  21204. }
  21205. },
  21206. /* 部分键盘操作,触发updateSections事件 */
  21207. 'keyup': function (type, e) {
  21208. var me = this,
  21209. range = me.selection.getRange();
  21210. if(range.collapsed != true) {
  21211. me.fireEvent('updateSections');
  21212. } else {
  21213. var keyCode = e.keyCode || e.which;
  21214. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  21215. me.fireEvent('updateSections');
  21216. }
  21217. }
  21218. }
  21219. },
  21220. commands:{
  21221. 'getsections': {
  21222. execCommand: function (cmd, levels) {
  21223. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  21224. for (var i = 0; i < levelFn.length; i++) {
  21225. if (typeof levelFn[i] == 'string') {
  21226. levelFn[i] = function(fn){
  21227. return function(node){
  21228. return node.tagName == fn.toUpperCase()
  21229. };
  21230. }(levelFn[i]);
  21231. } else if (typeof levelFn[i] != 'function') {
  21232. levelFn[i] = function (node) {
  21233. return null;
  21234. }
  21235. }
  21236. }
  21237. function getSectionLevel(node) {
  21238. for (var i = 0; i < levelFn.length; i++) {
  21239. if (levelFn[i](node)) return i;
  21240. }
  21241. return -1;
  21242. }
  21243. var me = this,
  21244. Directory = getSection({'level':-1, 'title':'root'}),
  21245. previous = Directory;
  21246. function traversal(node, Directory) {
  21247. var level,
  21248. tmpSection = null,
  21249. parent,
  21250. child,
  21251. children = node.childNodes;
  21252. for (var i = 0, len = children.length; i < len; i++) {
  21253. child = children[i];
  21254. level = getSectionLevel(child);
  21255. if (level >= 0) {
  21256. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  21257. current = getSection({
  21258. 'tag': child.tagName,
  21259. 'title': child.innerText || child.textContent || '',
  21260. 'level': level,
  21261. 'dom': child,
  21262. 'startAddress': utils.clone(address, []),
  21263. 'endAddress': utils.clone(address, []),
  21264. 'children': []
  21265. });
  21266. previous.nextSection = current;
  21267. current.previousSection = previous;
  21268. parent = previous;
  21269. while(level <= parent.level){
  21270. parent = parent.parentSection;
  21271. }
  21272. current.parentSection = parent;
  21273. parent.children.push(current);
  21274. tmpSection = previous = current;
  21275. } else {
  21276. child.nodeType === 1 && traversal(child, Directory);
  21277. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  21278. }
  21279. }
  21280. }
  21281. traversal(me.body, Directory);
  21282. return Directory;
  21283. },
  21284. notNeedUndo: true
  21285. },
  21286. 'movesection': {
  21287. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  21288. var me = this,
  21289. targetAddress,
  21290. target;
  21291. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  21292. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  21293. target = getNodeFromAddress(targetAddress, me.body);
  21294. /* 判断目标地址是否被源章节包含 */
  21295. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  21296. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  21297. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  21298. current,
  21299. nextNode;
  21300. if(isAfter) {
  21301. current = endNode;
  21302. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  21303. nextNode = current.previousSibling;
  21304. domUtils.insertAfter(target, current);
  21305. if(current == startNode) break;
  21306. current = nextNode;
  21307. }
  21308. } else {
  21309. current = startNode;
  21310. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  21311. nextNode = current.nextSibling;
  21312. target.parentNode.insertBefore(current, target);
  21313. if(current == endNode) break;
  21314. current = nextNode;
  21315. }
  21316. }
  21317. me.fireEvent('updateSections');
  21318. /* 获取地址的包含关系 */
  21319. function isContainsAddress(startAddress, endAddress, addressTarget){
  21320. var isAfterStartAddress = false,
  21321. isBeforeEndAddress = false;
  21322. for(var i = 0; i< startAddress.length; i++){
  21323. if(i >= addressTarget.length) break;
  21324. if(addressTarget[i] > startAddress[i]) {
  21325. isAfterStartAddress = true;
  21326. break;
  21327. } else if(addressTarget[i] < startAddress[i]) {
  21328. break;
  21329. }
  21330. }
  21331. for(var i = 0; i< endAddress.length; i++){
  21332. if(i >= addressTarget.length) break;
  21333. if(addressTarget[i] < startAddress[i]) {
  21334. isBeforeEndAddress = true;
  21335. break;
  21336. } else if(addressTarget[i] > startAddress[i]) {
  21337. break;
  21338. }
  21339. }
  21340. return isAfterStartAddress && isBeforeEndAddress;
  21341. }
  21342. }
  21343. },
  21344. 'deletesection': {
  21345. execCommand: function (cmd, section, keepChildren) {
  21346. var me = this;
  21347. if(!section) return;
  21348. function getNodeFromAddress(startAddress) {
  21349. var current = me.body;
  21350. for(var i = 0;i < startAddress.length; i++) {
  21351. if(!current.childNodes) return null;
  21352. current = current.childNodes[startAddress[i]];
  21353. }
  21354. return current;
  21355. }
  21356. var startNode = getNodeFromAddress(section.startAddress),
  21357. endNode = getNodeFromAddress(section.endAddress),
  21358. current = startNode,
  21359. nextNode;
  21360. if(!keepChildren) {
  21361. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  21362. nextNode = current.nextSibling;
  21363. domUtils.remove(current);
  21364. current = nextNode;
  21365. }
  21366. } else {
  21367. domUtils.remove(current);
  21368. }
  21369. me.fireEvent('updateSections');
  21370. }
  21371. },
  21372. 'selectsection': {
  21373. execCommand: function (cmd, section) {
  21374. if(!section && !section.dom) return false;
  21375. var me = this,
  21376. range = me.selection.getRange(),
  21377. address = {
  21378. 'startAddress':utils.clone(section.startAddress, []),
  21379. 'endAddress':utils.clone(section.endAddress, [])
  21380. };
  21381. address.endAddress[address.endAddress.length - 1]++;
  21382. range.moveToAddress(address).select().scrollToView();
  21383. return true;
  21384. },
  21385. notNeedUndo: true
  21386. },
  21387. 'scrolltosection': {
  21388. execCommand: function (cmd, section) {
  21389. if(!section && !section.dom) return false;
  21390. var me = this,
  21391. range = me.selection.getRange(),
  21392. address = {
  21393. 'startAddress':section.startAddress,
  21394. 'endAddress':section.endAddress
  21395. };
  21396. address.endAddress[address.endAddress.length - 1]++;
  21397. range.moveToAddress(address).scrollToView();
  21398. return true;
  21399. },
  21400. notNeedUndo: true
  21401. }
  21402. }
  21403. }
  21404. });
  21405. var baidu = baidu || {};
  21406. baidu.editor = baidu.editor || {};
  21407. baidu.editor.ui = {};
  21408. (function (){
  21409. var browser = baidu.editor.browser,
  21410. domUtils = baidu.editor.dom.domUtils;
  21411. var magic = '$EDITORUI';
  21412. var root = window[magic] = {};
  21413. var uidMagic = 'ID' + magic;
  21414. var uidCount = 0;
  21415. var uiUtils = baidu.editor.ui.uiUtils = {
  21416. uid: function (obj){
  21417. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  21418. },
  21419. hook: function ( fn, callback ) {
  21420. var dg;
  21421. if (fn && fn._callbacks) {
  21422. dg = fn;
  21423. } else {
  21424. dg = function (){
  21425. var q;
  21426. if (fn) {
  21427. q = fn.apply(this, arguments);
  21428. }
  21429. var callbacks = dg._callbacks;
  21430. var k = callbacks.length;
  21431. while (k --) {
  21432. var r = callbacks[k].apply(this, arguments);
  21433. if (q === undefined) {
  21434. q = r;
  21435. }
  21436. }
  21437. return q;
  21438. };
  21439. dg._callbacks = [];
  21440. }
  21441. dg._callbacks.push(callback);
  21442. return dg;
  21443. },
  21444. createElementByHtml: function (html){
  21445. var el = document.createElement('div');
  21446. el.innerHTML = html;
  21447. el = el.firstChild;
  21448. el.parentNode.removeChild(el);
  21449. return el;
  21450. },
  21451. getViewportElement: function (){
  21452. return (browser.ie && browser.quirks) ?
  21453. document.body : document.documentElement;
  21454. },
  21455. getClientRect: function (element){
  21456. var bcr;
  21457. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  21458. try{
  21459. bcr = element.getBoundingClientRect();
  21460. }catch(e){
  21461. bcr={left:0,top:0,height:0,width:0}
  21462. }
  21463. var rect = {
  21464. left: Math.round(bcr.left),
  21465. top: Math.round(bcr.top),
  21466. height: Math.round(bcr.bottom - bcr.top),
  21467. width: Math.round(bcr.right - bcr.left)
  21468. };
  21469. var doc;
  21470. while ((doc = element.ownerDocument) !== document &&
  21471. (element = domUtils.getWindow(doc).frameElement)) {
  21472. bcr = element.getBoundingClientRect();
  21473. rect.left += bcr.left;
  21474. rect.top += bcr.top;
  21475. }
  21476. rect.bottom = rect.top + rect.height;
  21477. rect.right = rect.left + rect.width;
  21478. return rect;
  21479. },
  21480. getViewportRect: function (){
  21481. var viewportEl = uiUtils.getViewportElement();
  21482. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  21483. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  21484. return {
  21485. left: 0,
  21486. top: 0,
  21487. height: height,
  21488. width: width,
  21489. bottom: height,
  21490. right: width
  21491. };
  21492. },
  21493. setViewportOffset: function (element, offset){
  21494. var rect;
  21495. var fixedLayer = uiUtils.getFixedLayer();
  21496. if (element.parentNode === fixedLayer) {
  21497. element.style.left = offset.left + 'px';
  21498. element.style.top = offset.top + 'px';
  21499. } else {
  21500. domUtils.setViewportOffset(element, offset);
  21501. }
  21502. },
  21503. getEventOffset: function (evt){
  21504. var el = evt.target || evt.srcElement;
  21505. var rect = uiUtils.getClientRect(el);
  21506. var offset = uiUtils.getViewportOffsetByEvent(evt);
  21507. return {
  21508. left: offset.left - rect.left,
  21509. top: offset.top - rect.top
  21510. };
  21511. },
  21512. getViewportOffsetByEvent: function (evt){
  21513. var el = evt.target || evt.srcElement;
  21514. var frameEl = domUtils.getWindow(el).frameElement;
  21515. var offset = {
  21516. left: evt.clientX,
  21517. top: evt.clientY
  21518. };
  21519. if (frameEl && el.ownerDocument !== document) {
  21520. var rect = uiUtils.getClientRect(frameEl);
  21521. offset.left += rect.left;
  21522. offset.top += rect.top;
  21523. }
  21524. return offset;
  21525. },
  21526. setGlobal: function (id, obj){
  21527. root[id] = obj;
  21528. return magic + '["' + id + '"]';
  21529. },
  21530. unsetGlobal: function (id){
  21531. delete root[id];
  21532. },
  21533. copyAttributes: function (tgt, src){
  21534. var attributes = src.attributes;
  21535. var k = attributes.length;
  21536. while (k --) {
  21537. var attrNode = attributes[k];
  21538. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  21539. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  21540. }
  21541. }
  21542. if (src.className) {
  21543. domUtils.addClass(tgt,src.className);
  21544. }
  21545. if (src.style.cssText) {
  21546. tgt.style.cssText += ';' + src.style.cssText;
  21547. }
  21548. },
  21549. removeStyle: function (el, styleName){
  21550. if (el.style.removeProperty) {
  21551. el.style.removeProperty(styleName);
  21552. } else if (el.style.removeAttribute) {
  21553. el.style.removeAttribute(styleName);
  21554. } else throw '';
  21555. },
  21556. contains: function (elA, elB){
  21557. return elA && elB && (elA === elB ? false : (
  21558. elA.contains ? elA.contains(elB) :
  21559. elA.compareDocumentPosition(elB) & 16
  21560. ));
  21561. },
  21562. startDrag: function (evt, callbacks,doc){
  21563. var doc = doc || document;
  21564. var startX = evt.clientX;
  21565. var startY = evt.clientY;
  21566. function handleMouseMove(evt){
  21567. var x = evt.clientX - startX;
  21568. var y = evt.clientY - startY;
  21569. callbacks.ondragmove(x, y,evt);
  21570. if (evt.stopPropagation) {
  21571. evt.stopPropagation();
  21572. } else {
  21573. evt.cancelBubble = true;
  21574. }
  21575. }
  21576. if (doc.addEventListener) {
  21577. function handleMouseUp(evt){
  21578. doc.removeEventListener('mousemove', handleMouseMove, true);
  21579. doc.removeEventListener('mouseup', handleMouseUp, true);
  21580. window.removeEventListener('mouseup', handleMouseUp, true);
  21581. callbacks.ondragstop();
  21582. }
  21583. doc.addEventListener('mousemove', handleMouseMove, true);
  21584. doc.addEventListener('mouseup', handleMouseUp, true);
  21585. window.addEventListener('mouseup', handleMouseUp, true);
  21586. evt.preventDefault();
  21587. } else {
  21588. var elm = evt.srcElement;
  21589. elm.setCapture();
  21590. function releaseCaptrue(){
  21591. elm.releaseCapture();
  21592. elm.detachEvent('onmousemove', handleMouseMove);
  21593. elm.detachEvent('onmouseup', releaseCaptrue);
  21594. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  21595. callbacks.ondragstop();
  21596. }
  21597. elm.attachEvent('onmousemove', handleMouseMove);
  21598. elm.attachEvent('onmouseup', releaseCaptrue);
  21599. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  21600. evt.returnValue = false;
  21601. }
  21602. callbacks.ondragstart();
  21603. },
  21604. getFixedLayer: function (){
  21605. var layer = document.getElementById('edui_fixedlayer');
  21606. if (layer == null) {
  21607. layer = document.createElement('div');
  21608. layer.id = 'edui_fixedlayer';
  21609. document.body.appendChild(layer);
  21610. if (browser.ie && browser.version <= 8) {
  21611. layer.style.position = 'absolute';
  21612. bindFixedLayer();
  21613. setTimeout(updateFixedOffset);
  21614. } else {
  21615. layer.style.position = 'fixed';
  21616. }
  21617. layer.style.left = '0';
  21618. layer.style.top = '0';
  21619. layer.style.width = '0';
  21620. layer.style.height = '0';
  21621. }
  21622. return layer;
  21623. },
  21624. makeUnselectable: function (element){
  21625. if (browser.opera || (browser.ie && browser.version < 9)) {
  21626. element.unselectable = 'on';
  21627. if (element.hasChildNodes()) {
  21628. for (var i=0; i<element.childNodes.length; i++) {
  21629. if (element.childNodes[i].nodeType == 1) {
  21630. uiUtils.makeUnselectable(element.childNodes[i]);
  21631. }
  21632. }
  21633. }
  21634. } else {
  21635. if (element.style.MozUserSelect !== undefined) {
  21636. element.style.MozUserSelect = 'none';
  21637. } else if (element.style.WebkitUserSelect !== undefined) {
  21638. element.style.WebkitUserSelect = 'none';
  21639. } else if (element.style.KhtmlUserSelect !== undefined) {
  21640. element.style.KhtmlUserSelect = 'none';
  21641. }
  21642. }
  21643. }
  21644. };
  21645. function updateFixedOffset(){
  21646. var layer = document.getElementById('edui_fixedlayer');
  21647. uiUtils.setViewportOffset(layer, {
  21648. left: 0,
  21649. top: 0
  21650. });
  21651. // layer.style.display = 'none';
  21652. // layer.style.display = 'block';
  21653. //#trace: 1354
  21654. // setTimeout(updateFixedOffset);
  21655. }
  21656. function bindFixedLayer(adjOffset){
  21657. domUtils.on(window, 'scroll', updateFixedOffset);
  21658. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  21659. }
  21660. })();
  21661. (function () {
  21662. var utils = baidu.editor.utils,
  21663. uiUtils = baidu.editor.ui.uiUtils,
  21664. EventBase = baidu.editor.EventBase,
  21665. UIBase = baidu.editor.ui.UIBase = function () {
  21666. };
  21667. UIBase.prototype = {
  21668. className:'',
  21669. uiName:'',
  21670. initOptions:function (options) {
  21671. var me = this;
  21672. for (var k in options) {
  21673. me[k] = options[k];
  21674. }
  21675. this.id = this.id || 'edui' + uiUtils.uid();
  21676. },
  21677. initUIBase:function () {
  21678. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  21679. },
  21680. render:function (holder) {
  21681. var html = this.renderHtml();
  21682. var el = uiUtils.createElementByHtml(html);
  21683. //by xuheng 给每个node添加class
  21684. var list = domUtils.getElementsByTagName(el, "*");
  21685. var theme = "edui-" + (this.theme || this.editor.options.theme);
  21686. var layer = document.getElementById('edui_fixedlayer');
  21687. for (var i = 0, node; node = list[i++];) {
  21688. domUtils.addClass(node, theme);
  21689. }
  21690. domUtils.addClass(el, theme);
  21691. if(layer){
  21692. layer.className="";
  21693. domUtils.addClass(layer,theme);
  21694. }
  21695. var seatEl = this.getDom();
  21696. if (seatEl != null) {
  21697. seatEl.parentNode.replaceChild(el, seatEl);
  21698. uiUtils.copyAttributes(el, seatEl);
  21699. } else {
  21700. if (typeof holder == 'string') {
  21701. holder = document.getElementById(holder);
  21702. }
  21703. holder = holder || uiUtils.getFixedLayer();
  21704. domUtils.addClass(holder, theme);
  21705. holder.appendChild(el);
  21706. }
  21707. this.postRender();
  21708. },
  21709. getDom:function (name) {
  21710. if (!name) {
  21711. return document.getElementById(this.id);
  21712. } else {
  21713. return document.getElementById(this.id + '_' + name);
  21714. }
  21715. },
  21716. postRender:function () {
  21717. this.fireEvent('postrender');
  21718. },
  21719. getHtmlTpl:function () {
  21720. return '';
  21721. },
  21722. formatHtml:function (tpl) {
  21723. var prefix = 'edui-' + this.uiName;
  21724. return (tpl
  21725. .replace(/##/g, this.id)
  21726. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  21727. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  21728. .replace(/\$\$/g, this._globalKey));
  21729. },
  21730. renderHtml:function () {
  21731. return this.formatHtml(this.getHtmlTpl());
  21732. },
  21733. dispose:function () {
  21734. var box = this.getDom();
  21735. if (box) baidu.editor.dom.domUtils.remove(box);
  21736. uiUtils.unsetGlobal(this.id);
  21737. }
  21738. };
  21739. utils.inherits(UIBase, EventBase);
  21740. })();
  21741. (function (){
  21742. var utils = baidu.editor.utils,
  21743. UIBase = baidu.editor.ui.UIBase,
  21744. Separator = baidu.editor.ui.Separator = function (options){
  21745. this.initOptions(options);
  21746. this.initSeparator();
  21747. };
  21748. Separator.prototype = {
  21749. uiName: 'separator',
  21750. initSeparator: function (){
  21751. this.initUIBase();
  21752. },
  21753. getHtmlTpl: function (){
  21754. return '<div id="##" class="edui-box %%"></div>';
  21755. }
  21756. };
  21757. utils.inherits(Separator, UIBase);
  21758. })();
  21759. ///import core
  21760. ///import uicore
  21761. (function (){
  21762. var utils = baidu.editor.utils,
  21763. domUtils = baidu.editor.dom.domUtils,
  21764. UIBase = baidu.editor.ui.UIBase,
  21765. uiUtils = baidu.editor.ui.uiUtils;
  21766. var Mask = baidu.editor.ui.Mask = function (options){
  21767. this.initOptions(options);
  21768. this.initUIBase();
  21769. };
  21770. Mask.prototype = {
  21771. getHtmlTpl: function (){
  21772. return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>';
  21773. },
  21774. postRender: function (){
  21775. var me = this;
  21776. domUtils.on(window, 'resize', function (){
  21777. setTimeout(function (){
  21778. if (!me.isHidden()) {
  21779. me._fill();
  21780. }
  21781. });
  21782. });
  21783. },
  21784. show: function (zIndex){
  21785. this._fill();
  21786. this.getDom().style.display = '';
  21787. this.getDom().style.zIndex = zIndex;
  21788. },
  21789. hide: function (){
  21790. this.getDom().style.display = 'none';
  21791. this.getDom().style.zIndex = '';
  21792. },
  21793. isHidden: function (){
  21794. return this.getDom().style.display == 'none';
  21795. },
  21796. _onMouseDown: function (){
  21797. return false;
  21798. },
  21799. _fill: function (){
  21800. var el = this.getDom();
  21801. var vpRect = uiUtils.getViewportRect();
  21802. el.style.width = vpRect.width + 'px';
  21803. el.style.height = vpRect.height + 'px';
  21804. }
  21805. };
  21806. utils.inherits(Mask, UIBase);
  21807. })();
  21808. ///import core
  21809. ///import uicore
  21810. (function () {
  21811. var utils = baidu.editor.utils,
  21812. uiUtils = baidu.editor.ui.uiUtils,
  21813. domUtils = baidu.editor.dom.domUtils,
  21814. UIBase = baidu.editor.ui.UIBase,
  21815. Popup = baidu.editor.ui.Popup = function (options){
  21816. this.initOptions(options);
  21817. this.initPopup();
  21818. };
  21819. var allPopups = [];
  21820. function closeAllPopup( evt,el ){
  21821. for ( var i = 0; i < allPopups.length; i++ ) {
  21822. var pop = allPopups[i];
  21823. if (!pop.isHidden()) {
  21824. if (pop.queryAutoHide(el) !== false) {
  21825. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  21826. pop.hide();
  21827. }
  21828. }
  21829. }
  21830. if(allPopups.length)
  21831. pop.editor.fireEvent("afterhidepop");
  21832. }
  21833. Popup.postHide = closeAllPopup;
  21834. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  21835. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  21836. Popup.prototype = {
  21837. SHADOW_RADIUS: 5,
  21838. content: null,
  21839. _hidden: false,
  21840. autoRender: true,
  21841. canSideLeft: true,
  21842. canSideUp: true,
  21843. initPopup: function (){
  21844. this.initUIBase();
  21845. allPopups.push( this );
  21846. },
  21847. getHtmlTpl: function (){
  21848. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  21849. ' <div id="##_body" class="edui-popup-body">' +
  21850. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  21851. ' <div class="edui-shadow"></div>' +
  21852. ' <div id="##_content" class="edui-popup-content">' +
  21853. this.getContentHtmlTpl() +
  21854. ' </div>' +
  21855. ' </div>' +
  21856. '</div>';
  21857. },
  21858. getContentHtmlTpl: function (){
  21859. if(this.content){
  21860. if (typeof this.content == 'string') {
  21861. return this.content;
  21862. }
  21863. return this.content.renderHtml();
  21864. }else{
  21865. return ''
  21866. }
  21867. },
  21868. _UIBase_postRender: UIBase.prototype.postRender,
  21869. postRender: function (){
  21870. if (this.content instanceof UIBase) {
  21871. this.content.postRender();
  21872. }
  21873. //捕获鼠标滚轮
  21874. if( this.captureWheel && !this.captured ) {
  21875. this.captured = true;
  21876. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  21877. _height = this.getDom().offsetHeight,
  21878. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  21879. content = this.getDom('content'),
  21880. ifr = this.getDom('body').getElementsByTagName('iframe'),
  21881. me = this;
  21882. ifr.length && ( ifr = ifr[0] );
  21883. while( _top + _height > winHeight ) {
  21884. _height -= 30;
  21885. content.style.height = _height + 'px';
  21886. //同步更改iframe高度
  21887. ifr && ( ifr.style.height = _height + 'px' );
  21888. }
  21889. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  21890. if( window.XMLHttpRequest ) {
  21891. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  21892. if(e.preventDefault) {
  21893. e.preventDefault();
  21894. } else {
  21895. e.returnValue = false;
  21896. }
  21897. if( e.wheelDelta ) {
  21898. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  21899. } else {
  21900. content.scrollTop -= ( e.detail / -3 )*60;
  21901. }
  21902. });
  21903. } else {
  21904. //ie6
  21905. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  21906. e.returnValue = false;
  21907. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  21908. });
  21909. }
  21910. }
  21911. this.fireEvent('postRenderAfter');
  21912. this.hide(true);
  21913. this._UIBase_postRender();
  21914. },
  21915. _doAutoRender: function (){
  21916. if (!this.getDom() && this.autoRender) {
  21917. this.render();
  21918. }
  21919. },
  21920. mesureSize: function (){
  21921. var box = this.getDom('content');
  21922. return uiUtils.getClientRect(box);
  21923. },
  21924. fitSize: function (){
  21925. if( this.captureWheel && this.sized ) {
  21926. return this.__size;
  21927. }
  21928. this.sized = true;
  21929. var popBodyEl = this.getDom('body');
  21930. popBodyEl.style.width = '';
  21931. popBodyEl.style.height = '';
  21932. var size = this.mesureSize();
  21933. if( this.captureWheel ) {
  21934. popBodyEl.style.width = -(-20 -size.width) + 'px';
  21935. var height = parseInt( this.getDom('content').style.height, 10 );
  21936. !window.isNaN( height ) && ( size.height = height );
  21937. } else {
  21938. popBodyEl.style.width = size.width + 'px';
  21939. }
  21940. popBodyEl.style.height = size.height + 'px';
  21941. this.__size = size;
  21942. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  21943. return size;
  21944. },
  21945. showAnchor: function ( element, hoz ){
  21946. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  21947. },
  21948. showAnchorRect: function ( rect, hoz, adj ){
  21949. this._doAutoRender();
  21950. var vpRect = uiUtils.getViewportRect();
  21951. this._show();
  21952. var popSize = this.fitSize();
  21953. var sideLeft, sideUp, left, top;
  21954. if (hoz) {
  21955. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  21956. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  21957. left = (sideLeft ? rect.left - popSize.width : rect.right);
  21958. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  21959. } else {
  21960. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  21961. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  21962. left = (sideLeft ? rect.right - popSize.width : rect.left);
  21963. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  21964. }
  21965. var popEl = this.getDom();
  21966. uiUtils.setViewportOffset(popEl, {
  21967. left: left,
  21968. top: top
  21969. });
  21970. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  21971. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  21972. if(this.editor){
  21973. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  21974. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  21975. }
  21976. },
  21977. showAt: function (offset) {
  21978. var left = offset.left;
  21979. var top = offset.top;
  21980. var rect = {
  21981. left: left,
  21982. top: top,
  21983. right: left,
  21984. bottom: top,
  21985. height: 0,
  21986. width: 0
  21987. };
  21988. this.showAnchorRect(rect, false, true);
  21989. },
  21990. _show: function (){
  21991. if (this._hidden) {
  21992. var box = this.getDom();
  21993. box.style.display = '';
  21994. this._hidden = false;
  21995. // if (box.setActive) {
  21996. // box.setActive();
  21997. // }
  21998. this.fireEvent('show');
  21999. }
  22000. },
  22001. isHidden: function (){
  22002. return this._hidden;
  22003. },
  22004. show: function (){
  22005. this._doAutoRender();
  22006. this._show();
  22007. },
  22008. hide: function (notNofity){
  22009. if (!this._hidden && this.getDom()) {
  22010. this.getDom().style.display = 'none';
  22011. this._hidden = true;
  22012. if (!notNofity) {
  22013. this.fireEvent('hide');
  22014. }
  22015. }
  22016. },
  22017. queryAutoHide: function (el){
  22018. return !el || !uiUtils.contains(this.getDom(), el);
  22019. }
  22020. };
  22021. utils.inherits(Popup, UIBase);
  22022. domUtils.on( document, 'mousedown', function ( evt ) {
  22023. var el = evt.target || evt.srcElement;
  22024. closeAllPopup( evt,el );
  22025. } );
  22026. domUtils.on( window, 'scroll', function (evt,el) {
  22027. closeAllPopup( evt,el );
  22028. } );
  22029. })();
  22030. ///import core
  22031. ///import uicore
  22032. (function (){
  22033. var utils = baidu.editor.utils,
  22034. UIBase = baidu.editor.ui.UIBase,
  22035. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  22036. this.initOptions(options);
  22037. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  22038. this.initUIBase();
  22039. };
  22040. ColorPicker.prototype = {
  22041. getHtmlTpl: function (){
  22042. return genColorPicker(this.noColorText,this.editor);
  22043. },
  22044. _onTableClick: function (evt){
  22045. var tgt = evt.target || evt.srcElement;
  22046. var color = tgt.getAttribute('data-color');
  22047. if (color) {
  22048. this.fireEvent('pickcolor', color);
  22049. }
  22050. },
  22051. _onTableOver: function (evt){
  22052. var tgt = evt.target || evt.srcElement;
  22053. var color = tgt.getAttribute('data-color');
  22054. if (color) {
  22055. this.getDom('preview').style.backgroundColor = color;
  22056. }
  22057. },
  22058. _onTableOut: function (){
  22059. this.getDom('preview').style.backgroundColor = '';
  22060. },
  22061. _onPickNoColor: function (){
  22062. this.fireEvent('picknocolor');
  22063. }
  22064. };
  22065. utils.inherits(ColorPicker, UIBase);
  22066. var COLORS = (
  22067. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  22068. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  22069. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  22070. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  22071. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  22072. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  22073. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  22074. function genColorPicker(noColorText,editor){
  22075. var html = '<div id="##" class="edui-colorpicker %%">' +
  22076. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  22077. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  22078. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  22079. '</div>' +
  22080. '<table class="edui-box" style="border-collapse: collapse;" onmouseover="$$._onTableOver(event, this);" onmouseout="$$._onTableOut(event, this);" onclick="return $$._onTableClick(event, this);" cellspacing="0" cellpadding="0">' +
  22081. '<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;padding-top: 2px"><td colspan="10">'+editor.getLang("themeColor")+'</td> </tr>'+
  22082. '<tr class="edui-colorpicker-tablefirstrow" >';
  22083. for (var i=0; i<COLORS.length; i++) {
  22084. if (i && i%10 === 0) {
  22085. html += '</tr>'+(i==60?'<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;"><td colspan="10">'+editor.getLang("standardColor")+'</td></tr>':'')+'<tr'+(i==60?' class="edui-colorpicker-tablefirstrow"':'')+'>';
  22086. }
  22087. html += i<70 ? '<td style="padding: 0 2px;"><a hidefocus title="'+COLORS[i]+'" onclick="return false;" href="javascript:" unselectable="on" class="edui-box edui-colorpicker-colorcell"' +
  22088. ' data-color="#'+ COLORS[i] +'"'+
  22089. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  22090. (i<10 || i>=60?'border-width:1px;':
  22091. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  22092. 'border-width:0 1px 0 1px;')+
  22093. '"' +
  22094. '></a></td>':'';
  22095. }
  22096. html += '</tr></table></div>';
  22097. return html;
  22098. }
  22099. })();
  22100. ///import core
  22101. ///import uicore
  22102. (function (){
  22103. var utils = baidu.editor.utils,
  22104. uiUtils = baidu.editor.ui.uiUtils,
  22105. UIBase = baidu.editor.ui.UIBase;
  22106. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  22107. this.initOptions(options);
  22108. this.initTablePicker();
  22109. };
  22110. TablePicker.prototype = {
  22111. defaultNumRows: 10,
  22112. defaultNumCols: 10,
  22113. maxNumRows: 20,
  22114. maxNumCols: 20,
  22115. numRows: 10,
  22116. numCols: 10,
  22117. lengthOfCellSide: 22,
  22118. initTablePicker: function (){
  22119. this.initUIBase();
  22120. },
  22121. getHtmlTpl: function (){
  22122. var me = this;
  22123. return '<div id="##" class="edui-tablepicker %%">' +
  22124. '<div class="edui-tablepicker-body">' +
  22125. '<div class="edui-infoarea">' +
  22126. '<span id="##_label" class="edui-label"></span>' +
  22127. '</div>' +
  22128. '<div class="edui-pickarea"' +
  22129. ' onmousemove="$$._onMouseMove(event, this);"' +
  22130. ' onmouseover="$$._onMouseOver(event, this);"' +
  22131. ' onmouseout="$$._onMouseOut(event, this);"' +
  22132. ' onclick="$$._onClick(event, this);"' +
  22133. '>' +
  22134. '<div id="##_overlay" class="edui-overlay"></div>' +
  22135. '</div>' +
  22136. '</div>' +
  22137. '</div>';
  22138. },
  22139. _UIBase_render: UIBase.prototype.render,
  22140. render: function (holder){
  22141. this._UIBase_render(holder);
  22142. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  22143. },
  22144. _track: function (numCols, numRows){
  22145. var style = this.getDom('overlay').style;
  22146. var sideLen = this.lengthOfCellSide;
  22147. style.width = numCols * sideLen + 'px';
  22148. style.height = numRows * sideLen + 'px';
  22149. var label = this.getDom('label');
  22150. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  22151. this.numCols = numCols;
  22152. this.numRows = numRows;
  22153. },
  22154. _onMouseOver: function (evt, el){
  22155. var rel = evt.relatedTarget || evt.fromElement;
  22156. if (!uiUtils.contains(el, rel) && el !== rel) {
  22157. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  22158. this.getDom('overlay').style.visibility = '';
  22159. }
  22160. },
  22161. _onMouseOut: function (evt, el){
  22162. var rel = evt.relatedTarget || evt.toElement;
  22163. if (!uiUtils.contains(el, rel) && el !== rel) {
  22164. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  22165. this.getDom('overlay').style.visibility = 'hidden';
  22166. }
  22167. },
  22168. _onMouseMove: function (evt, el){
  22169. var style = this.getDom('overlay').style;
  22170. var offset = uiUtils.getEventOffset(evt);
  22171. var sideLen = this.lengthOfCellSide;
  22172. var numCols = Math.ceil(offset.left / sideLen);
  22173. var numRows = Math.ceil(offset.top / sideLen);
  22174. this._track(numCols, numRows);
  22175. },
  22176. _onClick: function (){
  22177. this.fireEvent('picktable', this.numCols, this.numRows);
  22178. }
  22179. };
  22180. utils.inherits(TablePicker, UIBase);
  22181. })();
  22182. (function (){
  22183. var browser = baidu.editor.browser,
  22184. domUtils = baidu.editor.dom.domUtils,
  22185. uiUtils = baidu.editor.ui.uiUtils;
  22186. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  22187. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  22188. ( browser.ie ? (
  22189. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  22190. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  22191. : (
  22192. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  22193. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  22194. baidu.editor.ui.Stateful = {
  22195. alwalysHoverable: false,
  22196. target:null,//目标元素和this指向dom不一样
  22197. Stateful_init: function (){
  22198. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  22199. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  22200. },
  22201. Stateful_getHtmlTpl: function (){
  22202. var tpl = this._Stateful_dGetHtmlTpl();
  22203. // 使用function避免$转义
  22204. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  22205. },
  22206. Stateful_onMouseEnter: function (evt, el){
  22207. this.target=el;
  22208. if (!this.isDisabled() || this.alwalysHoverable) {
  22209. this.addState('hover');
  22210. this.fireEvent('over');
  22211. }
  22212. },
  22213. Stateful_onMouseLeave: function (evt, el){
  22214. if (!this.isDisabled() || this.alwalysHoverable) {
  22215. this.removeState('hover');
  22216. this.removeState('active');
  22217. this.fireEvent('out');
  22218. }
  22219. },
  22220. Stateful_onMouseOver: function (evt, el){
  22221. var rel = evt.relatedTarget;
  22222. if (!uiUtils.contains(el, rel) && el !== rel) {
  22223. this.Stateful_onMouseEnter(evt, el);
  22224. }
  22225. },
  22226. Stateful_onMouseOut: function (evt, el){
  22227. var rel = evt.relatedTarget;
  22228. if (!uiUtils.contains(el, rel) && el !== rel) {
  22229. this.Stateful_onMouseLeave(evt, el);
  22230. }
  22231. },
  22232. Stateful_onMouseDown: function (evt, el){
  22233. if (!this.isDisabled()) {
  22234. this.addState('active');
  22235. }
  22236. },
  22237. Stateful_onMouseUp: function (evt, el){
  22238. if (!this.isDisabled()) {
  22239. this.removeState('active');
  22240. }
  22241. },
  22242. Stateful_postRender: function (){
  22243. if (this.disabled && !this.hasState('disabled')) {
  22244. this.addState('disabled');
  22245. }
  22246. },
  22247. hasState: function (state){
  22248. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  22249. },
  22250. addState: function (state){
  22251. if (!this.hasState(state)) {
  22252. this.getStateDom().className += ' edui-state-' + state;
  22253. }
  22254. },
  22255. removeState: function (state){
  22256. if (this.hasState(state)) {
  22257. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  22258. }
  22259. },
  22260. getStateDom: function (){
  22261. return this.getDom('state');
  22262. },
  22263. isChecked: function (){
  22264. return this.hasState('checked');
  22265. },
  22266. setChecked: function (checked){
  22267. if (!this.isDisabled() && checked) {
  22268. this.addState('checked');
  22269. } else {
  22270. this.removeState('checked');
  22271. }
  22272. },
  22273. isDisabled: function (){
  22274. return this.hasState('disabled');
  22275. },
  22276. setDisabled: function (disabled){
  22277. if (disabled) {
  22278. this.removeState('hover');
  22279. this.removeState('checked');
  22280. this.removeState('active');
  22281. this.addState('disabled');
  22282. } else {
  22283. this.removeState('disabled');
  22284. }
  22285. }
  22286. };
  22287. })();
  22288. ///import core
  22289. ///import uicore
  22290. ///import ui/stateful.js
  22291. (function (){
  22292. var utils = baidu.editor.utils,
  22293. UIBase = baidu.editor.ui.UIBase,
  22294. Stateful = baidu.editor.ui.Stateful,
  22295. Button = baidu.editor.ui.Button = function (options){
  22296. this.initOptions(options);
  22297. this.initButton();
  22298. };
  22299. Button.prototype = {
  22300. uiName: 'button',
  22301. label: '',
  22302. title: '',
  22303. showIcon: true,
  22304. showText: true,
  22305. initButton: function (){
  22306. this.initUIBase();
  22307. this.Stateful_init();
  22308. },
  22309. getHtmlTpl: function (){
  22310. return '<div id="##" class="edui-box %%">' +
  22311. '<div id="##_state" stateful>' +
  22312. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  22313. ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' +
  22314. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  22315. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  22316. '</div>' +
  22317. '</div>' +
  22318. '</div></div>';
  22319. },
  22320. postRender: function (){
  22321. this.Stateful_postRender();
  22322. this.setDisabled(this.disabled)
  22323. },
  22324. _onClick: function (){
  22325. if (!this.isDisabled()) {
  22326. this.fireEvent('click');
  22327. }
  22328. }
  22329. };
  22330. utils.inherits(Button, UIBase);
  22331. utils.extend(Button.prototype, Stateful);
  22332. })();
  22333. ///import core
  22334. ///import uicore
  22335. ///import ui/stateful.js
  22336. (function (){
  22337. var utils = baidu.editor.utils,
  22338. uiUtils = baidu.editor.ui.uiUtils,
  22339. domUtils = baidu.editor.dom.domUtils,
  22340. UIBase = baidu.editor.ui.UIBase,
  22341. Stateful = baidu.editor.ui.Stateful,
  22342. SplitButton = baidu.editor.ui.SplitButton = function (options){
  22343. this.initOptions(options);
  22344. this.initSplitButton();
  22345. };
  22346. SplitButton.prototype = {
  22347. popup: null,
  22348. uiName: 'splitbutton',
  22349. title: '',
  22350. initSplitButton: function (){
  22351. this.initUIBase();
  22352. this.Stateful_init();
  22353. var me = this;
  22354. if (this.popup != null) {
  22355. var popup = this.popup;
  22356. this.popup = null;
  22357. this.setPopup(popup);
  22358. }
  22359. },
  22360. _UIBase_postRender: UIBase.prototype.postRender,
  22361. postRender: function (){
  22362. this.Stateful_postRender();
  22363. this._UIBase_postRender();
  22364. },
  22365. setPopup: function (popup){
  22366. if (this.popup === popup) return;
  22367. if (this.popup != null) {
  22368. this.popup.dispose();
  22369. }
  22370. popup.addListener('show', utils.bind(this._onPopupShow, this));
  22371. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  22372. popup.addListener('postrender', utils.bind(function (){
  22373. popup.getDom('body').appendChild(
  22374. uiUtils.createElementByHtml('<div id="' +
  22375. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  22376. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  22377. );
  22378. popup.getDom().className += ' ' + this.className;
  22379. }, this));
  22380. this.popup = popup;
  22381. },
  22382. _onPopupShow: function (){
  22383. this.addState('opened');
  22384. },
  22385. _onPopupHide: function (){
  22386. this.removeState('opened');
  22387. },
  22388. getHtmlTpl: function (){
  22389. return '<div id="##" class="edui-box %%">' +
  22390. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  22391. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  22392. '<div class="edui-box edui-icon"></div>' +
  22393. '</div>' +
  22394. '<div class="edui-box edui-splitborder"></div>' +
  22395. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  22396. '</div></div></div>';
  22397. },
  22398. showPopup: function (){
  22399. // 当popup往上弹出的时候,做特殊处理
  22400. var rect = uiUtils.getClientRect(this.getDom());
  22401. rect.top -= this.popup.SHADOW_RADIUS;
  22402. rect.height += this.popup.SHADOW_RADIUS;
  22403. this.popup.showAnchorRect(rect);
  22404. },
  22405. _onArrowClick: function (event, el){
  22406. if (!this.isDisabled()) {
  22407. this.showPopup();
  22408. }
  22409. },
  22410. _onButtonClick: function (){
  22411. if (!this.isDisabled()) {
  22412. this.fireEvent('buttonclick');
  22413. }
  22414. }
  22415. };
  22416. utils.inherits(SplitButton, UIBase);
  22417. utils.extend(SplitButton.prototype, Stateful, true);
  22418. })();
  22419. ///import core
  22420. ///import uicore
  22421. ///import ui/colorpicker.js
  22422. ///import ui/popup.js
  22423. ///import ui/splitbutton.js
  22424. (function (){
  22425. var utils = baidu.editor.utils,
  22426. uiUtils = baidu.editor.ui.uiUtils,
  22427. ColorPicker = baidu.editor.ui.ColorPicker,
  22428. Popup = baidu.editor.ui.Popup,
  22429. SplitButton = baidu.editor.ui.SplitButton,
  22430. ColorButton = baidu.editor.ui.ColorButton = function (options){
  22431. this.initOptions(options);
  22432. this.initColorButton();
  22433. };
  22434. ColorButton.prototype = {
  22435. initColorButton: function (){
  22436. var me = this;
  22437. this.popup = new Popup({
  22438. content: new ColorPicker({
  22439. noColorText: me.editor.getLang("clearColor"),
  22440. editor:me.editor,
  22441. onpickcolor: function (t, color){
  22442. me._onPickColor(color);
  22443. },
  22444. onpicknocolor: function (t, color){
  22445. me._onPickNoColor(color);
  22446. }
  22447. }),
  22448. editor:me.editor
  22449. });
  22450. this.initSplitButton();
  22451. },
  22452. _SplitButton_postRender: SplitButton.prototype.postRender,
  22453. postRender: function (){
  22454. this._SplitButton_postRender();
  22455. this.getDom('button_body').appendChild(
  22456. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  22457. );
  22458. this.getDom().className += ' edui-colorbutton';
  22459. },
  22460. setColor: function (color){
  22461. this.getDom('colorlump').style.backgroundColor = color;
  22462. this.color = color;
  22463. },
  22464. _onPickColor: function (color){
  22465. if (this.fireEvent('pickcolor', color) !== false) {
  22466. this.setColor(color);
  22467. this.popup.hide();
  22468. }
  22469. },
  22470. _onPickNoColor: function (color){
  22471. if (this.fireEvent('picknocolor') !== false) {
  22472. this.popup.hide();
  22473. }
  22474. }
  22475. };
  22476. utils.inherits(ColorButton, SplitButton);
  22477. })();
  22478. ///import core
  22479. ///import uicore
  22480. ///import ui/popup.js
  22481. ///import ui/tablepicker.js
  22482. ///import ui/splitbutton.js
  22483. (function (){
  22484. var utils = baidu.editor.utils,
  22485. Popup = baidu.editor.ui.Popup,
  22486. TablePicker = baidu.editor.ui.TablePicker,
  22487. SplitButton = baidu.editor.ui.SplitButton,
  22488. TableButton = baidu.editor.ui.TableButton = function (options){
  22489. this.initOptions(options);
  22490. this.initTableButton();
  22491. };
  22492. TableButton.prototype = {
  22493. initTableButton: function (){
  22494. var me = this;
  22495. this.popup = new Popup({
  22496. content: new TablePicker({
  22497. editor:me.editor,
  22498. onpicktable: function (t, numCols, numRows){
  22499. me._onPickTable(numCols, numRows);
  22500. }
  22501. }),
  22502. 'editor':me.editor
  22503. });
  22504. this.initSplitButton();
  22505. },
  22506. _onPickTable: function (numCols, numRows){
  22507. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  22508. this.popup.hide();
  22509. }
  22510. }
  22511. };
  22512. utils.inherits(TableButton, SplitButton);
  22513. })();
  22514. ///import core
  22515. ///import uicore
  22516. (function () {
  22517. var utils = baidu.editor.utils,
  22518. UIBase = baidu.editor.ui.UIBase;
  22519. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  22520. this.initOptions(options);
  22521. this.initAutoTypeSetPicker();
  22522. };
  22523. AutoTypeSetPicker.prototype = {
  22524. initAutoTypeSetPicker:function () {
  22525. this.initUIBase();
  22526. },
  22527. getHtmlTpl:function () {
  22528. var me = this.editor,
  22529. opt = me.options.autotypeset,
  22530. lang = me.getLang("autoTypeSet");
  22531. var textAlignInputName = 'textAlignValue' + me.uid,
  22532. imageBlockInputName = 'imageBlockLineValue' + me.uid;
  22533. return '<div id="##" class="edui-autotypesetpicker %%">' +
  22534. '<div class="edui-autotypesetpicker-body">' +
  22535. '<table >' +
  22536. '<tr><td nowrap colspan="2"><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "" ) + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "" ) + '>' + lang.delLine + '</td></tr>' +
  22537. '<tr><td nowrap colspan="2"><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "" ) + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "" ) + '>' + lang.indent + '</td></tr>' +
  22538. '<tr><td nowrap colspan="2"><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td><td colspan="2" id="' + textAlignInputName + '"><input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + ' </tr>' +
  22539. '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  22540. '<td nowrap colspan="2" id="'+ imageBlockInputName +'">' +
  22541. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  22542. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  22543. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  22544. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' +
  22545. '<tr><td nowrap colspan="2"><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "" ) + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "" ) + '>' + lang.removeFontFamily + '</td></tr>' +
  22546. '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  22547. '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  22548. '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' +
  22549. '</table>' +
  22550. '</div>' +
  22551. '</div>';
  22552. },
  22553. _UIBase_render:UIBase.prototype.render
  22554. };
  22555. utils.inherits(AutoTypeSetPicker, UIBase);
  22556. })();
  22557. ///import core
  22558. ///import uicore
  22559. ///import ui/popup.js
  22560. ///import ui/autotypesetpicker.js
  22561. ///import ui/splitbutton.js
  22562. (function (){
  22563. var utils = baidu.editor.utils,
  22564. Popup = baidu.editor.ui.Popup,
  22565. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  22566. SplitButton = baidu.editor.ui.SplitButton,
  22567. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  22568. this.initOptions(options);
  22569. this.initAutoTypeSetButton();
  22570. };
  22571. function getPara(me){
  22572. var opt = me.editor.options.autotypeset,
  22573. cont = me.getDom(),
  22574. editorId = me.editor.uid,
  22575. inputType = null,
  22576. attrName = null,
  22577. ipts = domUtils.getElementsByTagName(cont,"input");
  22578. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  22579. inputType = ipt.getAttribute("type");
  22580. if(inputType=="checkbox"){
  22581. attrName = ipt.getAttribute("name");
  22582. opt[attrName] && delete opt[attrName];
  22583. if(ipt.checked){
  22584. var attrValue = document.getElementById( attrName+"Value" + editorId );
  22585. if(attrValue){
  22586. if(/input/ig.test(attrValue.tagName)){
  22587. opt[attrName] = attrValue.value;
  22588. }else{
  22589. var iptChilds = attrValue.getElementsByTagName("input");
  22590. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  22591. if(iptchild.checked){
  22592. opt[attrName] = iptchild.value;
  22593. break;
  22594. }
  22595. }
  22596. }
  22597. }else{
  22598. opt[attrName] = true;
  22599. }
  22600. }
  22601. }
  22602. }
  22603. var selects = domUtils.getElementsByTagName(cont,"select");
  22604. for(var i=0,si;si=selects[i++];){
  22605. var attr = si.getAttribute('name');
  22606. opt[attr] = opt[attr] ? si.value : '';
  22607. }
  22608. me.editor.options.autotypeset = opt;
  22609. }
  22610. AutoTypeSetButton.prototype = {
  22611. initAutoTypeSetButton: function (){
  22612. var me = this;
  22613. this.popup = new Popup({
  22614. //传入配置参数
  22615. content: new AutoTypeSetPicker({editor:me.editor}),
  22616. 'editor':me.editor,
  22617. hide : function(){
  22618. if (!this._hidden && this.getDom()) {
  22619. getPara(this);
  22620. this.getDom().style.display = 'none';
  22621. this._hidden = true;
  22622. this.fireEvent('hide');
  22623. }
  22624. }
  22625. });
  22626. var flag = 0;
  22627. this.popup.addListener('postRenderAfter',function(){
  22628. var popupUI = this;
  22629. if(flag)return;
  22630. var cont = this.getDom(),
  22631. btn = cont.getElementsByTagName('button')[0];
  22632. btn.onclick = function(){
  22633. getPara(popupUI);
  22634. me.editor.execCommand('autotypeset');
  22635. popupUI.hide()
  22636. };
  22637. flag = 1;
  22638. });
  22639. this.initSplitButton();
  22640. }
  22641. };
  22642. utils.inherits(AutoTypeSetButton, SplitButton);
  22643. })();
  22644. ///import core
  22645. ///import uicore
  22646. (function () {
  22647. var utils = baidu.editor.utils,
  22648. Popup = baidu.editor.ui.Popup,
  22649. Stateful = baidu.editor.ui.Stateful,
  22650. UIBase = baidu.editor.ui.UIBase;
  22651. /**
  22652. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  22653. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  22654. * @update 2013/4/2 hancong03@baidu.com
  22655. */
  22656. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  22657. this.initOptions(options);
  22658. this.initSelected();
  22659. this.initCellAlignPicker();
  22660. };
  22661. CellAlignPicker.prototype = {
  22662. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  22663. initSelected: function(){
  22664. var status = {
  22665. valign: {
  22666. top: 0,
  22667. middle: 1,
  22668. bottom: 2
  22669. },
  22670. align: {
  22671. left: 0,
  22672. center: 1,
  22673. right: 2
  22674. },
  22675. count: 3
  22676. },
  22677. result = -1;
  22678. if( this.selected ) {
  22679. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  22680. }
  22681. },
  22682. initCellAlignPicker:function () {
  22683. this.initUIBase();
  22684. this.Stateful_init();
  22685. },
  22686. getHtmlTpl:function () {
  22687. var alignType = [ 'left', 'center', 'right' ],
  22688. COUNT = 9,
  22689. tempClassName = null,
  22690. tempIndex = -1,
  22691. tmpl = [];
  22692. for( var i= 0; i<COUNT; i++ ) {
  22693. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  22694. tempIndex = i % 3;
  22695. tempIndex === 0 && tmpl.push('<tr>');
  22696. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  22697. tempIndex === 2 && tmpl.push('</tr>');
  22698. }
  22699. return '<div id="##" class="edui-cellalignpicker %%">' +
  22700. '<div class="edui-cellalignpicker-body">' +
  22701. '<table onclick="$$._onClick(event);">' +
  22702. tmpl.join('') +
  22703. '</table>' +
  22704. '</div>' +
  22705. '</div>';
  22706. },
  22707. getStateDom: function (){
  22708. return this.target;
  22709. },
  22710. _onClick: function (evt){
  22711. var target= evt.target || evt.srcElement;
  22712. if(/icon/.test(target.className)){
  22713. this.items[target.parentNode.getAttribute("index")].onclick();
  22714. Popup.postHide(evt);
  22715. }
  22716. },
  22717. _UIBase_render:UIBase.prototype.render
  22718. };
  22719. utils.inherits(CellAlignPicker, UIBase);
  22720. utils.extend(CellAlignPicker.prototype, Stateful,true);
  22721. })();
  22722. ///import core
  22723. ///import uicore
  22724. (function () {
  22725. var utils = baidu.editor.utils,
  22726. Stateful = baidu.editor.ui.Stateful,
  22727. uiUtils = baidu.editor.ui.uiUtils,
  22728. UIBase = baidu.editor.ui.UIBase;
  22729. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  22730. this.initOptions(options);
  22731. this.initPastePicker();
  22732. };
  22733. PastePicker.prototype = {
  22734. initPastePicker:function () {
  22735. this.initUIBase();
  22736. this.Stateful_init();
  22737. },
  22738. getHtmlTpl:function () {
  22739. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  22740. '<div class="edui-pastecontainer">' +
  22741. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  22742. '<div class="edui-button">' +
  22743. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  22744. '<div class="edui-richtxticon"></div></div>' +
  22745. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  22746. '<div class="edui-tagicon"></div></div>' +
  22747. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  22748. '<div class="edui-plaintxticon"></div></div>' +
  22749. '</div>' +
  22750. '</div>' +
  22751. '</div>'
  22752. },
  22753. getStateDom:function () {
  22754. return this.target;
  22755. },
  22756. format:function (param) {
  22757. this.editor.ui._isTransfer = true;
  22758. this.editor.fireEvent('pasteTransfer', param);
  22759. },
  22760. _onClick:function (cur) {
  22761. var node = domUtils.getNextDomNode(cur),
  22762. screenHt = uiUtils.getViewportRect().height,
  22763. subPop = uiUtils.getClientRect(node);
  22764. if ((subPop.top + subPop.height) > screenHt)
  22765. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  22766. else
  22767. node.style.top = "";
  22768. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  22769. node.style.visibility = "visible";
  22770. domUtils.addClass(cur, "edui-state-opened");
  22771. } else {
  22772. node.style.visibility = "hidden";
  22773. domUtils.removeClasses(cur, "edui-state-opened")
  22774. }
  22775. },
  22776. _UIBase_render:UIBase.prototype.render
  22777. };
  22778. utils.inherits(PastePicker, UIBase);
  22779. utils.extend(PastePicker.prototype, Stateful, true);
  22780. })();
  22781. (function (){
  22782. var utils = baidu.editor.utils,
  22783. uiUtils = baidu.editor.ui.uiUtils,
  22784. UIBase = baidu.editor.ui.UIBase,
  22785. Toolbar = baidu.editor.ui.Toolbar = function (options){
  22786. this.initOptions(options);
  22787. this.initToolbar();
  22788. };
  22789. Toolbar.prototype = {
  22790. items: null,
  22791. initToolbar: function (){
  22792. this.items = this.items || [];
  22793. this.initUIBase();
  22794. },
  22795. add: function (item){
  22796. this.items.push(item);
  22797. },
  22798. getHtmlTpl: function (){
  22799. var buff = [];
  22800. for (var i=0; i<this.items.length; i++) {
  22801. buff[i] = this.items[i].renderHtml();
  22802. }
  22803. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  22804. buff.join('') +
  22805. '</div>'
  22806. },
  22807. postRender: function (){
  22808. var box = this.getDom();
  22809. for (var i=0; i<this.items.length; i++) {
  22810. this.items[i].postRender();
  22811. }
  22812. uiUtils.makeUnselectable(box);
  22813. },
  22814. _onMouseDown: function (){
  22815. return false;
  22816. }
  22817. };
  22818. utils.inherits(Toolbar, UIBase);
  22819. })();
  22820. ///import core
  22821. ///import uicore
  22822. ///import ui\popup.js
  22823. ///import ui\stateful.js
  22824. (function () {
  22825. var utils = baidu.editor.utils,
  22826. domUtils = baidu.editor.dom.domUtils,
  22827. uiUtils = baidu.editor.ui.uiUtils,
  22828. UIBase = baidu.editor.ui.UIBase,
  22829. Popup = baidu.editor.ui.Popup,
  22830. Stateful = baidu.editor.ui.Stateful,
  22831. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  22832. Menu = baidu.editor.ui.Menu = function (options) {
  22833. this.initOptions(options);
  22834. this.initMenu();
  22835. };
  22836. var menuSeparator = {
  22837. renderHtml:function () {
  22838. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  22839. },
  22840. postRender:function () {
  22841. },
  22842. queryAutoHide:function () {
  22843. return true;
  22844. }
  22845. };
  22846. Menu.prototype = {
  22847. items:null,
  22848. uiName:'menu',
  22849. initMenu:function () {
  22850. this.items = this.items || [];
  22851. this.initPopup();
  22852. this.initItems();
  22853. },
  22854. initItems:function () {
  22855. for (var i = 0; i < this.items.length; i++) {
  22856. var item = this.items[i];
  22857. if (item == '-') {
  22858. this.items[i] = this.getSeparator();
  22859. } else if (!(item instanceof MenuItem)) {
  22860. item.editor = this.editor;
  22861. item.theme = this.editor.options.theme;
  22862. this.items[i] = this.createItem(item);
  22863. }
  22864. }
  22865. },
  22866. getSeparator:function () {
  22867. return menuSeparator;
  22868. },
  22869. createItem:function (item) {
  22870. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  22871. item.menu = this;
  22872. return new MenuItem(item);
  22873. },
  22874. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  22875. getContentHtmlTpl:function () {
  22876. if (this.items.length == 0) {
  22877. return this._Popup_getContentHtmlTpl();
  22878. }
  22879. var buff = [];
  22880. for (var i = 0; i < this.items.length; i++) {
  22881. var item = this.items[i];
  22882. buff[i] = item.renderHtml();
  22883. }
  22884. return ('<div class="%%-body">' + buff.join('') + '</div>');
  22885. },
  22886. _Popup_postRender:Popup.prototype.postRender,
  22887. postRender:function () {
  22888. var me = this;
  22889. for (var i = 0; i < this.items.length; i++) {
  22890. var item = this.items[i];
  22891. item.ownerMenu = this;
  22892. item.postRender();
  22893. }
  22894. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  22895. evt = evt || event;
  22896. var rel = evt.relatedTarget || evt.fromElement;
  22897. var el = me.getDom();
  22898. if (!uiUtils.contains(el, rel) && el !== rel) {
  22899. me.fireEvent('over');
  22900. }
  22901. });
  22902. this._Popup_postRender();
  22903. },
  22904. queryAutoHide:function (el) {
  22905. if (el) {
  22906. if (uiUtils.contains(this.getDom(), el)) {
  22907. return false;
  22908. }
  22909. for (var i = 0; i < this.items.length; i++) {
  22910. var item = this.items[i];
  22911. if (item.queryAutoHide(el) === false) {
  22912. return false;
  22913. }
  22914. }
  22915. }
  22916. },
  22917. clearItems:function () {
  22918. for (var i = 0; i < this.items.length; i++) {
  22919. var item = this.items[i];
  22920. clearTimeout(item._showingTimer);
  22921. clearTimeout(item._closingTimer);
  22922. if (item.subMenu) {
  22923. item.subMenu.destroy();
  22924. }
  22925. }
  22926. this.items = [];
  22927. },
  22928. destroy:function () {
  22929. if (this.getDom()) {
  22930. domUtils.remove(this.getDom());
  22931. }
  22932. this.clearItems();
  22933. },
  22934. dispose:function () {
  22935. this.destroy();
  22936. }
  22937. };
  22938. utils.inherits(Menu, Popup);
  22939. /**
  22940. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  22941. * @type {Function}
  22942. */
  22943. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  22944. this.initOptions(options);
  22945. this.initUIBase();
  22946. this.Stateful_init();
  22947. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  22948. if (options.className && options.className.indexOf("aligntd") != -1) {
  22949. var me = this;
  22950. //获取单元格对齐初始状态
  22951. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  22952. this.subMenu = new Popup({
  22953. content:new CellAlignPicker(this.subMenu),
  22954. parentMenu:me,
  22955. editor:me.editor,
  22956. destroy:function () {
  22957. if (this.getDom()) {
  22958. domUtils.remove(this.getDom());
  22959. }
  22960. }
  22961. });
  22962. this.subMenu.addListener("postRenderAfter", function () {
  22963. domUtils.on(this.getDom(), "mouseover", function () {
  22964. me.addState('opened');
  22965. });
  22966. });
  22967. } else {
  22968. this.subMenu = new Menu(this.subMenu);
  22969. }
  22970. }
  22971. };
  22972. MenuItem.prototype = {
  22973. label:'',
  22974. subMenu:null,
  22975. ownerMenu:null,
  22976. uiName:'menuitem',
  22977. alwalysHoverable:true,
  22978. getHtmlTpl:function () {
  22979. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  22980. '<div class="%%-body">' +
  22981. this.renderLabelHtml() +
  22982. '</div>' +
  22983. '</div>';
  22984. },
  22985. postRender:function () {
  22986. var me = this;
  22987. this.addListener('over', function () {
  22988. me.ownerMenu.fireEvent('submenuover', me);
  22989. if (me.subMenu) {
  22990. me.delayShowSubMenu();
  22991. }
  22992. });
  22993. if (this.subMenu) {
  22994. this.getDom().className += ' edui-hassubmenu';
  22995. this.subMenu.render();
  22996. this.addListener('out', function () {
  22997. me.delayHideSubMenu();
  22998. });
  22999. this.subMenu.addListener('over', function () {
  23000. clearTimeout(me._closingTimer);
  23001. me._closingTimer = null;
  23002. me.addState('opened');
  23003. });
  23004. this.ownerMenu.addListener('hide', function () {
  23005. me.hideSubMenu();
  23006. });
  23007. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  23008. if (subMenu !== me) {
  23009. me.delayHideSubMenu();
  23010. }
  23011. });
  23012. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  23013. this.subMenu.queryAutoHide = function (el) {
  23014. if (el && uiUtils.contains(me.getDom(), el)) {
  23015. return false;
  23016. }
  23017. return this._bakQueryAutoHide(el);
  23018. };
  23019. }
  23020. this.getDom().style.tabIndex = '-1';
  23021. uiUtils.makeUnselectable(this.getDom());
  23022. this.Stateful_postRender();
  23023. },
  23024. delayShowSubMenu:function () {
  23025. var me = this;
  23026. if (!me.isDisabled()) {
  23027. me.addState('opened');
  23028. clearTimeout(me._showingTimer);
  23029. clearTimeout(me._closingTimer);
  23030. me._closingTimer = null;
  23031. me._showingTimer = setTimeout(function () {
  23032. me.showSubMenu();
  23033. }, 250);
  23034. }
  23035. },
  23036. delayHideSubMenu:function () {
  23037. var me = this;
  23038. if (!me.isDisabled()) {
  23039. me.removeState('opened');
  23040. clearTimeout(me._showingTimer);
  23041. if (!me._closingTimer) {
  23042. me._closingTimer = setTimeout(function () {
  23043. if (!me.hasState('opened')) {
  23044. me.hideSubMenu();
  23045. }
  23046. me._closingTimer = null;
  23047. }, 400);
  23048. }
  23049. }
  23050. },
  23051. renderLabelHtml:function () {
  23052. return '<div class="edui-arrow"></div>' +
  23053. '<div class="edui-box edui-icon"></div>' +
  23054. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  23055. },
  23056. getStateDom:function () {
  23057. return this.getDom();
  23058. },
  23059. queryAutoHide:function (el) {
  23060. if (this.subMenu && this.hasState('opened')) {
  23061. return this.subMenu.queryAutoHide(el);
  23062. }
  23063. },
  23064. _onClick:function (event, this_) {
  23065. if (this.hasState('disabled')) return;
  23066. if (this.fireEvent('click', event, this_) !== false) {
  23067. if (this.subMenu) {
  23068. this.showSubMenu();
  23069. } else {
  23070. Popup.postHide(event);
  23071. }
  23072. }
  23073. },
  23074. showSubMenu:function () {
  23075. var rect = uiUtils.getClientRect(this.getDom());
  23076. rect.right -= 5;
  23077. rect.left += 2;
  23078. rect.width -= 7;
  23079. rect.top -= 4;
  23080. rect.bottom += 4;
  23081. rect.height += 8;
  23082. this.subMenu.showAnchorRect(rect, true, true);
  23083. },
  23084. hideSubMenu:function () {
  23085. this.subMenu.hide();
  23086. }
  23087. };
  23088. utils.inherits(MenuItem, UIBase);
  23089. utils.extend(MenuItem.prototype, Stateful, true);
  23090. })();
  23091. ///import core
  23092. ///import uicore
  23093. ///import ui/menu.js
  23094. ///import ui/splitbutton.js
  23095. (function (){
  23096. // todo: menu和item提成通用list
  23097. var utils = baidu.editor.utils,
  23098. uiUtils = baidu.editor.ui.uiUtils,
  23099. Menu = baidu.editor.ui.Menu,
  23100. SplitButton = baidu.editor.ui.SplitButton,
  23101. Combox = baidu.editor.ui.Combox = function (options){
  23102. this.initOptions(options);
  23103. this.initCombox();
  23104. };
  23105. Combox.prototype = {
  23106. uiName: 'combox',
  23107. initCombox: function (){
  23108. var me = this;
  23109. this.items = this.items || [];
  23110. for (var i=0; i<this.items.length; i++) {
  23111. var item = this.items[i];
  23112. item.uiName = 'listitem';
  23113. item.index = i;
  23114. item.onclick = function (){
  23115. me.selectByIndex(this.index);
  23116. };
  23117. }
  23118. this.popup = new Menu({
  23119. items: this.items,
  23120. uiName: 'list',
  23121. editor:this.editor,
  23122. captureWheel: true,
  23123. combox: this
  23124. });
  23125. this.initSplitButton();
  23126. },
  23127. _SplitButton_postRender: SplitButton.prototype.postRender,
  23128. postRender: function (){
  23129. this._SplitButton_postRender();
  23130. this.setLabel(this.label || '');
  23131. this.setValue(this.initValue || '');
  23132. },
  23133. showPopup: function (){
  23134. var rect = uiUtils.getClientRect(this.getDom());
  23135. rect.top += 1;
  23136. rect.bottom -= 1;
  23137. rect.height -= 2;
  23138. this.popup.showAnchorRect(rect);
  23139. },
  23140. getValue: function (){
  23141. return this.value;
  23142. },
  23143. setValue: function (value){
  23144. var index = this.indexByValue(value);
  23145. if (index != -1) {
  23146. this.selectedIndex = index;
  23147. this.setLabel(this.items[index].label);
  23148. this.value = this.items[index].value;
  23149. } else {
  23150. this.selectedIndex = -1;
  23151. this.setLabel(this.getLabelForUnknowValue(value));
  23152. this.value = value;
  23153. }
  23154. },
  23155. setLabel: function (label){
  23156. this.getDom('button_body').innerHTML = label;
  23157. this.label = label;
  23158. },
  23159. getLabelForUnknowValue: function (value){
  23160. return value;
  23161. },
  23162. indexByValue: function (value){
  23163. for (var i=0; i<this.items.length; i++) {
  23164. if (value == this.items[i].value) {
  23165. return i;
  23166. }
  23167. }
  23168. return -1;
  23169. },
  23170. getItem: function (index){
  23171. return this.items[index];
  23172. },
  23173. selectByIndex: function (index){
  23174. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  23175. this.selectedIndex = index;
  23176. this.value = this.items[index].value;
  23177. this.setLabel(this.items[index].label);
  23178. }
  23179. }
  23180. };
  23181. utils.inherits(Combox, SplitButton);
  23182. })();
  23183. ///import core
  23184. ///import uicore
  23185. ///import ui/mask.js
  23186. ///import ui/button.js
  23187. (function (){
  23188. var utils = baidu.editor.utils,
  23189. domUtils = baidu.editor.dom.domUtils,
  23190. uiUtils = baidu.editor.ui.uiUtils,
  23191. Mask = baidu.editor.ui.Mask,
  23192. UIBase = baidu.editor.ui.UIBase,
  23193. Button = baidu.editor.ui.Button,
  23194. Dialog = baidu.editor.ui.Dialog = function (options){
  23195. this.initOptions(utils.extend({
  23196. autoReset: true,
  23197. draggable: true,
  23198. onok: function (){},
  23199. oncancel: function (){},
  23200. onclose: function (t, ok){
  23201. return ok ? this.onok() : this.oncancel();
  23202. },
  23203. //是否控制dialog中的scroll事件, 默认为不阻止
  23204. holdScroll: false
  23205. },options));
  23206. this.initDialog();
  23207. };
  23208. var modalMask;
  23209. var dragMask;
  23210. Dialog.prototype = {
  23211. draggable: false,
  23212. uiName: 'dialog',
  23213. initDialog: function (){
  23214. var me = this,
  23215. theme=this.editor.options.theme;
  23216. this.initUIBase();
  23217. this.modalMask = (modalMask || (modalMask = new Mask({
  23218. className: 'edui-dialog-modalmask',
  23219. theme:theme
  23220. })));
  23221. this.dragMask = (dragMask || (dragMask = new Mask({
  23222. className: 'edui-dialog-dragmask',
  23223. theme:theme
  23224. })));
  23225. this.closeButton = new Button({
  23226. className: 'edui-dialog-closebutton',
  23227. title: me.closeDialog,
  23228. theme:theme,
  23229. onclick: function (){
  23230. me.close(false);
  23231. }
  23232. });
  23233. this.fullscreen && this.initResizeEvent();
  23234. if (this.buttons) {
  23235. for (var i=0; i<this.buttons.length; i++) {
  23236. if (!(this.buttons[i] instanceof Button)) {
  23237. this.buttons[i] = new Button(this.buttons[i]);
  23238. }
  23239. }
  23240. }
  23241. },
  23242. initResizeEvent: function () {
  23243. var me = this;
  23244. domUtils.on( window, "resize", function () {
  23245. if ( me._hidden || me._hidden === undefined ) {
  23246. return;
  23247. }
  23248. if ( me.__resizeTimer ) {
  23249. window.clearTimeout( me.__resizeTimer );
  23250. }
  23251. me.__resizeTimer = window.setTimeout( function () {
  23252. me.__resizeTimer = null;
  23253. var dialogWrapNode = me.getDom(),
  23254. contentNode = me.getDom('content'),
  23255. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  23256. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  23257. vpRect = uiUtils.getViewportRect();
  23258. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  23259. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  23260. dialogWrapNode.style.width = vpRect.width + "px";
  23261. dialogWrapNode.style.height = vpRect.height + "px";
  23262. me.fireEvent( "resize" );
  23263. }, 100 );
  23264. } );
  23265. },
  23266. fitSize: function (){
  23267. var popBodyEl = this.getDom('body');
  23268. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  23269. // uiUtils.removeStyle(popBodyEl, 'width');
  23270. // uiUtils.removeStyle(popBodyEl, 'height');
  23271. // }
  23272. var size = this.mesureSize();
  23273. popBodyEl.style.width = size.width + 'px';
  23274. popBodyEl.style.height = size.height + 'px';
  23275. return size;
  23276. },
  23277. safeSetOffset: function (offset){
  23278. var me = this;
  23279. var el = me.getDom();
  23280. var vpRect = uiUtils.getViewportRect();
  23281. var rect = uiUtils.getClientRect(el);
  23282. var left = offset.left;
  23283. if (left + rect.width > vpRect.right) {
  23284. left = vpRect.right - rect.width;
  23285. }
  23286. var top = offset.top;
  23287. if (top + rect.height > vpRect.bottom) {
  23288. top = vpRect.bottom - rect.height;
  23289. }
  23290. el.style.left = Math.max(left, 0) + 'px';
  23291. el.style.top = Math.max(top, 0) + 'px';
  23292. },
  23293. showAtCenter: function (){
  23294. var vpRect = uiUtils.getViewportRect();
  23295. if ( !this.fullscreen ) {
  23296. this.getDom().style.display = '';
  23297. var popSize = this.fitSize();
  23298. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  23299. var left = vpRect.width / 2 - popSize.width / 2;
  23300. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  23301. var popEl = this.getDom();
  23302. this.safeSetOffset({
  23303. left: Math.max(left | 0, 0),
  23304. top: Math.max(top | 0, 0)
  23305. });
  23306. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  23307. popEl.className += ' edui-state-centered';
  23308. }
  23309. } else {
  23310. var dialogWrapNode = this.getDom(),
  23311. contentNode = this.getDom('content');
  23312. dialogWrapNode.style.display = "block";
  23313. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  23314. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  23315. dialogWrapNode.style.left = "-100000px";
  23316. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  23317. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  23318. dialogWrapNode.style.width = vpRect.width + "px";
  23319. dialogWrapNode.style.height = vpRect.height + "px";
  23320. dialogWrapNode.style.left = 0;
  23321. //保存环境的overflow值
  23322. this._originalContext = {
  23323. html: {
  23324. overflowX: document.documentElement.style.overflowX,
  23325. overflowY: document.documentElement.style.overflowY
  23326. },
  23327. body: {
  23328. overflowX: document.body.style.overflowX,
  23329. overflowY: document.body.style.overflowY
  23330. }
  23331. };
  23332. document.documentElement.style.overflowX = 'hidden';
  23333. document.documentElement.style.overflowY = 'hidden';
  23334. document.body.style.overflowX = 'hidden';
  23335. document.body.style.overflowY = 'hidden';
  23336. }
  23337. this._show();
  23338. },
  23339. getContentHtml: function (){
  23340. var contentHtml = '';
  23341. if (typeof this.content == 'string') {
  23342. contentHtml = this.content;
  23343. } else if (this.iframeUrl) {
  23344. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  23345. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  23346. }
  23347. return contentHtml;
  23348. },
  23349. getHtmlTpl: function (){
  23350. var footHtml = '';
  23351. if (this.buttons) {
  23352. var buff = [];
  23353. for (var i=0; i<this.buttons.length; i++) {
  23354. buff[i] = this.buttons[i].renderHtml();
  23355. }
  23356. footHtml = '<div class="%%-foot">' +
  23357. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  23358. '</div>';
  23359. }
  23360. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  23361. '<div class="%%-shadow"></div>' +
  23362. '<div id="##_titlebar" class="%%-titlebar">' +
  23363. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  23364. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  23365. '</div>' +
  23366. this.closeButton.renderHtml() +
  23367. '</div>' +
  23368. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  23369. footHtml +
  23370. '</div></div></div>';
  23371. },
  23372. postRender: function (){
  23373. // todo: 保持居中/记住上次关闭位置选项
  23374. if (!this.modalMask.getDom()) {
  23375. this.modalMask.render();
  23376. this.modalMask.hide();
  23377. }
  23378. if (!this.dragMask.getDom()) {
  23379. this.dragMask.render();
  23380. this.dragMask.hide();
  23381. }
  23382. var me = this;
  23383. this.addListener('show', function (){
  23384. me.modalMask.show(this.getDom().style.zIndex - 2);
  23385. });
  23386. this.addListener('hide', function (){
  23387. me.modalMask.hide();
  23388. });
  23389. if (this.buttons) {
  23390. for (var i=0; i<this.buttons.length; i++) {
  23391. this.buttons[i].postRender();
  23392. }
  23393. }
  23394. domUtils.on(window, 'resize', function (){
  23395. setTimeout(function (){
  23396. if (!me.isHidden()) {
  23397. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  23398. }
  23399. });
  23400. });
  23401. //hold住scroll事件,防止dialog的滚动影响页面
  23402. if( this.holdScroll ) {
  23403. if( !me.iframeUrl ) {
  23404. domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  23405. domUtils.preventDefault(e);
  23406. } );
  23407. } else {
  23408. me.addListener('dialogafterreset', function(){
  23409. window.setTimeout(function(){
  23410. var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  23411. if( browser.ie ) {
  23412. var timer = window.setInterval(function(){
  23413. if( iframeWindow.document && iframeWindow.document.body ) {
  23414. window.clearInterval( timer );
  23415. timer = null;
  23416. domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  23417. domUtils.preventDefault(e);
  23418. } );
  23419. }
  23420. }, 100);
  23421. } else {
  23422. domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  23423. domUtils.preventDefault(e);
  23424. } );
  23425. }
  23426. }, 1);
  23427. });
  23428. }
  23429. }
  23430. this._hide();
  23431. },
  23432. mesureSize: function (){
  23433. var body = this.getDom('body');
  23434. var width = uiUtils.getClientRect(this.getDom('content')).width;
  23435. var dialogBodyStyle = body.style;
  23436. dialogBodyStyle.width = width;
  23437. return uiUtils.getClientRect(body);
  23438. },
  23439. _onTitlebarMouseDown: function (evt, el){
  23440. if (this.draggable) {
  23441. var rect;
  23442. var vpRect = uiUtils.getViewportRect();
  23443. var me = this;
  23444. uiUtils.startDrag(evt, {
  23445. ondragstart: function (){
  23446. rect = uiUtils.getClientRect(me.getDom());
  23447. me.getDom('contmask').style.visibility = 'visible';
  23448. me.dragMask.show(me.getDom().style.zIndex - 1);
  23449. },
  23450. ondragmove: function (x, y){
  23451. var left = rect.left + x;
  23452. var top = rect.top + y;
  23453. me.safeSetOffset({
  23454. left: left,
  23455. top: top
  23456. });
  23457. },
  23458. ondragstop: function (){
  23459. me.getDom('contmask').style.visibility = 'hidden';
  23460. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  23461. me.dragMask.hide();
  23462. }
  23463. });
  23464. }
  23465. },
  23466. reset: function (){
  23467. this.getDom('content').innerHTML = this.getContentHtml();
  23468. this.fireEvent('dialogafterreset');
  23469. },
  23470. _show: function (){
  23471. if (this._hidden) {
  23472. this.getDom().style.display = '';
  23473. //要高过编辑器的zindxe
  23474. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  23475. this._hidden = false;
  23476. this.fireEvent('show');
  23477. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  23478. }
  23479. },
  23480. isHidden: function (){
  23481. return this._hidden;
  23482. },
  23483. _hide: function (){
  23484. if (!this._hidden) {
  23485. var wrapNode = this.getDom();
  23486. wrapNode.style.display = 'none';
  23487. wrapNode.style.zIndex = '';
  23488. wrapNode.style.width = '';
  23489. wrapNode.style.height = '';
  23490. this._hidden = true;
  23491. this.fireEvent('hide');
  23492. }
  23493. },
  23494. open: function (){
  23495. if (this.autoReset) {
  23496. //有可能还没有渲染
  23497. try{
  23498. this.reset();
  23499. }catch(e){
  23500. this.render();
  23501. this.open()
  23502. }
  23503. }
  23504. this.showAtCenter();
  23505. if (this.iframeUrl) {
  23506. try {
  23507. this.getDom('iframe').focus();
  23508. } catch(ex){}
  23509. }
  23510. },
  23511. _onCloseButtonClick: function (evt, el){
  23512. this.close(false);
  23513. },
  23514. close: function (ok){
  23515. if (this.fireEvent('close', ok) !== false) {
  23516. //还原环境
  23517. if ( this.fullscreen ) {
  23518. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  23519. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  23520. document.body.style.overflowX = this._originalContext.body.overflowX;
  23521. document.body.style.overflowY = this._originalContext.body.overflowY;
  23522. delete this._originalContext;
  23523. }
  23524. this._hide();
  23525. }
  23526. }
  23527. };
  23528. utils.inherits(Dialog, UIBase);
  23529. })();
  23530. ///import core
  23531. ///import uicore
  23532. ///import ui/menu.js
  23533. ///import ui/splitbutton.js
  23534. (function (){
  23535. var utils = baidu.editor.utils,
  23536. Menu = baidu.editor.ui.Menu,
  23537. SplitButton = baidu.editor.ui.SplitButton,
  23538. MenuButton = baidu.editor.ui.MenuButton = function (options){
  23539. this.initOptions(options);
  23540. this.initMenuButton();
  23541. };
  23542. MenuButton.prototype = {
  23543. initMenuButton: function (){
  23544. var me = this;
  23545. this.uiName = "menubutton";
  23546. this.popup = new Menu({
  23547. items: me.items,
  23548. className: me.className,
  23549. editor:me.editor
  23550. });
  23551. this.popup.addListener('show', function (){
  23552. var list = this;
  23553. for (var i=0; i<list.items.length; i++) {
  23554. list.items[i].removeState('checked');
  23555. if (list.items[i].value == me._value) {
  23556. list.items[i].addState('checked');
  23557. this.value = me._value;
  23558. }
  23559. }
  23560. });
  23561. this.initSplitButton();
  23562. },
  23563. setValue : function(value){
  23564. this._value = value;
  23565. }
  23566. };
  23567. utils.inherits(MenuButton, SplitButton);
  23568. })();
  23569. //ui跟编辑器的适配層
  23570. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  23571. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  23572. (function () {
  23573. var utils = baidu.editor.utils;
  23574. var editorui = baidu.editor.ui;
  23575. var _Dialog = editorui.Dialog;
  23576. editorui.buttons = {};
  23577. editorui.Dialog = function (options) {
  23578. var dialog = new _Dialog(options);
  23579. dialog.addListener('hide', function () {
  23580. if (dialog.editor) {
  23581. var editor = dialog.editor;
  23582. try {
  23583. if (browser.gecko) {
  23584. var y = editor.window.scrollY,
  23585. x = editor.window.scrollX;
  23586. editor.body.focus();
  23587. editor.window.scrollTo(x, y);
  23588. } else {
  23589. editor.focus();
  23590. }
  23591. } catch (ex) {
  23592. }
  23593. }
  23594. });
  23595. return dialog;
  23596. };
  23597. var iframeUrlMap = {
  23598. 'anchor':'~/dialogs/anchor/anchor.html',
  23599. 'insertimage':'~/dialogs/image/image.html',
  23600. 'link':'~/dialogs/link/link.html',
  23601. 'spechars':'~/dialogs/spechars/spechars.html',
  23602. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  23603. 'map':'~/dialogs/map/map.html',
  23604. 'gmap':'~/dialogs/gmap/gmap.html',
  23605. 'insertvideo':'~/dialogs/video/video.html',
  23606. 'help':'~/dialogs/help/help.html',
  23607. 'preview':'~/dialogs/preview/preview.html',
  23608. 'emotion':'~/dialogs/emotion/emotion.html',
  23609. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  23610. 'attachment':'~/dialogs/attachment/attachment.html',
  23611. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  23612. 'edittip':'~/dialogs/table/edittip.html',
  23613. 'edittable':'~/dialogs/table/edittable.html',
  23614. 'edittd':'~/dialogs/table/edittd.html',
  23615. 'webapp':'~/dialogs/webapp/webapp.html',
  23616. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  23617. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  23618. 'music':'~/dialogs/music/music.html',
  23619. 'template':'~/dialogs/template/template.html',
  23620. 'background':'~/dialogs/background/background.html',
  23621. 'charts': '~/dialogs/charts/charts.html'
  23622. };
  23623. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  23624. var btnCmds = ['undo', 'redo', 'formatmatch',
  23625. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  23626. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  23627. 'blockquote', 'pasteplain', 'pagebreak',
  23628. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  23629. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  23630. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  23631. for (var i = 0, ci; ci = btnCmds[i++];) {
  23632. ci = ci.toLowerCase();
  23633. editorui[ci] = function (cmd) {
  23634. return function (editor) {
  23635. var ui = new editorui.Button({
  23636. className:'edui-for-' + cmd,
  23637. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  23638. onclick:function () {
  23639. editor.execCommand(cmd);
  23640. },
  23641. theme:editor.options.theme,
  23642. showText:false
  23643. });
  23644. editorui.buttons[cmd] = ui;
  23645. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23646. var state = editor.queryCommandState(cmd);
  23647. if (state == -1) {
  23648. ui.setDisabled(true);
  23649. ui.setChecked(false);
  23650. } else {
  23651. if (!uiReady) {
  23652. ui.setDisabled(false);
  23653. ui.setChecked(state);
  23654. }
  23655. }
  23656. });
  23657. return ui;
  23658. };
  23659. }(ci);
  23660. }
  23661. //清除文档
  23662. editorui.cleardoc = function (editor) {
  23663. var ui = new editorui.Button({
  23664. className:'edui-for-cleardoc',
  23665. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  23666. theme:editor.options.theme,
  23667. onclick:function () {
  23668. if (confirm(editor.getLang("confirmClear"))) {
  23669. editor.execCommand('cleardoc');
  23670. }
  23671. }
  23672. });
  23673. editorui.buttons["cleardoc"] = ui;
  23674. editor.addListener('selectionchange', function () {
  23675. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  23676. });
  23677. return ui;
  23678. };
  23679. //排版,图片排版,文字方向
  23680. var typeset = {
  23681. 'justify':['left', 'right', 'center', 'justify'],
  23682. 'imagefloat':['none', 'left', 'center', 'right'],
  23683. 'directionality':['ltr', 'rtl']
  23684. };
  23685. for (var p in typeset) {
  23686. (function (cmd, val) {
  23687. for (var i = 0, ci; ci = val[i++];) {
  23688. (function (cmd2) {
  23689. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  23690. var ui = new editorui.Button({
  23691. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  23692. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  23693. theme:editor.options.theme,
  23694. onclick:function () {
  23695. editor.execCommand(cmd, cmd2);
  23696. }
  23697. });
  23698. editorui.buttons[cmd] = ui;
  23699. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23700. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  23701. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  23702. });
  23703. return ui;
  23704. };
  23705. })(ci)
  23706. }
  23707. })(p, typeset[p])
  23708. }
  23709. //字体颜色和背景颜色
  23710. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  23711. editorui[ci] = function (cmd) {
  23712. return function (editor) {
  23713. var ui = new editorui.ColorButton({
  23714. className:'edui-for-' + cmd,
  23715. color:'default',
  23716. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  23717. editor:editor,
  23718. onpickcolor:function (t, color) {
  23719. editor.execCommand(cmd, color);
  23720. },
  23721. onpicknocolor:function () {
  23722. editor.execCommand(cmd, 'default');
  23723. this.setColor('transparent');
  23724. this.color = 'default';
  23725. },
  23726. onbuttonclick:function () {
  23727. editor.execCommand(cmd, this.color);
  23728. }
  23729. });
  23730. editorui.buttons[cmd] = ui;
  23731. editor.addListener('selectionchange', function () {
  23732. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  23733. });
  23734. return ui;
  23735. };
  23736. }(ci);
  23737. }
  23738. var dialogBtns = {
  23739. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  23740. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  23741. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  23742. };
  23743. for (var p in dialogBtns) {
  23744. (function (type, vals) {
  23745. for (var i = 0, ci; ci = vals[i++];) {
  23746. //todo opera下存在问题
  23747. if (browser.opera && ci === "searchreplace") {
  23748. continue;
  23749. }
  23750. (function (cmd) {
  23751. editorui[cmd] = function (editor, iframeUrl, title) {
  23752. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  23753. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  23754. var dialog;
  23755. //没有iframeUrl不创建dialog
  23756. if (iframeUrl) {
  23757. dialog = new editorui.Dialog(utils.extend({
  23758. iframeUrl:editor.ui.mapUrl(iframeUrl),
  23759. editor:editor,
  23760. className:'edui-for-' + cmd,
  23761. title:title,
  23762. holdScroll: cmd === 'insertimage',
  23763. fullscreen: /charts|preview/.test(cmd),
  23764. closeDialog:editor.getLang("closeDialog")
  23765. }, type == 'ok' ? {
  23766. buttons:[
  23767. {
  23768. className:'edui-okbutton',
  23769. label:editor.getLang("ok"),
  23770. editor:editor,
  23771. onclick:function () {
  23772. dialog.close(true);
  23773. }
  23774. },
  23775. {
  23776. className:'edui-cancelbutton',
  23777. label:editor.getLang("cancel"),
  23778. editor:editor,
  23779. onclick:function () {
  23780. dialog.close(false);
  23781. }
  23782. }
  23783. ]
  23784. } : {}));
  23785. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  23786. }
  23787. var ui = new editorui.Button({
  23788. className:'edui-for-' + cmd,
  23789. title:title,
  23790. onclick:function () {
  23791. if (dialog) {
  23792. switch (cmd) {
  23793. case "wordimage":
  23794. var images = editor.execCommand("wordimage");
  23795. if (images && images.length) {
  23796. dialog.render();
  23797. dialog.open();
  23798. }
  23799. break;
  23800. case "scrawl":
  23801. if (editor.queryCommandState("scrawl") != -1) {
  23802. dialog.render();
  23803. dialog.open();
  23804. }
  23805. break;
  23806. default:
  23807. dialog.render();
  23808. dialog.open();
  23809. }
  23810. }
  23811. },
  23812. theme:editor.options.theme,
  23813. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  23814. });
  23815. editorui.buttons[cmd] = ui;
  23816. editor.addListener('selectionchange', function () {
  23817. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  23818. var unNeedCheckState = {'edittable':1};
  23819. if (cmd in unNeedCheckState)return;
  23820. var state = editor.queryCommandState(cmd);
  23821. if (ui.getDom()) {
  23822. ui.setDisabled(state == -1);
  23823. ui.setChecked(state);
  23824. }
  23825. });
  23826. return ui;
  23827. };
  23828. })(ci.toLowerCase())
  23829. }
  23830. })(p, dialogBtns[p])
  23831. }
  23832. editorui.snapscreen = function (editor, iframeUrl, title) {
  23833. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  23834. var ui = new editorui.Button({
  23835. className:'edui-for-snapscreen',
  23836. title:title,
  23837. onclick:function () {
  23838. editor.execCommand("snapscreen");
  23839. },
  23840. theme:editor.options.theme
  23841. });
  23842. editorui.buttons['snapscreen'] = ui;
  23843. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  23844. if (iframeUrl) {
  23845. var dialog = new editorui.Dialog({
  23846. iframeUrl:editor.ui.mapUrl(iframeUrl),
  23847. editor:editor,
  23848. className:'edui-for-snapscreen',
  23849. title:title,
  23850. buttons:[
  23851. {
  23852. className:'edui-okbutton',
  23853. label:editor.getLang("ok"),
  23854. editor:editor,
  23855. onclick:function () {
  23856. dialog.close(true);
  23857. }
  23858. },
  23859. {
  23860. className:'edui-cancelbutton',
  23861. label:editor.getLang("cancel"),
  23862. editor:editor,
  23863. onclick:function () {
  23864. dialog.close(false);
  23865. }
  23866. }
  23867. ]
  23868. });
  23869. dialog.render();
  23870. editor.ui._dialogs["snapscreenDialog"] = dialog;
  23871. }
  23872. editor.addListener('selectionchange', function () {
  23873. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  23874. });
  23875. return ui;
  23876. };
  23877. editorui.insertcode = function (editor, list, title) {
  23878. list = editor.options['insertcode'] || [];
  23879. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  23880. // if (!list.length) return;
  23881. var items = [];
  23882. utils.each(list,function(key,val){
  23883. items.push({
  23884. label:key,
  23885. value:val,
  23886. theme:editor.options.theme,
  23887. renderLabelHtml:function () {
  23888. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  23889. }
  23890. });
  23891. });
  23892. var ui = new editorui.Combox({
  23893. editor:editor,
  23894. items:items,
  23895. onselect:function (t, index) {
  23896. editor.execCommand('insertcode', this.items[index].value);
  23897. },
  23898. onbuttonclick:function () {
  23899. this.showPopup();
  23900. },
  23901. title:title,
  23902. initValue:title,
  23903. className:'edui-for-insertcode',
  23904. indexByValue:function (value) {
  23905. if (value) {
  23906. for (var i = 0, ci; ci = this.items[i]; i++) {
  23907. if (ci.value.indexOf(value) != -1)
  23908. return i;
  23909. }
  23910. }
  23911. return -1;
  23912. }
  23913. });
  23914. editorui.buttons['insertcode'] = ui;
  23915. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23916. if (!uiReady) {
  23917. var state = editor.queryCommandState('insertcode');
  23918. if (state == -1) {
  23919. ui.setDisabled(true);
  23920. } else {
  23921. ui.setDisabled(false);
  23922. var value = editor.queryCommandValue('insertcode');
  23923. if(!value){
  23924. ui.setValue(title);
  23925. return;
  23926. }
  23927. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  23928. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  23929. ui.setValue(value);
  23930. }
  23931. }
  23932. });
  23933. return ui;
  23934. };
  23935. editorui.fontfamily = function (editor, list, title) {
  23936. list = editor.options['fontfamily'] || [];
  23937. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  23938. if (!list.length) return;
  23939. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  23940. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  23941. (function (key, val) {
  23942. items.push({
  23943. label:key,
  23944. value:val,
  23945. theme:editor.options.theme,
  23946. renderLabelHtml:function () {
  23947. return '<div class="edui-label %%-label" style="font-family:' +
  23948. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  23949. }
  23950. });
  23951. })(ci.label || langLabel, ci.val)
  23952. }
  23953. var ui = new editorui.Combox({
  23954. editor:editor,
  23955. items:items,
  23956. onselect:function (t, index) {
  23957. editor.execCommand('FontFamily', this.items[index].value);
  23958. },
  23959. onbuttonclick:function () {
  23960. this.showPopup();
  23961. },
  23962. title:title,
  23963. initValue:title,
  23964. className:'edui-for-fontfamily',
  23965. indexByValue:function (value) {
  23966. if (value) {
  23967. for (var i = 0, ci; ci = this.items[i]; i++) {
  23968. if (ci.value.indexOf(value) != -1)
  23969. return i;
  23970. }
  23971. }
  23972. return -1;
  23973. }
  23974. });
  23975. editorui.buttons['fontfamily'] = ui;
  23976. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23977. if (!uiReady) {
  23978. var state = editor.queryCommandState('FontFamily');
  23979. if (state == -1) {
  23980. ui.setDisabled(true);
  23981. } else {
  23982. ui.setDisabled(false);
  23983. var value = editor.queryCommandValue('FontFamily');
  23984. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  23985. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  23986. ui.setValue(value);
  23987. }
  23988. }
  23989. });
  23990. return ui;
  23991. };
  23992. editorui.fontsize = function (editor, list, title) {
  23993. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  23994. list = list || editor.options['fontsize'] || [];
  23995. if (!list.length) return;
  23996. var items = [];
  23997. for (var i = 0; i < list.length; i++) {
  23998. var size = list[i] + 'px';
  23999. items.push({
  24000. label:size,
  24001. value:size,
  24002. theme:editor.options.theme,
  24003. renderLabelHtml:function () {
  24004. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  24005. this.value + '">' + (this.label || '') + '</div>';
  24006. }
  24007. });
  24008. }
  24009. var ui = new editorui.Combox({
  24010. editor:editor,
  24011. items:items,
  24012. title:title,
  24013. initValue:title,
  24014. onselect:function (t, index) {
  24015. editor.execCommand('FontSize', this.items[index].value);
  24016. },
  24017. onbuttonclick:function () {
  24018. this.showPopup();
  24019. },
  24020. className:'edui-for-fontsize'
  24021. });
  24022. editorui.buttons['fontsize'] = ui;
  24023. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  24024. if (!uiReady) {
  24025. var state = editor.queryCommandState('FontSize');
  24026. if (state == -1) {
  24027. ui.setDisabled(true);
  24028. } else {
  24029. ui.setDisabled(false);
  24030. ui.setValue(editor.queryCommandValue('FontSize'));
  24031. }
  24032. }
  24033. });
  24034. return ui;
  24035. };
  24036. editorui.paragraph = function (editor, list, title) {
  24037. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  24038. list = editor.options['paragraph'] || [];
  24039. if (utils.isEmptyObject(list)) return;
  24040. var items = [];
  24041. for (var i in list) {
  24042. items.push({
  24043. value:i,
  24044. label:list[i] || editor.getLang("paragraph")[i],
  24045. theme:editor.options.theme,
  24046. renderLabelHtml:function () {
  24047. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  24048. }
  24049. })
  24050. }
  24051. var ui = new editorui.Combox({
  24052. editor:editor,
  24053. items:items,
  24054. title:title,
  24055. initValue:title,
  24056. className:'edui-for-paragraph',
  24057. onselect:function (t, index) {
  24058. editor.execCommand('Paragraph', this.items[index].value);
  24059. },
  24060. onbuttonclick:function () {
  24061. this.showPopup();
  24062. }
  24063. });
  24064. editorui.buttons['paragraph'] = ui;
  24065. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  24066. if (!uiReady) {
  24067. var state = editor.queryCommandState('Paragraph');
  24068. if (state == -1) {
  24069. ui.setDisabled(true);
  24070. } else {
  24071. ui.setDisabled(false);
  24072. var value = editor.queryCommandValue('Paragraph');
  24073. var index = ui.indexByValue(value);
  24074. if (index != -1) {
  24075. ui.setValue(value);
  24076. } else {
  24077. ui.setValue(ui.initValue);
  24078. }
  24079. }
  24080. }
  24081. });
  24082. return ui;
  24083. };
  24084. //自定义标题
  24085. editorui.customstyle = function (editor) {
  24086. var list = editor.options['customstyle'] || [],
  24087. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  24088. if (!list.length)return;
  24089. var langCs = editor.getLang('customstyle');
  24090. for (var i = 0, items = [], t; t = list[i++];) {
  24091. (function (t) {
  24092. var ck = {};
  24093. ck.label = t.label ? t.label : langCs[t.name];
  24094. ck.style = t.style;
  24095. ck.className = t.className;
  24096. ck.tag = t.tag;
  24097. items.push({
  24098. label:ck.label,
  24099. value:ck,
  24100. theme:editor.options.theme,
  24101. renderLabelHtml:function () {
  24102. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  24103. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  24104. + '</div>';
  24105. }
  24106. });
  24107. })(t);
  24108. }
  24109. var ui = new editorui.Combox({
  24110. editor:editor,
  24111. items:items,
  24112. title:title,
  24113. initValue:title,
  24114. className:'edui-for-customstyle',
  24115. onselect:function (t, index) {
  24116. editor.execCommand('customstyle', this.items[index].value);
  24117. },
  24118. onbuttonclick:function () {
  24119. this.showPopup();
  24120. },
  24121. indexByValue:function (value) {
  24122. for (var i = 0, ti; ti = this.items[i++];) {
  24123. if (ti.label == value) {
  24124. return i - 1
  24125. }
  24126. }
  24127. return -1;
  24128. }
  24129. });
  24130. editorui.buttons['customstyle'] = ui;
  24131. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  24132. if (!uiReady) {
  24133. var state = editor.queryCommandState('customstyle');
  24134. if (state == -1) {
  24135. ui.setDisabled(true);
  24136. } else {
  24137. ui.setDisabled(false);
  24138. var value = editor.queryCommandValue('customstyle');
  24139. var index = ui.indexByValue(value);
  24140. if (index != -1) {
  24141. ui.setValue(value);
  24142. } else {
  24143. ui.setValue(ui.initValue);
  24144. }
  24145. }
  24146. }
  24147. });
  24148. return ui;
  24149. };
  24150. editorui.inserttable = function (editor, iframeUrl, title) {
  24151. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  24152. var ui = new editorui.TableButton({
  24153. editor:editor,
  24154. title:title,
  24155. className:'edui-for-inserttable',
  24156. onpicktable:function (t, numCols, numRows) {
  24157. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  24158. },
  24159. onbuttonclick:function () {
  24160. this.showPopup();
  24161. }
  24162. });
  24163. editorui.buttons['inserttable'] = ui;
  24164. editor.addListener('selectionchange', function () {
  24165. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  24166. });
  24167. return ui;
  24168. };
  24169. editorui.lineheight = function (editor) {
  24170. var val = editor.options.lineheight || [];
  24171. if (!val.length)return;
  24172. for (var i = 0, ci, items = []; ci = val[i++];) {
  24173. items.push({
  24174. //todo:写死了
  24175. label:ci,
  24176. value:ci,
  24177. theme:editor.options.theme,
  24178. onclick:function () {
  24179. editor.execCommand("lineheight", this.value);
  24180. }
  24181. })
  24182. }
  24183. var ui = new editorui.MenuButton({
  24184. editor:editor,
  24185. className:'edui-for-lineheight',
  24186. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  24187. items:items,
  24188. onbuttonclick:function () {
  24189. var value = editor.queryCommandValue('LineHeight') || this.value;
  24190. editor.execCommand("LineHeight", value);
  24191. }
  24192. });
  24193. editorui.buttons['lineheight'] = ui;
  24194. editor.addListener('selectionchange', function () {
  24195. var state = editor.queryCommandState('LineHeight');
  24196. if (state == -1) {
  24197. ui.setDisabled(true);
  24198. } else {
  24199. ui.setDisabled(false);
  24200. var value = editor.queryCommandValue('LineHeight');
  24201. value && ui.setValue((value + '').replace(/cm/, ''));
  24202. ui.setChecked(state)
  24203. }
  24204. });
  24205. return ui;
  24206. };
  24207. var rowspacings = ['top', 'bottom'];
  24208. for (var r = 0, ri; ri = rowspacings[r++];) {
  24209. (function (cmd) {
  24210. editorui['rowspacing' + cmd] = function (editor) {
  24211. var val = editor.options['rowspacing' + cmd] || [];
  24212. if (!val.length) return null;
  24213. for (var i = 0, ci, items = []; ci = val[i++];) {
  24214. items.push({
  24215. label:ci,
  24216. value:ci,
  24217. theme:editor.options.theme,
  24218. onclick:function () {
  24219. editor.execCommand("rowspacing", this.value, cmd);
  24220. }
  24221. })
  24222. }
  24223. var ui = new editorui.MenuButton({
  24224. editor:editor,
  24225. className:'edui-for-rowspacing' + cmd,
  24226. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  24227. items:items,
  24228. onbuttonclick:function () {
  24229. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  24230. editor.execCommand("rowspacing", value, cmd);
  24231. }
  24232. });
  24233. editorui.buttons[cmd] = ui;
  24234. editor.addListener('selectionchange', function () {
  24235. var state = editor.queryCommandState('rowspacing', cmd);
  24236. if (state == -1) {
  24237. ui.setDisabled(true);
  24238. } else {
  24239. ui.setDisabled(false);
  24240. var value = editor.queryCommandValue('rowspacing', cmd);
  24241. value && ui.setValue((value + '').replace(/%/, ''));
  24242. ui.setChecked(state)
  24243. }
  24244. });
  24245. return ui;
  24246. }
  24247. })(ri)
  24248. }
  24249. //有序,无序列表
  24250. var lists = ['insertorderedlist', 'insertunorderedlist'];
  24251. for (var l = 0, cl; cl = lists[l++];) {
  24252. (function (cmd) {
  24253. editorui[cmd] = function (editor) {
  24254. var vals = editor.options[cmd],
  24255. _onMenuClick = function () {
  24256. editor.execCommand(cmd, this.value);
  24257. }, items = [];
  24258. for (var i in vals) {
  24259. items.push({
  24260. label:vals[i] || editor.getLang()[cmd][i] || "",
  24261. value:i,
  24262. theme:editor.options.theme,
  24263. onclick:_onMenuClick
  24264. })
  24265. }
  24266. var ui = new editorui.MenuButton({
  24267. editor:editor,
  24268. className:'edui-for-' + cmd,
  24269. title:editor.getLang("labelMap." + cmd) || '',
  24270. 'items':items,
  24271. onbuttonclick:function () {
  24272. var value = editor.queryCommandValue(cmd) || this.value;
  24273. editor.execCommand(cmd, value);
  24274. }
  24275. });
  24276. editorui.buttons[cmd] = ui;
  24277. editor.addListener('selectionchange', function () {
  24278. var state = editor.queryCommandState(cmd);
  24279. if (state == -1) {
  24280. ui.setDisabled(true);
  24281. } else {
  24282. ui.setDisabled(false);
  24283. var value = editor.queryCommandValue(cmd);
  24284. ui.setValue(value);
  24285. ui.setChecked(state)
  24286. }
  24287. });
  24288. return ui;
  24289. };
  24290. })(cl)
  24291. }
  24292. editorui.fullscreen = function (editor, title) {
  24293. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  24294. var ui = new editorui.Button({
  24295. className:'edui-for-fullscreen',
  24296. title:title,
  24297. theme:editor.options.theme,
  24298. onclick:function () {
  24299. if (editor.ui) {
  24300. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  24301. }
  24302. this.setChecked(editor.ui.isFullScreen());
  24303. }
  24304. });
  24305. editorui.buttons['fullscreen'] = ui;
  24306. editor.addListener('selectionchange', function () {
  24307. var state = editor.queryCommandState('fullscreen');
  24308. ui.setDisabled(state == -1);
  24309. ui.setChecked(editor.ui.isFullScreen());
  24310. });
  24311. return ui;
  24312. };
  24313. // 表情
  24314. editorui["emotion"] = function (editor, iframeUrl) {
  24315. var cmd = "emotion";
  24316. var ui = new editorui.MultiMenuPop({
  24317. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  24318. editor:editor,
  24319. className:'edui-for-' + cmd,
  24320. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  24321. });
  24322. editorui.buttons[cmd] = ui;
  24323. editor.addListener('selectionchange', function () {
  24324. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  24325. });
  24326. return ui;
  24327. };
  24328. editorui.autotypeset = function (editor) {
  24329. var ui = new editorui.AutoTypeSetButton({
  24330. editor:editor,
  24331. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  24332. className:'edui-for-autotypeset',
  24333. onbuttonclick:function () {
  24334. editor.execCommand('autotypeset')
  24335. }
  24336. });
  24337. editorui.buttons['autotypeset'] = ui;
  24338. editor.addListener('selectionchange', function () {
  24339. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  24340. });
  24341. return ui;
  24342. };
  24343. })();
  24344. ///import core
  24345. ///commands 全屏
  24346. ///commandsName FullScreen
  24347. ///commandsTitle 全屏
  24348. (function () {
  24349. var utils = baidu.editor.utils,
  24350. uiUtils = baidu.editor.ui.uiUtils,
  24351. UIBase = baidu.editor.ui.UIBase,
  24352. domUtils = baidu.editor.dom.domUtils;
  24353. var nodeStack = [];
  24354. function EditorUI(options) {
  24355. this.initOptions(options);
  24356. this.initEditorUI();
  24357. }
  24358. EditorUI.prototype = {
  24359. uiName:'editor',
  24360. initEditorUI:function () {
  24361. this.editor.ui = this;
  24362. this._dialogs = {};
  24363. this.initUIBase();
  24364. this._initToolbars();
  24365. var editor = this.editor,
  24366. me = this;
  24367. editor.addListener('ready', function () {
  24368. //提供getDialog方法
  24369. editor.getDialog = function (name) {
  24370. return editor.ui._dialogs[name + "Dialog"];
  24371. };
  24372. domUtils.on(editor.window, 'scroll', function (evt) {
  24373. baidu.editor.ui.Popup.postHide(evt);
  24374. });
  24375. //提供编辑器实时宽高(全屏时宽高不变化)
  24376. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  24377. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  24378. //display bottom-bar label based on config
  24379. if (editor.options.elementPathEnabled) {
  24380. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  24381. }
  24382. if (editor.options.wordCount) {
  24383. function countFn() {
  24384. setCount(editor,me);
  24385. domUtils.un(editor.document, "click", arguments.callee);
  24386. }
  24387. domUtils.on(editor.document, "click", countFn);
  24388. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  24389. }
  24390. editor.ui._scale();
  24391. if (editor.options.scaleEnabled) {
  24392. if (editor.autoHeightEnabled) {
  24393. editor.disableAutoHeight();
  24394. }
  24395. me.enableScale();
  24396. } else {
  24397. me.disableScale();
  24398. }
  24399. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  24400. editor.ui.getDom('elementpath').style.display = "none";
  24401. editor.ui.getDom('wordcount').style.display = "none";
  24402. editor.ui.getDom('scale').style.display = "none";
  24403. }
  24404. if (!editor.selection.isFocus())return;
  24405. editor.fireEvent('selectionchange', false, true);
  24406. });
  24407. editor.addListener('mousedown', function (t, evt) {
  24408. var el = evt.target || evt.srcElement;
  24409. baidu.editor.ui.Popup.postHide(evt, el);
  24410. baidu.editor.ui.ShortCutMenu.postHide(evt);
  24411. });
  24412. editor.addListener("delcells", function () {
  24413. if (UE.ui['edittip']) {
  24414. new UE.ui['edittip'](editor);
  24415. }
  24416. editor.getDialog('edittip').open();
  24417. });
  24418. var pastePop, isPaste = false, timer;
  24419. editor.addListener("afterpaste", function () {
  24420. if(editor.queryCommandState('pasteplain'))
  24421. return;
  24422. if(baidu.editor.ui.PastePicker){
  24423. pastePop = new baidu.editor.ui.Popup({
  24424. content:new baidu.editor.ui.PastePicker({editor:editor}),
  24425. editor:editor,
  24426. className:'edui-wordpastepop'
  24427. });
  24428. pastePop.render();
  24429. }
  24430. isPaste = true;
  24431. });
  24432. editor.addListener("afterinserthtml", function () {
  24433. clearTimeout(timer);
  24434. timer = setTimeout(function () {
  24435. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  24436. if(pastePop.isHidden()){
  24437. var span = domUtils.createElement(editor.document, 'span', {
  24438. 'style':"line-height:0px;",
  24439. 'innerHTML':'\ufeff'
  24440. }),
  24441. range = editor.selection.getRange();
  24442. range.insertNode(span);
  24443. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  24444. pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  24445. domUtils.remove(span);
  24446. }else{
  24447. pastePop.show();
  24448. }
  24449. delete editor.ui._isTransfer;
  24450. isPaste = false;
  24451. }
  24452. }, 200)
  24453. });
  24454. editor.addListener('contextmenu', function (t, evt) {
  24455. baidu.editor.ui.Popup.postHide(evt);
  24456. });
  24457. editor.addListener('keydown', function (t, evt) {
  24458. if (pastePop) pastePop.dispose(evt);
  24459. var keyCode = evt.keyCode || evt.which;
  24460. if(evt.altKey&&keyCode==90){
  24461. UE.ui.buttons['fullscreen'].onclick();
  24462. }
  24463. });
  24464. editor.addListener('wordcount', function (type) {
  24465. setCount(this,me);
  24466. });
  24467. function setCount(editor,ui) {
  24468. editor.setOpt({
  24469. wordCount:true,
  24470. maximumWords:10000,
  24471. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  24472. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  24473. });
  24474. var opt = editor.options,
  24475. max = opt.maximumWords,
  24476. msg = opt.wordCountMsg ,
  24477. errMsg = opt.wordOverFlowMsg,
  24478. countDom = ui.getDom('wordcount');
  24479. if (!opt.wordCount) {
  24480. return;
  24481. }
  24482. var count = editor.getContentLength(true);
  24483. if (count > max) {
  24484. countDom.innerHTML = errMsg;
  24485. editor.fireEvent("wordcountoverflow");
  24486. } else {
  24487. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  24488. }
  24489. }
  24490. editor.addListener('selectionchange', function () {
  24491. if (editor.options.elementPathEnabled) {
  24492. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  24493. }
  24494. if (editor.options.scaleEnabled) {
  24495. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  24496. }
  24497. });
  24498. var popup = new baidu.editor.ui.Popup({
  24499. editor:editor,
  24500. content:'',
  24501. className:'edui-bubble',
  24502. _onEditButtonClick:function () {
  24503. this.hide();
  24504. editor.ui._dialogs.linkDialog.open();
  24505. },
  24506. _onImgEditButtonClick:function (name) {
  24507. this.hide();
  24508. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  24509. },
  24510. _onImgSetFloat:function (value) {
  24511. this.hide();
  24512. editor.execCommand("imagefloat", value);
  24513. },
  24514. _setIframeAlign:function (value) {
  24515. var frame = popup.anchorEl;
  24516. var newFrame = frame.cloneNode(true);
  24517. switch (value) {
  24518. case -2:
  24519. newFrame.setAttribute("align", "");
  24520. break;
  24521. case -1:
  24522. newFrame.setAttribute("align", "left");
  24523. break;
  24524. case 1:
  24525. newFrame.setAttribute("align", "right");
  24526. break;
  24527. }
  24528. frame.parentNode.insertBefore(newFrame, frame);
  24529. domUtils.remove(frame);
  24530. popup.anchorEl = newFrame;
  24531. popup.showAnchor(popup.anchorEl);
  24532. },
  24533. _updateIframe:function () {
  24534. var frame = editor._iframe = popup.anchorEl;
  24535. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  24536. editor.selection.getRange().selectNode(frame).select();
  24537. editor.ui._dialogs.mapDialog.open();
  24538. popup.hide();
  24539. } else {
  24540. editor.ui._dialogs.insertframeDialog.open();
  24541. popup.hide();
  24542. }
  24543. },
  24544. _onRemoveButtonClick:function (cmdName) {
  24545. editor.execCommand(cmdName);
  24546. this.hide();
  24547. },
  24548. queryAutoHide:function (el) {
  24549. if (el && el.ownerDocument == editor.document) {
  24550. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  24551. return el !== popup.anchorEl;
  24552. }
  24553. }
  24554. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  24555. }
  24556. });
  24557. popup.render();
  24558. if (editor.options.imagePopup) {
  24559. editor.addListener('mouseover', function (t, evt) {
  24560. evt = evt || window.event;
  24561. var el = evt.target || evt.srcElement;
  24562. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  24563. var html = popup.formatHtml(
  24564. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._setIframeAlign(-2) class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(-1) class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(1) class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  24565. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  24566. if (html) {
  24567. popup.getDom('content').innerHTML = html;
  24568. popup.anchorEl = el;
  24569. popup.showAnchor(popup.anchorEl);
  24570. } else {
  24571. popup.hide();
  24572. }
  24573. }
  24574. });
  24575. editor.addListener('selectionchange', function (t, causeByUi) {
  24576. if (!causeByUi) return;
  24577. var html = '', str = "",
  24578. img = editor.selection.getRange().getClosedNode(),
  24579. dialogs = editor.ui._dialogs;
  24580. if (img && img.tagName == 'IMG') {
  24581. var dialogName = 'insertimageDialog';
  24582. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  24583. dialogName = "insertvideoDialog"
  24584. }
  24585. if (img.className.indexOf("edui-faked-webapp") != -1) {
  24586. dialogName = "webappDialog"
  24587. }
  24588. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  24589. dialogName = "mapDialog"
  24590. }
  24591. if (img.className.indexOf("edui-faked-music") != -1) {
  24592. dialogName = "musicDialog"
  24593. }
  24594. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  24595. dialogName = "gmapDialog"
  24596. }
  24597. if (img.getAttribute("anchorname")) {
  24598. dialogName = "anchorDialog";
  24599. html = popup.formatHtml(
  24600. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  24601. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  24602. }
  24603. if (img.getAttribute("word_img")) {
  24604. //todo 放到dialog去做查询
  24605. editor.word_img = [img.getAttribute("word_img")];
  24606. dialogName = "wordimageDialog"
  24607. }
  24608. if (!dialogs[dialogName]) {
  24609. return;
  24610. }
  24611. str = '<nobr>' + editor.getLang("property") + ': '+
  24612. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  24613. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  24614. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  24615. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  24616. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  24617. !html && (html = popup.formatHtml(str))
  24618. }
  24619. if (editor.ui._dialogs.linkDialog) {
  24620. var link = editor.queryCommandValue('link');
  24621. var url;
  24622. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  24623. var txt = url;
  24624. if (url.length > 30) {
  24625. txt = url.substring(0, 20) + "...";
  24626. }
  24627. if (html) {
  24628. html += '<div style="height:5px;"></div>'
  24629. }
  24630. html += popup.formatHtml(
  24631. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  24632. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  24633. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  24634. popup.showAnchor(link);
  24635. }
  24636. }
  24637. if (html) {
  24638. popup.getDom('content').innerHTML = html;
  24639. popup.anchorEl = img || link;
  24640. popup.showAnchor(popup.anchorEl);
  24641. } else {
  24642. popup.hide();
  24643. }
  24644. });
  24645. }
  24646. },
  24647. _initToolbars:function () {
  24648. var editor = this.editor;
  24649. var toolbars = this.toolbars || [];
  24650. var toolbarUis = [];
  24651. for (var i = 0; i < toolbars.length; i++) {
  24652. var toolbar = toolbars[i];
  24653. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  24654. for (var j = 0; j < toolbar.length; j++) {
  24655. var toolbarItem = toolbar[j];
  24656. var toolbarItemUi = null;
  24657. if (typeof toolbarItem == 'string') {
  24658. toolbarItem = toolbarItem.toLowerCase();
  24659. if (toolbarItem == '|') {
  24660. toolbarItem = 'Separator';
  24661. }
  24662. if(toolbarItem == '||'){
  24663. toolbarItem = 'Breakline';
  24664. }
  24665. if (baidu.editor.ui[toolbarItem]) {
  24666. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  24667. }
  24668. //fullscreen这里单独处理一下,放到首行去
  24669. if (toolbarItem == 'fullscreen') {
  24670. if (toolbarUis && toolbarUis[0]) {
  24671. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  24672. } else {
  24673. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  24674. }
  24675. continue;
  24676. }
  24677. } else {
  24678. toolbarItemUi = toolbarItem;
  24679. }
  24680. if (toolbarItemUi && toolbarItemUi.id) {
  24681. toolbarUi.add(toolbarItemUi);
  24682. }
  24683. }
  24684. toolbarUis[i] = toolbarUi;
  24685. }
  24686. this.toolbars = toolbarUis;
  24687. },
  24688. getHtmlTpl:function () {
  24689. return '<div id="##" class="%%">' +
  24690. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  24691. (this.toolbars.length ?
  24692. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  24693. this.renderToolbarBoxHtml() +
  24694. '</div></div>' : '') +
  24695. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  24696. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  24697. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  24698. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  24699. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  24700. '</div>' +
  24701. '</div>' +
  24702. '<div id="##_iframeholder" class="%%-iframeholder"></div>' +
  24703. //modify wdcount by matao
  24704. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  24705. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  24706. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  24707. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  24708. '</tr></table></div>' +
  24709. '<div id="##_scalelayer"></div>' +
  24710. '</div>';
  24711. },
  24712. showWordImageDialog:function () {
  24713. this._dialogs['wordimageDialog'].open();
  24714. },
  24715. renderToolbarBoxHtml:function () {
  24716. var buff = [];
  24717. for (var i = 0; i < this.toolbars.length; i++) {
  24718. buff.push(this.toolbars[i].renderHtml());
  24719. }
  24720. return buff.join('');
  24721. },
  24722. setFullScreen:function (fullscreen) {
  24723. var editor = this.editor,
  24724. container = editor.container.parentNode.parentNode;
  24725. if (this._fullscreen != fullscreen) {
  24726. this._fullscreen = fullscreen;
  24727. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  24728. if (baidu.editor.browser.gecko) {
  24729. var bk = editor.selection.getRange().createBookmark();
  24730. }
  24731. if (fullscreen) {
  24732. while (container.tagName != "BODY") {
  24733. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  24734. nodeStack.push(position);
  24735. container.style.position = "static";
  24736. container = container.parentNode;
  24737. }
  24738. this._bakHtmlOverflow = document.documentElement.style.overflow;
  24739. this._bakBodyOverflow = document.body.style.overflow;
  24740. this._bakAutoHeight = this.editor.autoHeightEnabled;
  24741. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  24742. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  24743. if (this._bakAutoHeight) {
  24744. //当全屏时不能执行自动长高
  24745. editor.autoHeightEnabled = false;
  24746. this.editor.disableAutoHeight();
  24747. }
  24748. document.documentElement.style.overflow = 'hidden';
  24749. //修复,滚动条不收起的问题
  24750. window.scrollTo(0,window.scrollY);
  24751. this._bakCssText = this.getDom().style.cssText;
  24752. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  24753. editor.iframe.parentNode.style.width = '';
  24754. this._updateFullScreen();
  24755. } else {
  24756. while (container.tagName != "BODY") {
  24757. container.style.position = nodeStack.shift();
  24758. container = container.parentNode;
  24759. }
  24760. this.getDom().style.cssText = this._bakCssText;
  24761. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  24762. if (this._bakAutoHeight) {
  24763. editor.autoHeightEnabled = true;
  24764. this.editor.enableAutoHeight();
  24765. }
  24766. document.documentElement.style.overflow = this._bakHtmlOverflow;
  24767. document.body.style.overflow = this._bakBodyOverflow;
  24768. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  24769. window.scrollTo(0, this._bakScrollTop);
  24770. }
  24771. if (browser.gecko && editor.body.contentEditable === 'true') {
  24772. var input = document.createElement('input');
  24773. document.body.appendChild(input);
  24774. editor.body.contentEditable = false;
  24775. setTimeout(function () {
  24776. input.focus();
  24777. setTimeout(function () {
  24778. editor.body.contentEditable = true;
  24779. editor.fireEvent('fullscreenchanged', fullscreen);
  24780. editor.selection.getRange().moveToBookmark(bk).select(true);
  24781. baidu.editor.dom.domUtils.remove(input);
  24782. fullscreen && window.scroll(0, 0);
  24783. }, 0)
  24784. }, 0)
  24785. }
  24786. if(editor.body.contentEditable === 'true'){
  24787. this.editor.fireEvent('fullscreenchanged', fullscreen);
  24788. this.triggerLayout();
  24789. }
  24790. }
  24791. },
  24792. _updateFullScreen:function () {
  24793. if (this._fullscreen) {
  24794. var vpRect = uiUtils.getViewportRect();
  24795. this.getDom().style.cssText = 'border:0;position:absolute;left:0;top:' + (this.editor.options.topOffset || 0) + 'px;width:' + vpRect.width + 'px;height:' + vpRect.height + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 100);
  24796. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  24797. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0));
  24798. //不手动调一下,会导致全屏失效
  24799. if(browser.gecko){
  24800. try{
  24801. window.onresize();
  24802. }catch(e){
  24803. }
  24804. }
  24805. }
  24806. },
  24807. _updateElementPath:function () {
  24808. var bottom = this.getDom('elementpath'), list;
  24809. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  24810. var buff = [];
  24811. for (var i = 0, ci; ci = list[i]; i++) {
  24812. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  24813. }
  24814. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  24815. } else {
  24816. bottom.style.display = 'none'
  24817. }
  24818. },
  24819. disableElementPath:function () {
  24820. var bottom = this.getDom('elementpath');
  24821. bottom.innerHTML = '';
  24822. bottom.style.display = 'none';
  24823. this.elementPathEnabled = false;
  24824. },
  24825. enableElementPath:function () {
  24826. var bottom = this.getDom('elementpath');
  24827. bottom.style.display = '';
  24828. this.elementPathEnabled = true;
  24829. this._updateElementPath();
  24830. },
  24831. _scale:function () {
  24832. var doc = document,
  24833. editor = this.editor,
  24834. editorHolder = editor.container,
  24835. editorDocument = editor.document,
  24836. toolbarBox = this.getDom("toolbarbox"),
  24837. bottombar = this.getDom("bottombar"),
  24838. scale = this.getDom("scale"),
  24839. scalelayer = this.getDom("scalelayer");
  24840. var isMouseMove = false,
  24841. position = null,
  24842. minEditorHeight = 0,
  24843. minEditorWidth = editor.options.minFrameWidth,
  24844. pageX = 0,
  24845. pageY = 0,
  24846. scaleWidth = 0,
  24847. scaleHeight = 0;
  24848. function down() {
  24849. position = domUtils.getXY(editorHolder);
  24850. if (!minEditorHeight) {
  24851. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  24852. }
  24853. scalelayer.style.cssText = "position:absolute;left:0;display:;top:0;background-color:#41ABFF;opacity:0.4;filter: Alpha(opacity=40);width:" + editorHolder.offsetWidth + "px;height:"
  24854. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  24855. domUtils.on(doc, "mousemove", move);
  24856. domUtils.on(editorDocument, "mouseup", up);
  24857. domUtils.on(doc, "mouseup", up);
  24858. }
  24859. var me = this;
  24860. //by xuheng 全屏时关掉缩放
  24861. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  24862. if (fullScreen) {
  24863. me.disableScale();
  24864. } else {
  24865. if (me.editor.options.scaleEnabled) {
  24866. me.enableScale();
  24867. var tmpNode = me.editor.document.createElement('span');
  24868. me.editor.body.appendChild(tmpNode);
  24869. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  24870. domUtils.remove(tmpNode)
  24871. }
  24872. }
  24873. });
  24874. function move(event) {
  24875. clearSelection();
  24876. var e = event || window.event;
  24877. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  24878. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  24879. scaleWidth = pageX - position.x;
  24880. scaleHeight = pageY - position.y;
  24881. if (scaleWidth >= minEditorWidth) {
  24882. isMouseMove = true;
  24883. scalelayer.style.width = scaleWidth + 'px';
  24884. }
  24885. if (scaleHeight >= minEditorHeight) {
  24886. isMouseMove = true;
  24887. scalelayer.style.height = scaleHeight + "px";
  24888. }
  24889. }
  24890. function up() {
  24891. if (isMouseMove) {
  24892. isMouseMove = false;
  24893. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  24894. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  24895. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2);
  24896. }
  24897. if (scalelayer) {
  24898. scalelayer.style.display = "none";
  24899. }
  24900. clearSelection();
  24901. domUtils.un(doc, "mousemove", move);
  24902. domUtils.un(editorDocument, "mouseup", up);
  24903. domUtils.un(doc, "mouseup", up);
  24904. }
  24905. function clearSelection() {
  24906. if (browser.ie)
  24907. doc.selection.clear();
  24908. else
  24909. window.getSelection().removeAllRanges();
  24910. }
  24911. this.enableScale = function () {
  24912. //trace:2868
  24913. if (editor.queryCommandState("source") == 1) return;
  24914. scale.style.display = "";
  24915. this.scaleEnabled = true;
  24916. domUtils.on(scale, "mousedown", down);
  24917. };
  24918. this.disableScale = function () {
  24919. scale.style.display = "none";
  24920. this.scaleEnabled = false;
  24921. domUtils.un(scale, "mousedown", down);
  24922. };
  24923. },
  24924. isFullScreen:function () {
  24925. return this._fullscreen;
  24926. },
  24927. postRender:function () {
  24928. UIBase.prototype.postRender.call(this);
  24929. for (var i = 0; i < this.toolbars.length; i++) {
  24930. this.toolbars[i].postRender();
  24931. }
  24932. var me = this;
  24933. var timerId,
  24934. domUtils = baidu.editor.dom.domUtils,
  24935. updateFullScreenTime = function () {
  24936. clearTimeout(timerId);
  24937. timerId = setTimeout(function () {
  24938. me._updateFullScreen();
  24939. });
  24940. };
  24941. domUtils.on(window, 'resize', updateFullScreenTime);
  24942. me.addListener('destroy', function () {
  24943. domUtils.un(window, 'resize', updateFullScreenTime);
  24944. clearTimeout(timerId);
  24945. })
  24946. },
  24947. showToolbarMsg:function (msg, flag) {
  24948. this.getDom('toolbarmsg_label').innerHTML = msg;
  24949. this.getDom('toolbarmsg').style.display = '';
  24950. //
  24951. if (!flag) {
  24952. var w = this.getDom('upload_dialog');
  24953. w.style.display = 'none';
  24954. }
  24955. },
  24956. hideToolbarMsg:function () {
  24957. this.getDom('toolbarmsg').style.display = 'none';
  24958. },
  24959. mapUrl:function (url) {
  24960. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  24961. },
  24962. triggerLayout:function () {
  24963. var dom = this.getDom();
  24964. if (dom.style.zoom == '1') {
  24965. dom.style.zoom = '100%';
  24966. } else {
  24967. dom.style.zoom = '1';
  24968. }
  24969. }
  24970. };
  24971. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  24972. var instances = {};
  24973. UE.ui.Editor = function (options) {
  24974. var editor = new UE.Editor(options);
  24975. editor.options.editor = editor;
  24976. utils.loadFile(document, {
  24977. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  24978. tag:"link",
  24979. type:"text/css",
  24980. rel:"stylesheet"
  24981. });
  24982. var oldRender = editor.render;
  24983. editor.render = function (holder) {
  24984. if (holder.constructor === String) {
  24985. editor.key = holder;
  24986. instances[holder] = editor;
  24987. }
  24988. utils.domReady(function () {
  24989. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  24990. function renderUI() {
  24991. editor.setOpt({
  24992. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  24993. });
  24994. new EditorUI(editor.options);
  24995. if (holder) {
  24996. if (holder.constructor === String) {
  24997. holder = document.getElementById(holder);
  24998. }
  24999. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  25000. if (holder && /script|textarea/ig.test(holder.tagName)) {
  25001. var newDiv = document.createElement('div');
  25002. holder.parentNode.insertBefore(newDiv, holder);
  25003. var cont = holder.value || holder.innerHTML;
  25004. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  25005. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  25006. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  25007. .replace(/>[\n\r\t]+</g, '><');
  25008. holder.className && (newDiv.className = holder.className);
  25009. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  25010. if (/textarea/i.test(holder.tagName)) {
  25011. editor.textarea = holder;
  25012. editor.textarea.style.display = 'none';
  25013. } else {
  25014. holder.parentNode.removeChild(holder);
  25015. holder.id && (newDiv.id = holder.id);
  25016. }
  25017. holder = newDiv;
  25018. holder.innerHTML = '';
  25019. }
  25020. }
  25021. domUtils.addClass(holder, "edui-" + editor.options.theme);
  25022. editor.ui.render(holder);
  25023. var opt = editor.options;
  25024. //给实例添加一个编辑器的容器引用
  25025. editor.container = editor.ui.getDom();
  25026. var parents = domUtils.findParents(holder,true);
  25027. var displays = [];
  25028. for(var i = 0 ,ci;ci=parents[i];i++){
  25029. displays[i] = ci.style.display;
  25030. ci.style.display = 'block'
  25031. }
  25032. if (opt.initialFrameWidth) {
  25033. opt.minFrameWidth = opt.initialFrameWidth;
  25034. } else {
  25035. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  25036. }
  25037. if (opt.initialFrameHeight) {
  25038. opt.minFrameHeight = opt.initialFrameHeight;
  25039. } else {
  25040. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  25041. }
  25042. for(var i = 0 ,ci;ci=parents[i];i++){
  25043. ci.style.display = displays[i]
  25044. }
  25045. //编辑器最外容器设置了高度,会导致,编辑器不占位
  25046. //todo 先去掉,没有找到原因
  25047. if(holder.style.height){
  25048. holder.style.height = ''
  25049. }
  25050. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  25051. editor.container.style.zIndex = opt.zIndex;
  25052. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  25053. editor.fireEvent("afteruiready");
  25054. }
  25055. })
  25056. };
  25057. return editor;
  25058. };
  25059. /**
  25060. * @file
  25061. * @name UE
  25062. * @short UE
  25063. * @desc UEditor的顶部命名空间
  25064. */
  25065. /**
  25066. * @name getEditor
  25067. * @since 1.2.4+
  25068. * @grammar UE.getEditor(id,[opt]) => Editor实例
  25069. * @desc 提供一个全局的方法得到编辑器实例
  25070. *
  25071. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  25072. * * ''opt'' 编辑器的可选参数
  25073. * @example
  25074. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  25075. * this.setContent('hello')
  25076. * }});
  25077. * UE.getEditor('containerId'); //返回刚创建的实例
  25078. *
  25079. */
  25080. UE.getEditor = function (id, opt) {
  25081. var editor = instances[id];
  25082. if (!editor) {
  25083. editor = instances[id] = new UE.ui.Editor(opt);
  25084. editor.render(id);
  25085. }
  25086. return editor;
  25087. };
  25088. UE.delEditor = function (id) {
  25089. var editor;
  25090. if (editor = instances[id]) {
  25091. editor.key && editor.destroy();
  25092. delete instances[id]
  25093. }
  25094. }
  25095. })();
  25096. ///import core
  25097. ///import uicore
  25098. ///commands 表情
  25099. (function(){
  25100. var utils = baidu.editor.utils,
  25101. Popup = baidu.editor.ui.Popup,
  25102. SplitButton = baidu.editor.ui.SplitButton,
  25103. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  25104. this.initOptions(options);
  25105. this.initMultiMenu();
  25106. };
  25107. MultiMenuPop.prototype = {
  25108. initMultiMenu: function (){
  25109. var me = this;
  25110. this.popup = new Popup({
  25111. content: '',
  25112. editor : me.editor,
  25113. iframe_rendered: false,
  25114. onshow: function (){
  25115. if (!this.iframe_rendered) {
  25116. this.iframe_rendered = true;
  25117. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  25118. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25119. }
  25120. }
  25121. // canSideUp:false,
  25122. // canSideLeft:false
  25123. });
  25124. this.onbuttonclick = function(){
  25125. this.showPopup();
  25126. };
  25127. this.initSplitButton();
  25128. }
  25129. };
  25130. utils.inherits(MultiMenuPop, SplitButton);
  25131. })();
  25132. (function () {
  25133. var UI = baidu.editor.ui,
  25134. UIBase = UI.UIBase,
  25135. uiUtils = UI.uiUtils,
  25136. utils = baidu.editor.utils,
  25137. domUtils = baidu.editor.dom.domUtils;
  25138. var allMenus = [],//存储所有快捷菜单
  25139. timeID,
  25140. isSubMenuShow = false;//是否有子pop显示
  25141. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25142. this.initOptions (options);
  25143. this.initShortCutMenu ();
  25144. };
  25145. ShortCutMenu.postHide = hideAllMenu;
  25146. ShortCutMenu.prototype = {
  25147. isHidden : true ,
  25148. SPACE : 5 ,
  25149. initShortCutMenu : function () {
  25150. this.items = this.items || [];
  25151. this.initUIBase ();
  25152. this.initItems ();
  25153. this.initEvent ();
  25154. allMenus.push (this);
  25155. } ,
  25156. initEvent : function () {
  25157. var me = this,
  25158. doc = me.editor.document;
  25159. domUtils.on (doc , "mousemove" , function (e) {
  25160. if (me.isHidden === false) {
  25161. //有pop显示就不隐藏快捷菜单
  25162. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  25163. var flag = true,
  25164. el = me.getDom (),
  25165. wt = el.offsetWidth,
  25166. ht = el.offsetHeight,
  25167. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25168. distanceY = ht / 2,//距离中心Y标准
  25169. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  25170. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  25171. clearTimeout (timeID);
  25172. timeID = setTimeout (function () {
  25173. if (y > 0 && y < distanceY) {
  25174. me.setOpacity (el , "1");
  25175. } else if (y > distanceY && y < distanceY + 70) {
  25176. me.setOpacity (el , "0.5");
  25177. flag = false;
  25178. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25179. me.hide ();
  25180. }
  25181. if (flag && x > 0 && x < distanceX) {
  25182. me.setOpacity (el , "1")
  25183. } else if (x > distanceX && x < distanceX + 70) {
  25184. me.setOpacity (el , "0.5")
  25185. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25186. me.hide ();
  25187. }
  25188. });
  25189. }
  25190. });
  25191. //ie\ff下 mouseout不准
  25192. if (browser.chrome) {
  25193. domUtils.on (doc , "mouseout" , function (e) {
  25194. var relatedTgt = e.relatedTarget || e.toElement;
  25195. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25196. me.hide ();
  25197. }
  25198. });
  25199. }
  25200. me.editor.addListener ("afterhidepop" , function () {
  25201. if (!me.isHidden) {
  25202. isSubMenuShow = true;
  25203. }
  25204. });
  25205. } ,
  25206. initItems : function () {
  25207. if (utils.isArray (this.items)) {
  25208. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25209. var item = this.items[i].toLowerCase ();
  25210. if (UI[item]) {
  25211. this.items[i] = new UI[item] (this.editor);
  25212. this.items[i].className += " edui-shortcutsubmenu ";
  25213. }
  25214. }
  25215. }
  25216. } ,
  25217. setOpacity : function (el , value) {
  25218. if (browser.ie && browser.version < 9) {
  25219. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25220. } else {
  25221. el.style.opacity = value;
  25222. }
  25223. } ,
  25224. getSubMenuMark : function () {
  25225. isSubMenuShow = false;
  25226. var layerEle = uiUtils.getFixedLayer ();
  25227. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25228. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25229. });
  25230. for (var i = 0, node ; node = list[i++] ;) {
  25231. if (node.style.display != "none") {
  25232. isSubMenuShow = true;
  25233. }
  25234. }
  25235. return isSubMenuShow;
  25236. } ,
  25237. show : function (e , hasContextmenu) {
  25238. var me = this,
  25239. offset = {},
  25240. el = this.getDom (),
  25241. fixedlayer = uiUtils.getFixedLayer ();
  25242. function setPos (offset) {
  25243. if (offset.left < 0) {
  25244. offset.left = 0;
  25245. }
  25246. if (offset.top < 0) {
  25247. offset.top = 0;
  25248. }
  25249. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25250. }
  25251. function setPosByCxtMenu (menu) {
  25252. if (!menu.tagName) {
  25253. menu = menu.getDom ();
  25254. }
  25255. offset.left = parseInt (menu.style.left);
  25256. offset.top = parseInt (menu.style.top);
  25257. offset.top -= el.offsetHeight + 15;
  25258. setPos (offset);
  25259. }
  25260. me.eventType = e.type;
  25261. el.style.cssText = "display:block;left:-9999px";
  25262. if (e.type == "contextmenu" && hasContextmenu) {
  25263. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25264. if (menu) {
  25265. setPosByCxtMenu (menu)
  25266. } else {
  25267. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25268. setPosByCxtMenu (menu);
  25269. });
  25270. }
  25271. } else {
  25272. offset = uiUtils.getViewportOffsetByEvent (e);
  25273. offset.top -= el.offsetHeight + me.SPACE;
  25274. offset.left += me.SPACE + 20;
  25275. setPos (offset);
  25276. me.setOpacity (el , 0.2);
  25277. }
  25278. me.isHidden = false;
  25279. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25280. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25281. if (me.editor) {
  25282. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25283. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25284. }
  25285. } ,
  25286. hide : function () {
  25287. if (this.getDom ()) {
  25288. this.getDom ().style.display = "none";
  25289. }
  25290. this.isHidden = true;
  25291. } ,
  25292. postRender : function () {
  25293. if (utils.isArray (this.items)) {
  25294. for (var i = 0, item ; item = this.items[i++] ;) {
  25295. item.postRender ();
  25296. }
  25297. }
  25298. } ,
  25299. getHtmlTpl : function () {
  25300. var buff;
  25301. if (utils.isArray (this.items)) {
  25302. buff = [];
  25303. for (var i = 0 ; i < this.items.length ; i++) {
  25304. buff[i] = this.items[i].renderHtml ();
  25305. }
  25306. buff = buff.join ("");
  25307. } else {
  25308. buff = this.items;
  25309. }
  25310. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25311. buff +
  25312. '</div>';
  25313. }
  25314. };
  25315. utils.inherits (ShortCutMenu , UIBase);
  25316. function hideAllMenu (e) {
  25317. var tgt = e.target || e.srcElement,
  25318. cur = domUtils.findParent (tgt , function (node) {
  25319. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25320. } , true);
  25321. if (!cur) {
  25322. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25323. menu.hide ()
  25324. }
  25325. }
  25326. }
  25327. domUtils.on (document , 'mousedown' , function (e) {
  25328. hideAllMenu (e);
  25329. });
  25330. domUtils.on (window , 'scroll' , function (e) {
  25331. hideAllMenu (e);
  25332. });
  25333. }) ();
  25334. (function (){
  25335. var utils = baidu.editor.utils,
  25336. UIBase = baidu.editor.ui.UIBase,
  25337. Breakline = baidu.editor.ui.Breakline = function (options){
  25338. this.initOptions(options);
  25339. this.initSeparator();
  25340. };
  25341. Breakline.prototype = {
  25342. uiName: 'Breakline',
  25343. initSeparator: function (){
  25344. this.initUIBase();
  25345. },
  25346. getHtmlTpl: function (){
  25347. return '<br/>';
  25348. }
  25349. };
  25350. utils.inherits(Breakline, UIBase);
  25351. })();
  25352. })()