ueditor.all.js 1023 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542
  1. /*!
  2. * UEditor
  3. * version: 1.3.6
  4. * build: Wed Dec 25 2013 12:38:56 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. keys:{
  1593. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1594. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1595. 37:1, 38:1, 39:1, 40:1,
  1596. 13:1 /*enter*/
  1597. },
  1598. /**
  1599. * 获取节点A相对于节点B的位置关系
  1600. * @method getPosition
  1601. * @param { Node } nodeA 需要查询位置关系的节点A
  1602. * @param { Node } nodeB 需要查询位置关系的节点B
  1603. * @return { Number } 节点A与节点B的关系
  1604. * @example
  1605. * ```javascript
  1606. * //output: 20
  1607. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1608. *
  1609. * switch ( position ) {
  1610. *
  1611. * //0
  1612. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1613. * console.log('元素相同');
  1614. * break;
  1615. * //1
  1616. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1617. * console.log('两个节点在不同的文档中');
  1618. * break;
  1619. * //2
  1620. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1621. * console.log('节点A在节点B之后');
  1622. * break;
  1623. * //4
  1624. * case UE.dom.domUtils.POSITION_PRECEDING;
  1625. * console.log('节点A在节点B之前');
  1626. * break;
  1627. * //8
  1628. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1629. * console.log('节点A被节点B包含');
  1630. * break;
  1631. * case 10:
  1632. * console.log('节点A被节点B包含且节点A在节点B之后');
  1633. * break;
  1634. * //16
  1635. * case UE.dom.domUtils.POSITION_CONTAINS:
  1636. * console.log('节点A包含节点B');
  1637. * break;
  1638. * case 20:
  1639. * console.log('节点A包含节点B且节点A在节点B之前');
  1640. * break;
  1641. *
  1642. * }
  1643. * ```
  1644. */
  1645. getPosition:function (nodeA, nodeB) {
  1646. // 如果两个节点是同一个节点
  1647. if (nodeA === nodeB) {
  1648. // domUtils.POSITION_IDENTICAL
  1649. return 0;
  1650. }
  1651. var node,
  1652. parentsA = [nodeA],
  1653. parentsB = [nodeB];
  1654. node = nodeA;
  1655. while (node = node.parentNode) {
  1656. // 如果nodeB是nodeA的祖先节点
  1657. if (node === nodeB) {
  1658. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1659. return 10;
  1660. }
  1661. parentsA.push(node);
  1662. }
  1663. node = nodeB;
  1664. while (node = node.parentNode) {
  1665. // 如果nodeA是nodeB的祖先节点
  1666. if (node === nodeA) {
  1667. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1668. return 20;
  1669. }
  1670. parentsB.push(node);
  1671. }
  1672. parentsA.reverse();
  1673. parentsB.reverse();
  1674. if (parentsA[0] !== parentsB[0]) {
  1675. // domUtils.POSITION_DISCONNECTED
  1676. return 1;
  1677. }
  1678. var i = -1;
  1679. while (i++, parentsA[i] === parentsB[i]) {
  1680. }
  1681. nodeA = parentsA[i];
  1682. nodeB = parentsB[i];
  1683. while (nodeA = nodeA.nextSibling) {
  1684. if (nodeA === nodeB) {
  1685. // domUtils.POSITION_PRECEDING
  1686. return 4
  1687. }
  1688. }
  1689. // domUtils.POSITION_FOLLOWING
  1690. return 2;
  1691. },
  1692. /**
  1693. * 检测节点node在父节点中的索引位置
  1694. * @method getNodeIndex
  1695. * @param { Node } node 需要检测的节点对象
  1696. * @return { Number } 该节点在父节点中的位置
  1697. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1698. */
  1699. /**
  1700. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1701. * @method getNodeIndex
  1702. * @param { Node } node 需要检测的节点对象
  1703. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1704. * @return { Number } 该节点在父节点中的位置
  1705. * @example
  1706. * ```javascript
  1707. *
  1708. * var node = document.createElement("div");
  1709. *
  1710. * node.appendChild( document.createTextNode( "hello" ) );
  1711. * node.appendChild( document.createTextNode( "world" ) );
  1712. * node.appendChild( node = document.createElement( "div" ) );
  1713. *
  1714. * //output: 2
  1715. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1716. *
  1717. * //output: 1
  1718. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1719. *
  1720. * ```
  1721. */
  1722. getNodeIndex:function (node, ignoreTextNode) {
  1723. var preNode = node,
  1724. i = 0;
  1725. while (preNode = preNode.previousSibling) {
  1726. if (ignoreTextNode && preNode.nodeType == 3) {
  1727. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1728. i++;
  1729. }
  1730. continue;
  1731. }
  1732. i++;
  1733. }
  1734. return i;
  1735. },
  1736. /**
  1737. * 检测节点node是否在给定的document对象上
  1738. * @method inDoc
  1739. * @param { Node } node 需要检测的节点对象
  1740. * @param { DomDocument } doc 需要检测的document对象
  1741. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1742. * @example
  1743. * ```javascript
  1744. *
  1745. * var node = document.createElement("div");
  1746. *
  1747. * //output: false
  1748. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1749. *
  1750. * document.body.appendChild( node );
  1751. *
  1752. * //output: true
  1753. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1754. *
  1755. * ```
  1756. */
  1757. inDoc:function (node, doc) {
  1758. return domUtils.getPosition(node, doc) == 10;
  1759. },
  1760. /**
  1761. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1762. * 查找的起点是给定node节点的父节点。
  1763. * @method findParent
  1764. * @param { Node } node 需要查找的节点
  1765. * @param { Function } filterFn 自定义的过滤方法。
  1766. * @warning 查找的终点是到body节点为止
  1767. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1768. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1769. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1770. * @example
  1771. * ```javascript
  1772. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1773. *
  1774. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1775. * return node.tagName === "HTML";
  1776. *
  1777. * } );
  1778. *
  1779. * //output: true
  1780. * console.log( filterNode === null );
  1781. * ```
  1782. */
  1783. /**
  1784. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1785. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1786. * @method findParent
  1787. * @param { Node } node 需要查找的节点
  1788. * @param { Function } filterFn 自定义的过滤方法。
  1789. * @param { Boolean } includeSelf 查找过程是否包含自身
  1790. * @warning 查找的终点是到body节点为止
  1791. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1792. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1793. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1794. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1795. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1796. * @example
  1797. * ```html
  1798. * <body>
  1799. *
  1800. * <div id="test">
  1801. * </div>
  1802. *
  1803. * <script type="text/javascript">
  1804. *
  1805. * //output: DIV, BODY
  1806. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1807. *
  1808. * console.log( node.tagName );
  1809. * return false;
  1810. *
  1811. * }, true );
  1812. *
  1813. * </script>
  1814. * </body>
  1815. * ```
  1816. */
  1817. findParent:function (node, filterFn, includeSelf) {
  1818. if (node && !domUtils.isBody(node)) {
  1819. node = includeSelf ? node : node.parentNode;
  1820. while (node) {
  1821. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  1822. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  1823. }
  1824. node = node.parentNode;
  1825. }
  1826. }
  1827. return null;
  1828. },
  1829. /**
  1830. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  1831. * @method findParentByTagName
  1832. * @param { Node } node 需要查找的节点对象
  1833. * @param { Array } tagNames 需要查找的父节点的名称数组
  1834. * @warning 查找的终点是到body节点为止
  1835. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  1836. * @example
  1837. * ```javascript
  1838. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  1839. * //output: BODY
  1840. * console.log( node.tagName );
  1841. * ```
  1842. */
  1843. /**
  1844. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  1845. * 否则, 起点是node的父节点。
  1846. * @method findParentByTagName
  1847. * @param { Node } node 需要查找的节点对象
  1848. * @param { Array } tagNames 需要查找的父节点的名称数组
  1849. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  1850. * @warning 查找的终点是到body节点为止
  1851. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  1852. * @example
  1853. * ```javascript
  1854. * var queryTarget = document.getElementsByTagName("div")[0];
  1855. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  1856. * //output: true
  1857. * console.log( queryTarget === node );
  1858. * ```
  1859. */
  1860. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  1861. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  1862. return domUtils.findParent(node, function (node) {
  1863. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  1864. }, includeSelf);
  1865. },
  1866. /**
  1867. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  1868. * @method findParents
  1869. * @param { Node } node 需要查找的节点对象
  1870. * @return { Array } 给定节点的祖先节点数组
  1871. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  1872. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  1873. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  1874. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  1875. */
  1876. /**
  1877. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  1878. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  1879. * @method findParents
  1880. * @param { Node } node 需要查找的节点对象
  1881. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  1882. * @return { Array } 给定节点的祖先节点数组
  1883. */
  1884. findParents:function (node, includeSelf, filterFn, closerFirst) {
  1885. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  1886. while (node = domUtils.findParent(node, filterFn)) {
  1887. parents.push(node);
  1888. }
  1889. return closerFirst ? parents : parents.reverse();
  1890. },
  1891. /**
  1892. * 在节点node后面插入新节点newNode
  1893. * @method insertAfter
  1894. * @param { Node } node 目标节点
  1895. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  1896. * @return { Node } 新插入的节点
  1897. */
  1898. insertAfter:function (node, newNode) {
  1899. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  1900. node.parentNode.appendChild(newNode);
  1901. },
  1902. /**
  1903. * 删除节点node及其下属的所有节点
  1904. * @method remove
  1905. * @param { Node } node 需要删除的节点对象
  1906. * @return { Node } 返回刚删除的节点对象
  1907. * @example
  1908. * ```html
  1909. * <div id="test">
  1910. * <div id="child">你好</div>
  1911. * </div>
  1912. * <script>
  1913. * UE.dom.domUtils.remove( document.body, false );
  1914. * //output: false
  1915. * console.log( document.getElementById( "child" ) !== null );
  1916. * </script>
  1917. * ```
  1918. */
  1919. /**
  1920. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  1921. * @method remove
  1922. * @param { Node } node 需要删除的节点对象
  1923. * @param { Boolean } keepChildren 是否需要保留子节点
  1924. * @return { Node } 返回刚删除的节点对象
  1925. * @example
  1926. * ```html
  1927. * <div id="test">
  1928. * <div id="child">你好</div>
  1929. * </div>
  1930. * <script>
  1931. * UE.dom.domUtils.remove( document.body, true );
  1932. * //output: true
  1933. * console.log( document.getElementById( "child" ) !== null );
  1934. * </script>
  1935. * ```
  1936. */
  1937. remove:function (node, keepChildren) {
  1938. var parent = node.parentNode,
  1939. child;
  1940. if (parent) {
  1941. if (keepChildren && node.hasChildNodes()) {
  1942. while (child = node.firstChild) {
  1943. parent.insertBefore(child, node);
  1944. }
  1945. }
  1946. parent.removeChild(node);
  1947. }
  1948. return node;
  1949. },
  1950. /**
  1951. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  1952. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  1953. * @method getNextDomNode
  1954. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1955. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1956. * @example
  1957. * ```html
  1958. * <body>
  1959. * <div id="test">
  1960. * <span></span>
  1961. * </div>
  1962. * <i>xxx</i>
  1963. * </body>
  1964. * <script>
  1965. *
  1966. * //output: i节点
  1967. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1968. *
  1969. * </script>
  1970. * ```
  1971. * @example
  1972. * ```html
  1973. * <body>
  1974. * <div>
  1975. * <span></span>
  1976. * <i id="test">xxx</i>
  1977. * </div>
  1978. * <b>xxx</b>
  1979. * </body>
  1980. * <script>
  1981. *
  1982. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  1983. * //output: b节点
  1984. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  1985. *
  1986. * </script>
  1987. * ```
  1988. */
  1989. /**
  1990. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  1991. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  1992. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  1993. * @method getNextDomNode
  1994. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  1995. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  1996. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  1997. * @see UE.dom.domUtils.getNextDomNode(Node)
  1998. */
  1999. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2000. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2001. },
  2002. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2003. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2004. },
  2005. /**
  2006. * 检测节点node是否属是UEditor定义的bookmark节点
  2007. * @method isBookmarkNode
  2008. * @private
  2009. * @param { Node } node 需要检测的节点对象
  2010. * @return { Boolean } 是否是bookmark节点
  2011. * @example
  2012. * ```html
  2013. * <span id="_baidu_bookmark_1"></span>
  2014. * <script>
  2015. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2016. * //output: true
  2017. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2018. * </script>
  2019. * ```
  2020. */
  2021. isBookmarkNode:function (node) {
  2022. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2023. },
  2024. /**
  2025. * 获取节点node所属的window对象
  2026. * @method getWindow
  2027. * @param { Node } node 节点对象
  2028. * @return { Window } 当前节点所属的window对象
  2029. * @example
  2030. * ```javascript
  2031. * //output: true
  2032. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2033. * ```
  2034. */
  2035. getWindow:function (node) {
  2036. var doc = node.ownerDocument || node;
  2037. return doc.defaultView || doc.parentWindow;
  2038. },
  2039. /**
  2040. * 获取离nodeA与nodeB最近的公共的祖先节点
  2041. * @method getCommonAncestor
  2042. * @param { Node } nodeA 第一个节点
  2043. * @param { Node } nodeB 第二个节点
  2044. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2045. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2046. * @example
  2047. * ```javascript
  2048. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2049. * //output: true
  2050. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2051. * ```
  2052. */
  2053. getCommonAncestor:function (nodeA, nodeB) {
  2054. if (nodeA === nodeB)
  2055. return nodeA;
  2056. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2057. while (parent = parent.parentNode) {
  2058. if (parent === nodeB) {
  2059. return parent;
  2060. }
  2061. parentsA.push(parent);
  2062. }
  2063. parent = nodeB;
  2064. while (parent = parent.parentNode) {
  2065. if (parent === nodeA)
  2066. return parent;
  2067. parentsB.push(parent);
  2068. }
  2069. parentsA.reverse();
  2070. parentsB.reverse();
  2071. while (i++, parentsA[i] === parentsB[i]) {
  2072. }
  2073. return i == 0 ? null : parentsA[i - 1];
  2074. },
  2075. /**
  2076. * 清除node节点左右连续为空的兄弟inline节点
  2077. * @method clearEmptySibling
  2078. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2079. * 则这些兄弟节点将被删除
  2080. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2081. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2082. * @example
  2083. * ```html
  2084. * <body>
  2085. * <div></div>
  2086. * <span id="test"></span>
  2087. * <i></i>
  2088. * <b></b>
  2089. * <em>xxx</em>
  2090. * <span></span>
  2091. * </body>
  2092. * <script>
  2093. *
  2094. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2095. *
  2096. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2097. * console.log( document.body.innerHTML );
  2098. *
  2099. * </script>
  2100. * ```
  2101. */
  2102. /**
  2103. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2104. * 则忽略对右边兄弟节点的操作。
  2105. * @method clearEmptySibling
  2106. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2107. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2108. * 则这些兄弟节点将被删除
  2109. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2110. */
  2111. /**
  2112. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2113. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2114. * @method clearEmptySibling
  2115. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2116. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2117. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2118. * 则这些兄弟节点将被删除
  2119. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2120. */
  2121. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2122. function clear(next, dir) {
  2123. var tmpNode;
  2124. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2125. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2126. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2127. tmpNode = next[dir];
  2128. domUtils.remove(next);
  2129. next = tmpNode;
  2130. }
  2131. }
  2132. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2133. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2134. },
  2135. /**
  2136. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2137. * @method split
  2138. * @param { Node } textNode 需要拆分的文本节点对象
  2139. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2140. * @return { Node } 拆分后形成的新节点
  2141. * @example
  2142. * ```html
  2143. * <div id="test">abcdef</div>
  2144. * <script>
  2145. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2146. * //output: def
  2147. * console.log( newNode.nodeValue );
  2148. * </script>
  2149. * ```
  2150. */
  2151. split:function (node, offset) {
  2152. var doc = node.ownerDocument;
  2153. if (browser.ie && offset == node.nodeValue.length) {
  2154. var next = doc.createTextNode('');
  2155. return domUtils.insertAfter(node, next);
  2156. }
  2157. var retval = node.splitText(offset);
  2158. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2159. if (browser.ie8) {
  2160. var tmpNode = doc.createTextNode('');
  2161. domUtils.insertAfter(retval, tmpNode);
  2162. domUtils.remove(tmpNode);
  2163. }
  2164. return retval;
  2165. },
  2166. /**
  2167. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2168. * @method isWhitespace
  2169. * @param { Node } node 需要检测的节点对象
  2170. * @return { Boolean } 检测的节点是否为空
  2171. * @example
  2172. * ```html
  2173. * <div id="test">
  2174. *
  2175. * </div>
  2176. * <script>
  2177. * //output: true
  2178. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2179. * </script>
  2180. * ```
  2181. */
  2182. isWhitespace:function (node) {
  2183. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2184. },
  2185. /**
  2186. * 获取元素element相对于viewport的位置坐标
  2187. * @method getXY
  2188. * @param { Node } element 需要计算位置的节点对象
  2189. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2190. * y代表垂直偏移距离。
  2191. *
  2192. * @example
  2193. * ```javascript
  2194. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2195. * //output: test的坐标为: 12, 24
  2196. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2197. * ```
  2198. */
  2199. getXY:function (element) {
  2200. var x = 0, y = 0;
  2201. while (element.offsetParent) {
  2202. y += element.offsetTop;
  2203. x += element.offsetLeft;
  2204. element = element.offsetParent;
  2205. }
  2206. return { 'x':x, 'y':y};
  2207. },
  2208. /**
  2209. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2210. * @method on
  2211. * @param { Node } element 需要绑定事件的节点对象
  2212. * @param { String } type 绑定的事件类型
  2213. * @param { Function } handler 事件处理器
  2214. * @example
  2215. * ```javascript
  2216. * UE.dom.domUtils.on(document.body,"click",function(e){
  2217. * //e为事件对象,this为被点击元素对戏那个
  2218. * });
  2219. * ```
  2220. */
  2221. /**
  2222. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2223. * @method on
  2224. * @param { Node } element 需要绑定事件的节点对象
  2225. * @param { Array } type 绑定的事件类型数组
  2226. * @param { Function } handler 事件处理器
  2227. * @example
  2228. * ```javascript
  2229. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2230. * //evt为事件对象,this为被点击元素对象
  2231. * });
  2232. * ```
  2233. */
  2234. on:function (element, type, handler) {
  2235. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2236. k = types.length;
  2237. if (k) while (k--) {
  2238. type = types[k];
  2239. if (element.addEventListener) {
  2240. element.addEventListener(type, handler, false);
  2241. } else {
  2242. if (!handler._d) {
  2243. handler._d = {
  2244. els : []
  2245. };
  2246. }
  2247. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2248. if (!handler._d[key] || index == -1) {
  2249. if(index == -1){
  2250. handler._d.els.push(element);
  2251. }
  2252. if(!handler._d[key]){
  2253. handler._d[key] = function (evt) {
  2254. return handler.call(evt.srcElement, evt || window.event);
  2255. };
  2256. }
  2257. element.attachEvent('on' + type, handler._d[key]);
  2258. }
  2259. }
  2260. }
  2261. element = null;
  2262. },
  2263. /**
  2264. * 解除DOM事件绑定
  2265. * @method un
  2266. * @param { Node } element 需要解除事件绑定的节点对象
  2267. * @param { String } type 需要接触绑定的事件类型
  2268. * @param { Function } handler 对应的事件处理器
  2269. * @example
  2270. * ```javascript
  2271. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2272. * //evt为事件对象,this为被点击元素对象
  2273. * });
  2274. * ```
  2275. */
  2276. /**
  2277. * 解除DOM事件绑定
  2278. * @method un
  2279. * @param { Node } element 需要解除事件绑定的节点对象
  2280. * @param { Array } type 需要接触绑定的事件类型数组
  2281. * @param { Function } handler 对应的事件处理器
  2282. * @example
  2283. * ```javascript
  2284. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2285. * //evt为事件对象,this为被点击元素对象
  2286. * });
  2287. * ```
  2288. */
  2289. un:function (element, type, handler) {
  2290. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2291. k = types.length;
  2292. if (k) while (k--) {
  2293. type = types[k];
  2294. if (element.removeEventListener) {
  2295. element.removeEventListener(type, handler, false);
  2296. } else {
  2297. var key = type + handler.toString();
  2298. try{
  2299. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2300. }catch(e){}
  2301. if (handler._d && handler._d[key]) {
  2302. var index = utils.indexOf(handler._d.els,element);
  2303. if(index!=-1){
  2304. handler._d.els.splice(index,1);
  2305. }
  2306. handler._d.els.length == 0 && delete handler._d[key];
  2307. }
  2308. }
  2309. }
  2310. },
  2311. /**
  2312. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2313. * @method isSameElement
  2314. * @param { Node } nodeA 需要比较的节点
  2315. * @param { Node } nodeB 需要比较的节点
  2316. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2317. * @example
  2318. * ```html
  2319. * <span style="font-size:12px">ssss</span>
  2320. * <span style="font-size:12px">bbbbb</span>
  2321. * <span style="font-size:13px">ssss</span>
  2322. * <span style="font-size:14px">bbbbb</span>
  2323. *
  2324. * <script>
  2325. *
  2326. * var nodes = document.getElementsByTagName( "span" );
  2327. *
  2328. * //output: true
  2329. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2330. *
  2331. * //output: false
  2332. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2333. *
  2334. * </script>
  2335. * ```
  2336. */
  2337. isSameElement:function (nodeA, nodeB) {
  2338. if (nodeA.tagName != nodeB.tagName) {
  2339. return false;
  2340. }
  2341. var thisAttrs = nodeA.attributes,
  2342. otherAttrs = nodeB.attributes;
  2343. if (!ie && thisAttrs.length != otherAttrs.length) {
  2344. return false;
  2345. }
  2346. var attrA, attrB, al = 0, bl = 0;
  2347. for (var i = 0; attrA = thisAttrs[i++];) {
  2348. if (attrA.nodeName == 'style') {
  2349. if (attrA.specified) {
  2350. al++;
  2351. }
  2352. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2353. continue;
  2354. } else {
  2355. return false;
  2356. }
  2357. }
  2358. if (ie) {
  2359. if (attrA.specified) {
  2360. al++;
  2361. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2362. } else {
  2363. continue;
  2364. }
  2365. } else {
  2366. attrB = nodeB.attributes[attrA.nodeName];
  2367. }
  2368. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2369. return false;
  2370. }
  2371. }
  2372. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2373. if (ie) {
  2374. for (i = 0; attrB = otherAttrs[i++];) {
  2375. if (attrB.specified) {
  2376. bl++;
  2377. }
  2378. }
  2379. if (al != bl) {
  2380. return false;
  2381. }
  2382. }
  2383. return true;
  2384. },
  2385. /**
  2386. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2387. * @method isSameStyle
  2388. * @param { Node } nodeA 需要比较的节点
  2389. * @param { Node } nodeB 需要比较的节点
  2390. * @return { Boolean } 两个节点是否具有相同的style属性值
  2391. * @example
  2392. * ```html
  2393. * <span style="font-size:12px">ssss</span>
  2394. * <span style="font-size:12px">bbbbb</span>
  2395. * <span style="font-size:13px">ssss</span>
  2396. * <span style="font-size:14px">bbbbb</span>
  2397. *
  2398. * <script>
  2399. *
  2400. * var nodes = document.getElementsByTagName( "span" );
  2401. *
  2402. * //output: true
  2403. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2404. *
  2405. * //output: false
  2406. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2407. *
  2408. * </script>
  2409. * ```
  2410. */
  2411. isSameStyle:function (nodeA, nodeB) {
  2412. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2413. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2414. if (browser.opera) {
  2415. styleA = nodeA.style;
  2416. styleB = nodeB.style;
  2417. if (styleA.length != styleB.length)
  2418. return false;
  2419. for (var p in styleA) {
  2420. if (/^(\d+|csstext)$/i.test(p)) {
  2421. continue;
  2422. }
  2423. if (styleA[p] != styleB[p]) {
  2424. return false;
  2425. }
  2426. }
  2427. return true;
  2428. }
  2429. if (!styleA || !styleB) {
  2430. return styleA == styleB;
  2431. }
  2432. styleA = styleA.split(';');
  2433. styleB = styleB.split(';');
  2434. if (styleA.length != styleB.length) {
  2435. return false;
  2436. }
  2437. for (var i = 0, ci; ci = styleA[i++];) {
  2438. if (utils.indexOf(styleB, ci) == -1) {
  2439. return false;
  2440. }
  2441. }
  2442. return true;
  2443. },
  2444. /**
  2445. * 检查节点node是否为block元素
  2446. * @method isBlockElm
  2447. * @param { Node } node 需要检测的节点对象
  2448. * @return { Boolean } 是否是block元素节点
  2449. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2450. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2451. * @example
  2452. * ```html
  2453. * <span id="test1" style="display: block"></span>
  2454. * <span id="test2"></span>
  2455. * <div id="test3" style="display: inline"></div>
  2456. *
  2457. * <script>
  2458. *
  2459. * //output: true
  2460. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2461. *
  2462. * //output: false
  2463. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2464. *
  2465. * //output: true
  2466. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2467. *
  2468. * </script>
  2469. * ```
  2470. */
  2471. isBlockElm:function (node) {
  2472. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2473. },
  2474. /**
  2475. * 检测node节点是否为body节点
  2476. * @method isBody
  2477. * @param { Element } node 需要检测的dom元素
  2478. * @return { Boolean } 给定的元素是否是body元素
  2479. * @example
  2480. * ```javascript
  2481. * //output: true
  2482. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2483. * ```
  2484. */
  2485. isBody:function (node) {
  2486. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2487. },
  2488. /**
  2489. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2490. * 拆分形成的两个节点之间是node节点
  2491. * @method breakParent
  2492. * @param { Node } node 作为分界的节点对象
  2493. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2494. * @return { Node } 给定的node分界节点
  2495. * @example
  2496. * ```javascript
  2497. *
  2498. * var node = document.createElement("span"),
  2499. * wrapNode = document.createElement( "div" ),
  2500. * parent = document.createElement("p");
  2501. *
  2502. * parent.appendChild( node );
  2503. * wrapNode.appendChild( parent );
  2504. *
  2505. * //拆分前
  2506. * //output: <p><span></span></p>
  2507. * console.log( wrapNode.innerHTML );
  2508. *
  2509. *
  2510. * UE.dom.domUtils.breakParent( node, parent );
  2511. * //拆分后
  2512. * //output: <p></p><span></span><p></p>
  2513. * console.log( wrapNode.innerHTML );
  2514. *
  2515. * ```
  2516. */
  2517. breakParent:function (node, parent) {
  2518. var tmpNode,
  2519. parentClone = node,
  2520. clone = node,
  2521. leftNodes,
  2522. rightNodes;
  2523. do {
  2524. parentClone = parentClone.parentNode;
  2525. if (leftNodes) {
  2526. tmpNode = parentClone.cloneNode(false);
  2527. tmpNode.appendChild(leftNodes);
  2528. leftNodes = tmpNode;
  2529. tmpNode = parentClone.cloneNode(false);
  2530. tmpNode.appendChild(rightNodes);
  2531. rightNodes = tmpNode;
  2532. } else {
  2533. leftNodes = parentClone.cloneNode(false);
  2534. rightNodes = leftNodes.cloneNode(false);
  2535. }
  2536. while (tmpNode = clone.previousSibling) {
  2537. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2538. }
  2539. while (tmpNode = clone.nextSibling) {
  2540. rightNodes.appendChild(tmpNode);
  2541. }
  2542. clone = parentClone;
  2543. } while (parent !== parentClone);
  2544. tmpNode = parent.parentNode;
  2545. tmpNode.insertBefore(leftNodes, parent);
  2546. tmpNode.insertBefore(rightNodes, parent);
  2547. tmpNode.insertBefore(node, rightNodes);
  2548. domUtils.remove(parent);
  2549. return node;
  2550. },
  2551. /**
  2552. * 检查节点node是否是空inline节点
  2553. * @method isEmptyInlineElement
  2554. * @param { Node } node 需要检测的节点对象
  2555. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2556. * @example
  2557. * ```html
  2558. * <b><i></i></b> => 1
  2559. * <b><i></i><u></u></b> => 1
  2560. * <b></b> => 1
  2561. * <b>xx<i></i></b> => 0
  2562. * ```
  2563. */
  2564. isEmptyInlineElement:function (node) {
  2565. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2566. return 0;
  2567. }
  2568. node = node.firstChild;
  2569. while (node) {
  2570. //如果是创建的bookmark就跳过
  2571. if (domUtils.isBookmarkNode(node)) {
  2572. return 0;
  2573. }
  2574. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2575. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2576. ) {
  2577. return 0;
  2578. }
  2579. node = node.nextSibling;
  2580. }
  2581. return 1;
  2582. },
  2583. /**
  2584. * 删除node节点下首尾两端的空白文本子节点
  2585. * @method trimWhiteTextNode
  2586. * @param { Element } node 需要执行删除操作的元素对象
  2587. * @example
  2588. * ```javascript
  2589. * var node = document.createElement("div");
  2590. *
  2591. * node.appendChild( document.createTextNode( "" ) );
  2592. *
  2593. * node.appendChild( document.createElement("div") );
  2594. *
  2595. * node.appendChild( document.createTextNode( "" ) );
  2596. *
  2597. * //3
  2598. * console.log( node.childNodes.length );
  2599. *
  2600. * UE.dom.domUtils.trimWhiteTextNode( node );
  2601. *
  2602. * //1
  2603. * console.log( node.childNodes.length );
  2604. * ```
  2605. */
  2606. trimWhiteTextNode:function (node) {
  2607. function remove(dir) {
  2608. var child;
  2609. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2610. node.removeChild(child);
  2611. }
  2612. }
  2613. remove('firstChild');
  2614. remove('lastChild');
  2615. },
  2616. /*
  2617. * 合并node节点下相同的子节点
  2618. * @name mergeChild
  2619. * @desc
  2620. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2621. * @example
  2622. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2623. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2624. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2625. */
  2626. mergeChild:function (node, tagName, attrs) {
  2627. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2628. for (var i = 0, ci; ci = list[i++];) {
  2629. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2630. continue;
  2631. }
  2632. //span单独处理
  2633. if (ci.tagName.toLowerCase() == 'span') {
  2634. if (node === ci.parentNode) {
  2635. domUtils.trimWhiteTextNode(node);
  2636. if (node.childNodes.length == 1) {
  2637. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2638. domUtils.remove(ci, true);
  2639. continue;
  2640. }
  2641. }
  2642. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2643. if (attrs) {
  2644. var style = attrs.style;
  2645. if (style) {
  2646. style = style.split(';');
  2647. for (var j = 0, s; s = style[j++];) {
  2648. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2649. }
  2650. }
  2651. }
  2652. if (domUtils.isSameStyle(ci, node)) {
  2653. domUtils.remove(ci, true);
  2654. }
  2655. continue;
  2656. }
  2657. if (domUtils.isSameElement(node, ci)) {
  2658. domUtils.remove(ci, true);
  2659. }
  2660. }
  2661. },
  2662. /**
  2663. * 原生方法getElementsByTagName的封装
  2664. * @method getElementsByTagName
  2665. * @param { Node } node 目标节点对象
  2666. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2667. * @return { Array } 符合条件的节点集合
  2668. */
  2669. getElementsByTagName:function (node, name,filter) {
  2670. if(filter && utils.isString(filter)){
  2671. var className = filter;
  2672. filter = function(node){return domUtils.hasClass(node,className)}
  2673. }
  2674. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2675. var arr = [];
  2676. for(var n = 0,ni;ni=name[n++];){
  2677. var list = node.getElementsByTagName(ni);
  2678. for (var i = 0, ci; ci = list[i++];) {
  2679. if(!filter || filter(ci))
  2680. arr.push(ci);
  2681. }
  2682. }
  2683. return arr;
  2684. },
  2685. /**
  2686. * 将节点node提取到父节点上
  2687. * @method mergeToParent
  2688. * @param { Element } node 需要提取的元素对象
  2689. * @example
  2690. * ```html
  2691. * <div id="parent">
  2692. * <div id="sub">
  2693. * <span id="child"></span>
  2694. * </div>
  2695. * </div>
  2696. *
  2697. * <script>
  2698. *
  2699. * var child = document.getElementById( "child" );
  2700. *
  2701. * //output: sub
  2702. * console.log( child.parentNode.id );
  2703. *
  2704. * UE.dom.domUtils.mergeToParent( child );
  2705. *
  2706. * //output: parent
  2707. * console.log( child.parentNode.id );
  2708. *
  2709. * </script>
  2710. * ```
  2711. */
  2712. mergeToParent:function (node) {
  2713. var parent = node.parentNode;
  2714. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2715. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2716. domUtils.trimWhiteTextNode(parent);
  2717. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2718. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2719. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2720. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2721. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2722. parent = parent.parentNode;
  2723. continue;
  2724. } else {
  2725. parent.style.cssText += ";" + node.style.cssText;
  2726. //trace:952 a标签要保持下划线
  2727. if (parent.tagName == 'A') {
  2728. parent.style.textDecoration = 'underline';
  2729. }
  2730. }
  2731. }
  2732. if (parent.tagName != 'A') {
  2733. parent === node.parentNode && domUtils.remove(node, true);
  2734. break;
  2735. }
  2736. }
  2737. parent = parent.parentNode;
  2738. }
  2739. },
  2740. /**
  2741. * 合并节点node的左右兄弟节点
  2742. * @method mergeSibling
  2743. * @param { Element } node 需要合并的目标节点
  2744. * @example
  2745. * ```html
  2746. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2747. *
  2748. * <script>
  2749. * var demoNode = document.getElementById("test");
  2750. * UE.dom.domUtils.mergeSibling( demoNode );
  2751. * //output: xxxxoooxxxx
  2752. * console.log( demoNode.innerHTML );
  2753. * </script>
  2754. * ```
  2755. */
  2756. /**
  2757. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2758. * @method mergeSibling
  2759. * @param { Element } node 需要合并的目标节点
  2760. * @param { Boolean } ignorePre 是否忽略合并左节点
  2761. * @example
  2762. * ```html
  2763. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2764. *
  2765. * <script>
  2766. * var demoNode = document.getElementById("test");
  2767. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2768. * //output: oooxxxx
  2769. * console.log( demoNode.innerHTML );
  2770. * </script>
  2771. * ```
  2772. */
  2773. /**
  2774. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2775. * @method mergeSibling
  2776. * @param { Element } node 需要合并的目标节点
  2777. * @param { Boolean } ignorePre 是否忽略合并左节点
  2778. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2779. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2780. * @example
  2781. * ```html
  2782. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2783. *
  2784. * <script>
  2785. * var demoNode = document.getElementById("test");
  2786. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2787. * //output: xxxxooo
  2788. * console.log( demoNode.innerHTML );
  2789. * </script>
  2790. * ```
  2791. */
  2792. mergeSibling:function (node, ignorePre, ignoreNext) {
  2793. function merge(rtl, start, node) {
  2794. var next;
  2795. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2796. while (next.firstChild) {
  2797. if (start == 'firstChild') {
  2798. node.insertBefore(next.lastChild, node.firstChild);
  2799. } else {
  2800. node.appendChild(next.firstChild);
  2801. }
  2802. }
  2803. domUtils.remove(next);
  2804. }
  2805. }
  2806. !ignorePre && merge('previousSibling', 'firstChild', node);
  2807. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2808. },
  2809. /**
  2810. * 设置节点node及其子节点不会被选中
  2811. * @method unSelectable
  2812. * @param { Element } node 需要执行操作的dom元素
  2813. * @remind 执行该操作后的节点, 将不能被鼠标选中
  2814. * @example
  2815. * ```javascript
  2816. * UE.dom.domUtils.unSelectable( document.body );
  2817. * ```
  2818. */
  2819. unSelectable:ie || browser.opera ? function (node) {
  2820. //for ie9
  2821. node.onselectstart = function () {
  2822. return false;
  2823. };
  2824. node.onclick = node.onkeyup = node.onkeydown = function () {
  2825. return false;
  2826. };
  2827. node.unselectable = 'on';
  2828. node.setAttribute("unselectable", "on");
  2829. for (var i = 0, ci; ci = node.all[i++];) {
  2830. switch (ci.tagName.toLowerCase()) {
  2831. case 'iframe' :
  2832. case 'textarea' :
  2833. case 'input' :
  2834. case 'select' :
  2835. break;
  2836. default :
  2837. ci.unselectable = 'on';
  2838. node.setAttribute("unselectable", "on");
  2839. }
  2840. }
  2841. } : function (node) {
  2842. node.style.MozUserSelect =
  2843. node.style.webkitUserSelect =
  2844. node.style.KhtmlUserSelect = 'none';
  2845. },
  2846. /**
  2847. * 删除节点node上的指定属性名称的属性
  2848. * @method removeAttributes
  2849. * @param { Node } node 需要删除属性的节点对象
  2850. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  2851. * @example
  2852. * ```html
  2853. * <div id="wrap">
  2854. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  2855. * </div>
  2856. *
  2857. * <script>
  2858. *
  2859. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  2860. *
  2861. * //output: <span style="font-size:14px;">xxxxx</span>
  2862. * console.log( document.getElementById("wrap").innerHTML );
  2863. *
  2864. * </script>
  2865. * ```
  2866. */
  2867. /**
  2868. * 删除节点node上的指定属性名称的属性
  2869. * @method removeAttributes
  2870. * @param { Node } node 需要删除属性的节点对象
  2871. * @param { Array } attrNames 需要删除的属性名数组
  2872. * @example
  2873. * ```html
  2874. * <div id="wrap">
  2875. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  2876. * </div>
  2877. *
  2878. * <script>
  2879. *
  2880. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  2881. *
  2882. * //output: <span style="font-size:14px;">xxxxx</span>
  2883. * console.log( document.getElementById("wrap").innerHTML );
  2884. *
  2885. * </script>
  2886. * ```
  2887. */
  2888. removeAttributes:function (node, attrNames) {
  2889. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  2890. for (var i = 0, ci; ci = attrNames[i++];) {
  2891. ci = attrFix[ci] || ci;
  2892. switch (ci) {
  2893. case 'className':
  2894. node[ci] = '';
  2895. break;
  2896. case 'style':
  2897. node.style.cssText = '';
  2898. /*update-begin--Author:dangzhenghui Date:20170625 for:ueditor bug*/
  2899. if (node.getAttributeNode('style') !== null){
  2900. !browser.ie && node.removeAttributeNode(node.getAttributeNode('style'))
  2901. }
  2902. /*update-end--Author:dangzhenghui Date:20170625 for:ueditor bug*/
  2903. }
  2904. node.removeAttribute(ci);
  2905. }
  2906. },
  2907. /**
  2908. * 在doc下创建一个标签名为tag,属性为attrs的元素
  2909. * @method createElement
  2910. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  2911. * @param { String } tagName 需要创建的元素的标签名
  2912. * @param { Object } attrs 新创建的元素的属性key-value集合
  2913. * @return { Element } 新创建的元素对象
  2914. * @example
  2915. * ```javascript
  2916. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  2917. * id: 'test'
  2918. * } );
  2919. *
  2920. * //output: DIV
  2921. * console.log( ele.tagName );
  2922. *
  2923. * //output: test
  2924. * console.log( ele.id );
  2925. *
  2926. * ```
  2927. */
  2928. createElement:function (doc, tag, attrs) {
  2929. return domUtils.setAttributes(doc.createElement(tag), attrs)
  2930. },
  2931. /**
  2932. * 为节点node添加属性attrs,attrs为属性键值对
  2933. * @method setAttributes
  2934. * @param { Element } node 需要设置属性的元素对象
  2935. * @param { Object } attrs 需要设置的属性名-值对
  2936. * @return { Element } 设置属性的元素对象
  2937. * @example
  2938. * ```html
  2939. * <span id="test"></span>
  2940. *
  2941. * <script>
  2942. *
  2943. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  2944. * id: 'demo'
  2945. * } );
  2946. *
  2947. * //output: demo
  2948. * console.log( testNode.id );
  2949. *
  2950. * </script>
  2951. *
  2952. */
  2953. setAttributes:function (node, attrs) {
  2954. for (var attr in attrs) {
  2955. if(attrs.hasOwnProperty(attr)){
  2956. var value = attrs[attr];
  2957. switch (attr) {
  2958. case 'class':
  2959. //ie下要这样赋值,setAttribute不起作用
  2960. node.className = value;
  2961. break;
  2962. case 'style' :
  2963. node.style.cssText = node.style.cssText + ";" + value;
  2964. break;
  2965. case 'innerHTML':
  2966. node[attr] = value;
  2967. break;
  2968. case 'value':
  2969. node.value = value;
  2970. break;
  2971. default:
  2972. node.setAttribute(attrFix[attr] || attr, value);
  2973. }
  2974. }
  2975. }
  2976. return node;
  2977. },
  2978. /**
  2979. * 获取元素element经过计算后的样式值
  2980. * @method getComputedStyle
  2981. * @param { Element } element 需要获取样式的元素对象
  2982. * @param { String } styleName 需要获取的样式名
  2983. * @return { String } 获取到的样式值
  2984. * @example
  2985. * ```html
  2986. * <style type="text/css">
  2987. * #test {
  2988. * font-size: 15px;
  2989. * }
  2990. * </style>
  2991. *
  2992. * <span id="test"></span>
  2993. *
  2994. * <script>
  2995. * //output: 15px
  2996. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  2997. * </script>
  2998. * ```
  2999. */
  3000. getComputedStyle:function (element, styleName) {
  3001. //一下的属性单独处理
  3002. var pros = 'width height top left';
  3003. if(pros.indexOf(styleName) > -1){
  3004. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3005. }
  3006. //忽略文本节点
  3007. if (element.nodeType == 3) {
  3008. element = element.parentNode;
  3009. }
  3010. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3011. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3012. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3013. var span = element.ownerDocument.createElement('span');
  3014. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3015. span.innerHTML = '.';
  3016. element.appendChild(span);
  3017. var result = span.offsetHeight;
  3018. element.removeChild(span);
  3019. span = null;
  3020. return result + 'px';
  3021. }
  3022. try {
  3023. var value = domUtils.getStyle(element, styleName) ||
  3024. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3025. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3026. } catch (e) {
  3027. return "";
  3028. }
  3029. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3030. },
  3031. /**
  3032. * 删除元素element指定的className
  3033. * @method removeClasses
  3034. * @param { Element } ele 需要删除class的元素节点
  3035. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3036. * @example
  3037. * ```html
  3038. * <span id="test" class="test1 test2 test3">xxx</span>
  3039. *
  3040. * <script>
  3041. *
  3042. * var testNode = document.getElementById( "test" );
  3043. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3044. *
  3045. * //output: test3
  3046. * console.log( testNode.className );
  3047. *
  3048. * </script>
  3049. * ```
  3050. */
  3051. /**
  3052. * 删除元素element指定的className
  3053. * @method removeClasses
  3054. * @param { Element } ele 需要删除class的元素节点
  3055. * @param { Array } classNames 需要删除的className数组
  3056. * @example
  3057. * ```html
  3058. * <span id="test" class="test1 test2 test3">xxx</span>
  3059. *
  3060. * <script>
  3061. *
  3062. * var testNode = document.getElementById( "test" );
  3063. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3064. *
  3065. * //output: test3
  3066. * console.log( testNode.className );
  3067. *
  3068. * </script>
  3069. * ```
  3070. */
  3071. removeClasses:function (elm, classNames) {
  3072. classNames = utils.isArray(classNames) ? classNames :
  3073. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3074. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3075. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3076. }
  3077. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3078. if(cls){
  3079. elm.className = cls;
  3080. }else{
  3081. domUtils.removeAttributes(elm,['class']);
  3082. }
  3083. },
  3084. /**
  3085. * 给元素element添加className
  3086. * @method addClass
  3087. * @param { Node } ele 需要增加className的元素
  3088. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3089. * @remind 相同的类名不会被重复添加
  3090. * @example
  3091. * ```html
  3092. * <span id="test" class="cls1 cls2"></span>
  3093. *
  3094. * <script>
  3095. * var testNode = document.getElementById("test");
  3096. *
  3097. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3098. *
  3099. * //output: cl1 cls2 cls3 cls4
  3100. * console.log( testNode.className );
  3101. *
  3102. * <script>
  3103. * ```
  3104. */
  3105. /**
  3106. * 给元素element添加className
  3107. * @method addClass
  3108. * @param { Node } ele 需要增加className的元素
  3109. * @param { Array } classNames 需要添加的className的数组
  3110. * @remind 相同的类名不会被重复添加
  3111. * @example
  3112. * ```html
  3113. * <span id="test" class="cls1 cls2"></span>
  3114. *
  3115. * <script>
  3116. * var testNode = document.getElementById("test");
  3117. *
  3118. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3119. *
  3120. * //output: cl1 cls2 cls3 cls4
  3121. * console.log( testNode.className );
  3122. *
  3123. * <script>
  3124. * ```
  3125. */
  3126. addClass:function (elm, classNames) {
  3127. if(!elm)return;
  3128. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3129. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3130. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3131. cls += ' ' + ci;
  3132. }
  3133. }
  3134. elm.className = utils.trim(cls);
  3135. },
  3136. /**
  3137. * 判断元素element是否包含给定的样式类名className
  3138. * @method hasClass
  3139. * @param { Node } ele 需要检测的元素
  3140. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3141. * @return { Boolean } 元素是否包含所有给定的className
  3142. * @example
  3143. * ```html
  3144. * <span id="test1" class="cls1 cls2"></span>
  3145. *
  3146. * <script>
  3147. * var test1 = document.getElementById("test1");
  3148. *
  3149. * //output: false
  3150. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3151. *
  3152. * //output: true
  3153. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3154. * </script>
  3155. * ```
  3156. */
  3157. /**
  3158. * 判断元素element是否包含给定的样式类名className
  3159. * @method hasClass
  3160. * @param { Node } ele 需要检测的元素
  3161. * @param { Array } classNames 需要检测的className数组
  3162. * @return { Boolean } 元素是否包含所有给定的className
  3163. * @example
  3164. * ```html
  3165. * <span id="test1" class="cls1 cls2"></span>
  3166. *
  3167. * <script>
  3168. * var test1 = document.getElementById("test1");
  3169. *
  3170. * //output: false
  3171. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3172. *
  3173. * //output: true
  3174. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3175. * </script>
  3176. * ```
  3177. */
  3178. hasClass:function (element, className) {
  3179. if(utils.isRegExp(className)){
  3180. return className.test(element.className)
  3181. }
  3182. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3183. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3184. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3185. return false;
  3186. }
  3187. }
  3188. return i - 1 == className.length;
  3189. },
  3190. /**
  3191. * 阻止事件默认行为
  3192. * @method preventDefault
  3193. * @param { Event } evt 需要阻止默认行为的事件对象
  3194. * @example
  3195. * ```javascript
  3196. * UE.dom.domUtils.preventDefault( evt );
  3197. * ```
  3198. */
  3199. preventDefault:function (evt) {
  3200. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3201. },
  3202. /**
  3203. * 删除元素element指定的样式
  3204. * @method removeStyle
  3205. * @param { Element } element 需要删除样式的元素
  3206. * @param { String } styleName 需要删除的样式名
  3207. * @example
  3208. * ```html
  3209. * <span id="test" style="color: red; background: blue;"></span>
  3210. *
  3211. * <script>
  3212. *
  3213. * var testNode = document.getElementById("test");
  3214. *
  3215. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3216. *
  3217. * //output: background: blue;
  3218. * console.log( testNode.style.cssText );
  3219. *
  3220. * </script>
  3221. * ```
  3222. */
  3223. removeStyle:function (element, name) {
  3224. if(browser.ie ){
  3225. //针对color先单独处理一下
  3226. if(name == 'color'){
  3227. name = '(^|;)' + name;
  3228. }
  3229. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3230. }else{
  3231. if (element.style.removeProperty) {
  3232. element.style.removeProperty (name);
  3233. }else {
  3234. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3235. }
  3236. }
  3237. if (!element.style.cssText) {
  3238. domUtils.removeAttributes(element, ['style']);
  3239. }
  3240. },
  3241. /**
  3242. * 获取元素element的style属性的指定值
  3243. * @method getStyle
  3244. * @param { Element } element 需要获取属性值的元素
  3245. * @param { String } styleName 需要获取的style的名称
  3246. * @warning 该方法仅获取元素style属性中所标明的值
  3247. * @return { String } 该元素包含指定的style属性值
  3248. * @example
  3249. * ```html
  3250. * <div id="test" style="color: red;"></div>
  3251. *
  3252. * <script>
  3253. *
  3254. * var testNode = document.getElementById( "test" );
  3255. *
  3256. * //output: red
  3257. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3258. *
  3259. * //output: ""
  3260. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3261. *
  3262. * </script>
  3263. * ```
  3264. */
  3265. getStyle:function (element, name) {
  3266. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3267. return utils.fixColor(name, value);
  3268. },
  3269. /**
  3270. * 为元素element设置样式属性值
  3271. * @method setStyle
  3272. * @param { Element } element 需要设置样式的元素
  3273. * @param { String } styleName 样式名
  3274. * @param { String } styleValue 样式值
  3275. * @example
  3276. * ```html
  3277. * <div id="test"></div>
  3278. *
  3279. * <script>
  3280. *
  3281. * var testNode = document.getElementById( "test" );
  3282. *
  3283. * //output: ""
  3284. * console.log( testNode.style.color );
  3285. *
  3286. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3287. * //output: "red"
  3288. * console.log( testNode.style.color );
  3289. *
  3290. * </script>
  3291. * ```
  3292. */
  3293. setStyle:function (element, name, value) {
  3294. element.style[utils.cssStyleToDomStyle(name)] = value;
  3295. if(!utils.trim(element.style.cssText)){
  3296. this.removeAttributes(element,'style')
  3297. }
  3298. },
  3299. /**
  3300. * 为元素element设置多个样式属性值
  3301. * @method setStyles
  3302. * @param { Element } element 需要设置样式的元素
  3303. * @param { Object } styles 样式名值对
  3304. * @example
  3305. * ```html
  3306. * <div id="test"></div>
  3307. *
  3308. * <script>
  3309. *
  3310. * var testNode = document.getElementById( "test" );
  3311. *
  3312. * //output: ""
  3313. * console.log( testNode.style.color );
  3314. *
  3315. * UE.dom.domUtils.setStyles( testNode, {
  3316. * 'color': 'red'
  3317. * } );
  3318. * //output: "red"
  3319. * console.log( testNode.style.color );
  3320. *
  3321. * </script>
  3322. * ```
  3323. */
  3324. setStyles:function (element, styles) {
  3325. for (var name in styles) {
  3326. if (styles.hasOwnProperty(name)) {
  3327. domUtils.setStyle(element, name, styles[name]);
  3328. }
  3329. }
  3330. },
  3331. /**
  3332. * 删除_moz_dirty属性
  3333. * @private
  3334. * @method removeDirtyAttr
  3335. */
  3336. removeDirtyAttr:function (node) {
  3337. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3338. ci.removeAttribute('_moz_dirty');
  3339. }
  3340. node.removeAttribute('_moz_dirty');
  3341. },
  3342. /**
  3343. * 获取子节点的数量
  3344. * @method getChildCount
  3345. * @param { Element } node 需要检测的元素
  3346. * @return { Number } 给定的node元素的子节点数量
  3347. * @example
  3348. * ```html
  3349. * <div id="test">
  3350. * <span></span>
  3351. * </div>
  3352. *
  3353. * <script>
  3354. *
  3355. * //output: 3
  3356. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3357. *
  3358. * </script>
  3359. * ```
  3360. */
  3361. /**
  3362. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3363. * @method getChildCount
  3364. * @param { Element } node 需要检测的元素
  3365. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3366. * @return { Number } 符合过滤条件的node元素的子节点数量
  3367. * @example
  3368. * ```html
  3369. * <div id="test">
  3370. * <span></span>
  3371. * </div>
  3372. *
  3373. * <script>
  3374. *
  3375. * //output: 1
  3376. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3377. *
  3378. * return node.nodeType === 1;
  3379. *
  3380. * } ) );
  3381. *
  3382. * </script>
  3383. * ```
  3384. */
  3385. getChildCount:function (node, fn) {
  3386. var count = 0, first = node.firstChild;
  3387. fn = fn || function () {
  3388. return 1;
  3389. };
  3390. while (first) {
  3391. if (fn(first)) {
  3392. count++;
  3393. }
  3394. first = first.nextSibling;
  3395. }
  3396. return count;
  3397. },
  3398. /**
  3399. * 判断给定节点是否为空节点
  3400. * @method isEmptyNode
  3401. * @param { Node } node 需要检测的节点对象
  3402. * @return { Boolean } 节点是否为空
  3403. * @example
  3404. * ```javascript
  3405. * UE.dom.domUtils.isEmptyNode( document.body );
  3406. * ```
  3407. */
  3408. isEmptyNode:function (node) {
  3409. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3410. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3411. }) == 0
  3412. },
  3413. clearSelectedArr:function (nodes) {
  3414. var node;
  3415. while (node = nodes.pop()) {
  3416. domUtils.removeAttributes(node, ['class']);
  3417. }
  3418. },
  3419. /**
  3420. * 将显示区域滚动到指定节点的位置
  3421. * @method scrollToView
  3422. * @param {Node} node 节点
  3423. * @param {window} win window对象
  3424. * @param {Number} offsetTop 距离上方的偏移量
  3425. */
  3426. scrollToView:function (node, win, offsetTop) {
  3427. var getViewPaneSize = function () {
  3428. var doc = win.document,
  3429. mode = doc.compatMode == 'CSS1Compat';
  3430. return {
  3431. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3432. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3433. };
  3434. },
  3435. getScrollPosition = function (win) {
  3436. if ('pageXOffset' in win) {
  3437. return {
  3438. x:win.pageXOffset || 0,
  3439. y:win.pageYOffset || 0
  3440. };
  3441. }
  3442. else {
  3443. var doc = win.document;
  3444. return {
  3445. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3446. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3447. };
  3448. }
  3449. };
  3450. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3451. offset += (node.offsetHeight || 0);
  3452. var elementPosition = domUtils.getXY(node);
  3453. offset += elementPosition.y;
  3454. var currentScroll = getScrollPosition(win).y;
  3455. // offset += 50;
  3456. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3457. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3458. }
  3459. },
  3460. /**
  3461. * 判断给定节点是否为br
  3462. * @method isBr
  3463. * @param { Node } node 需要判断的节点对象
  3464. * @return { Boolean } 给定的节点是否是br节点
  3465. */
  3466. isBr:function (node) {
  3467. return node.nodeType == 1 && node.tagName == 'BR';
  3468. },
  3469. /**
  3470. * 判断给定的节点是否是一个“填充”节点
  3471. * @private
  3472. * @method isFillChar
  3473. * @param { Node } node 需要判断的节点
  3474. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3475. * @returns { Boolean } 节点是否是填充节点
  3476. */
  3477. isFillChar:function (node,isInStart) {
  3478. if(node.nodeType != 3)
  3479. return false;
  3480. var text = node.nodeValue;
  3481. if(isInStart){
  3482. return new RegExp('^' + domUtils.fillChar).test(text)
  3483. }
  3484. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3485. },
  3486. isStartInblock:function (range) {
  3487. var tmpRange = range.cloneRange(),
  3488. flag = 0,
  3489. start = tmpRange.startContainer,
  3490. tmp;
  3491. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3492. start = start.childNodes[tmpRange.startOffset];
  3493. var pre = start.previousSibling;
  3494. while(pre && domUtils.isFillChar(pre)){
  3495. start = pre;
  3496. pre = pre.previousSibling;
  3497. }
  3498. }
  3499. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3500. tmpRange.setStartBefore(start);
  3501. start = tmpRange.startContainer;
  3502. }
  3503. while (start && domUtils.isFillChar(start)) {
  3504. tmp = start;
  3505. start = start.previousSibling
  3506. }
  3507. if (tmp) {
  3508. tmpRange.setStartBefore(tmp);
  3509. start = tmpRange.startContainer;
  3510. }
  3511. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3512. tmpRange.setStart(start, 0).collapse(true);
  3513. }
  3514. while (!tmpRange.startOffset) {
  3515. start = tmpRange.startContainer;
  3516. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3517. flag = 1;
  3518. break;
  3519. }
  3520. var pre = tmpRange.startContainer.previousSibling,
  3521. tmpNode;
  3522. if (!pre) {
  3523. tmpRange.setStartBefore(tmpRange.startContainer);
  3524. } else {
  3525. while (pre && domUtils.isFillChar(pre)) {
  3526. tmpNode = pre;
  3527. pre = pre.previousSibling;
  3528. }
  3529. if (tmpNode) {
  3530. tmpRange.setStartBefore(tmpNode);
  3531. } else {
  3532. tmpRange.setStartBefore(tmpRange.startContainer);
  3533. }
  3534. }
  3535. }
  3536. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3537. },
  3538. /**
  3539. * 判断给定的元素是否是一个空元素
  3540. * @method isEmptyBlock
  3541. * @param { Element } node 需要判断的元素
  3542. * @return { Boolean } 是否是空元素
  3543. * @example
  3544. * ```html
  3545. * <div id="test"></div>
  3546. *
  3547. * <script>
  3548. * //output: true
  3549. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3550. * </script>
  3551. * ```
  3552. */
  3553. /**
  3554. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3555. * @method isEmptyBlock
  3556. * @param { Element } node 需要判断的元素
  3557. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3558. * @return { Boolean } 是否是空元素
  3559. */
  3560. isEmptyBlock:function (node,reg) {
  3561. if(node.nodeType != 1)
  3562. return 0;
  3563. reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g');
  3564. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3565. return 0;
  3566. }
  3567. for (var n in dtd.$isNotEmpty) {
  3568. if (node.getElementsByTagName(n).length) {
  3569. return 0;
  3570. }
  3571. }
  3572. return 1;
  3573. },
  3574. /**
  3575. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3576. * @method setViewportOffset
  3577. * @param { Element } element 需要设置偏移量的元素
  3578. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3579. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3580. * offset.top的距离
  3581. * @example
  3582. * ```html
  3583. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3584. *
  3585. * <script>
  3586. *
  3587. * var testNode = document.getElementById("test");
  3588. *
  3589. * UE.dom.domUtils.setViewportOffset( testNode, {
  3590. * left: 200,
  3591. * top: 50
  3592. * } );
  3593. *
  3594. * //output: top: 300px; left: 100px; position: absolute;
  3595. * console.log( testNode.style.cssText );
  3596. *
  3597. * </script>
  3598. * ```
  3599. */
  3600. setViewportOffset:function (element, offset) {
  3601. var left = parseInt(element.style.left) | 0;
  3602. var top = parseInt(element.style.top) | 0;
  3603. var rect = element.getBoundingClientRect();
  3604. var offsetLeft = offset.left - rect.left;
  3605. var offsetTop = offset.top - rect.top;
  3606. if (offsetLeft) {
  3607. element.style.left = left + offsetLeft + 'px';
  3608. }
  3609. if (offsetTop) {
  3610. element.style.top = top + offsetTop + 'px';
  3611. }
  3612. },
  3613. /**
  3614. * 用“填充字符”填充节点
  3615. * @method fillNode
  3616. * @private
  3617. * @param { DomDocument } doc 填充的节点所在的docment对象
  3618. * @param { Node } node 需要填充的节点对象
  3619. * @example
  3620. * ```html
  3621. * <div id="test"></div>
  3622. *
  3623. * <script>
  3624. * var testNode = document.getElementById("test");
  3625. *
  3626. * //output: 0
  3627. * console.log( testNode.childNodes.length );
  3628. *
  3629. * UE.dom.domUtils.fillNode( document, testNode );
  3630. *
  3631. * //output: 1
  3632. * console.log( testNode.childNodes.length );
  3633. *
  3634. * </script>
  3635. * ```
  3636. */
  3637. fillNode:function (doc, node) {
  3638. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3639. node.innerHTML = '';
  3640. node.appendChild(tmpNode);
  3641. },
  3642. /**
  3643. * 把节点src的所有子节点追加到另一个节点tag上去
  3644. * @method moveChild
  3645. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3646. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3647. * @example
  3648. * ```html
  3649. * <div id="test1">
  3650. * <span></span>
  3651. * </div>
  3652. * <div id="test2">
  3653. * <div></div>
  3654. * </div>
  3655. *
  3656. * <script>
  3657. *
  3658. * var test1 = document.getElementById("test1"),
  3659. * test2 = document.getElementById("test2");
  3660. *
  3661. * UE.dom.domUtils.moveChild( test1, test2 );
  3662. *
  3663. * //output: ""(空字符串)
  3664. * console.log( test1.innerHTML );
  3665. *
  3666. * //output: "<div></div><span></span>"
  3667. * console.log( test2.innerHTML );
  3668. *
  3669. * </script>
  3670. * ```
  3671. */
  3672. /**
  3673. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3674. * @method moveChild
  3675. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3676. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3677. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3678. * @example
  3679. * ```html
  3680. * <div id="test1">
  3681. * <span></span>
  3682. * </div>
  3683. * <div id="test2">
  3684. * <div></div>
  3685. * </div>
  3686. *
  3687. * <script>
  3688. *
  3689. * var test1 = document.getElementById("test1"),
  3690. * test2 = document.getElementById("test2");
  3691. *
  3692. * UE.dom.domUtils.moveChild( test1, test2, true );
  3693. *
  3694. * //output: ""(空字符串)
  3695. * console.log( test1.innerHTML );
  3696. *
  3697. * //output: "<span></span><div></div>"
  3698. * console.log( test2.innerHTML );
  3699. *
  3700. * </script>
  3701. * ```
  3702. */
  3703. moveChild:function (src, tag, dir) {
  3704. while (src.firstChild) {
  3705. if (dir && tag.firstChild) {
  3706. tag.insertBefore(src.lastChild, tag.firstChild);
  3707. } else {
  3708. tag.appendChild(src.firstChild);
  3709. }
  3710. }
  3711. },
  3712. /**
  3713. * 判断节点的标签上是否不存在任何属性
  3714. * @method hasNoAttributes
  3715. * @private
  3716. * @param { Node } node 需要检测的节点对象
  3717. * @return { Boolean } 节点是否不包含任何属性
  3718. * @example
  3719. * ```html
  3720. * <div id="test"><span>xxxx</span></div>
  3721. *
  3722. * <script>
  3723. *
  3724. * //output: false
  3725. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3726. *
  3727. * //output: true
  3728. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3729. *
  3730. * </script>
  3731. * ```
  3732. */
  3733. hasNoAttributes:function (node) {
  3734. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3735. },
  3736. /**
  3737. * 检测节点是否是UEditor所使用的辅助节点
  3738. * @method isCustomeNode
  3739. * @private
  3740. * @param { Node } node 需要检测的节点
  3741. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3742. * @return { Boolean } 给定的节点是否是一个辅助节点
  3743. */
  3744. isCustomeNode:function (node) {
  3745. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3746. },
  3747. /**
  3748. * 检测节点的标签是否是给定的标签
  3749. * @method isTagNode
  3750. * @param { Node } node 需要检测的节点对象
  3751. * @param { String } tagName 标签
  3752. * @return { Boolean } 节点的标签是否是给定的标签
  3753. * @example
  3754. * ```html
  3755. * <div id="test"></div>
  3756. *
  3757. * <script>
  3758. *
  3759. * //output: true
  3760. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3761. *
  3762. * </script>
  3763. * ```
  3764. */
  3765. isTagNode:function (node, tagNames) {
  3766. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3767. },
  3768. /**
  3769. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3770. * @method filterNodeList
  3771. * @param { Array } nodeList 需要过滤的节点数组
  3772. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3773. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3774. * @example
  3775. * ```javascript
  3776. * var divNodes = document.getElementsByTagName("div");
  3777. * divNodes = [].slice.call( divNodes, 0 );
  3778. *
  3779. * //output: null
  3780. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3781. * return node.tagName.toLowerCase() !== 'div';
  3782. * } ) );
  3783. * ```
  3784. */
  3785. /**
  3786. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3787. * @method filterNodeList
  3788. * @param { Array } nodeList 需要过滤的节点数组
  3789. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3790. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3791. * @example
  3792. * ```javascript
  3793. * var divNodes = document.getElementsByTagName("div");
  3794. * divNodes = [].slice.call( divNodes, 0 );
  3795. *
  3796. * //output: null
  3797. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3798. * ```
  3799. */
  3800. /**
  3801. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3802. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3803. * @method filterNodeList
  3804. * @param { Array } nodeList 需要过滤的节点数组
  3805. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3806. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3807. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3808. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3809. * @example
  3810. * ```javascript
  3811. * var divNodes = document.getElementsByTagName("div");
  3812. * divNodes = [].slice.call( divNodes, 0 );
  3813. *
  3814. * //output: 3(假定有3个div)
  3815. * console.log( divNodes.length );
  3816. *
  3817. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3818. * return node.tagName.toLowerCase() === 'div';
  3819. * }, true );
  3820. *
  3821. * //output: 3
  3822. * console.log( nodes.length );
  3823. *
  3824. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3825. * return node.tagName.toLowerCase() === 'div';
  3826. * }, false );
  3827. *
  3828. * //output: div
  3829. * console.log( node.nodeName );
  3830. * ```
  3831. */
  3832. filterNodeList : function(nodelist,filter,forAll){
  3833. var results = [];
  3834. if(!utils .isFunction(filter)){
  3835. var str = filter;
  3836. filter = function(n){
  3837. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  3838. };
  3839. }
  3840. utils.each(nodelist,function(n){
  3841. filter(n) && results.push(n)
  3842. });
  3843. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  3844. },
  3845. /**
  3846. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  3847. * @method isInNodeEndBoundary
  3848. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  3849. * @param node 需要检测的节点对象
  3850. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  3851. */
  3852. isInNodeEndBoundary : function (rng,node){
  3853. var start = rng.startContainer;
  3854. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  3855. return 0;
  3856. }
  3857. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  3858. return 0;
  3859. }
  3860. while(start !== node){
  3861. if(start.nextSibling){
  3862. return 0
  3863. };
  3864. start = start.parentNode;
  3865. }
  3866. return 1;
  3867. },
  3868. isBoundaryNode : function (node,dir){
  3869. var tmp;
  3870. while(!domUtils.isBody(node)){
  3871. tmp = node;
  3872. node = node.parentNode;
  3873. if(tmp !== node[dir]){
  3874. return false;
  3875. }
  3876. }
  3877. return true;
  3878. }
  3879. };
  3880. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  3881. /**
  3882. * Range封装
  3883. * @file
  3884. * @module UE.dom
  3885. * @class Range
  3886. * @since 1.2.6.1
  3887. */
  3888. /**
  3889. * dom操作封装
  3890. * @unfile
  3891. * @module UE.dom
  3892. */
  3893. /**
  3894. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  3895. * @unfile
  3896. * @module UE.dom
  3897. * @class Range
  3898. */
  3899. (function () {
  3900. var guid = 0,
  3901. fillChar = domUtils.fillChar,
  3902. fillData;
  3903. /*
  3904. * 更新range的collapse状态
  3905. * @param {Range} range range对象
  3906. */
  3907. function updateCollapse(range) {
  3908. range.collapsed =
  3909. range.startContainer && range.endContainer &&
  3910. range.startContainer === range.endContainer &&
  3911. range.startOffset == range.endOffset;
  3912. }
  3913. function selectOneNode(rng){
  3914. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  3915. }
  3916. function setEndPoint(toStart, node, offset, range) {
  3917. //如果node是自闭合标签要处理
  3918. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  3919. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  3920. node = node.parentNode;
  3921. }
  3922. if (toStart) {
  3923. range.startContainer = node;
  3924. range.startOffset = offset;
  3925. if (!range.endContainer) {
  3926. range.collapse(true);
  3927. }
  3928. } else {
  3929. range.endContainer = node;
  3930. range.endOffset = offset;
  3931. if (!range.startContainer) {
  3932. range.collapse(false);
  3933. }
  3934. }
  3935. updateCollapse(range);
  3936. return range;
  3937. }
  3938. function execContentsAction(range, action) {
  3939. //调整边界
  3940. //range.includeBookmark();
  3941. var start = range.startContainer,
  3942. end = range.endContainer,
  3943. startOffset = range.startOffset,
  3944. endOffset = range.endOffset,
  3945. doc = range.document,
  3946. frag = doc.createDocumentFragment(),
  3947. tmpStart, tmpEnd;
  3948. if (start.nodeType == 1) {
  3949. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  3950. }
  3951. if (end.nodeType == 1) {
  3952. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  3953. }
  3954. if (start === end && start.nodeType == 3) {
  3955. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  3956. //is not clone
  3957. if (action) {
  3958. start.deleteData(startOffset, endOffset - startOffset);
  3959. range.collapse(true);
  3960. }
  3961. return frag;
  3962. }
  3963. var current, currentLevel, clone = frag,
  3964. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  3965. for (var i = 0; startParents[i] == endParents[i];) {
  3966. i++;
  3967. }
  3968. for (var j = i, si; si = startParents[j]; j++) {
  3969. current = si.nextSibling;
  3970. if (si == start) {
  3971. if (!tmpStart) {
  3972. if (range.startContainer.nodeType == 3) {
  3973. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  3974. //is not clone
  3975. if (action) {
  3976. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  3977. }
  3978. } else {
  3979. clone.appendChild(!action ? start.cloneNode(true) : start);
  3980. }
  3981. }
  3982. } else {
  3983. currentLevel = si.cloneNode(false);
  3984. clone.appendChild(currentLevel);
  3985. }
  3986. while (current) {
  3987. if (current === end || current === endParents[j]) {
  3988. break;
  3989. }
  3990. si = current.nextSibling;
  3991. clone.appendChild(!action ? current.cloneNode(true) : current);
  3992. current = si;
  3993. }
  3994. clone = currentLevel;
  3995. }
  3996. clone = frag;
  3997. if (!startParents[i]) {
  3998. clone.appendChild(startParents[i - 1].cloneNode(false));
  3999. clone = clone.firstChild;
  4000. }
  4001. for (var j = i, ei; ei = endParents[j]; j++) {
  4002. current = ei.previousSibling;
  4003. if (ei == end) {
  4004. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4005. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4006. //is not clone
  4007. if (action) {
  4008. end.deleteData(0, endOffset);
  4009. }
  4010. }
  4011. } else {
  4012. currentLevel = ei.cloneNode(false);
  4013. clone.appendChild(currentLevel);
  4014. }
  4015. //如果两端同级,右边第一次已经被开始做了
  4016. if (j != i || !startParents[i]) {
  4017. while (current) {
  4018. if (current === start) {
  4019. break;
  4020. }
  4021. ei = current.previousSibling;
  4022. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4023. current = ei;
  4024. }
  4025. }
  4026. clone = currentLevel;
  4027. }
  4028. if (action) {
  4029. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4030. }
  4031. tmpStart && domUtils.remove(tmpStart);
  4032. tmpEnd && domUtils.remove(tmpEnd);
  4033. return frag;
  4034. }
  4035. /**
  4036. * 创建一个跟document绑定的空的Range实例
  4037. * @constructor
  4038. * @param { Document } document 新建的选区所属的文档对象
  4039. */
  4040. /**
  4041. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4042. */
  4043. /**
  4044. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4045. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4046. */
  4047. /**
  4048. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4049. */
  4050. /**
  4051. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4052. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4053. */
  4054. /**
  4055. * @property { Boolean } collapsed 当前Range是否闭合
  4056. * @default true
  4057. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4058. */
  4059. /**
  4060. * @property { Document } document 当前Range所属的Document对象
  4061. * @remind 不同range的的document属性可以是不同的
  4062. */
  4063. var Range = dom.Range = function (document) {
  4064. var me = this;
  4065. me.startContainer =
  4066. me.startOffset =
  4067. me.endContainer =
  4068. me.endOffset = null;
  4069. me.document = document;
  4070. me.collapsed = true;
  4071. };
  4072. /*
  4073. * 删除fillData
  4074. * @param doc
  4075. * @param excludeNode
  4076. */
  4077. function removeFillData(doc, excludeNode) {
  4078. try {
  4079. if (fillData && domUtils.inDoc(fillData, doc)) {
  4080. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4081. var tmpNode = fillData.parentNode;
  4082. domUtils.remove(fillData);
  4083. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4084. //safari的contains有bug
  4085. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4086. ) {
  4087. fillData = tmpNode.parentNode;
  4088. domUtils.remove(tmpNode);
  4089. tmpNode = fillData;
  4090. }
  4091. } else {
  4092. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4093. }
  4094. }
  4095. } catch (e) {
  4096. }
  4097. }
  4098. /*
  4099. * @param node
  4100. * @param dir
  4101. */
  4102. function mergeSibling(node, dir) {
  4103. var tmpNode;
  4104. node = node[dir];
  4105. while (node && domUtils.isFillChar(node)) {
  4106. tmpNode = node[dir];
  4107. domUtils.remove(node);
  4108. node = tmpNode;
  4109. }
  4110. }
  4111. Range.prototype = {
  4112. /**
  4113. * 克隆选区的内容到一个DocumentFragment里
  4114. * @method cloneContents
  4115. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4116. * @example
  4117. * ```html
  4118. * <body>
  4119. * <!-- 中括号表示选区 -->
  4120. * <b>x<i>x[x</i>xx]x</b>
  4121. *
  4122. * <script>
  4123. * //range是已选中的选区
  4124. * var fragment = range.cloneContents(),
  4125. * node = document.createElement("div");
  4126. *
  4127. * node.appendChild( fragment );
  4128. *
  4129. * //output: <i>x</i>xx
  4130. * console.log( node.innerHTML );
  4131. *
  4132. * </script>
  4133. * </body>
  4134. * ```
  4135. */
  4136. cloneContents:function () {
  4137. return this.collapsed ? null : execContentsAction(this, 0);
  4138. },
  4139. /**
  4140. * 删除当前选区范围中的所有内容
  4141. * @method deleteContents
  4142. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4143. * @return { UE.dom.Range } 当前操作的Range对象
  4144. * @example
  4145. * ```html
  4146. * <body>
  4147. * <!-- 中括号表示选区 -->
  4148. * <b>x<i>x[x</i>xx]x</b>
  4149. *
  4150. * <script>
  4151. * //range是已选中的选区
  4152. * range.deleteContents();
  4153. *
  4154. * //竖线表示闭合后的选区位置
  4155. * //output: <b>x<i>x</i>|x</b>
  4156. * console.log( document.body.innerHTML );
  4157. *
  4158. * //此时, range的各项属性为
  4159. * //output: B
  4160. * console.log( range.startContainer.tagName );
  4161. * //output: 2
  4162. * console.log( range.startOffset );
  4163. * //output: B
  4164. * console.log( range.endContainer.tagName );
  4165. * //output: 2
  4166. * console.log( range.endOffset );
  4167. * //output: true
  4168. * console.log( range.collapsed );
  4169. *
  4170. * </script>
  4171. * </body>
  4172. * ```
  4173. */
  4174. deleteContents:function () {
  4175. var txt;
  4176. if (!this.collapsed) {
  4177. execContentsAction(this, 1);
  4178. }
  4179. if (browser.webkit) {
  4180. txt = this.startContainer;
  4181. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4182. this.setStartBefore(txt).collapse(true);
  4183. domUtils.remove(txt);
  4184. }
  4185. }
  4186. return this;
  4187. },
  4188. /**
  4189. * 将当前选区的内容提取到一个DocumentFragment里
  4190. * @method extractContents
  4191. * @remind 执行该操作后, 选区将变成闭合状态
  4192. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4193. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4194. * @example
  4195. * ```html
  4196. * <body>
  4197. * <!-- 中括号表示选区 -->
  4198. * <b>x<i>x[x</i>xx]x</b>
  4199. *
  4200. * <script>
  4201. * //range是已选中的选区
  4202. * var fragment = range.extractContents(),
  4203. * node = document.createElement( "div" );
  4204. *
  4205. * node.appendChild( fragment );
  4206. *
  4207. * //竖线表示闭合后的选区位置
  4208. *
  4209. * //output: <b>x<i>x</i>|x</b>
  4210. * console.log( document.body.innerHTML );
  4211. * //output: <i>x</i>xx
  4212. * console.log( node.innerHTML );
  4213. *
  4214. * //此时, range的各项属性为
  4215. * //output: B
  4216. * console.log( range.startContainer.tagName );
  4217. * //output: 2
  4218. * console.log( range.startOffset );
  4219. * //output: B
  4220. * console.log( range.endContainer.tagName );
  4221. * //output: 2
  4222. * console.log( range.endOffset );
  4223. * //output: true
  4224. * console.log( range.collapsed );
  4225. *
  4226. * </script>
  4227. * </body>
  4228. */
  4229. extractContents:function () {
  4230. return this.collapsed ? null : execContentsAction(this, 2);
  4231. },
  4232. /**
  4233. * 设置Range的开始容器节点和偏移量
  4234. * @method setStart
  4235. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4236. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4237. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4238. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4239. * 中的索引
  4240. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4241. * @param { int } offset 选区的开始位置偏移量
  4242. * @return { UE.dom.Range } 当前range对象
  4243. * @example
  4244. * ```html
  4245. * <!-- 选区 -->
  4246. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4247. *
  4248. * <script>
  4249. *
  4250. * //执行操作
  4251. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4252. *
  4253. * //此时, 选区变成了
  4254. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4255. *
  4256. * </script>
  4257. * ```
  4258. * @example
  4259. * ```html
  4260. * <!-- 选区 -->
  4261. * <b>xxx<img>[xx]x</b>
  4262. *
  4263. * <script>
  4264. *
  4265. * //执行操作
  4266. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4267. *
  4268. * //此时, 选区变成了
  4269. * //<b>xxx[<img>xx]x</b>
  4270. *
  4271. * </script>
  4272. * ```
  4273. */
  4274. setStart:function (node, offset) {
  4275. return setEndPoint(true, node, offset, this);
  4276. },
  4277. /**
  4278. * 设置Range的结束容器和偏移量
  4279. * @method setEnd
  4280. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4281. * @param { int } offset 结束边界的偏移量
  4282. * @see UE.dom.Range:setStart(Node,int)
  4283. * @return { UE.dom.Range } 当前range对象
  4284. */
  4285. setEnd:function (node, offset) {
  4286. return setEndPoint(false, node, offset, this);
  4287. },
  4288. /**
  4289. * 将Range开始位置设置到node节点之后
  4290. * @method setStartAfter
  4291. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4292. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4293. * @return { UE.dom.Range } 当前range对象
  4294. * @example
  4295. * ```html
  4296. * <!-- 选区示例 -->
  4297. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4298. *
  4299. * <script>
  4300. *
  4301. * //执行操作
  4302. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4303. *
  4304. * //结果选区
  4305. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4306. *
  4307. * </script>
  4308. * ```
  4309. */
  4310. setStartAfter:function (node) {
  4311. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4312. },
  4313. /**
  4314. * 将Range开始位置设置到node节点之前
  4315. * @method setStartBefore
  4316. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4317. * @param { Node } node 新的选区开始位置在该节点之前
  4318. * @see UE.dom.Range:setStartAfter(Node)
  4319. * @return { UE.dom.Range } 当前range对象
  4320. */
  4321. setStartBefore:function (node) {
  4322. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4323. },
  4324. /**
  4325. * 将Range结束位置设置到node节点之后
  4326. * @method setEndAfter
  4327. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4328. * @param { Node } node 目标节点
  4329. * @see UE.dom.Range:setStartAfter(Node)
  4330. * @return { UE.dom.Range } 当前range对象
  4331. * @example
  4332. * ```html
  4333. * <!-- 选区示例 -->
  4334. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4335. *
  4336. * <script>
  4337. *
  4338. * //执行操作
  4339. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4340. *
  4341. * //结果选区
  4342. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4343. *
  4344. * </script>
  4345. * ```
  4346. */
  4347. setEndAfter:function (node) {
  4348. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4349. },
  4350. /**
  4351. * 将Range结束位置设置到node节点之前
  4352. * @method setEndBefore
  4353. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4354. * @param { Node } node 目标节点
  4355. * @see UE.dom.Range:setEndAfter(Node)
  4356. * @return { UE.dom.Range } 当前range对象
  4357. */
  4358. setEndBefore:function (node) {
  4359. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4360. },
  4361. /**
  4362. * 设置Range的开始位置到node节点内的第一个子节点之前
  4363. * @method setStartAtFirst
  4364. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4365. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4366. * @param { Node } node 目标节点
  4367. * @see UE.dom.Range:setStartBefore(Node)
  4368. * @return { UE.dom.Range } 当前range对象
  4369. * @example
  4370. * ```html
  4371. * <!-- 选区示例 -->
  4372. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4373. *
  4374. * <script>
  4375. *
  4376. * //执行操作
  4377. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4378. *
  4379. * //结果选区
  4380. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4381. *
  4382. * </script>
  4383. * ```
  4384. */
  4385. setStartAtFirst:function (node) {
  4386. return this.setStart(node, 0);
  4387. },
  4388. /**
  4389. * 设置Range的开始位置到node节点内的最后一个节点之后
  4390. * @method setStartAtLast
  4391. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4392. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4393. * @param { Node } node 目标节点
  4394. * @see UE.dom.Range:setStartAtFirst(Node)
  4395. * @return { UE.dom.Range } 当前range对象
  4396. */
  4397. setStartAtLast:function (node) {
  4398. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4399. },
  4400. /**
  4401. * 设置Range的结束位置到node节点内的第一个节点之前
  4402. * @method setEndAtFirst
  4403. * @param { Node } node 目标节点
  4404. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4405. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4406. * @see UE.dom.Range:setStartAtFirst(Node)
  4407. * @return { UE.dom.Range } 当前range对象
  4408. */
  4409. setEndAtFirst:function (node) {
  4410. return this.setEnd(node, 0);
  4411. },
  4412. /**
  4413. * 设置Range的结束位置到node节点内的最后一个节点之后
  4414. * @method setEndAtLast
  4415. * @param { Node } node 目标节点
  4416. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4417. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4418. * @see UE.dom.Range:setStartAtFirst(Node)
  4419. * @return { UE.dom.Range } 当前range对象
  4420. */
  4421. setEndAtLast:function (node) {
  4422. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4423. },
  4424. /**
  4425. * 选中给定节点
  4426. * @method selectNode
  4427. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4428. * 而endOffset为startOffset+1
  4429. * @param { Node } node 需要选中的节点
  4430. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4431. * @example
  4432. * ```html
  4433. * <!-- 选区示例 -->
  4434. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4435. *
  4436. * <script>
  4437. *
  4438. * //执行操作
  4439. * range.selectNode( document.getElementsByTagName("i")[0] );
  4440. *
  4441. * //结果选区
  4442. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4443. *
  4444. * </script>
  4445. * ```
  4446. */
  4447. selectNode:function (node) {
  4448. return this.setStartBefore(node).setEndAfter(node);
  4449. },
  4450. /**
  4451. * 选中给定节点内部的所有节点
  4452. * @method selectNodeContents
  4453. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4454. * 而endOffset是该节点的子节点数。
  4455. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4456. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4457. * @example
  4458. * ```html
  4459. * <!-- 选区示例 -->
  4460. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4461. *
  4462. * <script>
  4463. *
  4464. * //执行操作
  4465. * range.selectNode( document.getElementsByTagName("b")[0] );
  4466. *
  4467. * //结果选区
  4468. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4469. *
  4470. * </script>
  4471. * ```
  4472. */
  4473. selectNodeContents:function (node) {
  4474. return this.setStart(node, 0).setEndAtLast(node);
  4475. },
  4476. /**
  4477. * clone当前Range对象
  4478. * @method cloneRange
  4479. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4480. * @return { UE.dom.Range } 当前range对象的一个副本
  4481. */
  4482. cloneRange:function () {
  4483. var me = this;
  4484. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4485. },
  4486. /**
  4487. * 向当前选区的结束处闭合选区
  4488. * @method collapse
  4489. * @return { UE.dom.Range } 当前range对象
  4490. * @example
  4491. * ```html
  4492. * <!-- 选区示例 -->
  4493. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4494. *
  4495. * <script>
  4496. *
  4497. * //执行操作
  4498. * range.collapse();
  4499. *
  4500. * //结果选区
  4501. * //“|”表示选区已闭合
  4502. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4503. *
  4504. * </script>
  4505. * ```
  4506. */
  4507. /**
  4508. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4509. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4510. * @method collapse
  4511. * @param { Boolean } toStart 是否向选区开始处闭合
  4512. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4513. * @see UE.dom.Range:collapse()
  4514. * @example
  4515. * ```html
  4516. * <!-- 选区示例 -->
  4517. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4518. *
  4519. * <script>
  4520. *
  4521. * //执行操作
  4522. * range.collapse( true );
  4523. *
  4524. * //结果选区
  4525. * //“|”表示选区已闭合
  4526. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4527. *
  4528. * </script>
  4529. * ```
  4530. */
  4531. collapse:function (toStart) {
  4532. var me = this;
  4533. if (toStart) {
  4534. me.endContainer = me.startContainer;
  4535. me.endOffset = me.startOffset;
  4536. } else {
  4537. me.startContainer = me.endContainer;
  4538. me.startOffset = me.endOffset;
  4539. }
  4540. me.collapsed = true;
  4541. return me;
  4542. },
  4543. /**
  4544. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4545. * @method shrinkBoundary
  4546. * @return { UE.dom.Range } 当前range对象
  4547. * @example
  4548. * ```html
  4549. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4550. * ```
  4551. *
  4552. * @example
  4553. * ```html
  4554. * <!-- 选区示例 -->
  4555. * <b>x[xx</b><i>]xxx</i>
  4556. *
  4557. * <script>
  4558. *
  4559. * //执行收缩
  4560. * range.shrinkBoundary();
  4561. *
  4562. * //结果选区
  4563. * //<b>x[xx]</b><i>xxx</i>
  4564. * </script>
  4565. * ```
  4566. *
  4567. * @example
  4568. * ```html
  4569. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4570. * ```
  4571. */
  4572. /**
  4573. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4574. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4575. * @method shrinkBoundary
  4576. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4577. * @return { UE.dom.Range } 当前range对象
  4578. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4579. */
  4580. shrinkBoundary:function (ignoreEnd) {
  4581. var me = this, child,
  4582. collapsed = me.collapsed;
  4583. function check(node){
  4584. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4585. }
  4586. while (me.startContainer.nodeType == 1 //是element
  4587. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4588. && check(child)) {
  4589. me.setStart(child, 0);
  4590. }
  4591. if (collapsed) {
  4592. return me.collapse(true);
  4593. }
  4594. if (!ignoreEnd) {
  4595. while (me.endContainer.nodeType == 1//是element
  4596. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4597. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4598. && check(child)) {
  4599. me.setEnd(child, child.childNodes.length);
  4600. }
  4601. }
  4602. return me;
  4603. },
  4604. /**
  4605. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4606. * @method getCommonAncestor
  4607. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4608. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4609. * @example
  4610. * ```html
  4611. * //选区示例
  4612. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4613. * <script>
  4614. *
  4615. * var node = range.getCommonAncestor();
  4616. *
  4617. * //公共祖先节点是: b节点
  4618. * //输出: B
  4619. * console.log(node.tagName);
  4620. *
  4621. * </script>
  4622. * ```
  4623. */
  4624. /**
  4625. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4626. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4627. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4628. * @method getCommonAncestor
  4629. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4630. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4631. * @see UE.dom.Range:getCommonAncestor()
  4632. * @example
  4633. * ```html
  4634. * <body>
  4635. *
  4636. * <!-- 选区示例 -->
  4637. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4638. *
  4639. * <script>
  4640. *
  4641. * var node = range.getCommonAncestor( false );
  4642. *
  4643. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4644. * //output: B
  4645. * console.log( node.tagName );
  4646. *
  4647. * </script>
  4648. *
  4649. * </body>
  4650. * ```
  4651. */
  4652. /**
  4653. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4654. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4655. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4656. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4657. * @method getCommonAncestor
  4658. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4659. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4660. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4661. * @see UE.dom.Range:getCommonAncestor()
  4662. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4663. * @example
  4664. * ```html
  4665. * <body>
  4666. *
  4667. * <!-- 选区示例 -->
  4668. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4669. *
  4670. * <script>
  4671. *
  4672. * var node = range.getCommonAncestor( true, false );
  4673. *
  4674. * //output: SPAN
  4675. * console.log( node.tagName );
  4676. *
  4677. * </script>
  4678. *
  4679. * </body>
  4680. * ```
  4681. */
  4682. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4683. var me = this,
  4684. start = me.startContainer,
  4685. end = me.endContainer;
  4686. if (start === end) {
  4687. if (includeSelf && selectOneNode(this)) {
  4688. start = start.childNodes[me.startOffset];
  4689. if(start.nodeType == 1)
  4690. return start;
  4691. }
  4692. //只有在上来就相等的情况下才会出现是文本的情况
  4693. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4694. }
  4695. return domUtils.getCommonAncestor(start, end);
  4696. },
  4697. /**
  4698. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4699. * @method trimBoundary
  4700. * @remind 该操作有可能会引起文本节点被切开
  4701. * @return { UE.dom.Range } 当前range对象
  4702. * @example
  4703. * ```html
  4704. *
  4705. * //选区示例
  4706. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4707. *
  4708. * <script>
  4709. * //未调整前, 选区的开始容器和结束都是文本节点
  4710. * //执行调整
  4711. * range.trimBoundary();
  4712. *
  4713. * //调整之后, 容器节点变成了i节点
  4714. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4715. * </script>
  4716. * ```
  4717. */
  4718. /**
  4719. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4720. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4721. * @method trimBoundary
  4722. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4723. * @return { UE.dom.Range } 当前range对象
  4724. * @example
  4725. * ```html
  4726. *
  4727. * //选区示例
  4728. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4729. *
  4730. * <script>
  4731. * //未调整前, 选区的开始容器和结束都是文本节点
  4732. * //执行调整
  4733. * range.trimBoundary( true );
  4734. *
  4735. * //调整之后, 开始容器节点变成了i节点
  4736. * //但是, 结束容器没有发生变化
  4737. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4738. * </script>
  4739. * ```
  4740. */
  4741. trimBoundary:function (ignoreEnd) {
  4742. this.txtToElmBoundary();
  4743. var start = this.startContainer,
  4744. offset = this.startOffset,
  4745. collapsed = this.collapsed,
  4746. end = this.endContainer;
  4747. if (start.nodeType == 3) {
  4748. if (offset == 0) {
  4749. this.setStartBefore(start);
  4750. } else {
  4751. if (offset >= start.nodeValue.length) {
  4752. this.setStartAfter(start);
  4753. } else {
  4754. var textNode = domUtils.split(start, offset);
  4755. //跟新结束边界
  4756. if (start === end) {
  4757. this.setEnd(textNode, this.endOffset - offset);
  4758. } else if (start.parentNode === end) {
  4759. this.endOffset += 1;
  4760. }
  4761. this.setStartBefore(textNode);
  4762. }
  4763. }
  4764. if (collapsed) {
  4765. return this.collapse(true);
  4766. }
  4767. }
  4768. if (!ignoreEnd) {
  4769. offset = this.endOffset;
  4770. end = this.endContainer;
  4771. if (end.nodeType == 3) {
  4772. if (offset == 0) {
  4773. this.setEndBefore(end);
  4774. } else {
  4775. offset < end.nodeValue.length && domUtils.split(end, offset);
  4776. this.setEndAfter(end);
  4777. }
  4778. }
  4779. }
  4780. return this;
  4781. },
  4782. /**
  4783. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4784. * @method txtToElmBoundary
  4785. * @remind 该操作不会修改dom节点
  4786. * @return { UE.dom.Range } 当前range对象
  4787. */
  4788. /**
  4789. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4790. * ignoreCollapsed 的值决定是否执行该调整
  4791. * @method txtToElmBoundary
  4792. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4793. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4794. * @return { UE.dom.Range } 当前range对象
  4795. */
  4796. txtToElmBoundary:function (ignoreCollapsed) {
  4797. function adjust(r, c) {
  4798. var container = r[c + 'Container'],
  4799. offset = r[c + 'Offset'];
  4800. if (container.nodeType == 3) {
  4801. if (!offset) {
  4802. r['set' + c.replace(/(\w)/, function (a) {
  4803. return a.toUpperCase();
  4804. }) + 'Before'](container);
  4805. } else if (offset >= container.nodeValue.length) {
  4806. r['set' + c.replace(/(\w)/, function (a) {
  4807. return a.toUpperCase();
  4808. }) + 'After' ](container);
  4809. }
  4810. }
  4811. }
  4812. if (ignoreCollapsed || !this.collapsed) {
  4813. adjust(this, 'start');
  4814. adjust(this, 'end');
  4815. }
  4816. return this;
  4817. },
  4818. /**
  4819. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  4820. * @method insertNode
  4821. * @param { Node } node 需要插入的节点
  4822. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  4823. * @return { UE.dom.Range } 当前range对象
  4824. */
  4825. insertNode:function (node) {
  4826. var first = node, length = 1;
  4827. if (node.nodeType == 11) {
  4828. first = node.firstChild;
  4829. length = node.childNodes.length;
  4830. }
  4831. this.trimBoundary(true);
  4832. var start = this.startContainer,
  4833. offset = this.startOffset;
  4834. var nextNode = start.childNodes[ offset ];
  4835. if (nextNode) {
  4836. start.insertBefore(node, nextNode);
  4837. } else {
  4838. start.appendChild(node);
  4839. }
  4840. if (first.parentNode === this.endContainer) {
  4841. this.endOffset = this.endOffset + length;
  4842. }
  4843. return this.setStartBefore(first);
  4844. },
  4845. /**
  4846. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  4847. * @method setCursor
  4848. * @return { UE.dom.Range } 当前range对象
  4849. * @see UE.dom.Range:collapse()
  4850. */
  4851. /**
  4852. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  4853. * @method setCursor
  4854. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  4855. * 反之,则向开始容器方向闭合
  4856. * @return { UE.dom.Range } 当前range对象
  4857. * @see UE.dom.Range:collapse(Boolean)
  4858. */
  4859. setCursor:function (toEnd, noFillData) {
  4860. return this.collapse(!toEnd).select(noFillData);
  4861. },
  4862. /**
  4863. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  4864. * @method createBookmark
  4865. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  4866. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  4867. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  4868. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  4869. * 返回的记录的类型为ID, 反之则为引用
  4870. */
  4871. createBookmark:function (serialize, same) {
  4872. var endNode,
  4873. startNode = this.document.createElement('span');
  4874. startNode.style.cssText = 'display:none;line-height:0px;';
  4875. startNode.appendChild(this.document.createTextNode('\u200D'));
  4876. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  4877. if (!this.collapsed) {
  4878. endNode = startNode.cloneNode(true);
  4879. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  4880. }
  4881. this.insertNode(startNode);
  4882. if (endNode) {
  4883. this.collapse().insertNode(endNode).setEndBefore(endNode);
  4884. }
  4885. this.setStartAfter(startNode);
  4886. return {
  4887. start:serialize ? startNode.id : startNode,
  4888. end:endNode ? serialize ? endNode.id : endNode : null,
  4889. id:serialize
  4890. }
  4891. },
  4892. /**
  4893. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  4894. * @method moveToBookmark
  4895. * @param { BookMark } bookmark createBookmark所创建的标签对象
  4896. * @return { UE.dom.Range } 当前range对象
  4897. * @see UE.dom.Range:createBookmark(Boolean)
  4898. */
  4899. moveToBookmark:function (bookmark) {
  4900. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  4901. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  4902. this.setStartBefore(start);
  4903. domUtils.remove(start);
  4904. if (end) {
  4905. this.setEndBefore(end);
  4906. domUtils.remove(end);
  4907. } else {
  4908. this.collapse(true);
  4909. }
  4910. return this;
  4911. },
  4912. /**
  4913. * 调整range的边界,使其"放大"到最近的父节点
  4914. * @method enlarge
  4915. * @remind 会引起选区的变化
  4916. * @return { UE.dom.Range } 当前range对象
  4917. */
  4918. /**
  4919. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  4920. * 要求扩大之后的父节点是block节点
  4921. * @method enlarge
  4922. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  4923. * @return { UE.dom.Range } 当前range对象
  4924. */
  4925. enlarge:function (toBlock, stopFn) {
  4926. var isBody = domUtils.isBody,
  4927. pre, node, tmp = this.document.createTextNode('');
  4928. if (toBlock) {
  4929. node = this.startContainer;
  4930. if (node.nodeType == 1) {
  4931. if (node.childNodes[this.startOffset]) {
  4932. pre = node = node.childNodes[this.startOffset]
  4933. } else {
  4934. node.appendChild(tmp);
  4935. pre = node = tmp;
  4936. }
  4937. } else {
  4938. pre = node;
  4939. }
  4940. while (1) {
  4941. if (domUtils.isBlockElm(node)) {
  4942. node = pre;
  4943. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  4944. node = pre;
  4945. }
  4946. this.setStartBefore(node);
  4947. break;
  4948. }
  4949. pre = node;
  4950. node = node.parentNode;
  4951. }
  4952. node = this.endContainer;
  4953. if (node.nodeType == 1) {
  4954. if (pre = node.childNodes[this.endOffset]) {
  4955. node.insertBefore(tmp, pre);
  4956. } else {
  4957. node.appendChild(tmp);
  4958. }
  4959. pre = node = tmp;
  4960. } else {
  4961. pre = node;
  4962. }
  4963. while (1) {
  4964. if (domUtils.isBlockElm(node)) {
  4965. node = pre;
  4966. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  4967. node = pre;
  4968. }
  4969. this.setEndAfter(node);
  4970. break;
  4971. }
  4972. pre = node;
  4973. node = node.parentNode;
  4974. }
  4975. if (tmp.parentNode === this.endContainer) {
  4976. this.endOffset--;
  4977. }
  4978. domUtils.remove(tmp);
  4979. }
  4980. // 扩展边界到最大
  4981. if (!this.collapsed) {
  4982. while (this.startOffset == 0) {
  4983. if (stopFn && stopFn(this.startContainer)) {
  4984. break;
  4985. }
  4986. if (isBody(this.startContainer)) {
  4987. break;
  4988. }
  4989. this.setStartBefore(this.startContainer);
  4990. }
  4991. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  4992. if (stopFn && stopFn(this.endContainer)) {
  4993. break;
  4994. }
  4995. if (isBody(this.endContainer)) {
  4996. break;
  4997. }
  4998. this.setEndAfter(this.endContainer);
  4999. }
  5000. }
  5001. return this;
  5002. },
  5003. enlargeToBlockElm:function(ignoreEnd){
  5004. while(!domUtils.isBlockElm(this.startContainer)){
  5005. this.setStartBefore(this.startContainer);
  5006. }
  5007. if(!ignoreEnd){
  5008. while(!domUtils.isBlockElm(this.endContainer)){
  5009. this.setEndAfter(this.endContainer);
  5010. }
  5011. }
  5012. return this;
  5013. },
  5014. /**
  5015. * 调整Range的边界,使其"缩小"到最合适的位置
  5016. * @method adjustmentBoundary
  5017. * @return { UE.dom.Range } 当前range对象
  5018. * @see UE.dom.Range:shrinkBoundary()
  5019. */
  5020. adjustmentBoundary:function () {
  5021. if (!this.collapsed) {
  5022. while (!domUtils.isBody(this.startContainer) &&
  5023. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5024. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5025. ) {
  5026. this.setStartAfter(this.startContainer);
  5027. }
  5028. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5029. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5030. ) {
  5031. this.setEndBefore(this.endContainer);
  5032. }
  5033. }
  5034. return this;
  5035. },
  5036. /**
  5037. * 给range选区中的内容添加给定的inline标签
  5038. * @method applyInlineStyle
  5039. * @param { String } tagName 需要添加的标签名
  5040. * @example
  5041. * ```html
  5042. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5043. * ```
  5044. */
  5045. /**
  5046. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5047. * @method applyInlineStyle
  5048. * @param { String } tagName 需要添加的标签名
  5049. * @param { Object } attrs 跟随新添加的标签的属性
  5050. * @return { UE.dom.Range } 当前选区
  5051. * @example
  5052. * ```html
  5053. * <p>xxxx[xxxx]x</p>
  5054. *
  5055. * ==>
  5056. *
  5057. * <!-- 执行操作 -->
  5058. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5059. *
  5060. * ==>
  5061. *
  5062. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5063. * ```
  5064. */
  5065. applyInlineStyle:function (tagName, attrs, list) {
  5066. if (this.collapsed)return this;
  5067. this.trimBoundary().enlarge(false,
  5068. function (node) {
  5069. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5070. }).adjustmentBoundary();
  5071. var bookmark = this.createBookmark(),
  5072. end = bookmark.end,
  5073. filterFn = function (node) {
  5074. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5075. },
  5076. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5077. node,
  5078. pre,
  5079. range = this.cloneRange();
  5080. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5081. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5082. range.setStartBefore(current);
  5083. node = current;
  5084. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5085. pre = node;
  5086. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5087. return dtd[tagName][parent.tagName];
  5088. });
  5089. }
  5090. var frag = range.setEndAfter(pre).extractContents(), elm;
  5091. if (list && list.length > 0) {
  5092. var level, top;
  5093. top = level = list[0].cloneNode(false);
  5094. for (var i = 1, ci; ci = list[i++];) {
  5095. level.appendChild(ci.cloneNode(false));
  5096. level = level.firstChild;
  5097. }
  5098. elm = level;
  5099. } else {
  5100. elm = range.document.createElement(tagName);
  5101. }
  5102. if (attrs) {
  5103. domUtils.setAttributes(elm, attrs);
  5104. }
  5105. elm.appendChild(frag);
  5106. range.insertNode(list ? top : elm);
  5107. //处理下滑线在a上的情况
  5108. var aNode;
  5109. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5110. domUtils.setAttributes(aNode, attrs);
  5111. domUtils.remove(elm, true);
  5112. elm = aNode;
  5113. } else {
  5114. domUtils.mergeSibling(elm);
  5115. domUtils.clearEmptySibling(elm);
  5116. }
  5117. //去除子节点相同的
  5118. domUtils.mergeChild(elm, attrs);
  5119. current = domUtils.getNextDomNode(elm, false, filterFn);
  5120. domUtils.mergeToParent(elm);
  5121. if (node === end) {
  5122. break;
  5123. }
  5124. } else {
  5125. current = domUtils.getNextDomNode(current, true, filterFn);
  5126. }
  5127. }
  5128. return this.moveToBookmark(bookmark);
  5129. },
  5130. /**
  5131. * 移除当前选区内指定的inline标签,但保留其中的内容
  5132. * @method removeInlineStyle
  5133. * @param { String } tagName 需要移除的标签名
  5134. * @return { UE.dom.Range } 当前的range对象
  5135. * @example
  5136. * ```html
  5137. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5138. * ```
  5139. */
  5140. /**
  5141. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5142. * @method removeInlineStyle
  5143. * @param { Array } tagNameArr 需要移除的标签名的数组
  5144. * @return { UE.dom.Range } 当前的range对象
  5145. * @see UE.dom.Range:removeInlineStyle(String)
  5146. */
  5147. removeInlineStyle:function (tagNames) {
  5148. if (this.collapsed)return this;
  5149. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5150. this.shrinkBoundary().adjustmentBoundary();
  5151. var start = this.startContainer, end = this.endContainer;
  5152. while (1) {
  5153. if (start.nodeType == 1) {
  5154. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5155. break;
  5156. }
  5157. if (start.tagName.toLowerCase() == 'body') {
  5158. start = null;
  5159. break;
  5160. }
  5161. }
  5162. start = start.parentNode;
  5163. }
  5164. while (1) {
  5165. if (end.nodeType == 1) {
  5166. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5167. break;
  5168. }
  5169. if (end.tagName.toLowerCase() == 'body') {
  5170. end = null;
  5171. break;
  5172. }
  5173. }
  5174. end = end.parentNode;
  5175. }
  5176. var bookmark = this.createBookmark(),
  5177. frag,
  5178. tmpRange;
  5179. if (start) {
  5180. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5181. frag = tmpRange.extractContents();
  5182. tmpRange.insertNode(frag);
  5183. domUtils.clearEmptySibling(start, true);
  5184. start.parentNode.insertBefore(bookmark.start, start);
  5185. }
  5186. if (end) {
  5187. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5188. frag = tmpRange.extractContents();
  5189. tmpRange.insertNode(frag);
  5190. domUtils.clearEmptySibling(end, false, true);
  5191. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5192. }
  5193. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5194. return node.nodeType == 1;
  5195. }), next;
  5196. while (current && current !== bookmark.end) {
  5197. next = domUtils.getNextDomNode(current, true, function (node) {
  5198. return node.nodeType == 1;
  5199. });
  5200. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5201. domUtils.remove(current, true);
  5202. }
  5203. current = next;
  5204. }
  5205. return this.moveToBookmark(bookmark);
  5206. },
  5207. /**
  5208. * 获取当前选中的自闭合的节点
  5209. * @method getClosedNode
  5210. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5211. */
  5212. getClosedNode:function () {
  5213. var node;
  5214. if (!this.collapsed) {
  5215. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5216. if (selectOneNode(range)) {
  5217. var child = range.startContainer.childNodes[range.startOffset];
  5218. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5219. node = child;
  5220. }
  5221. }
  5222. }
  5223. return node;
  5224. },
  5225. /**
  5226. * 在页面上高亮range所表示的选区
  5227. * @method select
  5228. * @return { UE.dom.Range } 返回当前Range对象
  5229. */
  5230. //这里不区分ie9以上,trace:3824
  5231. select:browser.ie ? function (noFillData, textRange) {
  5232. var nativeRange;
  5233. if (!this.collapsed)
  5234. this.shrinkBoundary();
  5235. var node = this.getClosedNode();
  5236. if (node && !textRange) {
  5237. try {
  5238. nativeRange = this.document.body.createControlRange();
  5239. nativeRange.addElement(node);
  5240. nativeRange.select();
  5241. } catch (e) {}
  5242. return this;
  5243. }
  5244. var bookmark = this.createBookmark(),
  5245. start = bookmark.start,
  5246. end;
  5247. nativeRange = this.document.body.createTextRange();
  5248. nativeRange.moveToElementText(start);
  5249. nativeRange.moveStart('character', 1);
  5250. if (!this.collapsed) {
  5251. var nativeRangeEnd = this.document.body.createTextRange();
  5252. end = bookmark.end;
  5253. nativeRangeEnd.moveToElementText(end);
  5254. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5255. } else {
  5256. if (!noFillData && this.startContainer.nodeType != 3) {
  5257. //使用<span>|x<span>固定住光标
  5258. var tmpText = this.document.createTextNode(fillChar),
  5259. tmp = this.document.createElement('span');
  5260. tmp.appendChild(this.document.createTextNode(fillChar));
  5261. start.parentNode.insertBefore(tmp, start);
  5262. start.parentNode.insertBefore(tmpText, start);
  5263. //当点b,i,u时,不能清除i上边的b
  5264. removeFillData(this.document, tmpText);
  5265. fillData = tmpText;
  5266. mergeSibling(tmp, 'previousSibling');
  5267. mergeSibling(start, 'nextSibling');
  5268. nativeRange.moveStart('character', -1);
  5269. nativeRange.collapse(true);
  5270. }
  5271. }
  5272. this.moveToBookmark(bookmark);
  5273. tmp && domUtils.remove(tmp);
  5274. //IE在隐藏状态下不支持range操作,catch一下
  5275. try {
  5276. nativeRange.select();
  5277. } catch (e) {
  5278. }
  5279. return this;
  5280. } : function (notInsertFillData) {
  5281. function checkOffset(rng){
  5282. function check(node,offset,dir){
  5283. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5284. rng[dir + 'Offset'] = node.nodeValue.length
  5285. }
  5286. }
  5287. check(rng.startContainer,rng.startOffset,'start');
  5288. check(rng.endContainer,rng.endOffset,'end');
  5289. }
  5290. var win = domUtils.getWindow(this.document),
  5291. sel = win.getSelection(),
  5292. txtNode;
  5293. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5294. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5295. browser.gecko ? this.document.body.focus() : win.focus();
  5296. if (sel) {
  5297. sel.removeAllRanges();
  5298. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5299. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5300. if (this.collapsed && !notInsertFillData) {
  5301. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5302. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5303. // var tmp = this.document.createTextNode('');
  5304. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5305. // }
  5306. //
  5307. //处理光标落在文本节点的情况
  5308. //处理以下的情况
  5309. //<b>|xxxx</b>
  5310. //<b>xxxx</b>|xxxx
  5311. //xxxx<b>|</b>
  5312. var start = this.startContainer,child = start;
  5313. if(start.nodeType == 1){
  5314. child = start.childNodes[this.startOffset];
  5315. }
  5316. if( !(start.nodeType == 3 && this.startOffset) &&
  5317. (child ?
  5318. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5319. :
  5320. (!start.lastChild || start.lastChild.nodeType != 3)
  5321. )
  5322. ){
  5323. txtNode = this.document.createTextNode(fillChar);
  5324. //跟着前边走
  5325. this.insertNode(txtNode);
  5326. removeFillData(this.document, txtNode);
  5327. mergeSibling(txtNode, 'previousSibling');
  5328. mergeSibling(txtNode, 'nextSibling');
  5329. fillData = txtNode;
  5330. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5331. }
  5332. }
  5333. var nativeRange = this.document.createRange();
  5334. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5335. var child = this.startContainer.childNodes[this.startOffset];
  5336. if(!child){
  5337. //往前靠拢
  5338. child = this.startContainer.lastChild;
  5339. if( child && domUtils.isBr(child)){
  5340. this.setStartBefore(child).collapse(true);
  5341. }
  5342. }else{
  5343. //向后靠拢
  5344. while(child && domUtils.isBlockElm(child)){
  5345. if(child.nodeType == 1 && child.childNodes[0]){
  5346. child = child.childNodes[0]
  5347. }else{
  5348. break;
  5349. }
  5350. }
  5351. child && this.setStartBefore(child).collapse(true)
  5352. }
  5353. }
  5354. //是createAddress最后一位算的不准,现在这里进行微调
  5355. checkOffset(this);
  5356. nativeRange.setStart(this.startContainer, this.startOffset);
  5357. nativeRange.setEnd(this.endContainer, this.endOffset);
  5358. sel.addRange(nativeRange);
  5359. }
  5360. return this;
  5361. },
  5362. /**
  5363. * 滚动到当前range开始的位置
  5364. * @method scrollToView
  5365. * @param { Window } win 当前range对象所属的window对象
  5366. * @return { UE.dom.Range } 当前Range对象
  5367. */
  5368. /**
  5369. * 滚动到距离当前range开始位置 offset 的位置处
  5370. * @method scrollToView
  5371. * @param { Window } win 当前range对象所属的window对象
  5372. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5373. * @return { UE.dom.Range } 当前Range对象
  5374. */
  5375. scrollToView:function (win, offset) {
  5376. win = win ? window : domUtils.getWindow(this.document);
  5377. var me = this,
  5378. span = me.document.createElement('span');
  5379. //trace:717
  5380. span.innerHTML = '&nbsp;';
  5381. me.cloneRange().insertNode(span);
  5382. domUtils.scrollToView(span, win, offset);
  5383. domUtils.remove(span);
  5384. return me;
  5385. },
  5386. /**
  5387. * 判断当前选区内容是否占位符
  5388. * @private
  5389. * @method inFillChar
  5390. * @return { Boolean } 如果是占位符返回true,否则返回false
  5391. */
  5392. inFillChar : function(){
  5393. var start = this.startContainer;
  5394. if(this.collapsed && start.nodeType == 3
  5395. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5396. ){
  5397. return true;
  5398. }
  5399. return false;
  5400. },
  5401. /**
  5402. * 保存
  5403. * @method createAddress
  5404. * @private
  5405. * @return { Boolean } 返回开始和结束的位置
  5406. * @example
  5407. * ```html
  5408. * <body>
  5409. * <p>
  5410. * aaaa
  5411. * <em>
  5412. * <!-- 选区开始 -->
  5413. * bbbb
  5414. * <!-- 选区结束 -->
  5415. * </em>
  5416. * </p>
  5417. *
  5418. * <script>
  5419. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5420. * console.log( range.createAddress() );
  5421. * </script>
  5422. * </body>
  5423. * ```
  5424. */
  5425. createAddress : function(ignoreEnd,ignoreTxt){
  5426. var addr = {},me = this;
  5427. function getAddress(isStart){
  5428. var node = isStart ? me.startContainer : me.endContainer;
  5429. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5430. addrs = [];
  5431. for(var i = 0,ci;ci = parents[i++];){
  5432. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5433. }
  5434. var firstIndex = 0;
  5435. if(ignoreTxt){
  5436. if(node.nodeType == 3){
  5437. var tmpNode = node.previousSibling;
  5438. while(tmpNode && tmpNode.nodeType == 3){
  5439. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5440. tmpNode = tmpNode.previousSibling;
  5441. }
  5442. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5443. }else{
  5444. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5445. if(node){
  5446. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5447. }else{
  5448. node = isStart ? me.startContainer : me.endContainer;
  5449. var first = node.firstChild;
  5450. while(first){
  5451. if(domUtils.isFillChar(first)){
  5452. first = first.nextSibling;
  5453. continue;
  5454. }
  5455. firstIndex++;
  5456. if(first.nodeType == 3){
  5457. while( first && first.nodeType == 3){
  5458. first = first.nextSibling;
  5459. }
  5460. }else{
  5461. first = first.nextSibling;
  5462. }
  5463. }
  5464. }
  5465. }
  5466. }else{
  5467. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5468. }
  5469. if(firstIndex < 0){
  5470. firstIndex = 0;
  5471. }
  5472. addrs.push(firstIndex);
  5473. return addrs;
  5474. }
  5475. addr.startAddress = getAddress(true);
  5476. if(!ignoreEnd){
  5477. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5478. }
  5479. return addr;
  5480. },
  5481. /**
  5482. * 保存
  5483. * @method createAddress
  5484. * @private
  5485. * @return { Boolean } 返回开始和结束的位置
  5486. * @example
  5487. * ```html
  5488. * <body>
  5489. * <p>
  5490. * aaaa
  5491. * <em>
  5492. * <!-- 选区开始 -->
  5493. * bbbb
  5494. * <!-- 选区结束 -->
  5495. * </em>
  5496. * </p>
  5497. *
  5498. * <script>
  5499. * var range = editor.selection.getRange();
  5500. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5501. * range.select();
  5502. * //output: 'bbbb'
  5503. * console.log(editor.selection.getText());
  5504. * </script>
  5505. * </body>
  5506. * ```
  5507. */
  5508. moveToAddress : function(addr,ignoreEnd){
  5509. var me = this;
  5510. function getNode(address,isStart){
  5511. var tmpNode = me.document.body,
  5512. parentNode,offset;
  5513. for(var i= 0,ci,l=address.length;i<l;i++){
  5514. ci = address[i];
  5515. parentNode = tmpNode;
  5516. tmpNode = tmpNode.childNodes[ci];
  5517. if(!tmpNode){
  5518. offset = ci;
  5519. break;
  5520. }
  5521. }
  5522. if(isStart){
  5523. if(tmpNode){
  5524. me.setStartBefore(tmpNode)
  5525. }else{
  5526. me.setStart(parentNode,offset)
  5527. }
  5528. }else{
  5529. if(tmpNode){
  5530. me.setEndBefore(tmpNode)
  5531. }else{
  5532. me.setEnd(parentNode,offset)
  5533. }
  5534. }
  5535. }
  5536. getNode(addr.startAddress,true);
  5537. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5538. return me;
  5539. },
  5540. /**
  5541. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5542. * @method equals
  5543. * @param { UE.dom.Range } 需要判断的Range对象
  5544. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5545. */
  5546. equals : function(rng){
  5547. for(var p in this){
  5548. if(this.hasOwnProperty(p)){
  5549. if(this[p] !== rng[p])
  5550. return false
  5551. }
  5552. }
  5553. return true;
  5554. },
  5555. /**
  5556. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5557. * 作为其参数。
  5558. * @method traversal
  5559. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5560. * @return { UE.dom.Range } 当前range对象
  5561. * @example
  5562. * ```html
  5563. *
  5564. * <body>
  5565. *
  5566. * <!-- 选区开始 -->
  5567. * <span></span>
  5568. * <a></a>
  5569. * <!-- 选区结束 -->
  5570. * </body>
  5571. *
  5572. * <script>
  5573. *
  5574. * //output: <span></span><a></a>
  5575. * console.log( range.cloneContents() );
  5576. *
  5577. * range.traversal( function ( node ) {
  5578. *
  5579. * if ( node.nodeType === 1 ) {
  5580. * node.className = "test";
  5581. * }
  5582. *
  5583. * } );
  5584. *
  5585. * //output: <span class="test"></span><a class="test"></a>
  5586. * console.log( range.cloneContents() );
  5587. *
  5588. * </script>
  5589. * ```
  5590. */
  5591. /**
  5592. * 遍历range内的节点。
  5593. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5594. * 作为其参数。
  5595. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5596. * 发doFn函数的执行
  5597. * @method traversal
  5598. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5599. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5600. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5601. * 会触发doFn。
  5602. * @return { UE.dom.Range } 当前range对象
  5603. * @see UE.dom.Range:traversal(Function)
  5604. * @example
  5605. * ```html
  5606. *
  5607. * <body>
  5608. *
  5609. * <!-- 选区开始 -->
  5610. * <span></span>
  5611. * <a></a>
  5612. * <!-- 选区结束 -->
  5613. * </body>
  5614. *
  5615. * <script>
  5616. *
  5617. * //output: <span></span><a></a>
  5618. * console.log( range.cloneContents() );
  5619. *
  5620. * range.traversal( function ( node ) {
  5621. *
  5622. * node.className = "test";
  5623. *
  5624. * }, function ( node ) {
  5625. * return node.nodeType === 1;
  5626. * } );
  5627. *
  5628. * //output: <span class="test"></span><a class="test"></a>
  5629. * console.log( range.cloneContents() );
  5630. *
  5631. * </script>
  5632. * ```
  5633. */
  5634. traversal:function(doFn,filterFn){
  5635. if (this.collapsed)
  5636. return this;
  5637. var bookmark = this.createBookmark(),
  5638. end = bookmark.end,
  5639. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5640. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5641. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5642. doFn(current);
  5643. current = tmpNode;
  5644. }
  5645. return this.moveToBookmark(bookmark);
  5646. }
  5647. };
  5648. })();
  5649. /**
  5650. * 选集
  5651. * @file
  5652. * @module UE.dom
  5653. * @class Selection
  5654. * @since 1.2.6.1
  5655. */
  5656. /**
  5657. * 选区集合
  5658. * @unfile
  5659. * @module UE.dom
  5660. * @class Selection
  5661. */
  5662. (function () {
  5663. function getBoundaryInformation( range, start ) {
  5664. var getIndex = domUtils.getNodeIndex;
  5665. range = range.duplicate();
  5666. range.collapse( start );
  5667. var parent = range.parentElement();
  5668. //如果节点里没有子节点,直接退出
  5669. if ( !parent.hasChildNodes() ) {
  5670. return {container:parent, offset:0};
  5671. }
  5672. var siblings = parent.children,
  5673. child,
  5674. testRange = range.duplicate(),
  5675. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5676. distance;
  5677. while ( startIndex <= endIndex ) {
  5678. index = Math.floor( (startIndex + endIndex) / 2 );
  5679. child = siblings[index];
  5680. testRange.moveToElementText( child );
  5681. var position = testRange.compareEndPoints( 'StartToStart', range );
  5682. if ( position > 0 ) {
  5683. endIndex = index - 1;
  5684. } else if ( position < 0 ) {
  5685. startIndex = index + 1;
  5686. } else {
  5687. //trace:1043
  5688. return {container:parent, offset:getIndex( child )};
  5689. }
  5690. }
  5691. if ( index == -1 ) {
  5692. testRange.moveToElementText( parent );
  5693. testRange.setEndPoint( 'StartToStart', range );
  5694. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5695. siblings = parent.childNodes;
  5696. if ( !distance ) {
  5697. child = siblings[siblings.length - 1];
  5698. return {container:child, offset:child.nodeValue.length};
  5699. }
  5700. var i = siblings.length;
  5701. while ( distance > 0 ){
  5702. distance -= siblings[ --i ].nodeValue.length;
  5703. }
  5704. return {container:siblings[i], offset:-distance};
  5705. }
  5706. testRange.collapse( position > 0 );
  5707. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5708. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5709. if ( !distance ) {
  5710. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5711. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5712. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5713. }
  5714. while ( distance > 0 ) {
  5715. try {
  5716. var pre = child;
  5717. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5718. distance -= child.nodeValue.length;
  5719. } catch ( e ) {
  5720. return {container:parent, offset:getIndex( pre )};
  5721. }
  5722. }
  5723. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5724. }
  5725. /*
  5726. * 将ieRange转换为Range对象
  5727. * @param {Range} ieRange ieRange对象
  5728. * @param {Range} range Range对象
  5729. * @return {Range} range 返回转换后的Range对象
  5730. */
  5731. function transformIERangeToRange( ieRange, range ) {
  5732. if ( ieRange.item ) {
  5733. range.selectNode( ieRange.item( 0 ) );
  5734. } else {
  5735. var bi = getBoundaryInformation( ieRange, true );
  5736. range.setStart( bi.container, bi.offset );
  5737. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5738. bi = getBoundaryInformation( ieRange, false );
  5739. range.setEnd( bi.container, bi.offset );
  5740. }
  5741. }
  5742. return range;
  5743. }
  5744. /*
  5745. * 获得ieRange
  5746. * @param {Selection} sel Selection对象
  5747. * @return {ieRange} 得到ieRange
  5748. */
  5749. function _getIERange( sel ) {
  5750. var ieRange;
  5751. //ie下有可能报错
  5752. try {
  5753. ieRange = sel.getNative().createRange();
  5754. } catch ( e ) {
  5755. return null;
  5756. }
  5757. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5758. if ( ( el.ownerDocument || el ) === sel.document ) {
  5759. return ieRange;
  5760. }
  5761. return null;
  5762. }
  5763. var Selection = dom.Selection = function ( doc ) {
  5764. var me = this, iframe;
  5765. me.document = doc;
  5766. if ( browser.ie9below ) {
  5767. iframe = domUtils.getWindow( doc ).frameElement;
  5768. domUtils.on( iframe, 'beforedeactivate', function () {
  5769. me._bakIERange = me.getIERange();
  5770. } );
  5771. domUtils.on( iframe, 'activate', function () {
  5772. try {
  5773. if ( !_getIERange( me ) && me._bakIERange ) {
  5774. me._bakIERange.select();
  5775. }
  5776. } catch ( ex ) {
  5777. }
  5778. me._bakIERange = null;
  5779. } );
  5780. }
  5781. iframe = doc = null;
  5782. };
  5783. Selection.prototype = {
  5784. rangeInBody : function(rng,txtRange){
  5785. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5786. return node === this.document.body || domUtils.inDoc(node,this.document);
  5787. },
  5788. /**
  5789. * 获取原生seleciton对象
  5790. * @method getNative
  5791. * @return { Object } 获得selection对象
  5792. * @example
  5793. * ```javascript
  5794. * editor.selection.getNative();
  5795. * ```
  5796. */
  5797. getNative:function () {
  5798. var doc = this.document;
  5799. try {
  5800. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5801. } catch ( e ) {
  5802. return null;
  5803. }
  5804. },
  5805. /**
  5806. * 获得ieRange
  5807. * @method getIERange
  5808. * @return { Object } 返回ie原生的Range
  5809. * @example
  5810. * ```javascript
  5811. * editor.selection.getIERange();
  5812. * ```
  5813. */
  5814. getIERange:function () {
  5815. var ieRange = _getIERange( this );
  5816. if ( !ieRange ) {
  5817. if ( this._bakIERange ) {
  5818. return this._bakIERange;
  5819. }
  5820. }
  5821. return ieRange;
  5822. },
  5823. /**
  5824. * 缓存当前选区的range和选区的开始节点
  5825. * @method cache
  5826. */
  5827. cache:function () {
  5828. this.clear();
  5829. this._cachedRange = this.getRange();
  5830. this._cachedStartElement = this.getStart();
  5831. this._cachedStartElementPath = this.getStartElementPath();
  5832. },
  5833. /**
  5834. * 获取选区开始位置的父节点到body
  5835. * @method getStartElementPath
  5836. * @return { Array } 返回父节点集合
  5837. * @example
  5838. * ```javascript
  5839. * editor.selection.getStartElementPath();
  5840. * ```
  5841. */
  5842. getStartElementPath:function () {
  5843. if ( this._cachedStartElementPath ) {
  5844. return this._cachedStartElementPath;
  5845. }
  5846. var start = this.getStart();
  5847. if ( start ) {
  5848. return domUtils.findParents( start, true, null, true )
  5849. }
  5850. return [];
  5851. },
  5852. /**
  5853. * 清空缓存
  5854. * @method clear
  5855. */
  5856. clear:function () {
  5857. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  5858. },
  5859. /**
  5860. * 编辑器是否得到了选区
  5861. * @method isFocus
  5862. */
  5863. isFocus:function () {
  5864. try {
  5865. if(browser.ie9below){
  5866. var nativeRange = _getIERange(this);
  5867. return !!(nativeRange && this.rangeInBody(nativeRange));
  5868. }else{
  5869. return !!this.getNative().rangeCount;
  5870. }
  5871. } catch ( e ) {
  5872. return false;
  5873. }
  5874. },
  5875. /**
  5876. * 获取选区对应的Range
  5877. * @method getRange
  5878. * @return { Object } 得到Range对象
  5879. * @example
  5880. * ```javascript
  5881. * editor.selection.getRange();
  5882. * ```
  5883. */
  5884. getRange:function () {
  5885. var me = this;
  5886. function optimze( range ) {
  5887. var child = me.document.body.firstChild,
  5888. collapsed = range.collapsed;
  5889. while ( child && child.firstChild ) {
  5890. range.setStart( child, 0 );
  5891. child = child.firstChild;
  5892. }
  5893. if ( !range.startContainer ) {
  5894. range.setStart( me.document.body, 0 )
  5895. }
  5896. if ( collapsed ) {
  5897. range.collapse( true );
  5898. }
  5899. }
  5900. if ( me._cachedRange != null ) {
  5901. return this._cachedRange;
  5902. }
  5903. var range = new baidu.editor.dom.Range( me.document );
  5904. if ( browser.ie9below ) {
  5905. var nativeRange = me.getIERange();
  5906. if ( nativeRange ) {
  5907. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  5908. try{
  5909. transformIERangeToRange( nativeRange, range );
  5910. }catch(e){
  5911. optimze( range );
  5912. }
  5913. } else {
  5914. optimze( range );
  5915. }
  5916. } else {
  5917. var sel = me.getNative();
  5918. if ( sel && sel.rangeCount ) {
  5919. var firstRange = sel.getRangeAt( 0 );
  5920. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  5921. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  5922. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  5923. optimze( range );
  5924. }
  5925. } else {
  5926. //trace:1734 有可能已经不在dom树上了,标识的节点
  5927. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  5928. return this._bakRange;
  5929. }
  5930. optimze( range );
  5931. }
  5932. }
  5933. return this._bakRange = range;
  5934. },
  5935. /**
  5936. * 获取开始元素,用于状态反射
  5937. * @method getStart
  5938. * @return { Element } 获得开始元素
  5939. * @example
  5940. * ```javascript
  5941. * editor.selection.getStart();
  5942. * ```
  5943. */
  5944. getStart:function () {
  5945. if ( this._cachedStartElement ) {
  5946. return this._cachedStartElement;
  5947. }
  5948. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  5949. tmpRange,
  5950. start, tmp, parent;
  5951. if ( browser.ie9below ) {
  5952. if ( !range ) {
  5953. //todo 给第一个值可能会有问题
  5954. return this.document.body.firstChild;
  5955. }
  5956. //control元素
  5957. if ( range.item ){
  5958. return range.item( 0 );
  5959. }
  5960. tmpRange = range.duplicate();
  5961. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  5962. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  5963. tmpRange.collapse( 1 );
  5964. start = tmpRange.parentElement();
  5965. parent = tmp = range.parentElement();
  5966. while ( tmp = tmp.parentNode ) {
  5967. if ( tmp == start ) {
  5968. start = parent;
  5969. break;
  5970. }
  5971. }
  5972. } else {
  5973. range.shrinkBoundary();
  5974. start = range.startContainer;
  5975. if ( start.nodeType == 1 && start.hasChildNodes() ){
  5976. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  5977. }
  5978. if ( start.nodeType == 3 ){
  5979. return start.parentNode;
  5980. }
  5981. }
  5982. return start;
  5983. },
  5984. /**
  5985. * 得到选区中的文本
  5986. * @method getText
  5987. * @return { String } 选区中包含的文本
  5988. * @example
  5989. * ```javascript
  5990. * editor.selection.getText();
  5991. * ```
  5992. */
  5993. getText:function () {
  5994. var nativeSel, nativeRange;
  5995. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  5996. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  5997. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  5998. }
  5999. return '';
  6000. },
  6001. /**
  6002. * 清除选区
  6003. * @method clearRange
  6004. * @example
  6005. * ```javascript
  6006. * editor.selection.clearRange();
  6007. * ```
  6008. */
  6009. clearRange : function(){
  6010. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6011. }
  6012. };
  6013. })();
  6014. /**
  6015. * 编辑器主类,包含编辑器提供的大部分公用接口
  6016. * @file
  6017. * @module UE
  6018. * @class Editor
  6019. * @since 1.2.6.1
  6020. */
  6021. /**
  6022. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6023. * @unfile
  6024. * @module UE
  6025. */
  6026. /**
  6027. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6028. * @unfile
  6029. * @module UE
  6030. * @class Editor
  6031. */
  6032. (function () {
  6033. var uid = 0, _selectionChangeTimer;
  6034. /**
  6035. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6036. * @private
  6037. * @method setValue
  6038. * @param { UE.Editor } editor 编辑器事例
  6039. */
  6040. function setValue(form, editor) {
  6041. var textarea;
  6042. if (editor.textarea) {
  6043. if (utils.isString(editor.textarea)) {
  6044. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6045. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6046. textarea = ti;
  6047. break;
  6048. }
  6049. }
  6050. } else {
  6051. textarea = editor.textarea;
  6052. }
  6053. }
  6054. if (!textarea) {
  6055. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6056. 'name': editor.options.textarea,
  6057. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6058. 'style': "display:none"
  6059. }));
  6060. //不要产生多个textarea
  6061. editor.textarea = textarea;
  6062. }
  6063. textarea.value = editor.hasContents() ?
  6064. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6065. ''
  6066. }
  6067. function loadPlugins(me){
  6068. //初始化插件
  6069. for (var pi in UE.plugins) {
  6070. UE.plugins[pi].call(me);
  6071. }
  6072. }
  6073. function checkCurLang(I18N){
  6074. for(var lang in I18N){
  6075. return lang
  6076. }
  6077. }
  6078. function langReadied(me){
  6079. me.langIsReady = true;
  6080. me.fireEvent("langReady");
  6081. }
  6082. /**
  6083. * 编辑器准备就绪后会触发该事件
  6084. * @module UE
  6085. * @class Editor
  6086. * @event ready
  6087. * @remind render方法执行完成之后,会触发该事件
  6088. * @remind
  6089. * @example
  6090. * ```javascript
  6091. * editor.addListener( 'ready', function( editor ) {
  6092. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6093. * } );
  6094. * ```
  6095. */
  6096. /**
  6097. * 执行destroy方法,会触发该事件
  6098. * @module UE
  6099. * @class Editor
  6100. * @event destroy
  6101. * @see UE.Editor:destroy()
  6102. */
  6103. /**
  6104. * 执行reset方法,会触发该事件
  6105. * @module UE
  6106. * @class Editor
  6107. * @event reset
  6108. * @see UE.Editor:reset()
  6109. */
  6110. /**
  6111. * 执行focus方法,会触发该事件
  6112. * @module UE
  6113. * @class Editor
  6114. * @event focus
  6115. * @see UE.Editor:focus(Boolean)
  6116. */
  6117. /**
  6118. * 语言加载完成会触发该事件
  6119. * @module UE
  6120. * @class Editor
  6121. * @event langReady
  6122. */
  6123. /**
  6124. * 运行命令之后会触发该命令
  6125. * @module UE
  6126. * @class Editor
  6127. * @event beforeExecCommand
  6128. */
  6129. /**
  6130. * 运行命令之后会触发该命令
  6131. * @module UE
  6132. * @class Editor
  6133. * @event afterExecCommand
  6134. */
  6135. /**
  6136. * 运行命令之前会触发该命令
  6137. * @module UE
  6138. * @class Editor
  6139. * @event firstBeforeExecCommand
  6140. */
  6141. /**
  6142. * 在getContent方法执行之前会触发该事件
  6143. * @module UE
  6144. * @class Editor
  6145. * @event beforeGetContent
  6146. * @see UE.Editor:getContent()
  6147. */
  6148. /**
  6149. * 在getContent方法执行之后会触发该事件
  6150. * @module UE
  6151. * @class Editor
  6152. * @event afterGetContent
  6153. * @see UE.Editor:getContent()
  6154. */
  6155. /**
  6156. * 在getAllHtml方法执行时会触发该事件
  6157. * @module UE
  6158. * @class Editor
  6159. * @event getAllHtml
  6160. * @see UE.Editor:getAllHtml()
  6161. */
  6162. /**
  6163. * 在setContent方法执行之前会触发该事件
  6164. * @module UE
  6165. * @class Editor
  6166. * @event beforeSetContent
  6167. * @see UE.Editor:setContent(String)
  6168. */
  6169. /**
  6170. * 在setContent方法执行之后会触发该事件
  6171. * @module UE
  6172. * @class Editor
  6173. * @event afterSetContent
  6174. * @see UE.Editor:setContent(String)
  6175. */
  6176. /**
  6177. * 每当编辑器内部选区发生改变时,将触发该事件
  6178. * @event selectionchange
  6179. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6180. * @example
  6181. * ```javascript
  6182. * editor.addListener( 'selectionchange', function( editor ) {
  6183. * console.log('选区发生改变');
  6184. * }
  6185. */
  6186. /**
  6187. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6188. * @module UE
  6189. * @class Editor
  6190. * @event beforeSelectionChange
  6191. * @see UE.Editor:selectionchange
  6192. */
  6193. /**
  6194. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6195. * @module UE
  6196. * @class Editor
  6197. * @event afterSelectionChange
  6198. * @see UE.Editor:selectionchange
  6199. */
  6200. /**
  6201. * 编辑器内容发生改变时会触发该事件
  6202. * @module UE
  6203. * @class Editor
  6204. * @event contentChange
  6205. */
  6206. /**
  6207. * 以默认参数构建一个编辑器实例
  6208. * @constructor
  6209. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6210. * @example
  6211. * ```javascript
  6212. * var editor = new UE.Editor();
  6213. * editor.execCommand('blod');
  6214. * ```
  6215. * @see UE.Config
  6216. */
  6217. /**
  6218. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6219. * @constructor
  6220. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6221. * @param { Object } setting 创建编辑器的参数
  6222. * @example
  6223. * ```javascript
  6224. * var editor = new UE.Editor();
  6225. * editor.execCommand('blod');
  6226. * ```
  6227. * @see UE.Config
  6228. */
  6229. var Editor = UE.Editor = function (options) {
  6230. var me = this;
  6231. me.uid = uid++;
  6232. EventBase.call(me);
  6233. me.commands = {};
  6234. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6235. me.shortcutkeys = {};
  6236. me.inputRules = [];
  6237. me.outputRules = [];
  6238. //设置默认的常用属性
  6239. me.setOpt({
  6240. isShow: true,
  6241. initialContent: '',
  6242. initialStyle:'',
  6243. autoClearinitialContent: false,
  6244. iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css',
  6245. textarea: 'editorValue',
  6246. focus: false,
  6247. focusInEnd: true,
  6248. autoClearEmptyNode: true,
  6249. fullscreen: false,
  6250. readonly: false,
  6251. zIndex: 999,
  6252. imagePopup: true,
  6253. enterTag: 'p',
  6254. customDomain: false,
  6255. lang: 'zh-cn',
  6256. langPath: me.options.UEDITOR_HOME_URL + 'lang/',
  6257. theme: 'default',
  6258. themePath: me.options.UEDITOR_HOME_URL + 'themes/',
  6259. allHtmlEnabled: false,
  6260. scaleEnabled: false,
  6261. tableNativeEditInFF: false,
  6262. autoSyncData : true,
  6263. fileNameFormat: '{time}{rand:6}'
  6264. });
  6265. if(!utils.isEmptyObject(UE.I18N)){
  6266. //修改默认的语言类型
  6267. me.options.lang = checkCurLang(UE.I18N);
  6268. UE.plugin.load(me);
  6269. langReadied(me);
  6270. }else{
  6271. utils.loadFile(document, {
  6272. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6273. tag: "script",
  6274. type: "text/javascript",
  6275. defer: "defer"
  6276. }, function () {
  6277. UE.plugin.load(me);
  6278. langReadied(me);
  6279. });
  6280. }
  6281. UE.instants['ueditorInstant' + me.uid] = me;
  6282. };
  6283. Editor.prototype = {
  6284. /**
  6285. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6286. * @method ready
  6287. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6288. * 立即触发该回调。
  6289. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6290. * @example
  6291. * ```javascript
  6292. * editor.ready( function( editor ) {
  6293. * editor.setContent('初始化完毕');
  6294. * } );
  6295. * ```
  6296. * @see UE.Editor.event:ready
  6297. */
  6298. ready: function (fn) {
  6299. var me = this;
  6300. if (fn) {
  6301. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6302. }
  6303. },
  6304. /**
  6305. * 该方法是提供给插件里面使用,设置配置项默认值
  6306. * @method setOpt
  6307. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6308. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6309. * @param { String } key 编辑器的可接受的选项名称
  6310. * @param { * } val 该选项可接受的值
  6311. * @example
  6312. * ```javascript
  6313. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6314. * ```
  6315. */
  6316. /**
  6317. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6318. * @method setOpt
  6319. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6320. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6321. * @param { Object } options 将要设置的选项的键值对对象
  6322. * @example
  6323. * ```javascript
  6324. * editor.setOpt( {
  6325. * 'initContent': '欢迎使用编辑器'
  6326. * } );
  6327. * ```
  6328. */
  6329. setOpt: function (key, val) {
  6330. var obj = {};
  6331. if (utils.isString(key)) {
  6332. obj[key] = val
  6333. } else {
  6334. obj = key;
  6335. }
  6336. utils.extend(this.options, obj, true);
  6337. },
  6338. /**
  6339. * 销毁编辑器实例,使用textarea代替
  6340. * @method destroy
  6341. * @example
  6342. * ```javascript
  6343. * editor.destroy();
  6344. * ```
  6345. */
  6346. destroy: function () {
  6347. var me = this;
  6348. me.fireEvent('destroy');
  6349. var container = me.container.parentNode;
  6350. var textarea = me.textarea;
  6351. if (!textarea) {
  6352. textarea = document.createElement('textarea');
  6353. container.parentNode.insertBefore(textarea, container);
  6354. } else {
  6355. textarea.style.display = ''
  6356. }
  6357. textarea.style.width = me.iframe.offsetWidth + 'px';
  6358. textarea.style.height = me.iframe.offsetHeight + 'px';
  6359. textarea.value = me.getContent();
  6360. textarea.id = me.key;
  6361. container.innerHTML = '';
  6362. domUtils.remove(container);
  6363. var key = me.key;
  6364. //trace:2004
  6365. for (var p in me) {
  6366. if (me.hasOwnProperty(p)) {
  6367. delete this[p];
  6368. }
  6369. }
  6370. UE.delEditor(key);
  6371. },
  6372. /**
  6373. * 渲染编辑器的DOM到指定容器
  6374. * @method render
  6375. * @param { String } containerId 指定一个容器ID
  6376. * @remind 执行该方法,会触发ready事件
  6377. * @warning 必须且只能调用一次
  6378. */
  6379. /**
  6380. * 渲染编辑器的DOM到指定容器
  6381. * @method render
  6382. * @param { Element } containerDom 直接指定容器对象
  6383. * @remind 执行该方法,会触发ready事件
  6384. * @warning 必须且只能调用一次
  6385. */
  6386. render: function (container) {
  6387. var me = this,
  6388. options = me.options,
  6389. getStyleValue=function(attr){
  6390. return parseInt(domUtils.getComputedStyle(container,attr));
  6391. };
  6392. if (utils.isString(container)) {
  6393. container = document.getElementById(container);
  6394. }
  6395. if (container) {
  6396. if(options.initialFrameWidth){
  6397. options.minFrameWidth = options.initialFrameWidth
  6398. }else{
  6399. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6400. }
  6401. if(options.initialFrameHeight){
  6402. options.minFrameHeight = options.initialFrameHeight
  6403. }else{
  6404. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6405. }
  6406. //update-begin--Author:yugwu Date:20170626 for:[TASK #2135]【浏览器兼容问题】IE8下样式乱了-------------------- --
  6407. container.style.width = !/^\+?[1-9][0-9]*$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6408. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6409. container.style.height = !/^\+?[1-9][0-9]*$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6410. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6411. //update-end--Author:yugwu Date:20170626 for:[TASK #2135]【浏览器兼容问题】IE8下样式乱了-------------------- --
  6412. container.style.zIndex = options.zIndex;
  6413. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6414. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6415. '<style type=\'text/css\'>' +
  6416. //设置四周的留边
  6417. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6418. //设置默认字体和字号
  6419. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6420. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6421. //设置段落间距
  6422. 'p{margin:5px 0;}</style>' +
  6423. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6424. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6425. '</head><body class=\'view\' ></body>' +
  6426. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6427. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6428. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6429. container.appendChild(domUtils.createElement(document, 'iframe', {
  6430. id: 'ueditor_' + me.uid,
  6431. width: "100%",
  6432. height: "100%",
  6433. frameborder: "0",
  6434. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6435. // scrolling :'no',
  6436. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6437. 'document.write("' + html + '");document.close();}())'
  6438. }));
  6439. container.style.overflow = 'hidden';
  6440. //解决如果是给定的百分比,会导致高度算不对的问题
  6441. setTimeout(function(){
  6442. if( /%$/.test(options.initialFrameWidth)){
  6443. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6444. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6445. // container.style.width = options.initialFrameWidth + 'px';
  6446. }
  6447. if(/%$/.test(options.initialFrameHeight)){
  6448. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6449. container.style.height = options.initialFrameHeight + 'px';
  6450. }
  6451. })
  6452. }
  6453. },
  6454. /**
  6455. * 编辑器初始化
  6456. * @method _setup
  6457. * @private
  6458. * @param { Element } doc 编辑器Iframe中的文档对象
  6459. */
  6460. _setup: function (doc) {
  6461. var me = this,
  6462. options = me.options;
  6463. if (ie) {
  6464. doc.body.disabled = true;
  6465. doc.body.contentEditable = true;
  6466. doc.body.disabled = false;
  6467. } else {
  6468. doc.body.contentEditable = true;
  6469. }
  6470. doc.body.spellcheck = false;
  6471. me.document = doc;
  6472. me.window = doc.defaultView || doc.parentWindow;
  6473. me.iframe = me.window.frameElement;
  6474. me.body = doc.body;
  6475. me.selection = new dom.Selection(doc);
  6476. //gecko初始化就能得到range,无法判断isFocus了
  6477. var geckoSel;
  6478. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6479. geckoSel.removeAllRanges();
  6480. }
  6481. this._initEvents();
  6482. //为form提交提供一个隐藏的textarea
  6483. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6484. if (form.tagName == 'FORM') {
  6485. me.form = form;
  6486. if(me.options.autoSyncData){
  6487. domUtils.on(me.window,'blur',function(){
  6488. setValue(form,me);
  6489. });
  6490. }else{
  6491. domUtils.on(form, 'submit', function () {
  6492. setValue(this, me);
  6493. });
  6494. }
  6495. break;
  6496. }
  6497. }
  6498. if (options.initialContent) {
  6499. if (options.autoClearinitialContent) {
  6500. var oldExecCommand = me.execCommand;
  6501. me.execCommand = function () {
  6502. me.fireEvent('firstBeforeExecCommand');
  6503. return oldExecCommand.apply(me, arguments);
  6504. };
  6505. this._setDefaultContent(options.initialContent);
  6506. } else
  6507. this.setContent(options.initialContent, false, true);
  6508. }
  6509. //编辑器不能为空内容
  6510. if (domUtils.isEmptyNode(me.body)) {
  6511. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6512. }
  6513. //如果要求focus, 就把光标定位到内容开始
  6514. if (options.focus) {
  6515. setTimeout(function () {
  6516. me.focus(me.options.focusInEnd);
  6517. //如果自动清除开着,就不需要做selectionchange;
  6518. !me.options.autoClearinitialContent && me._selectionChange();
  6519. }, 0);
  6520. }
  6521. if (!me.container) {
  6522. me.container = this.iframe.parentNode;
  6523. }
  6524. if (options.fullscreen && me.ui) {
  6525. me.ui.setFullScreen(true);
  6526. }
  6527. try {
  6528. me.document.execCommand('2D-position', false, false);
  6529. } catch (e) {
  6530. }
  6531. try {
  6532. me.document.execCommand('enableInlineTableEditing', false, false);
  6533. } catch (e) {
  6534. }
  6535. try {
  6536. me.document.execCommand('enableObjectResizing', false, false);
  6537. } catch (e) {
  6538. }
  6539. //挂接快捷键
  6540. me._bindshortcutKeys();
  6541. me.isReady = 1;
  6542. me.fireEvent('ready');
  6543. options.onready && options.onready.call(me);
  6544. if (!browser.ie9below) {
  6545. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6546. //chrome下会出现alt+tab切换时,导致选区位置不对
  6547. if (e.type == 'blur') {
  6548. me._bakRange = me.selection.getRange();
  6549. try {
  6550. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6551. me.selection.getNative().removeAllRanges();
  6552. } catch (e) {
  6553. me._bakNativeRange = null;
  6554. }
  6555. } else {
  6556. try {
  6557. me._bakRange && me._bakRange.select();
  6558. } catch (e) {
  6559. }
  6560. }
  6561. });
  6562. }
  6563. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6564. if (browser.gecko && browser.version <= 10902) {
  6565. //修复ff3.6初始化进来,不能点击获得焦点
  6566. me.body.contentEditable = false;
  6567. setTimeout(function () {
  6568. me.body.contentEditable = true;
  6569. }, 100);
  6570. setInterval(function () {
  6571. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6572. }, 100)
  6573. }
  6574. !options.isShow && me.setHide();
  6575. options.readonly && me.setDisabled();
  6576. },
  6577. /**
  6578. * 同步数据到编辑器所在的form
  6579. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6580. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6581. * @method sync
  6582. * @example
  6583. * ```javascript
  6584. * editor.sync();
  6585. * form.sumbit(); //form变量已经指向了form元素
  6586. * ```
  6587. */
  6588. /**
  6589. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6590. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6591. * @method sync
  6592. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6593. */
  6594. sync: function (formId) {
  6595. var me = this,
  6596. form = formId ? document.getElementById(formId) :
  6597. domUtils.findParent(me.iframe.parentNode, function (node) {
  6598. return node.tagName == 'FORM'
  6599. }, true);
  6600. form && setValue(form, me);
  6601. },
  6602. /**
  6603. * 设置编辑器高度
  6604. * @method setHeight
  6605. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6606. * @param { Number } number 设置的高度值,纯数值,不带单位
  6607. * @example
  6608. * ```javascript
  6609. * editor.setHeight(number);
  6610. * ```
  6611. */
  6612. setHeight: function (height,notSetHeight) {
  6613. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6614. this.iframe.parentNode.style.height = height + 'px';
  6615. }
  6616. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6617. this.body.style.height = height + 'px';
  6618. },
  6619. /**
  6620. * 为编辑器的编辑命令提供快捷键
  6621. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6622. * @method addshortcutkey
  6623. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6624. * @example
  6625. * ```javascript
  6626. * editor.addshortcutkey({
  6627. * "Bold" : "ctrl+66",//^B
  6628. * "Italic" : "ctrl+73", //^I
  6629. * });
  6630. * ```
  6631. */
  6632. /**
  6633. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6634. * @method addshortcutkey
  6635. * @param { String } cmd 触发快捷键时,响应的命令
  6636. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6637. * @example
  6638. * ```javascript
  6639. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6640. * ```
  6641. */
  6642. addshortcutkey: function (cmd, keys) {
  6643. var obj = {};
  6644. if (keys) {
  6645. obj[cmd] = keys
  6646. } else {
  6647. obj = cmd;
  6648. }
  6649. utils.extend(this.shortcutkeys, obj)
  6650. },
  6651. /**
  6652. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6653. * @method _bindshortcutKeys
  6654. * @private
  6655. */
  6656. _bindshortcutKeys: function () {
  6657. var me = this, shortcutkeys = this.shortcutkeys;
  6658. me.addListener('keydown', function (type, e) {
  6659. var keyCode = e.keyCode || e.which;
  6660. for (var i in shortcutkeys) {
  6661. var tmp = shortcutkeys[i].split(',');
  6662. for (var t = 0, ti; ti = tmp[t++];) {
  6663. ti = ti.split(':');
  6664. var key = ti[0], param = ti[1];
  6665. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6666. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6667. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6668. && keyCode == RegExp.$3
  6669. ) ||
  6670. keyCode == RegExp.$1
  6671. ) {
  6672. if (me.queryCommandState(i,param) != -1)
  6673. me.execCommand(i, param);
  6674. domUtils.preventDefault(e);
  6675. }
  6676. }
  6677. }
  6678. }
  6679. });
  6680. },
  6681. /**
  6682. * 获取编辑器的内容
  6683. * @method getContent
  6684. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6685. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6686. * @example
  6687. * ```javascript
  6688. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6689. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6690. * ```
  6691. */
  6692. /**
  6693. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6694. * @method getContent
  6695. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6696. * 代表当前编辑器的内容是否空,
  6697. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6698. * 经过内置过滤规则处理后的内容。
  6699. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6700. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6701. * @return { String } 编辑器的内容字符串
  6702. * @example
  6703. * ```javascript
  6704. * // editor 是一个编辑器的实例
  6705. * var content = editor.getContent( function ( editor ) {
  6706. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6707. * } );
  6708. * ```
  6709. */
  6710. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6711. var me = this;
  6712. if (cmd && utils.isFunction(cmd)) {
  6713. fn = cmd;
  6714. cmd = '';
  6715. }
  6716. if (fn ? !fn() : !this.hasContents()) {
  6717. return '';
  6718. }
  6719. me.fireEvent('beforegetcontent');
  6720. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6721. me.filterOutputRule(root);
  6722. me.fireEvent('aftergetcontent', cmd,root);
  6723. return root.toHtml(formatter);
  6724. },
  6725. /**
  6726. * 取得完整的html代码,可以直接显示成完整的html文档
  6727. * @method getAllHtml
  6728. * @return { String } 编辑器的内容html文档字符串
  6729. * @eaxmple
  6730. * ```javascript
  6731. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6732. * ```
  6733. */
  6734. getAllHtml: function () {
  6735. var me = this,
  6736. headHtml = [],
  6737. html = '';
  6738. me.fireEvent('getAllHtml', headHtml);
  6739. if (browser.ie && browser.version > 8) {
  6740. var headHtmlForIE9 = '';
  6741. utils.each(me.document.styleSheets, function (si) {
  6742. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6743. });
  6744. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6745. headHtmlForIE9 += si.outerHTML;
  6746. });
  6747. }
  6748. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6749. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6750. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6751. },
  6752. /**
  6753. * 得到编辑器的纯文本内容,但会保留段落格式
  6754. * @method getPlainTxt
  6755. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6756. * @example
  6757. * ```javascript
  6758. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6759. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6760. * ```
  6761. */
  6762. getPlainTxt: function () {
  6763. var reg = new RegExp(domUtils.fillChar, 'g'),
  6764. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6765. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6766. .replace(/<br\/?>/gi, '\n')
  6767. .replace(/<[^>/]+>/g, '')
  6768. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6769. return dtd.$block[c] ? '\n' : b ? b : '';
  6770. });
  6771. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6772. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6773. },
  6774. /**
  6775. * 获取编辑器中的纯文本内容,没有段落格式
  6776. * @method getContentTxt
  6777. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6778. * @example
  6779. * ```javascript
  6780. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6781. * console.log(editor.getPlainTxt()); //输出:"12
  6782. * ```
  6783. */
  6784. getContentTxt: function () {
  6785. var reg = new RegExp(domUtils.fillChar, 'g');
  6786. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6787. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6788. },
  6789. /**
  6790. * 设置编辑器的内容,可修改编辑器当前的html内容
  6791. * @method setContent
  6792. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6793. * @warning 该方法会触发selectionchange事件
  6794. * @param { String } html 要插入的html内容
  6795. * @example
  6796. * ```javascript
  6797. * editor.getContent('<p>test</p>');
  6798. * ```
  6799. */
  6800. /**
  6801. * 设置编辑器的内容,可修改编辑器当前的html内容
  6802. * @method setContent
  6803. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6804. * @warning 该方法会触发selectionchange事件
  6805. * @param { String } html 要插入的html内容
  6806. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6807. * @example
  6808. * ```javascript
  6809. * //假设设置前的编辑器内容是 <p>old text</p>
  6810. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6811. * ```
  6812. */
  6813. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6814. var me = this;
  6815. me.fireEvent('beforesetcontent', html);
  6816. var root = UE.htmlparser(html);
  6817. me.filterInputRule(root);
  6818. html = root.toHtml();
  6819. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6820. function isCdataDiv(node){
  6821. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6822. }
  6823. //给文本或者inline节点套p标签
  6824. if (me.options.enterTag == 'p') {
  6825. var child = this.body.firstChild, tmpNode;
  6826. if (!child || child.nodeType == 1 &&
  6827. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  6828. domUtils.isCustomeNode(child)
  6829. )
  6830. && child === this.body.lastChild) {
  6831. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  6832. } else {
  6833. var p = me.document.createElement('p');
  6834. while (child) {
  6835. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  6836. tmpNode = child.nextSibling;
  6837. p.appendChild(child);
  6838. child = tmpNode;
  6839. }
  6840. if (p.firstChild) {
  6841. if (!child) {
  6842. me.body.appendChild(p);
  6843. break;
  6844. } else {
  6845. child.parentNode.insertBefore(p, child);
  6846. p = me.document.createElement('p');
  6847. }
  6848. }
  6849. child = child.nextSibling;
  6850. }
  6851. }
  6852. }
  6853. me.fireEvent('aftersetcontent');
  6854. me.fireEvent('contentchange');
  6855. !notFireSelectionchange && me._selectionChange();
  6856. //清除保存的选区
  6857. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  6858. //trace:1742 setContent后gecko能得到焦点问题
  6859. var geckoSel;
  6860. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6861. geckoSel.removeAllRanges();
  6862. }
  6863. if(me.options.autoSyncData){
  6864. me.form && setValue(me.form,me);
  6865. }
  6866. },
  6867. /**
  6868. * 让编辑器获得焦点,默认focus到编辑器头部
  6869. * @method focus
  6870. * @example
  6871. * ```javascript
  6872. * editor.focus()
  6873. * ```
  6874. */
  6875. /**
  6876. * 让编辑器获得焦点,toEnd确定focus位置
  6877. * @method focus
  6878. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  6879. * @example
  6880. * ```javascript
  6881. * editor.focus(true)
  6882. * ```
  6883. */
  6884. focus: function (toEnd) {
  6885. try {
  6886. var me = this,
  6887. rng = me.selection.getRange();
  6888. if (toEnd) {
  6889. var node = me.body.lastChild;
  6890. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  6891. if(domUtils.isEmptyBlock(node)){
  6892. rng.setStartAtFirst(node)
  6893. }else{
  6894. rng.setStartAtLast(node)
  6895. }
  6896. rng.collapse(true);
  6897. }
  6898. rng.setCursor(true);
  6899. } else {
  6900. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  6901. var node = me.body.firstChild;
  6902. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  6903. rng.setStartAtFirst(node).collapse(true);
  6904. }
  6905. }
  6906. rng.select(true);
  6907. }
  6908. this.fireEvent('focus selectionchange');
  6909. } catch (e) {
  6910. }
  6911. },
  6912. isFocus:function(){
  6913. return this.selection.isFocus();
  6914. },
  6915. blur:function(){
  6916. var sel = this.selection.getNative();
  6917. if(sel.empty && browser.ie){
  6918. var nativeRng = document.body.createTextRange();
  6919. nativeRng.moveToElementText(document.body);
  6920. nativeRng.collapse(true);
  6921. nativeRng.select();
  6922. sel.empty()
  6923. }else{
  6924. sel.removeAllRanges()
  6925. }
  6926. //this.fireEvent('blur selectionchange');
  6927. },
  6928. /**
  6929. * 初始化UE事件及部分事件代理
  6930. * @method _initEvents
  6931. * @private
  6932. */
  6933. _initEvents: function () {
  6934. var me = this,
  6935. doc = me.document,
  6936. win = me.window;
  6937. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  6938. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  6939. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  6940. domUtils.on(me.body,'drop',function(e){
  6941. //阻止ff下默认的弹出新页面打开图片
  6942. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  6943. me.fireEvent('contentchange')
  6944. });
  6945. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  6946. //特殊键不触发selectionchange
  6947. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  6948. return;
  6949. }
  6950. if (evt.button == 2)return;
  6951. me._selectionChange(250, evt);
  6952. });
  6953. },
  6954. /**
  6955. * 触发事件代理
  6956. * @method _proxyDomEvent
  6957. * @private
  6958. * @return { * } fireEvent的返回值
  6959. * @see UE.EventBase:fireEvent(String)
  6960. */
  6961. _proxyDomEvent: function (evt) {
  6962. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  6963. return false;
  6964. }
  6965. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  6966. return false;
  6967. }
  6968. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  6969. },
  6970. /**
  6971. * 变化选区
  6972. * @method _selectionChange
  6973. * @private
  6974. */
  6975. _selectionChange: function (delay, evt) {
  6976. var me = this;
  6977. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  6978. // if ( !me.selection.isFocus() ){
  6979. // return;
  6980. // }
  6981. var hackForMouseUp = false;
  6982. var mouseX, mouseY;
  6983. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  6984. var range = this.selection.getRange();
  6985. if (!range.collapsed) {
  6986. hackForMouseUp = true;
  6987. mouseX = evt.clientX;
  6988. mouseY = evt.clientY;
  6989. }
  6990. }
  6991. clearTimeout(_selectionChangeTimer);
  6992. _selectionChangeTimer = setTimeout(function () {
  6993. if (!me.selection || !me.selection.getNative()) {
  6994. return;
  6995. }
  6996. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  6997. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  6998. var ieRange;
  6999. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7000. ieRange = me.document.body.createTextRange();
  7001. try {
  7002. ieRange.moveToPoint(mouseX, mouseY);
  7003. } catch (ex) {
  7004. ieRange = null;
  7005. }
  7006. }
  7007. var bakGetIERange;
  7008. if (ieRange) {
  7009. bakGetIERange = me.selection.getIERange;
  7010. me.selection.getIERange = function () {
  7011. return ieRange;
  7012. };
  7013. }
  7014. me.selection.cache();
  7015. if (bakGetIERange) {
  7016. me.selection.getIERange = bakGetIERange;
  7017. }
  7018. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7019. me.fireEvent('beforeselectionchange');
  7020. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7021. me.fireEvent('selectionchange', !!evt);
  7022. me.fireEvent('afterselectionchange');
  7023. me.selection.clear();
  7024. }
  7025. }, delay || 50);
  7026. },
  7027. /**
  7028. * 执行编辑命令
  7029. * @method _callCmdFn
  7030. * @private
  7031. * @param { String } fnName 函数名称
  7032. * @param { * } args 传给命令函数的参数
  7033. * @return { * } 返回命令函数运行的返回值
  7034. */
  7035. _callCmdFn: function (fnName, args) {
  7036. var cmdName = args[0].toLowerCase(),
  7037. cmd, cmdFn;
  7038. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7039. cmdFn = cmd && cmd[fnName];
  7040. //没有querycommandstate或者没有command的都默认返回0
  7041. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7042. return 0;
  7043. } else if (cmdFn) {
  7044. return cmdFn.apply(this, args);
  7045. }
  7046. },
  7047. /**
  7048. * 执行编辑命令cmdName,完成富文本编辑效果
  7049. * @method execCommand
  7050. * @param { String } cmdName 需要执行的命令
  7051. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7052. * @return { * } 返回命令函数运行的返回值
  7053. * @example
  7054. * ```javascript
  7055. * editor.execCommand(cmdName);
  7056. * ```
  7057. */
  7058. execCommand: function (cmdName) {
  7059. cmdName = cmdName.toLowerCase();
  7060. var me = this,
  7061. result,
  7062. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7063. if (!cmd || !cmd.execCommand) {
  7064. return null;
  7065. }
  7066. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7067. me.__hasEnterExecCommand = true;
  7068. if (me.queryCommandState.apply(me,arguments) != -1) {
  7069. me.fireEvent('saveScene');
  7070. me.fireEvent('beforeexeccommand', cmdName);
  7071. result = this._callCmdFn('execCommand', arguments);
  7072. (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7073. me.fireEvent('afterexeccommand', cmdName);
  7074. me.fireEvent('saveScene');
  7075. }
  7076. me.__hasEnterExecCommand = false;
  7077. } else {
  7078. result = this._callCmdFn('execCommand', arguments);
  7079. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7080. }
  7081. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7082. return result;
  7083. },
  7084. /**
  7085. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7086. * @method queryCommandState
  7087. * @param { String } cmdName 需要查询的命令名称
  7088. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7089. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7090. * @example
  7091. * ```javascript
  7092. * editor.queryCommandState(cmdName) => (-1|0|1)
  7093. * ```
  7094. * @see COMMAND.LIST
  7095. */
  7096. queryCommandState: function (cmdName) {
  7097. return this._callCmdFn('queryCommandState', arguments);
  7098. },
  7099. /**
  7100. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7101. * @method queryCommandValue
  7102. * @param { String } cmdName 需要查询的命令名称
  7103. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7104. * @remind 只有部分插件有此方法
  7105. * @return { * } 返回每个命令特定的当前状态值
  7106. * @grammar editor.queryCommandValue(cmdName) => {*}
  7107. * @see COMMAND.LIST
  7108. */
  7109. queryCommandValue: function (cmdName) {
  7110. return this._callCmdFn('queryCommandValue', arguments);
  7111. },
  7112. /**
  7113. * 检查编辑区域中是否有内容
  7114. * @method hasContents
  7115. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7116. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7117. * @return { Boolean } 检查有内容返回true,否则返回false
  7118. * @example
  7119. * ```javascript
  7120. * editor.hasContents()
  7121. * ```
  7122. */
  7123. /**
  7124. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7125. * @method hasContents
  7126. * @param { Array } tags 传入数组判断时用到的节点类型
  7127. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7128. * @example
  7129. * ```javascript
  7130. * editor.hasContents(['span']);
  7131. * ```
  7132. */
  7133. hasContents: function (tags) {
  7134. if (tags) {
  7135. for (var i = 0, ci; ci = tags[i++];) {
  7136. if (this.document.getElementsByTagName(ci).length > 0) {
  7137. return true;
  7138. }
  7139. }
  7140. }
  7141. if (!domUtils.isEmptyBlock(this.body)) {
  7142. return true
  7143. }
  7144. //随时添加,定义的特殊标签如果存在,不能认为是空
  7145. tags = ['div'];
  7146. for (i = 0; ci = tags[i++];) {
  7147. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7148. for (var n = 0, cn; cn = nodes[n++];) {
  7149. if (domUtils.isCustomeNode(cn)) {
  7150. return true;
  7151. }
  7152. }
  7153. }
  7154. return false;
  7155. },
  7156. /**
  7157. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7158. * @method reset
  7159. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7160. * @example
  7161. * ```javascript
  7162. * editor.reset()
  7163. * ```
  7164. */
  7165. reset: function () {
  7166. this.fireEvent('reset');
  7167. },
  7168. /**
  7169. * 设置当前编辑区域可以编辑
  7170. * @method setEnabled
  7171. * @example
  7172. * ```javascript
  7173. * editor.setEnabled()
  7174. * ```
  7175. */
  7176. setEnabled: function () {
  7177. var me = this, range;
  7178. if (me.body.contentEditable == 'false') {
  7179. me.body.contentEditable = true;
  7180. range = me.selection.getRange();
  7181. //有可能内容丢失了
  7182. try {
  7183. range.moveToBookmark(me.lastBk);
  7184. delete me.lastBk
  7185. } catch (e) {
  7186. range.setStartAtFirst(me.body).collapse(true)
  7187. }
  7188. range.select(true);
  7189. if (me.bkqueryCommandState) {
  7190. me.queryCommandState = me.bkqueryCommandState;
  7191. delete me.bkqueryCommandState;
  7192. }
  7193. me.fireEvent('selectionchange');
  7194. }
  7195. },
  7196. enable: function () {
  7197. return this.setEnabled();
  7198. },
  7199. /** 设置当前编辑区域不可编辑
  7200. * @method setDisabled
  7201. */
  7202. /** 设置当前编辑区域不可编辑,except中的命令除外
  7203. * @method setDisabled
  7204. * @param { String } except 例外命令的字符串
  7205. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7206. * @example
  7207. * ```javascript
  7208. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7209. * ```
  7210. */
  7211. /** 设置当前编辑区域不可编辑,except中的命令除外
  7212. * @method setDisabled
  7213. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7214. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7215. * @example
  7216. * ```javascript
  7217. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7218. * ```
  7219. */
  7220. setDisabled: function (except) {
  7221. var me = this;
  7222. except = except ? utils.isArray(except) ? except : [except] : [];
  7223. if (me.body.contentEditable == 'true') {
  7224. if (!me.lastBk) {
  7225. me.lastBk = me.selection.getRange().createBookmark(true);
  7226. }
  7227. me.body.contentEditable = false;
  7228. me.bkqueryCommandState = me.queryCommandState;
  7229. me.queryCommandState = function (type) {
  7230. if (utils.indexOf(except, type) != -1) {
  7231. return me.bkqueryCommandState.apply(me, arguments);
  7232. }
  7233. return -1;
  7234. };
  7235. me.fireEvent('selectionchange');
  7236. }
  7237. },
  7238. disable: function (except) {
  7239. return this.setDisabled(except);
  7240. },
  7241. /**
  7242. * 设置默认内容
  7243. * @method _setDefaultContent
  7244. * @private
  7245. * @param { String } cont 要存入的内容
  7246. */
  7247. _setDefaultContent: function () {
  7248. function clear() {
  7249. var me = this;
  7250. if (me.document.getElementById('initContent')) {
  7251. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7252. me.removeListener('firstBeforeExecCommand focus', clear);
  7253. setTimeout(function () {
  7254. me.focus();
  7255. me._selectionChange();
  7256. }, 0)
  7257. }
  7258. }
  7259. return function (cont) {
  7260. var me = this;
  7261. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7262. me.addListener('firstBeforeExecCommand focus', clear);
  7263. }
  7264. }(),
  7265. /**
  7266. * 显示编辑器
  7267. * @method setShow
  7268. * @example
  7269. * ```javascript
  7270. * editor.setShow()
  7271. * ```
  7272. */
  7273. setShow: function () {
  7274. var me = this, range = me.selection.getRange();
  7275. if (me.container.style.display == 'none') {
  7276. //有可能内容丢失了
  7277. try {
  7278. range.moveToBookmark(me.lastBk);
  7279. delete me.lastBk
  7280. } catch (e) {
  7281. range.setStartAtFirst(me.body).collapse(true)
  7282. }
  7283. //ie下focus实效,所以做了个延迟
  7284. setTimeout(function () {
  7285. range.select(true);
  7286. }, 100);
  7287. me.container.style.display = '';
  7288. }
  7289. },
  7290. show: function () {
  7291. return this.setShow();
  7292. },
  7293. /**
  7294. * 隐藏编辑器
  7295. * @method setHide
  7296. * @example
  7297. * ```javascript
  7298. * editor.setHide()
  7299. * ```
  7300. */
  7301. setHide: function () {
  7302. var me = this;
  7303. if (!me.lastBk) {
  7304. me.lastBk = me.selection.getRange().createBookmark(true);
  7305. }
  7306. me.container.style.display = 'none'
  7307. },
  7308. hide: function () {
  7309. return this.setHide();
  7310. },
  7311. /**
  7312. * 根据指定的路径,获取对应的语言资源
  7313. * @method getLang
  7314. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7315. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7316. * @example
  7317. * ```javascript
  7318. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7319. * ```
  7320. */
  7321. getLang: function (path) {
  7322. var lang = UE.I18N[this.options.lang];
  7323. if (!lang) {
  7324. throw Error("not import language file");
  7325. }
  7326. path = (path || "").split(".");
  7327. for (var i = 0, ci; ci = path[i++];) {
  7328. lang = lang[ci];
  7329. if (!lang)break;
  7330. }
  7331. return lang;
  7332. },
  7333. /**
  7334. * 计算编辑器html内容字符串的长度
  7335. * @method getContentLength
  7336. * @return { Number } 返回计算的长度
  7337. * @example
  7338. * ```javascript
  7339. * //编辑器html内容<p><strong>132</strong></p>
  7340. * editor.getContentLength() //返回27
  7341. * ```
  7342. */
  7343. /**
  7344. * 计算编辑器当前纯文本内容的长度
  7345. * @method getContentLength
  7346. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7347. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7348. * @example
  7349. * ```javascript
  7350. * //编辑器html内容<p><strong>132</strong></p>
  7351. * editor.getContentLength() //返回3
  7352. * ```
  7353. */
  7354. getContentLength: function (ingoneHtml, tagNames) {
  7355. var count = this.getContent(false,false,true).length;
  7356. if (ingoneHtml) {
  7357. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7358. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7359. for (var i = 0, ci; ci = tagNames[i++];) {
  7360. count += this.document.getElementsByTagName(ci).length;
  7361. }
  7362. }
  7363. return count;
  7364. },
  7365. /**
  7366. * 注册输入过滤规则
  7367. * @method addInputRule
  7368. * @param { Function } rule 要添加的过滤规则
  7369. * @example
  7370. * ```javascript
  7371. * editor.addInputRule(function(root){
  7372. * $.each(root.getNodesByTagName('div'),function(i,node){
  7373. * node.tagName="p";
  7374. * });
  7375. * });
  7376. * ```
  7377. */
  7378. addInputRule: function (rule) {
  7379. this.inputRules.push(rule);
  7380. },
  7381. /**
  7382. * 执行注册的过滤规则
  7383. * @method filterInputRule
  7384. * @param { UE.uNode } root 要过滤的uNode节点
  7385. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7386. * @example
  7387. * ```javascript
  7388. * editor.filterInputRule(editor.body);
  7389. * ```
  7390. * @see UE.Editor:addInputRule
  7391. */
  7392. filterInputRule: function (root) {
  7393. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7394. ci.call(this, root)
  7395. }
  7396. },
  7397. /**
  7398. * 注册输出过滤规则
  7399. * @method addOutputRule
  7400. * @param { Function } rule 要添加的过滤规则
  7401. * @example
  7402. * ```javascript
  7403. * editor.addOutputRule(function(root){
  7404. * $.each(root.getNodesByTagName('p'),function(i,node){
  7405. * node.tagName="div";
  7406. * });
  7407. * });
  7408. * ```
  7409. */
  7410. addOutputRule: function (rule) {
  7411. this.outputRules.push(rule)
  7412. },
  7413. /**
  7414. * 根据输出过滤规则,过滤编辑器内容
  7415. * @method filterOutputRule
  7416. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7417. * @param { UE.uNode } root 要过滤的uNode节点
  7418. * @example
  7419. * ```javascript
  7420. * editor.filterOutputRule(editor.body);
  7421. * ```
  7422. * @see UE.Editor:addOutputRule
  7423. */
  7424. filterOutputRule: function (root) {
  7425. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7426. ci.call(this, root)
  7427. }
  7428. }
  7429. };
  7430. utils.inherits(Editor, EventBase);
  7431. })();
  7432. /**
  7433. * @file
  7434. * @module UE.ajax
  7435. * @since 1.2.6.1
  7436. */
  7437. /**
  7438. * 提供对ajax请求的支持
  7439. * @module UE.ajax
  7440. */
  7441. UE.ajax = function() {
  7442. //创建一个ajaxRequest对象
  7443. var fnStr = 'XMLHttpRequest()';
  7444. try {
  7445. new ActiveXObject("Msxml2.XMLHTTP");
  7446. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7447. } catch (e) {
  7448. try {
  7449. new ActiveXObject("Microsoft.XMLHTTP");
  7450. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7451. } catch (e) {
  7452. }
  7453. }
  7454. var creatAjaxRequest = new Function('return new ' + fnStr);
  7455. /*
  7456. * 将json参数转化成适合ajax提交的参数列表
  7457. * @param json
  7458. */
  7459. function json2str(json) {
  7460. var strArr = [];
  7461. for (var i in json) {
  7462. //忽略默认的几个参数
  7463. if(i=="method" || i=="timeout" || i=="async") continue;
  7464. //传递过来的对象和函数不在提交之列
  7465. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7466. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7467. }
  7468. }
  7469. return strArr.join("&");
  7470. }
  7471. return {
  7472. /**
  7473. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7474. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7475. * @method request
  7476. * @param { URLString } url ajax请求的url地址
  7477. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7478. * @example
  7479. * ```javascript
  7480. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7481. * UE.ajax.requeset( 'sayhello.php', {
  7482. *
  7483. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7484. * method: 'GET',
  7485. *
  7486. * //超时时间。 默认为5000, 单位是ms
  7487. * timeout: 10000,
  7488. *
  7489. * //是否是异步请求。 true为异步请求, false为同步请求
  7490. * async: true,
  7491. *
  7492. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7493. * data: {
  7494. * name: 'ueditor'
  7495. * },
  7496. *
  7497. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7498. * onsuccess: function ( xhr ) {
  7499. * console.log( xhr.responseText );
  7500. * },
  7501. *
  7502. * //请求失败或者超时后的回调。
  7503. * onerror: function ( xhr ) {
  7504. * alert( 'Ajax请求失败' );
  7505. * }
  7506. *
  7507. * } );
  7508. * ```
  7509. */
  7510. /**
  7511. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7512. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7513. * @method request
  7514. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7515. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7516. * @example
  7517. * ```javascript
  7518. *
  7519. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7520. * UE.ajax.requeset( 'sayhello.php', {
  7521. *
  7522. * //请求的地址, 该项是必须的。
  7523. * url: 'sayhello.php'
  7524. *
  7525. * } );
  7526. * ```
  7527. */
  7528. request:function(url, ajaxOptions) {
  7529. var ajaxRequest = creatAjaxRequest(),
  7530. //是否超时
  7531. timeIsOut = false,
  7532. //默认参数
  7533. defaultAjaxOptions = {
  7534. method:"POST",
  7535. timeout:5000,
  7536. async:true,
  7537. data:{},//需要传递对象的话只能覆盖
  7538. onsuccess:function() {
  7539. },
  7540. onerror:function() {
  7541. }
  7542. };
  7543. if (typeof url === "object") {
  7544. ajaxOptions = url;
  7545. url = ajaxOptions.url;
  7546. }
  7547. if (!ajaxRequest || !url) return;
  7548. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7549. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7550. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7551. if (!utils.isEmptyObject(ajaxOpts.data)){
  7552. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7553. }
  7554. //超时检测
  7555. var timerID = setTimeout(function() {
  7556. if (ajaxRequest.readyState != 4) {
  7557. timeIsOut = true;
  7558. ajaxRequest.abort();
  7559. clearTimeout(timerID);
  7560. }
  7561. }, ajaxOpts.timeout);
  7562. var method = ajaxOpts.method.toUpperCase();
  7563. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7564. ajaxRequest.open(method, str, ajaxOpts.async);
  7565. ajaxRequest.onreadystatechange = function() {
  7566. if (ajaxRequest.readyState == 4) {
  7567. if (!timeIsOut && ajaxRequest.status == 200) {
  7568. ajaxOpts.onsuccess(ajaxRequest);
  7569. } else {
  7570. ajaxOpts.onerror(ajaxRequest);
  7571. }
  7572. }
  7573. };
  7574. if (method == "POST") {
  7575. ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7576. ajaxRequest.send(submitStr);
  7577. } else {
  7578. ajaxRequest.send(null);
  7579. }
  7580. }
  7581. };
  7582. }();
  7583. /**
  7584. * UE过滤word的静态方法
  7585. * @file
  7586. */
  7587. /**
  7588. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7589. * @module UE
  7590. */
  7591. /**
  7592. * 根据传入html字符串过滤word
  7593. * @module UE
  7594. * @since 1.2.6.1
  7595. * @method filterWord
  7596. * @param { String } html html字符串
  7597. * @return { String } 已过滤后的结果字符串
  7598. * @example
  7599. * ```javascript
  7600. * UE.filterWord(html);
  7601. * ```
  7602. */
  7603. var filterWord = UE.filterWord = function () {
  7604. //是否是word过来的内容
  7605. function isWordDocument( str ) {
  7606. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  7607. }
  7608. //去掉小数
  7609. function transUnit( v ) {
  7610. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  7611. return utils.transUnitToPx(m);
  7612. } );
  7613. return v;
  7614. }
  7615. function filterPasteWord( str ) {
  7616. return str.replace(/[\t\r\n]+/g,' ')
  7617. .replace( /<!--[\s\S]*?-->/ig, "" )
  7618. //转换图片
  7619. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  7620. //opera能自己解析出image所这里直接返回空
  7621. if(browser.opera){
  7622. return '';
  7623. }
  7624. try{
  7625. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  7626. if(/Bitmap/i.test(str)){
  7627. return '';
  7628. }
  7629. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  7630. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  7631. src = str.match(/src=\s*"([^"]*)"/i)[1];
  7632. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  7633. } catch(e){
  7634. return '';
  7635. }
  7636. })
  7637. //针对wps添加的多余标签处理
  7638. .replace(/<\/?div[^>]*>/g,'')
  7639. //去掉多余的属性
  7640. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  7641. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  7642. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  7643. //去掉多余的属性
  7644. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  7645. //保留list的标示
  7646. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  7647. })
  7648. //清除多余的font/span不能匹配&nbsp;有可能是空格
  7649. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  7650. return c.replace(/[\t\r\n ]+/g,' ')
  7651. })
  7652. //处理style的问题
  7653. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  7654. var n = [],
  7655. s = style.replace( /^\s+|\s+$/, '' )
  7656. .replace(/&#39;/g,'\'')
  7657. .replace( /&quot;/gi, "'" )
  7658. .split( /;\s*/g );
  7659. for ( var i = 0,v; v = s[i];i++ ) {
  7660. var name, value,
  7661. parts = v.split( ":" );
  7662. if ( parts.length == 2 ) {
  7663. name = parts[0].toLowerCase();
  7664. value = parts[1].toLowerCase();
  7665. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  7666. ||
  7667. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  7668. ){
  7669. continue;
  7670. }
  7671. switch ( name ) {
  7672. case "mso-padding-alt":
  7673. case "mso-padding-top-alt":
  7674. case "mso-padding-right-alt":
  7675. case "mso-padding-bottom-alt":
  7676. case "mso-padding-left-alt":
  7677. case "mso-margin-alt":
  7678. case "mso-margin-top-alt":
  7679. case "mso-margin-right-alt":
  7680. case "mso-margin-bottom-alt":
  7681. case "mso-margin-left-alt":
  7682. //ie下会出现挤到一起的情况
  7683. //case "mso-table-layout-alt":
  7684. case "mso-height":
  7685. case "mso-width":
  7686. case "mso-vertical-align-alt":
  7687. //trace:1819 ff下会解析出padding在table上
  7688. if(!/<table/.test(tag))
  7689. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  7690. continue;
  7691. case "horiz-align":
  7692. n[i] = "text-align:" + value;
  7693. continue;
  7694. case "vert-align":
  7695. n[i] = "vertical-align:" + value;
  7696. continue;
  7697. case "font-color":
  7698. case "mso-foreground":
  7699. n[i] = "color:" + value;
  7700. continue;
  7701. case "mso-background":
  7702. case "mso-highlight":
  7703. n[i] = "background:" + value;
  7704. continue;
  7705. case "mso-default-height":
  7706. n[i] = "min-height:" + transUnit( value );
  7707. continue;
  7708. case "mso-default-width":
  7709. n[i] = "min-width:" + transUnit( value );
  7710. continue;
  7711. case "mso-padding-between-alt":
  7712. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  7713. continue;
  7714. case "text-line-through":
  7715. if ( (value == "single") || (value == "double") ) {
  7716. n[i] = "text-decoration:line-through";
  7717. }
  7718. continue;
  7719. case "mso-zero-height":
  7720. if ( value == "yes" ) {
  7721. n[i] = "display:none";
  7722. }
  7723. continue;
  7724. // case 'background':
  7725. // break;
  7726. case 'margin':
  7727. if ( !/[1-9]/.test( value ) ) {
  7728. continue;
  7729. }
  7730. }
  7731. 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 )
  7732. ||
  7733. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  7734. ) {
  7735. continue;
  7736. }
  7737. n[i] = name + ":" + parts[1];
  7738. }
  7739. }
  7740. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  7741. })
  7742. .replace(/[\d.]+(cm|pt)/g,function(str){
  7743. return utils.transUnitToPx(str)
  7744. })
  7745. }
  7746. return function ( html ) {
  7747. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  7748. };
  7749. }();
  7750. /**
  7751. * 编辑器模拟的节点类
  7752. * @file
  7753. * @module UE
  7754. * @class uNode
  7755. * @since 1.2.6.1
  7756. */
  7757. /**
  7758. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7759. * @unfile
  7760. * @module UE
  7761. */
  7762. (function () {
  7763. /**
  7764. * 编辑器模拟的节点类
  7765. * @unfile
  7766. * @module UE
  7767. * @class uNode
  7768. */
  7769. /**
  7770. * 通过一个键值对,创建一个uNode对象
  7771. * @constructor
  7772. * @param { Object } attr 传入要创建的uNode的初始属性
  7773. * @example
  7774. * ```javascript
  7775. * var node = new uNode({
  7776. * type:'element',
  7777. * tagName:'span',
  7778. * attrs:{style:'font-size:14px;'}
  7779. * }
  7780. * ```
  7781. */
  7782. var uNode = UE.uNode = function (obj) {
  7783. this.type = obj.type;
  7784. this.data = obj.data;
  7785. this.tagName = obj.tagName;
  7786. this.parentNode = obj.parentNode;
  7787. this.attrs = obj.attrs || {};
  7788. this.children = obj.children;
  7789. };
  7790. var notTransAttrs = {
  7791. 'href':1,
  7792. 'src':1,
  7793. '_src':1,
  7794. '_href':1,
  7795. 'cdata_data':1
  7796. };
  7797. var notTransTagName = {
  7798. style:1,
  7799. script:1
  7800. };
  7801. var indentChar = ' ',
  7802. breakChar = '\n';
  7803. function insertLine(arr, current, begin) {
  7804. arr.push(breakChar);
  7805. return current + (begin ? 1 : -1);
  7806. }
  7807. function insertIndent(arr, current) {
  7808. //插入缩进
  7809. for (var i = 0; i < current; i++) {
  7810. arr.push(indentChar);
  7811. }
  7812. }
  7813. //创建uNode的静态方法
  7814. //支持标签和html
  7815. uNode.createElement = function (html) {
  7816. if (/[<>]/.test(html)) {
  7817. return UE.htmlparser(html).children[0]
  7818. } else {
  7819. return new uNode({
  7820. type:'element',
  7821. children:[],
  7822. tagName:html
  7823. })
  7824. }
  7825. };
  7826. uNode.createText = function (data,noTrans) {
  7827. return new UE.uNode({
  7828. type:'text',
  7829. 'data':noTrans ? data : utils.unhtml(data || '')
  7830. })
  7831. };
  7832. function nodeToHtml(node, arr, formatter, current) {
  7833. switch (node.type) {
  7834. case 'root':
  7835. for (var i = 0, ci; ci = node.children[i++];) {
  7836. //插入新行
  7837. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  7838. insertLine(arr, current, true);
  7839. insertIndent(arr, current)
  7840. }
  7841. nodeToHtml(ci, arr, formatter, current)
  7842. }
  7843. break;
  7844. case 'text':
  7845. isText(node, arr);
  7846. break;
  7847. case 'element':
  7848. isElement(node, arr, formatter, current);
  7849. break;
  7850. case 'comment':
  7851. isComment(node, arr, formatter);
  7852. }
  7853. return arr;
  7854. }
  7855. function isText(node, arr) {
  7856. if(node.parentNode.tagName == 'pre'){
  7857. //源码模式下输入html标签,不能做转换处理,直接输出
  7858. arr.push(node.data)
  7859. }else{
  7860. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  7861. }
  7862. }
  7863. function isElement(node, arr, formatter, current) {
  7864. var attrhtml = '';
  7865. if (node.attrs) {
  7866. attrhtml = [];
  7867. var attrs = node.attrs;
  7868. for (var a in attrs) {
  7869. //这里就针对
  7870. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  7871. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  7872. //有可能做的不够
  7873. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  7874. return '&quot;'
  7875. }) : utils.unhtml(attrs[a])) + '"' : ''))
  7876. }
  7877. attrhtml = attrhtml.join(' ');
  7878. }
  7879. arr.push('<' + node.tagName +
  7880. (attrhtml ? ' ' + attrhtml : '') +
  7881. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  7882. );
  7883. //插入新行
  7884. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  7885. if(node.children && node.children.length){
  7886. current = insertLine(arr, current, true);
  7887. insertIndent(arr, current)
  7888. }
  7889. }
  7890. if (node.children && node.children.length) {
  7891. for (var i = 0, ci; ci = node.children[i++];) {
  7892. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  7893. insertLine(arr, current);
  7894. insertIndent(arr, current)
  7895. }
  7896. nodeToHtml(ci, arr, formatter, current)
  7897. }
  7898. }
  7899. if (!dtd.$empty[node.tagName]) {
  7900. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  7901. if(node.children && node.children.length){
  7902. current = insertLine(arr, current);
  7903. insertIndent(arr, current)
  7904. }
  7905. }
  7906. arr.push('<\/' + node.tagName + '>');
  7907. }
  7908. }
  7909. function isComment(node, arr) {
  7910. arr.push('<!--' + node.data + '-->');
  7911. }
  7912. function getNodeById(root, id) {
  7913. var node;
  7914. if (root.type == 'element' && root.getAttr('id') == id) {
  7915. return root;
  7916. }
  7917. if (root.children && root.children.length) {
  7918. for (var i = 0, ci; ci = root.children[i++];) {
  7919. if (node = getNodeById(ci, id)) {
  7920. return node;
  7921. }
  7922. }
  7923. }
  7924. }
  7925. function getNodesByTagName(node, tagName, arr) {
  7926. if (node.type == 'element' && node.tagName == tagName) {
  7927. arr.push(node);
  7928. }
  7929. if (node.children && node.children.length) {
  7930. for (var i = 0, ci; ci = node.children[i++];) {
  7931. getNodesByTagName(ci, tagName, arr)
  7932. }
  7933. }
  7934. }
  7935. function nodeTraversal(root,fn){
  7936. if(root.children && root.children.length){
  7937. for(var i= 0,ci;ci=root.children[i];){
  7938. nodeTraversal(ci,fn);
  7939. //ci被替换的情况,这里就不再走 fn了
  7940. if(ci.parentNode ){
  7941. if(ci.children && ci.children.length){
  7942. fn(ci)
  7943. }
  7944. if(ci.parentNode) i++
  7945. }
  7946. }
  7947. }else{
  7948. fn(root)
  7949. }
  7950. }
  7951. uNode.prototype = {
  7952. /**
  7953. * 当前节点对象,转换成html文本
  7954. * @method toHtml
  7955. * @return { String } 返回转换后的html字符串
  7956. * @example
  7957. * ```javascript
  7958. * node.toHtml();
  7959. * ```
  7960. */
  7961. /**
  7962. * 当前节点对象,转换成html文本
  7963. * @method toHtml
  7964. * @param { Boolean } formatter 是否格式化返回值
  7965. * @return { String } 返回转换后的html字符串
  7966. * @example
  7967. * ```javascript
  7968. * node.toHtml( true );
  7969. * ```
  7970. */
  7971. toHtml:function (formatter) {
  7972. var arr = [];
  7973. nodeToHtml(this, arr, formatter, 0);
  7974. return arr.join('')
  7975. },
  7976. /**
  7977. * 获取节点的html内容
  7978. * @method innerHTML
  7979. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  7980. * @return { String } 返回节点的html内容
  7981. * @example
  7982. * ```javascript
  7983. * var htmlstr = node.innerHTML();
  7984. * ```
  7985. */
  7986. /**
  7987. * 设置节点的html内容
  7988. * @method innerHTML
  7989. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  7990. * @param { String } htmlstr 传入要设置的html内容
  7991. * @return { UE.uNode } 返回节点本身
  7992. * @example
  7993. * ```javascript
  7994. * node.innerHTML('<span>text</span>');
  7995. * ```
  7996. */
  7997. innerHTML:function (htmlstr) {
  7998. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  7999. return this;
  8000. }
  8001. if (utils.isString(htmlstr)) {
  8002. if(this.children){
  8003. for (var i = 0, ci; ci = this.children[i++];) {
  8004. ci.parentNode = null;
  8005. }
  8006. }
  8007. this.children = [];
  8008. var tmpRoot = UE.htmlparser(htmlstr);
  8009. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8010. this.children.push(ci);
  8011. ci.parentNode = this;
  8012. }
  8013. return this;
  8014. } else {
  8015. var tmpRoot = new UE.uNode({
  8016. type:'root',
  8017. children:this.children
  8018. });
  8019. return tmpRoot.toHtml();
  8020. }
  8021. },
  8022. /**
  8023. * 获取节点的纯文本内容
  8024. * @method innerText
  8025. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8026. * @return { String } 返回节点的存文本内容
  8027. * @example
  8028. * ```javascript
  8029. * var textStr = node.innerText();
  8030. * ```
  8031. */
  8032. /**
  8033. * 设置节点的纯文本内容
  8034. * @method innerText
  8035. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8036. * @param { String } textStr 传入要设置的文本内容
  8037. * @return { UE.uNode } 返回节点本身
  8038. * @example
  8039. * ```javascript
  8040. * node.innerText('<span>text</span>');
  8041. * ```
  8042. */
  8043. innerText:function (textStr,noTrans) {
  8044. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8045. return this;
  8046. }
  8047. if (textStr) {
  8048. if(this.children){
  8049. for (var i = 0, ci; ci = this.children[i++];) {
  8050. ci.parentNode = null;
  8051. }
  8052. }
  8053. this.children = [];
  8054. this.appendChild(uNode.createText(textStr,noTrans));
  8055. return this;
  8056. } else {
  8057. return this.toHtml().replace(/<[^>]+>/g, '');
  8058. }
  8059. },
  8060. /**
  8061. * 获取当前对象的data属性
  8062. * @method getData
  8063. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8064. * @example
  8065. * ```javascript
  8066. * node.getData();
  8067. * ```
  8068. */
  8069. getData:function () {
  8070. if (this.type == 'element')
  8071. return '';
  8072. return this.data
  8073. },
  8074. /**
  8075. * 获取当前节点下的第一个子节点
  8076. * @method firstChild
  8077. * @return { UE.uNode } 返回第一个子节点
  8078. * @example
  8079. * ```javascript
  8080. * node.firstChild(); //返回第一个子节点
  8081. * ```
  8082. */
  8083. firstChild:function () {
  8084. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8085. // return this;
  8086. // }
  8087. return this.children ? this.children[0] : null;
  8088. },
  8089. /**
  8090. * 获取当前节点下的最后一个子节点
  8091. * @method lastChild
  8092. * @return { UE.uNode } 返回最后一个子节点
  8093. * @example
  8094. * ```javascript
  8095. * node.lastChild(); //返回最后一个子节点
  8096. * ```
  8097. */
  8098. lastChild:function () {
  8099. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8100. // return this;
  8101. // }
  8102. return this.children ? this.children[this.children.length - 1] : null;
  8103. },
  8104. /**
  8105. * 获取和当前节点有相同父亲节点的前一个节点
  8106. * @method previousSibling
  8107. * @return { UE.uNode } 返回前一个节点
  8108. * @example
  8109. * ```javascript
  8110. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8111. * ```
  8112. */
  8113. previousSibling : function(){
  8114. var parent = this.parentNode;
  8115. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8116. if (ci === this) {
  8117. return i == 0 ? null : parent.children[i-1];
  8118. }
  8119. }
  8120. },
  8121. /**
  8122. * 获取和当前节点有相同父亲节点的后一个节点
  8123. * @method nextSibling
  8124. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8125. * @example
  8126. * ```javascript
  8127. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8128. * ```
  8129. */
  8130. nextSibling : function(){
  8131. var parent = this.parentNode;
  8132. for (var i = 0, ci; ci = parent.children[i++];) {
  8133. if (ci === this) {
  8134. return parent.children[i];
  8135. }
  8136. }
  8137. },
  8138. /**
  8139. * 用新的节点替换当前节点
  8140. * @method replaceChild
  8141. * @param { UE.uNode } target 要替换成该节点参数
  8142. * @param { UE.uNode } source 要被替换掉的节点
  8143. * @return { UE.uNode } 返回替换之后的节点对象
  8144. * @example
  8145. * ```javascript
  8146. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8147. * ```
  8148. */
  8149. replaceChild:function (target, source) {
  8150. if (this.children) {
  8151. if(target.parentNode){
  8152. target.parentNode.removeChild(target);
  8153. }
  8154. for (var i = 0, ci; ci = this.children[i]; i++) {
  8155. if (ci === source) {
  8156. this.children.splice(i, 1, target);
  8157. source.parentNode = null;
  8158. target.parentNode = this;
  8159. return target;
  8160. }
  8161. }
  8162. }
  8163. },
  8164. /**
  8165. * 在节点的子节点列表最后位置插入一个节点
  8166. * @method appendChild
  8167. * @param { UE.uNode } node 要插入的节点
  8168. * @return { UE.uNode } 返回刚插入的子节点
  8169. * @example
  8170. * ```javascript
  8171. * node.appendChild( newNode ); //在node内插入子节点newNode
  8172. * ```
  8173. */
  8174. appendChild:function (node) {
  8175. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8176. if (!this.children) {
  8177. this.children = []
  8178. }
  8179. if(node.parentNode){
  8180. node.parentNode.removeChild(node);
  8181. }
  8182. for (var i = 0, ci; ci = this.children[i]; i++) {
  8183. if (ci === node) {
  8184. this.children.splice(i, 1);
  8185. break;
  8186. }
  8187. }
  8188. this.children.push(node);
  8189. node.parentNode = this;
  8190. return node;
  8191. }
  8192. },
  8193. /**
  8194. * 在传入节点的前面插入一个节点
  8195. * @method insertBefore
  8196. * @param { UE.uNode } target 要插入的节点
  8197. * @param { UE.uNode } source 在该参数节点前面插入
  8198. * @return { UE.uNode } 返回刚插入的子节点
  8199. * @example
  8200. * ```javascript
  8201. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8202. * ```
  8203. */
  8204. insertBefore:function (target, source) {
  8205. if (this.children) {
  8206. if(target.parentNode){
  8207. target.parentNode.removeChild(target);
  8208. }
  8209. for (var i = 0, ci; ci = this.children[i]; i++) {
  8210. if (ci === source) {
  8211. this.children.splice(i, 0, target);
  8212. target.parentNode = this;
  8213. return target;
  8214. }
  8215. }
  8216. }
  8217. },
  8218. /**
  8219. * 在传入节点的后面插入一个节点
  8220. * @method insertAfter
  8221. * @param { UE.uNode } target 要插入的节点
  8222. * @param { UE.uNode } source 在该参数节点后面插入
  8223. * @return { UE.uNode } 返回刚插入的子节点
  8224. * @example
  8225. * ```javascript
  8226. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8227. * ```
  8228. */
  8229. insertAfter:function (target, source) {
  8230. if (this.children) {
  8231. if(target.parentNode){
  8232. target.parentNode.removeChild(target);
  8233. }
  8234. for (var i = 0, ci; ci = this.children[i]; i++) {
  8235. if (ci === source) {
  8236. this.children.splice(i + 1, 0, target);
  8237. target.parentNode = this;
  8238. return target;
  8239. }
  8240. }
  8241. }
  8242. },
  8243. /**
  8244. * 从当前节点的子节点列表中,移除节点
  8245. * @method removeChild
  8246. * @param { UE.uNode } node 要移除的节点引用
  8247. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8248. * @return { * } 返回刚移除的子节点
  8249. * @example
  8250. * ```javascript
  8251. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8252. * ```
  8253. */
  8254. removeChild:function (node,keepChildren) {
  8255. if (this.children) {
  8256. for (var i = 0, ci; ci = this.children[i]; i++) {
  8257. if (ci === node) {
  8258. this.children.splice(i, 1);
  8259. ci.parentNode = null;
  8260. if(keepChildren && ci.children && ci.children.length){
  8261. for(var j= 0,cj;cj=ci.children[j];j++){
  8262. this.children.splice(i+j,0,cj);
  8263. cj.parentNode = this;
  8264. }
  8265. }
  8266. return ci;
  8267. }
  8268. }
  8269. }
  8270. },
  8271. /**
  8272. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8273. * @method getAttr
  8274. * @param { String } attrName 要获取的属性名称
  8275. * @return { * } 返回attrs对象下的属性值
  8276. * @example
  8277. * ```javascript
  8278. * node.getAttr('title');
  8279. * ```
  8280. */
  8281. getAttr:function (attrName) {
  8282. return this.attrs && this.attrs[attrName.toLowerCase()]
  8283. },
  8284. /**
  8285. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8286. * @method setAttr
  8287. * @param { String } attrName 要设置的属性名称
  8288. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8289. * @return { * } 返回attrs对象下的属性值
  8290. * @example
  8291. * ```javascript
  8292. * node.setAttr('title','标题');
  8293. * ```
  8294. */
  8295. setAttr:function (attrName, attrVal) {
  8296. if (!attrName) {
  8297. delete this.attrs;
  8298. return;
  8299. }
  8300. if(!this.attrs){
  8301. this.attrs = {};
  8302. }
  8303. if (utils.isObject(attrName)) {
  8304. for (var a in attrName) {
  8305. if (!attrName[a]) {
  8306. delete this.attrs[a]
  8307. } else {
  8308. this.attrs[a.toLowerCase()] = attrName[a];
  8309. }
  8310. }
  8311. } else {
  8312. if (!attrVal) {
  8313. delete this.attrs[attrName]
  8314. } else {
  8315. this.attrs[attrName.toLowerCase()] = attrVal;
  8316. }
  8317. }
  8318. },
  8319. /**
  8320. * 获取当前节点在父节点下的位置索引
  8321. * @method getIndex
  8322. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8323. * @example
  8324. * ```javascript
  8325. * node.getIndex();
  8326. * ```
  8327. */
  8328. getIndex:function(){
  8329. var parent = this.parentNode;
  8330. for(var i= 0,ci;ci=parent.children[i];i++){
  8331. if(ci === this){
  8332. return i;
  8333. }
  8334. }
  8335. return -1;
  8336. },
  8337. /**
  8338. * 在当前节点下,根据id查找节点
  8339. * @method getNodeById
  8340. * @param { String } id 要查找的id
  8341. * @return { UE.uNode } 返回找到的节点
  8342. * @example
  8343. * ```javascript
  8344. * node.getNodeById('textId');
  8345. * ```
  8346. */
  8347. getNodeById:function (id) {
  8348. var node;
  8349. if (this.children && this.children.length) {
  8350. for (var i = 0, ci; ci = this.children[i++];) {
  8351. if (node = getNodeById(ci, id)) {
  8352. return node;
  8353. }
  8354. }
  8355. }
  8356. },
  8357. /**
  8358. * 在当前节点下,根据元素名称查找节点列表
  8359. * @method getNodesByTagName
  8360. * @param { String } tagNames 要查找的元素名称
  8361. * @return { Array } 返回找到的节点列表
  8362. * @example
  8363. * ```javascript
  8364. * node.getNodesByTagName('span');
  8365. * ```
  8366. */
  8367. getNodesByTagName:function (tagNames) {
  8368. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8369. var arr = [], me = this;
  8370. utils.each(tagNames, function (tagName) {
  8371. if (me.children && me.children.length) {
  8372. for (var i = 0, ci; ci = me.children[i++];) {
  8373. getNodesByTagName(ci, tagName, arr)
  8374. }
  8375. }
  8376. });
  8377. return arr;
  8378. },
  8379. /**
  8380. * 根据样式名称,获取节点的样式值
  8381. * @method getStyle
  8382. * @param { String } name 要获取的样式名称
  8383. * @return { String } 返回样式值
  8384. * @example
  8385. * ```javascript
  8386. * node.getStyle('font-size');
  8387. * ```
  8388. */
  8389. getStyle:function (name) {
  8390. var cssStyle = this.getAttr('style');
  8391. if (!cssStyle) {
  8392. return ''
  8393. }
  8394. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8395. var match = cssStyle.match(reg);
  8396. if (match && match[0]) {
  8397. return match[2]
  8398. }
  8399. return '';
  8400. },
  8401. /**
  8402. * 给节点设置样式
  8403. * @method setStyle
  8404. * @param { String } name 要设置的的样式名称
  8405. * @param { String } val 要设置的的样值
  8406. * @example
  8407. * ```javascript
  8408. * node.setStyle('font-size', '12px');
  8409. * ```
  8410. */
  8411. setStyle:function (name, val) {
  8412. function exec(name, val) {
  8413. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8414. cssStyle = cssStyle.replace(reg, '$1');
  8415. if (val) {
  8416. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8417. }
  8418. }
  8419. var cssStyle = this.getAttr('style');
  8420. if (!cssStyle) {
  8421. cssStyle = '';
  8422. }
  8423. if (utils.isObject(name)) {
  8424. for (var a in name) {
  8425. exec(a, name[a])
  8426. }
  8427. } else {
  8428. exec(name, val)
  8429. }
  8430. this.setAttr('style', utils.trim(cssStyle))
  8431. },
  8432. /**
  8433. * 传入一个函数,递归遍历当前节点下的所有节点
  8434. * @method traversal
  8435. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8436. * @example
  8437. * ```javascript
  8438. * traversal(node, function(){
  8439. * console.log(node.type);
  8440. * });
  8441. * ```
  8442. */
  8443. traversal:function(fn){
  8444. if(this.children && this.children.length){
  8445. nodeTraversal(this,fn);
  8446. }
  8447. return this;
  8448. }
  8449. }
  8450. })();
  8451. /**
  8452. * html字符串转换成uNode节点
  8453. * @file
  8454. * @module UE
  8455. * @since 1.2.6.1
  8456. */
  8457. /**
  8458. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8459. * @unfile
  8460. * @module UE
  8461. */
  8462. /**
  8463. * html字符串转换成uNode节点的静态方法
  8464. * @method htmlparser
  8465. * @param { String } htmlstr 要转换的html代码
  8466. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8467. * @return { uNode } 给定的html片段转换形成的uNode对象
  8468. * @example
  8469. * ```javascript
  8470. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8471. * ```
  8472. */
  8473. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8474. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8475. //先去掉了,加上的原因忘了,这里先记录
  8476. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8477. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8478. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8479. var allowEmptyTags = {
  8480. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8481. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8482. };
  8483. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8484. if(!ignoreBlank){
  8485. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8486. //br暂时单独处理
  8487. if(b && allowEmptyTags[b.toLowerCase()]){
  8488. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8489. }
  8490. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8491. });
  8492. }
  8493. var notTransAttrs = {
  8494. 'href':1,
  8495. 'src':1
  8496. };
  8497. var uNode = UE.uNode,
  8498. needParentNode = {
  8499. 'td':'tr',
  8500. 'tr':['tbody','thead','tfoot'],
  8501. 'tbody':'table',
  8502. 'th':'tr',
  8503. 'thead':'table',
  8504. 'tfoot':'table',
  8505. 'caption':'table',
  8506. 'li':['ul', 'ol'],
  8507. 'dt':'dl',
  8508. 'dd':'dl',
  8509. 'option':'select'
  8510. },
  8511. needChild = {
  8512. 'ol':'li',
  8513. 'ul':'li'
  8514. };
  8515. function text(parent, data) {
  8516. if(needChild[parent.tagName]){
  8517. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8518. parent.appendChild(tmpNode);
  8519. tmpNode.appendChild(uNode.createText(data));
  8520. parent = tmpNode;
  8521. }else{
  8522. parent.appendChild(uNode.createText(data));
  8523. }
  8524. }
  8525. function element(parent, tagName, htmlattr) {
  8526. var needParentTag;
  8527. if (needParentTag = needParentNode[tagName]) {
  8528. var tmpParent = parent,hasParent;
  8529. while(tmpParent.type != 'root'){
  8530. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8531. parent = tmpParent;
  8532. hasParent = true;
  8533. break;
  8534. }
  8535. tmpParent = tmpParent.parentNode;
  8536. }
  8537. if(!hasParent){
  8538. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8539. }
  8540. }
  8541. //按dtd处理嵌套
  8542. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8543. // parent = parent.parentNode;
  8544. var elm = new uNode({
  8545. parentNode:parent,
  8546. type:'element',
  8547. tagName:tagName.toLowerCase(),
  8548. //是自闭合的处理一下
  8549. children:dtd.$empty[tagName] ? null : []
  8550. });
  8551. //如果属性存在,处理属性
  8552. if (htmlattr) {
  8553. var attrs = {}, match;
  8554. while (match = re_attr.exec(htmlattr)) {
  8555. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8556. }
  8557. elm.attrs = attrs;
  8558. }
  8559. parent.children.push(elm);
  8560. //如果是自闭合节点返回父亲节点
  8561. return dtd.$empty[tagName] ? parent : elm
  8562. }
  8563. function comment(parent, data) {
  8564. parent.children.push(new uNode({
  8565. type:'comment',
  8566. data:data,
  8567. parentNode:parent
  8568. }));
  8569. }
  8570. var match, currentIndex = 0, nextIndex = 0;
  8571. //设置根节点
  8572. var root = new uNode({
  8573. type:'root',
  8574. children:[]
  8575. });
  8576. var currentParent = root;
  8577. while (match = re_tag.exec(htmlstr)) {
  8578. currentIndex = match.index;
  8579. try{
  8580. if (currentIndex > nextIndex) {
  8581. //text node
  8582. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8583. }
  8584. if (match[3]) {
  8585. if(dtd.$cdata[currentParent.tagName]){
  8586. text(currentParent, match[0]);
  8587. }else{
  8588. //start tag
  8589. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8590. }
  8591. } else if (match[1]) {
  8592. if(currentParent.type != 'root'){
  8593. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  8594. text(currentParent, match[0]);
  8595. }else{
  8596. var tmpParent = currentParent;
  8597. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  8598. currentParent = currentParent.parentNode;
  8599. if(currentParent.type == 'root'){
  8600. currentParent = tmpParent;
  8601. throw 'break'
  8602. }
  8603. }
  8604. //end tag
  8605. currentParent = currentParent.parentNode;
  8606. }
  8607. }
  8608. } else if (match[2]) {
  8609. //comment
  8610. comment(currentParent, match[2])
  8611. }
  8612. }catch(e){}
  8613. nextIndex = re_tag.lastIndex;
  8614. }
  8615. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  8616. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  8617. if (nextIndex < htmlstr.length) {
  8618. text(currentParent, htmlstr.slice(nextIndex));
  8619. }
  8620. return root;
  8621. };
  8622. /**
  8623. * UE过滤节点的静态方法
  8624. * @file
  8625. */
  8626. /**
  8627. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8628. * @module UE
  8629. */
  8630. /**
  8631. * 根据传入节点和过滤规则过滤相应节点
  8632. * @module UE
  8633. * @since 1.2.6.1
  8634. * @method filterNode
  8635. * @param { Object } root 指定root节点
  8636. * @param { Object } rules 过滤规则json对象
  8637. * @example
  8638. * ```javascript
  8639. * UE.filterNode(root,editor.options.filterRules);
  8640. * ```
  8641. */
  8642. var filterNode = UE.filterNode = function () {
  8643. function filterNode(node,rules){
  8644. switch (node.type) {
  8645. case 'text':
  8646. break;
  8647. case 'element':
  8648. var val;
  8649. if(val = rules[node.tagName]){
  8650. if(val === '-'){
  8651. node.parentNode.removeChild(node)
  8652. }else if(utils.isFunction(val)){
  8653. var parentNode = node.parentNode,
  8654. index = node.getIndex();
  8655. val(node);
  8656. if(node.parentNode){
  8657. if(node.children){
  8658. for(var i = 0,ci;ci=node.children[i];){
  8659. filterNode(ci,rules);
  8660. if(ci.parentNode){
  8661. i++;
  8662. }
  8663. }
  8664. }
  8665. }else{
  8666. for(var i = index,ci;ci=parentNode.children[i];){
  8667. filterNode(ci,rules);
  8668. if(ci.parentNode){
  8669. i++;
  8670. }
  8671. }
  8672. }
  8673. }else{
  8674. var attrs = val['$'];
  8675. if(attrs && node.attrs){
  8676. var tmpAttrs = {},tmpVal;
  8677. for(var a in attrs){
  8678. tmpVal = node.getAttr(a);
  8679. //todo 只先对style单独处理
  8680. if(a == 'style' && utils.isArray(attrs[a])){
  8681. var tmpCssStyle = [];
  8682. utils.each(attrs[a],function(v){
  8683. var tmp;
  8684. if(tmp = node.getStyle(v)){
  8685. tmpCssStyle.push(v + ':' + tmp);
  8686. }
  8687. });
  8688. tmpVal = tmpCssStyle.join(';')
  8689. }
  8690. if(tmpVal){
  8691. tmpAttrs[a] = tmpVal;
  8692. }
  8693. }
  8694. node.attrs = tmpAttrs;
  8695. }
  8696. if(node.children){
  8697. for(var i = 0,ci;ci=node.children[i];){
  8698. filterNode(ci,rules);
  8699. if(ci.parentNode){
  8700. i++;
  8701. }
  8702. }
  8703. }
  8704. }
  8705. }else{
  8706. //如果不在名单里扣出子节点并删除该节点,cdata除外
  8707. if(dtd.$cdata[node.tagName]){
  8708. node.parentNode.removeChild(node)
  8709. }else{
  8710. var parentNode = node.parentNode,
  8711. index = node.getIndex();
  8712. node.parentNode.removeChild(node,true);
  8713. for(var i = index,ci;ci=parentNode.children[i];){
  8714. filterNode(ci,rules);
  8715. if(ci.parentNode){
  8716. i++;
  8717. }
  8718. }
  8719. }
  8720. }
  8721. break;
  8722. case 'comment':
  8723. node.parentNode.removeChild(node)
  8724. }
  8725. }
  8726. return function(root,rules){
  8727. if(utils.isEmptyObject(rules)){
  8728. return root;
  8729. }
  8730. var val;
  8731. if(val = rules['-']){
  8732. utils.each(val.split(' '),function(k){
  8733. rules[k] = '-'
  8734. })
  8735. }
  8736. for(var i= 0,ci;ci=root.children[i];){
  8737. filterNode(ci,rules);
  8738. if(ci.parentNode){
  8739. i++;
  8740. }
  8741. }
  8742. return root;
  8743. }
  8744. }();
  8745. /*
  8746. * Created with JetBrains PhpStorm.
  8747. * User: campaign
  8748. * Date: 10/8/13
  8749. * Time: 6:15 PM
  8750. * To change this template use File | Settings | File Templates.
  8751. */
  8752. UE.plugin = function(){
  8753. var _plugins = {};
  8754. return {
  8755. register : function(pluginName,fn,oldOptionName,afterDisabled){
  8756. if(oldOptionName && utils.isFunction(oldOptionName)){
  8757. afterDisabled = oldOptionName;
  8758. oldOptionName = null
  8759. }
  8760. _plugins[pluginName] = {
  8761. optionName : oldOptionName || pluginName,
  8762. execFn : fn,
  8763. //当插件被禁用时执行
  8764. afterDisabled : afterDisabled
  8765. }
  8766. },
  8767. load : function(editor){
  8768. utils.each(_plugins,function(plugin){
  8769. var _export = plugin.execFn.call(editor);
  8770. if(editor.options[plugin.optionName] !== false){
  8771. if(_export){
  8772. //后边需要再做扩展
  8773. utils.each(_export,function(v,k){
  8774. switch(k.toLowerCase()){
  8775. case 'shortcutkey':
  8776. editor.addshortcutkey(v);
  8777. break;
  8778. case 'bindevents':
  8779. utils.each(v,function(fn,eventName){
  8780. editor.addListener(eventName,fn);
  8781. });
  8782. break;
  8783. case 'bindmultievents':
  8784. utils.each(utils.isArray(v) ? v:[v],function(event){
  8785. var types = utils.trim(event.type).split(/\s+/);
  8786. utils.each(types,function(eventName){
  8787. editor.addListener(eventName, event.handler);
  8788. });
  8789. });
  8790. break;
  8791. case 'commands':
  8792. utils.each(v,function(execFn,execName){
  8793. editor.commands[execName] = execFn
  8794. });
  8795. break;
  8796. case 'outputrule':
  8797. editor.addOutputRule(v);
  8798. break;
  8799. case 'inputrule':
  8800. editor.addInputRule(v);
  8801. break;
  8802. case 'defaultoptions':
  8803. editor.setOpt(v)
  8804. }
  8805. })
  8806. }
  8807. }else if(plugin.afterDisabled){
  8808. plugin.afterDisabled.call(editor)
  8809. }
  8810. });
  8811. //向下兼容
  8812. utils.each(UE.plugins,function(plugin){
  8813. plugin.call(editor);
  8814. });
  8815. },
  8816. run : function(plugnName,editor){
  8817. var plugin = _plugins[pluginName];
  8818. if(plugin){
  8819. plugin.exeFn.call(editor)
  8820. }
  8821. }
  8822. }
  8823. }();
  8824. ///import core
  8825. ///plugin 编辑器默认的过滤转换机制
  8826. UE.plugins['defaultfilter'] = function () {
  8827. var me = this;
  8828. me.setOpt({
  8829. 'allowDivTransToP':true,
  8830. 'disabledTableInTable':true
  8831. });
  8832. //默认的过滤处理
  8833. //进入编辑器的内容处理
  8834. me.addInputRule(function (root) {
  8835. var allowDivTransToP = this.options.allowDivTransToP;
  8836. var val;
  8837. function tdParent(node){
  8838. while(node && node.type == 'element'){
  8839. if(node.tagName == 'td'){
  8840. return true;
  8841. }
  8842. node = node.parentNode;
  8843. }
  8844. return false;
  8845. }
  8846. //进行默认的处理
  8847. root.traversal(function (node) {
  8848. if (node.type == 'element') {
  8849. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8850. if (!node.firstChild()) node.parentNode.removeChild(node);
  8851. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8852. node.parentNode.removeChild(node, true)
  8853. }
  8854. return;
  8855. }
  8856. switch (node.tagName) {
  8857. case 'style':
  8858. case 'script':
  8859. node.setAttr({
  8860. cdata_tag: node.tagName,
  8861. cdata_data: (node.innerHTML() || ''),
  8862. '_ue_custom_node_':'true'
  8863. });
  8864. node.tagName = 'div';
  8865. node.innerHTML('');
  8866. break;
  8867. case 'a':
  8868. if (val = node.getAttr('href')) {
  8869. node.setAttr('_href', val)
  8870. }
  8871. break;
  8872. case 'img':
  8873. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  8874. if (val = node.getAttr('src')) {
  8875. if (/^data:/.test(val)) {
  8876. node.parentNode.removeChild(node);
  8877. break;
  8878. }
  8879. }
  8880. node.setAttr('_src', node.getAttr('src'));
  8881. break;
  8882. case 'span':
  8883. if (browser.webkit && (val = node.getStyle('white-space'))) {
  8884. if (/nowrap|normal/.test(val)) {
  8885. node.setStyle('white-space', '');
  8886. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  8887. node.parentNode.removeChild(node, true)
  8888. }
  8889. }
  8890. }
  8891. break;
  8892. case 'p':
  8893. if (val = node.getAttr('align')) {
  8894. node.setAttr('align');
  8895. node.setStyle('text-align', val)
  8896. }
  8897. //trace:3431
  8898. // var cssStyle = node.getAttr('style');
  8899. // if (cssStyle) {
  8900. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  8901. // node.setAttr('style', cssStyle)
  8902. //
  8903. // }
  8904. //p标签不允许嵌套
  8905. utils.each(node.children,function(n){
  8906. if(n.type == 'element' && n.tagName == 'p'){
  8907. var next = n.nextSibling();
  8908. node.parentNode.insertAfter(n,node);
  8909. var last = n;
  8910. while(next){
  8911. var tmp = next.nextSibling();
  8912. node.parentNode.insertAfter(next,last);
  8913. last = next;
  8914. next = tmp;
  8915. }
  8916. return false;
  8917. }
  8918. });
  8919. if (!node.firstChild()) {
  8920. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  8921. }
  8922. break;
  8923. case 'div':
  8924. if(node.getAttr('cdata_tag')){
  8925. break;
  8926. }
  8927. //针对代码这里不处理插入代码的div
  8928. val = node.getAttr('class');
  8929. if(val && /^line number\d+/.test(val)){
  8930. break;
  8931. }
  8932. if(!allowDivTransToP){
  8933. break;
  8934. }
  8935. var tmpNode, p = UE.uNode.createElement('p');
  8936. while (tmpNode = node.firstChild()) {
  8937. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  8938. p.appendChild(tmpNode);
  8939. } else {
  8940. if (p.firstChild()) {
  8941. node.parentNode.insertBefore(p, node);
  8942. p = UE.uNode.createElement('p');
  8943. } else {
  8944. node.parentNode.insertBefore(tmpNode, node);
  8945. }
  8946. }
  8947. }
  8948. if (p.firstChild()) {
  8949. node.parentNode.insertBefore(p, node);
  8950. }
  8951. node.parentNode.removeChild(node);
  8952. break;
  8953. case 'dl':
  8954. node.tagName = 'ul';
  8955. break;
  8956. case 'dt':
  8957. case 'dd':
  8958. node.tagName = 'li';
  8959. break;
  8960. case 'li':
  8961. var className = node.getAttr('class');
  8962. if (!className || !/list\-/.test(className)) {
  8963. node.setAttr()
  8964. }
  8965. var tmpNodes = node.getNodesByTagName('ol ul');
  8966. UE.utils.each(tmpNodes, function (n) {
  8967. node.parentNode.insertAfter(n, node);
  8968. });
  8969. break;
  8970. case 'td':
  8971. case 'th':
  8972. case 'caption':
  8973. if(!node.children || !node.children.length){
  8974. node.appendChild(browser.ie ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  8975. }
  8976. break;
  8977. case 'table':
  8978. if(me.options.disabledTableInTable && tdParent(node)){
  8979. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  8980. node.parentNode.removeChild(node)
  8981. }
  8982. }
  8983. }
  8984. // if(node.type == 'comment'){
  8985. // node.parentNode.removeChild(node);
  8986. // }
  8987. })
  8988. });
  8989. //从编辑器出去的内容处理
  8990. me.addOutputRule(function (root) {
  8991. var val;
  8992. root.traversal(function (node) {
  8993. if (node.type == 'element') {
  8994. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8995. if (!node.firstChild()) node.parentNode.removeChild(node);
  8996. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  8997. node.parentNode.removeChild(node, true)
  8998. }
  8999. return;
  9000. }
  9001. switch (node.tagName) {
  9002. case 'div':
  9003. if (val = node.getAttr('cdata_tag')) {
  9004. node.tagName = val;
  9005. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9006. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9007. }
  9008. break;
  9009. case 'a':
  9010. if (val = node.getAttr('_href')) {
  9011. node.setAttr({
  9012. 'href': utils.html(val),
  9013. '_href': ''
  9014. })
  9015. }
  9016. break;
  9017. case 'img':
  9018. if (val = node.getAttr('_src')) {
  9019. node.setAttr({
  9020. 'src': node.getAttr('_src'),
  9021. '_src': ''
  9022. })
  9023. }
  9024. }
  9025. }
  9026. })
  9027. });
  9028. };
  9029. /**
  9030. * 插入html字符串插件
  9031. * @file
  9032. * @since 1.2.6.1
  9033. */
  9034. /**
  9035. * 插入html代码
  9036. * @command inserthtml
  9037. * @method execCommand
  9038. * @param { String } cmd 命令字符串
  9039. * @param { String } html 插入的html字符串
  9040. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9041. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9042. * @example
  9043. * ```javascript
  9044. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9045. * //执行命令,插入<b>CC</b>
  9046. * //插入后的效果 xxx<b>CC</b>xxx
  9047. * //<p>xx|xxx</p> 当前选区为闭合状态
  9048. * //插入<p>CC</p>
  9049. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9050. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9051. * //插入 xxxx
  9052. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9053. * ```
  9054. */
  9055. UE.commands['inserthtml'] = {
  9056. execCommand: function (command,html,notNeedFilter){
  9057. var me = this,
  9058. range,
  9059. div;
  9060. if(!html){
  9061. return;
  9062. }
  9063. if(me.fireEvent('beforeinserthtml',html) === true){
  9064. return;
  9065. }
  9066. range = me.selection.getRange();
  9067. div = range.document.createElement( 'div' );
  9068. div.style.display = 'inline';
  9069. if (!notNeedFilter) {
  9070. var root = UE.htmlparser(html);
  9071. //如果给了过滤规则就先进行过滤
  9072. if(me.options.filterRules){
  9073. UE.filterNode(root,me.options.filterRules);
  9074. }
  9075. //执行默认的处理
  9076. me.filterInputRule(root);
  9077. html = root.toHtml()
  9078. }
  9079. div.innerHTML = utils.trim( html );
  9080. if ( !range.collapsed ) {
  9081. var tmpNode = range.startContainer;
  9082. if(domUtils.isFillChar(tmpNode)){
  9083. range.setStartBefore(tmpNode)
  9084. }
  9085. tmpNode = range.endContainer;
  9086. if(domUtils.isFillChar(tmpNode)){
  9087. range.setEndAfter(tmpNode)
  9088. }
  9089. range.txtToElmBoundary();
  9090. //结束边界可能放到了br的前边,要把br包含进来
  9091. // x[xxx]<br/>
  9092. if(range.endContainer && range.endContainer.nodeType == 1){
  9093. tmpNode = range.endContainer.childNodes[range.endOffset];
  9094. if(tmpNode && domUtils.isBr(tmpNode)){
  9095. range.setEndAfter(tmpNode);
  9096. }
  9097. }
  9098. if(range.startOffset == 0){
  9099. tmpNode = range.startContainer;
  9100. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9101. tmpNode = range.endContainer;
  9102. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9103. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9104. range.setStart(me.body.firstChild,0).collapse(true)
  9105. }
  9106. }
  9107. }
  9108. !range.collapsed && range.deleteContents();
  9109. if(range.startContainer.nodeType == 1){
  9110. var child = range.startContainer.childNodes[range.startOffset],pre;
  9111. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9112. range.setEnd(pre,pre.childNodes.length).collapse();
  9113. while(child.firstChild){
  9114. pre.appendChild(child.firstChild);
  9115. }
  9116. domUtils.remove(child);
  9117. }
  9118. }
  9119. }
  9120. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9121. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9122. if(range.inFillChar()){
  9123. child = range.startContainer;
  9124. if(domUtils.isFillChar(child)){
  9125. range.setStartBefore(child).collapse(true);
  9126. domUtils.remove(child);
  9127. }else if(domUtils.isFillChar(child,true)){
  9128. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9129. range.startOffset--;
  9130. range.collapsed && range.collapse(true)
  9131. }
  9132. }
  9133. //列表单独处理
  9134. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9135. if(li){
  9136. var next,last;
  9137. while(child = div.firstChild){
  9138. //针对hr单独处理一下先
  9139. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9140. next = child.nextSibling;
  9141. range.insertNode( child).collapse();
  9142. last = child;
  9143. child = next;
  9144. }
  9145. if(child){
  9146. if(/^(ol|ul)$/i.test(child.tagName)){
  9147. while(child.firstChild){
  9148. last = child.firstChild;
  9149. domUtils.insertAfter(li,child.firstChild);
  9150. li = li.nextSibling;
  9151. }
  9152. domUtils.remove(child)
  9153. }else{
  9154. var tmpLi;
  9155. next = child.nextSibling;
  9156. tmpLi = me.document.createElement('li');
  9157. domUtils.insertAfter(li,tmpLi);
  9158. tmpLi.appendChild(child);
  9159. last = child;
  9160. child = next;
  9161. li = tmpLi;
  9162. }
  9163. }
  9164. }
  9165. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9166. if(domUtils.isEmptyBlock(li)){
  9167. domUtils.remove(li)
  9168. }
  9169. if(last){
  9170. range.setStartAfter(last).collapse(true).select(true)
  9171. }
  9172. }else{
  9173. while ( child = div.firstChild ) {
  9174. if(hadBreak){
  9175. var p = me.document.createElement('p');
  9176. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9177. nextNode = child.nextSibling;
  9178. p.appendChild(child);
  9179. child = nextNode;
  9180. }
  9181. if(p.firstChild){
  9182. child = p
  9183. }
  9184. }
  9185. range.insertNode( child );
  9186. nextNode = child.nextSibling;
  9187. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9188. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9189. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9190. if(!dtd[parent.tagName][child.nodeName]){
  9191. pre = parent;
  9192. }else{
  9193. tmp = child.parentNode;
  9194. while (tmp !== parent){
  9195. pre = tmp;
  9196. tmp = tmp.parentNode;
  9197. }
  9198. }
  9199. domUtils.breakParent( child, pre || tmp );
  9200. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9201. var pre = child.previousSibling;
  9202. domUtils.trimWhiteTextNode(pre);
  9203. if(!pre.childNodes.length){
  9204. domUtils.remove(pre);
  9205. }
  9206. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9207. if(!browser.ie &&
  9208. (next = child.nextSibling) &&
  9209. domUtils.isBlockElm(next) &&
  9210. next.lastChild &&
  9211. !domUtils.isBr(next.lastChild)){
  9212. next.appendChild(me.document.createElement('br'));
  9213. }
  9214. hadBreak = 1;
  9215. }
  9216. }
  9217. var next = child.nextSibling;
  9218. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9219. range.setStart(next,0).collapse(true);
  9220. break;
  9221. }
  9222. range.setEndAfter( child ).collapse();
  9223. }
  9224. child = range.startContainer;
  9225. if(nextNode && domUtils.isBr(nextNode)){
  9226. domUtils.remove(nextNode)
  9227. }
  9228. //用chrome可能有空白展位符
  9229. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9230. if(nextNode = child.nextSibling){
  9231. domUtils.remove(child);
  9232. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9233. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9234. }
  9235. }else{
  9236. try{
  9237. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9238. }catch(e){
  9239. range.setStartBefore(child);
  9240. domUtils.remove(child)
  9241. }
  9242. }
  9243. }
  9244. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9245. try{
  9246. range.select(true);
  9247. }catch(e){}
  9248. }
  9249. setTimeout(function(){
  9250. range = me.selection.getRange();
  9251. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9252. me.fireEvent('afterinserthtml');
  9253. },200);
  9254. }
  9255. };
  9256. /**
  9257. * 自动排版
  9258. * @file
  9259. * @since 1.2.6.1
  9260. */
  9261. /**
  9262. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9263. * @command autotypeset
  9264. * @method execCommand
  9265. * @param { String } cmd 命令字符串
  9266. * @example
  9267. * ```javascript
  9268. * editor.execCommand( 'autotypeset' );
  9269. * ```
  9270. */
  9271. UE.plugins['autotypeset'] = function(){
  9272. this.setOpt({'autotypeset':{
  9273. mergeEmptyline : true, //合并空行
  9274. removeClass : true, //去掉冗余的class
  9275. removeEmptyline : false, //去掉空行
  9276. textAlign : "left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9277. imageBlockLine : 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9278. pasteFilter : false, //根据规则过滤没事粘贴进来的内容
  9279. clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9280. clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9281. removeEmptyNode : false, // 去掉空节点
  9282. //可以去掉的标签
  9283. removeTagNames : utils.extend({div:1},dtd.$removeEmpty),
  9284. indent : false, // 行首缩进
  9285. indentValue : '2em' //行首缩进的大小
  9286. }});
  9287. var me = this,
  9288. opt = me.options.autotypeset,
  9289. remainClass = {
  9290. 'selectTdClass':1,
  9291. 'pagebreak':1,
  9292. 'anchorclass':1
  9293. },
  9294. remainTag = {
  9295. 'li':1
  9296. },
  9297. tags = {
  9298. div:1,
  9299. p:1,
  9300. //trace:2183 这些也认为是行
  9301. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9302. span:1
  9303. },
  9304. highlightCont;
  9305. //升级了版本,但配置项目里没有autotypeset
  9306. if(!opt){
  9307. return;
  9308. }
  9309. function isLine(node,notEmpty){
  9310. if(!node || node.nodeType == 3)
  9311. return 0;
  9312. if(domUtils.isBr(node))
  9313. return 1;
  9314. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9315. if(highlightCont && highlightCont.contains(node)
  9316. ||
  9317. node.getAttribute('pagebreak')
  9318. ){
  9319. return 0;
  9320. }
  9321. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9322. +']','g'));
  9323. }
  9324. }
  9325. function removeNotAttributeSpan(node){
  9326. if(!node.style.cssText){
  9327. domUtils.removeAttributes(node,['style']);
  9328. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9329. domUtils.remove(node,true);
  9330. }
  9331. }
  9332. }
  9333. function autotype(type,html){
  9334. var me = this,cont;
  9335. if(html){
  9336. if(!opt.pasteFilter){
  9337. return;
  9338. }
  9339. cont = me.document.createElement('div');
  9340. cont.innerHTML = html.html;
  9341. }else{
  9342. cont = me.document.body;
  9343. }
  9344. var nodes = domUtils.getElementsByTagName(cont,'*');
  9345. // 行首缩进,段落方向,段间距,段内间距
  9346. for(var i=0,ci;ci=nodes[i++];){
  9347. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9348. continue;
  9349. }
  9350. //font-size
  9351. if(opt.clearFontSize && ci.style.fontSize){
  9352. domUtils.removeStyle(ci,'font-size');
  9353. removeNotAttributeSpan(ci);
  9354. }
  9355. //font-family
  9356. if(opt.clearFontFamily && ci.style.fontFamily){
  9357. domUtils.removeStyle(ci,'font-family');
  9358. removeNotAttributeSpan(ci);
  9359. }
  9360. if(isLine(ci)){
  9361. //合并空行
  9362. if(opt.mergeEmptyline ){
  9363. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9364. while(isLine(next)){
  9365. tmpNode = next;
  9366. next = tmpNode.nextSibling;
  9367. if(isBr && (!next || next && !domUtils.isBr(next))){
  9368. break;
  9369. }
  9370. domUtils.remove(tmpNode);
  9371. }
  9372. }
  9373. //去掉空行,保留占位的空行
  9374. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9375. if(domUtils.isBr(ci)){
  9376. next = ci.nextSibling;
  9377. if(next && !domUtils.isBr(next)){
  9378. continue;
  9379. }
  9380. }
  9381. domUtils.remove(ci);
  9382. continue;
  9383. }
  9384. }
  9385. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9386. if(opt.indent){
  9387. ci.style.textIndent = opt.indentValue;
  9388. }
  9389. if(opt.textAlign){
  9390. ci.style.textAlign = opt.textAlign;
  9391. }
  9392. // if(opt.lineHeight)
  9393. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9394. }
  9395. //去掉class,保留的class不去掉
  9396. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9397. if(highlightCont && highlightCont.contains(ci)){
  9398. continue;
  9399. }
  9400. domUtils.removeAttributes(ci,['class']);
  9401. }
  9402. //表情不处理
  9403. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9404. if(html){
  9405. var img = ci;
  9406. switch (opt.imageBlockLine){
  9407. case 'left':
  9408. case 'right':
  9409. case 'none':
  9410. var pN = img.parentNode,tmpNode,pre,next;
  9411. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9412. pN = pN.parentNode;
  9413. }
  9414. tmpNode = pN;
  9415. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9416. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9417. pre = tmpNode.previousSibling;
  9418. next = tmpNode.nextSibling;
  9419. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9420. pre.appendChild(tmpNode.firstChild);
  9421. while(next.firstChild){
  9422. pre.appendChild(next.firstChild);
  9423. }
  9424. domUtils.remove(tmpNode);
  9425. domUtils.remove(next);
  9426. }else{
  9427. domUtils.setStyle(tmpNode,'text-align','');
  9428. }
  9429. }
  9430. }
  9431. domUtils.setStyle(img,'float',opt.imageBlockLine);
  9432. break;
  9433. case 'center':
  9434. if(me.queryCommandValue('imagefloat') != 'center'){
  9435. pN = img.parentNode;
  9436. domUtils.setStyle(img,'float','none');
  9437. tmpNode = img;
  9438. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  9439. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  9440. tmpNode = pN;
  9441. pN = pN.parentNode;
  9442. }
  9443. var pNode = me.document.createElement('p');
  9444. domUtils.setAttributes(pNode,{
  9445. style:'text-align:center'
  9446. });
  9447. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  9448. pNode.appendChild(tmpNode);
  9449. domUtils.setStyle(tmpNode,'float','');
  9450. }
  9451. }
  9452. }else{
  9453. var range = me.selection.getRange();
  9454. range.selectNode(ci).select();
  9455. me.execCommand('imagefloat',opt.imageBlockLine);
  9456. }
  9457. }
  9458. //去掉冗余的标签
  9459. if(opt.removeEmptyNode){
  9460. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  9461. domUtils.remove(ci);
  9462. }
  9463. }
  9464. }
  9465. if(html){
  9466. html.html = cont.innerHTML;
  9467. }
  9468. }
  9469. if(opt.pasteFilter){
  9470. me.addListener('beforepaste',autotype);
  9471. }
  9472. me.commands['autotypeset'] = {
  9473. execCommand:function () {
  9474. me.removeListener('beforepaste',autotype);
  9475. if(opt.pasteFilter){
  9476. me.addListener('beforepaste',autotype);
  9477. }
  9478. autotype.call(me)
  9479. }
  9480. };
  9481. };
  9482. /**
  9483. * 快捷键提交
  9484. * @file
  9485. * @since 1.2.6.1
  9486. */
  9487. /**
  9488. * 提交表单
  9489. * @command autosubmit
  9490. * @method execCommand
  9491. * @param { String } cmd 命令字符串
  9492. * @example
  9493. * ```javascript
  9494. * editor.execCommand( 'autosubmit' );
  9495. * ```
  9496. */
  9497. UE.plugin.register('autosubmit',function(){
  9498. return {
  9499. shortcutkey:{
  9500. "autosubmit":"ctrl+13" //手动提交
  9501. },
  9502. commands:{
  9503. 'autosubmit':{
  9504. execCommand:function () {
  9505. var me=this,
  9506. form = domUtils.findParentByTagName(me.iframe,"form", false);
  9507. if (form){
  9508. if(me.fireEvent("beforesubmit")===false){
  9509. return;
  9510. }
  9511. me.sync();
  9512. form.submit();
  9513. }
  9514. }
  9515. }
  9516. }
  9517. }
  9518. });
  9519. /**
  9520. * 背景插件,为UEditor提供设置背景功能
  9521. * @file
  9522. * @since 1.2.6.1
  9523. */
  9524. UE.plugin.register('background', function () {
  9525. var me = this,
  9526. cssRuleId = 'editor_background',
  9527. isSetColored,
  9528. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  9529. function stringToObj(str) {
  9530. var obj = {}, styles = str.split(';');
  9531. utils.each(styles, function (v) {
  9532. var index = v.indexOf(':'),
  9533. key = utils.trim(v.substr(0, index)).toLowerCase();
  9534. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  9535. });
  9536. return obj;
  9537. }
  9538. function setBackground(obj) {
  9539. if (obj) {
  9540. var styles = [];
  9541. for (var name in obj) {
  9542. if (obj.hasOwnProperty(name)) {
  9543. styles.push(name + ":" + obj[name] + '; ');
  9544. }
  9545. }
  9546. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  9547. } else {
  9548. utils.cssRule(cssRuleId, '', me.document)
  9549. }
  9550. }
  9551. //重写editor.hasContent方法
  9552. var orgFn = me.hasContents;
  9553. me.hasContents = function(){
  9554. if(me.queryCommandValue('background')){
  9555. return true
  9556. }
  9557. return orgFn.apply(me,arguments);
  9558. };
  9559. return {
  9560. bindEvents: {
  9561. 'getAllHtml': function (type, headHtml) {
  9562. var body = this.body,
  9563. su = domUtils.getComputedStyle(body, "background-image"),
  9564. url = "";
  9565. if (su.indexOf(me.options.imagePath) > 0) {
  9566. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  9567. } else {
  9568. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  9569. }
  9570. var html = '<style type="text/css">body{';
  9571. var bgObj = {
  9572. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  9573. 'background-image': url ? 'url(' + url + ')' : '',
  9574. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  9575. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  9576. 'height': domUtils.getComputedStyle(body, "height")
  9577. };
  9578. for (var name in bgObj) {
  9579. if (bgObj.hasOwnProperty(name)) {
  9580. html += name + ":" + bgObj[name] + "; ";
  9581. }
  9582. }
  9583. html += '}</style> ';
  9584. headHtml.push(html);
  9585. },
  9586. 'aftersetcontent': function () {
  9587. if(isSetColored == false) setBackground();
  9588. }
  9589. },
  9590. inputRule: function (root) {
  9591. isSetColored = false;
  9592. utils.each(root.getNodesByTagName('p'), function (p) {
  9593. var styles = p.getAttr('data-background');
  9594. if (styles) {
  9595. isSetColored = true;
  9596. setBackground(stringToObj(styles));
  9597. p.parentNode.removeChild(p);
  9598. }
  9599. })
  9600. },
  9601. outputRule: function (root) {
  9602. var me = this,
  9603. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  9604. if (styles) {
  9605. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  9606. }
  9607. },
  9608. commands: {
  9609. 'background': {
  9610. execCommand: function (cmd, obj) {
  9611. setBackground(obj);
  9612. },
  9613. queryCommandValue: function () {
  9614. var me = this,
  9615. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  9616. return styles ? stringToObj(styles[1]) : null;
  9617. },
  9618. notNeedUndo: true
  9619. }
  9620. }
  9621. }
  9622. });
  9623. /**
  9624. * 图片插入、排版插件
  9625. * @file
  9626. * @since 1.2.6.1
  9627. */
  9628. /**
  9629. * 图片对齐方式
  9630. * @command imagefloat
  9631. * @method execCommand
  9632. * @remind 值center为独占一行居中
  9633. * @param { String } cmd 命令字符串
  9634. * @param { String } align 对齐方式,可传left、right、none、center
  9635. * @remaind center表示图片独占一行
  9636. * @example
  9637. * ```javascript
  9638. * editor.execCommand( 'imagefloat', 'center' );
  9639. * ```
  9640. */
  9641. /**
  9642. * 如果选区所在位置是图片区域
  9643. * @command imagefloat
  9644. * @method queryCommandValue
  9645. * @param { String } cmd 命令字符串
  9646. * @return { String } 返回图片对齐方式
  9647. * @example
  9648. * ```javascript
  9649. * editor.queryCommandValue( 'imagefloat' );
  9650. * ```
  9651. */
  9652. UE.commands['imagefloat'] = {
  9653. execCommand:function (cmd, align) {
  9654. var me = this,
  9655. range = me.selection.getRange();
  9656. if (!range.collapsed) {
  9657. var img = range.getClosedNode();
  9658. if (img && img.tagName == 'IMG') {
  9659. switch (align) {
  9660. case 'left':
  9661. case 'right':
  9662. case 'none':
  9663. var pN = img.parentNode, tmpNode, pre, next;
  9664. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  9665. pN = pN.parentNode;
  9666. }
  9667. tmpNode = pN;
  9668. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  9669. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  9670. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  9671. }) == 1) {
  9672. pre = tmpNode.previousSibling;
  9673. next = tmpNode.nextSibling;
  9674. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  9675. pre.appendChild(tmpNode.firstChild);
  9676. while (next.firstChild) {
  9677. pre.appendChild(next.firstChild);
  9678. }
  9679. domUtils.remove(tmpNode);
  9680. domUtils.remove(next);
  9681. } else {
  9682. domUtils.setStyle(tmpNode, 'text-align', '');
  9683. }
  9684. }
  9685. range.selectNode(img).select();
  9686. }
  9687. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  9688. if(align == 'none'){
  9689. domUtils.removeAttributes(img,'align');
  9690. }
  9691. break;
  9692. case 'center':
  9693. if (me.queryCommandValue('imagefloat') != 'center') {
  9694. pN = img.parentNode;
  9695. domUtils.setStyle(img, 'float', '');
  9696. domUtils.removeAttributes(img,'align');
  9697. tmpNode = img;
  9698. while (pN && domUtils.getChildCount(pN, function (node) {
  9699. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  9700. }) == 1
  9701. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  9702. tmpNode = pN;
  9703. pN = pN.parentNode;
  9704. }
  9705. range.setStartBefore(tmpNode).setCursor(false);
  9706. pN = me.document.createElement('div');
  9707. pN.appendChild(tmpNode);
  9708. domUtils.setStyle(tmpNode, 'float', '');
  9709. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  9710. tmpNode = me.document.getElementById('_img_parent_tmp');
  9711. tmpNode.removeAttribute('id');
  9712. tmpNode = tmpNode.firstChild;
  9713. range.selectNode(tmpNode).select();
  9714. //去掉后边多余的元素
  9715. next = tmpNode.parentNode.nextSibling;
  9716. if (next && domUtils.isEmptyNode(next)) {
  9717. domUtils.remove(next);
  9718. }
  9719. }
  9720. break;
  9721. }
  9722. }
  9723. }
  9724. },
  9725. queryCommandValue:function () {
  9726. var range = this.selection.getRange(),
  9727. startNode, floatStyle;
  9728. if (range.collapsed) {
  9729. return 'none';
  9730. }
  9731. startNode = range.getClosedNode();
  9732. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  9733. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  9734. if (floatStyle == 'none') {
  9735. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  9736. }
  9737. return {
  9738. left:1,
  9739. right:1,
  9740. center:1
  9741. }[floatStyle] ? floatStyle : 'none';
  9742. }
  9743. return 'none';
  9744. },
  9745. queryCommandState:function () {
  9746. var range = this.selection.getRange(),
  9747. startNode;
  9748. if (range.collapsed) return -1;
  9749. startNode = range.getClosedNode();
  9750. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  9751. return 0;
  9752. }
  9753. return -1;
  9754. }
  9755. };
  9756. /**
  9757. * 插入图片
  9758. * @command insertimage
  9759. * @method execCommand
  9760. * @param { String } cmd 命令字符串
  9761. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  9762. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  9763. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  9764. * @example
  9765. * ```javascript
  9766. * editor.execCommand( 'insertimage', {
  9767. * src:'a/b/c.jpg',
  9768. * width:'100',
  9769. * height:'100'
  9770. * } );
  9771. * ```
  9772. * @example
  9773. * ```javascript
  9774. * editor.execCommand( 'insertimage', [{
  9775. * src:'a/b/c.jpg',
  9776. * width:'100',
  9777. * height:'100'
  9778. * },{
  9779. * src:'a/b/d.jpg',
  9780. * width:'100',
  9781. * height:'100'
  9782. * }] );
  9783. * ```
  9784. */
  9785. UE.commands['insertimage'] = {
  9786. execCommand:function (cmd, opt) {
  9787. opt = utils.isArray(opt) ? opt : [opt];
  9788. if (!opt.length) {
  9789. return;
  9790. }
  9791. var me = this,
  9792. range = me.selection.getRange(),
  9793. img = range.getClosedNode();
  9794. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  9795. var first = opt.shift();
  9796. var floatStyle = first['floatStyle'];
  9797. delete first['floatStyle'];
  9798. //// img.style.border = (first.border||0) +"px solid #000";
  9799. //// img.style.margin = (first.margin||0) +"px";
  9800. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  9801. domUtils.setAttributes(img, first);
  9802. me.execCommand('imagefloat', floatStyle);
  9803. if (opt.length > 0) {
  9804. range.setStartAfter(img).setCursor(false, true);
  9805. me.execCommand('insertimage', opt);
  9806. }
  9807. } else {
  9808. var html = [], str = '', ci;
  9809. ci = opt[0];
  9810. if (opt.length == 1) {
  9811. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  9812. (ci.width ? 'width="' + ci.width + '" ' : '') +
  9813. (ci.height ? ' height="' + ci.height + '" ' : '') +
  9814. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  9815. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  9816. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  9817. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  9818. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  9819. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  9820. if (ci['floatStyle'] == 'center') {
  9821. str = '<p style="text-align: center">' + str + '</p>';
  9822. }
  9823. html.push(str);
  9824. } else {
  9825. for (var i = 0; ci = opt[i++];) {
  9826. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  9827. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  9828. (ci.height ? ' height="' + ci.height + '" ' : '') +
  9829. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  9830. (ci.border || '') + '" ' +
  9831. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  9832. html.push(str);
  9833. }
  9834. }
  9835. me.execCommand('insertHtml', html.join(''));
  9836. }
  9837. }
  9838. };
  9839. /**
  9840. * 段落格式
  9841. * @file
  9842. * @since 1.2.6.1
  9843. */
  9844. /**
  9845. * 段落对齐方式
  9846. * @command justify
  9847. * @method execCommand
  9848. * @param { String } cmd 命令字符串
  9849. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  9850. * @example
  9851. * ```javascript
  9852. * editor.execCommand( 'justify', 'center' );
  9853. * ```
  9854. */
  9855. /**
  9856. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  9857. * @command justify
  9858. * @method queryCommandValue
  9859. * @param { String } cmd 命令字符串
  9860. * @return { String } 返回段落对齐方式
  9861. * @example
  9862. * ```javascript
  9863. * editor.queryCommandValue( 'justify' );
  9864. * ```
  9865. */
  9866. UE.plugins['justify']=function(){
  9867. var me=this,
  9868. block = domUtils.isBlockElm,
  9869. defaultValue = {
  9870. left:1,
  9871. right:1,
  9872. center:1,
  9873. justify:1
  9874. },
  9875. doJustify = function (range, style) {
  9876. var bookmark = range.createBookmark(),
  9877. filterFn = function (node) {
  9878. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  9879. };
  9880. range.enlarge(true);
  9881. var bookmark2 = range.createBookmark(),
  9882. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  9883. tmpRange = range.cloneRange(),
  9884. tmpNode;
  9885. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  9886. if (current.nodeType == 3 || !block(current)) {
  9887. tmpRange.setStartBefore(current);
  9888. while (current && current !== bookmark2.end && !block(current)) {
  9889. tmpNode = current;
  9890. current = domUtils.getNextDomNode(current, false, null, function (node) {
  9891. return !block(node);
  9892. });
  9893. }
  9894. tmpRange.setEndAfter(tmpNode);
  9895. var common = tmpRange.getCommonAncestor();
  9896. if (!domUtils.isBody(common) && block(common)) {
  9897. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  9898. current = common;
  9899. } else {
  9900. var p = range.document.createElement('p');
  9901. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  9902. var frag = tmpRange.extractContents();
  9903. p.appendChild(frag);
  9904. tmpRange.insertNode(p);
  9905. current = p;
  9906. }
  9907. current = domUtils.getNextDomNode(current, false, filterFn);
  9908. } else {
  9909. current = domUtils.getNextDomNode(current, true, filterFn);
  9910. }
  9911. }
  9912. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  9913. };
  9914. UE.commands['justify'] = {
  9915. execCommand:function (cmdName, align) {
  9916. var range = this.selection.getRange(),
  9917. txt;
  9918. //闭合时单独处理
  9919. if (range.collapsed) {
  9920. txt = this.document.createTextNode('p');
  9921. range.insertNode(txt);
  9922. }
  9923. doJustify(range, align);
  9924. if (txt) {
  9925. range.setStartBefore(txt).collapse(true);
  9926. domUtils.remove(txt);
  9927. }
  9928. range.select();
  9929. return true;
  9930. },
  9931. queryCommandValue:function () {
  9932. var startNode = this.selection.getStart(),
  9933. value = domUtils.getComputedStyle(startNode, 'text-align');
  9934. return defaultValue[value] ? value : 'left';
  9935. },
  9936. queryCommandState:function () {
  9937. var start = this.selection.getStart(),
  9938. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  9939. return cell? -1:0;
  9940. }
  9941. };
  9942. };
  9943. /**
  9944. * 字体颜色,背景色,字号,字体,下划线,删除线
  9945. * @file
  9946. * @since 1.2.6.1
  9947. */
  9948. /**
  9949. * 字体颜色
  9950. * @command forecolor
  9951. * @method execCommand
  9952. * @param { String } cmd 命令字符串
  9953. * @param { String } value 色值(必须十六进制)
  9954. * @example
  9955. * ```javascript
  9956. * editor.execCommand( 'forecolor', '#000' );
  9957. * ```
  9958. */
  9959. /**
  9960. * 返回选区字体颜色
  9961. * @command forecolor
  9962. * @method queryCommandValue
  9963. * @param { String } cmd 命令字符串
  9964. * @return { String } 返回字体颜色
  9965. * @example
  9966. * ```javascript
  9967. * editor.queryCommandValue( 'forecolor' );
  9968. * ```
  9969. */
  9970. /**
  9971. * 字体背景颜色
  9972. * @command backcolor
  9973. * @method execCommand
  9974. * @param { String } cmd 命令字符串
  9975. * @param { String } value 色值(必须十六进制)
  9976. * @example
  9977. * ```javascript
  9978. * editor.execCommand( 'backcolor', '#000' );
  9979. * ```
  9980. */
  9981. /**
  9982. * 返回选区字体颜色
  9983. * @command backcolor
  9984. * @method queryCommandValue
  9985. * @param { String } cmd 命令字符串
  9986. * @return { String } 返回字体背景颜色
  9987. * @example
  9988. * ```javascript
  9989. * editor.queryCommandValue( 'backcolor' );
  9990. * ```
  9991. */
  9992. /**
  9993. * 字体大小
  9994. * @command fontsize
  9995. * @method execCommand
  9996. * @param { String } cmd 命令字符串
  9997. * @param { String } value 字体大小
  9998. * @example
  9999. * ```javascript
  10000. * editor.execCommand( 'fontsize', '14px' );
  10001. * ```
  10002. */
  10003. /**
  10004. * 返回选区字体大小
  10005. * @command fontsize
  10006. * @method queryCommandValue
  10007. * @param { String } cmd 命令字符串
  10008. * @return { String } 返回字体大小
  10009. * @example
  10010. * ```javascript
  10011. * editor.queryCommandValue( 'fontsize' );
  10012. * ```
  10013. */
  10014. /**
  10015. * 字体样式
  10016. * @command fontfamily
  10017. * @method execCommand
  10018. * @param { String } cmd 命令字符串
  10019. * @param { String } value 字体样式
  10020. * @example
  10021. * ```javascript
  10022. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10023. * ```
  10024. */
  10025. /**
  10026. * 返回选区字体样式
  10027. * @command fontfamily
  10028. * @method queryCommandValue
  10029. * @param { String } cmd 命令字符串
  10030. * @return { String } 返回字体样式
  10031. * @example
  10032. * ```javascript
  10033. * editor.queryCommandValue( 'fontfamily' );
  10034. * ```
  10035. */
  10036. /**
  10037. * 字体下划线,与删除线互斥
  10038. * @command underline
  10039. * @method execCommand
  10040. * @param { String } cmd 命令字符串
  10041. * @example
  10042. * ```javascript
  10043. * editor.execCommand( 'underline' );
  10044. * ```
  10045. */
  10046. /**
  10047. * 字体删除线,与下划线互斥
  10048. * @command strikethrough
  10049. * @method execCommand
  10050. * @param { String } cmd 命令字符串
  10051. * @example
  10052. * ```javascript
  10053. * editor.execCommand( 'strikethrough' );
  10054. * ```
  10055. */
  10056. /**
  10057. * 字体边框
  10058. * @command fontborder
  10059. * @method execCommand
  10060. * @param { String } cmd 命令字符串
  10061. * @example
  10062. * ```javascript
  10063. * editor.execCommand( 'fontborder' );
  10064. * ```
  10065. */
  10066. UE.plugins['font'] = function () {
  10067. var me = this,
  10068. fonts = {
  10069. 'forecolor': 'color',
  10070. 'backcolor': 'background-color',
  10071. 'fontsize': 'font-size',
  10072. 'fontfamily': 'font-family',
  10073. 'underline': 'text-decoration',
  10074. 'strikethrough': 'text-decoration',
  10075. 'fontborder': 'border'
  10076. },
  10077. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10078. needSetChild = {
  10079. 'forecolor': 'color',
  10080. 'backcolor': 'background-color',
  10081. 'fontsize': 'font-size',
  10082. 'fontfamily': 'font-family'
  10083. };
  10084. me.setOpt({
  10085. 'fontfamily': [
  10086. { name: 'songti', val: '宋体,SimSun'},
  10087. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10088. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10089. { name: 'heiti', val: '黑体, SimHei'},
  10090. { name: 'lishu', val: '隶书, SimLi'},
  10091. { name: 'andaleMono', val: 'andale mono'},
  10092. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10093. { name: 'arialBlack', val: 'arial black,avant garde'},
  10094. { name: 'comicSansMs', val: 'comic sans ms'},
  10095. { name: 'impact', val: 'impact,chicago'},
  10096. { name: 'timesNewRoman', val: 'times new roman'}
  10097. ],
  10098. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10099. });
  10100. function mergeWithParent(node){
  10101. var parent;
  10102. while(parent = node.parentNode){
  10103. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10104. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10105. }) == 1) {
  10106. parent.style.cssText += node.style.cssText;
  10107. domUtils.remove(node,true);
  10108. node = parent;
  10109. }else{
  10110. break;
  10111. }
  10112. }
  10113. }
  10114. function mergeChild(rng,cmdName,value){
  10115. if(needSetChild[cmdName]){
  10116. rng.adjustmentBoundary();
  10117. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10118. var start = rng.startContainer.childNodes[rng.startOffset];
  10119. if(start && domUtils.isTagNode(start,'span')){
  10120. var bk = rng.createBookmark();
  10121. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10122. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10123. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10124. return;
  10125. }
  10126. domUtils.removeStyle(span,needSetChild[cmdName]);
  10127. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10128. domUtils.remove(span,true)
  10129. }
  10130. });
  10131. rng.moveToBookmark(bk)
  10132. }
  10133. }
  10134. }
  10135. }
  10136. function mergesibling(rng,cmdName,value) {
  10137. var collapsed = rng.collapsed,
  10138. bk = rng.createBookmark(), common;
  10139. if (collapsed) {
  10140. common = bk.start.parentNode;
  10141. while (dtd.$inline[common.tagName]) {
  10142. common = common.parentNode;
  10143. }
  10144. } else {
  10145. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10146. }
  10147. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10148. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10149. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10150. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10151. domUtils.remove(span, true);
  10152. }else{
  10153. domUtils.removeStyle(span,'border');
  10154. }
  10155. return
  10156. }
  10157. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10158. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10159. }
  10160. if(!(cmdName=='fontborder' && value=='none')){
  10161. var next = span.nextSibling;
  10162. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10163. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10164. span.appendChild(next);
  10165. next = span.nextSibling;
  10166. continue;
  10167. }
  10168. if (next.style.cssText == span.style.cssText) {
  10169. domUtils.moveChild(next, span);
  10170. domUtils.remove(next);
  10171. }
  10172. if (span.nextSibling === next)
  10173. break;
  10174. next = span.nextSibling;
  10175. }
  10176. }
  10177. mergeWithParent(span);
  10178. if(browser.ie && browser.version > 8 ){
  10179. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10180. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10181. if(parent && !/background-color/.test(span.style.cssText)){
  10182. span.style.backgroundColor = parent.style.backgroundColor;
  10183. }
  10184. }
  10185. });
  10186. rng.moveToBookmark(bk);
  10187. mergeChild(rng,cmdName,value)
  10188. }
  10189. me.addInputRule(function (root) {
  10190. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10191. if (node.tagName == 'font') {
  10192. var cssStyle = [];
  10193. for (var p in node.attrs) {
  10194. switch (p) {
  10195. case 'size':
  10196. cssStyle.push('font-size:' +
  10197. ({
  10198. '1':'10',
  10199. '2':'12',
  10200. '3':'16',
  10201. '4':'18',
  10202. '5':'24',
  10203. '6':'32',
  10204. '7':'48'
  10205. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10206. break;
  10207. case 'color':
  10208. cssStyle.push('color:' + node.attrs[p]);
  10209. break;
  10210. case 'face':
  10211. cssStyle.push('font-family:' + node.attrs[p]);
  10212. break;
  10213. case 'style':
  10214. cssStyle.push(node.attrs[p]);
  10215. }
  10216. }
  10217. node.attrs = {
  10218. 'style': cssStyle.join(';')
  10219. };
  10220. } else {
  10221. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10222. node.attrs = {
  10223. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10224. }
  10225. }
  10226. node.tagName = 'span';
  10227. });
  10228. // utils.each(root.getNodesByTagName('span'), function (node) {
  10229. // var val;
  10230. // if(val = node.getAttr('class')){
  10231. // if(/fontstrikethrough/.test(val)){
  10232. // node.setStyle('text-decoration','line-through');
  10233. // if(node.attrs['class']){
  10234. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10235. // }else{
  10236. // node.setAttr('class')
  10237. // }
  10238. // }
  10239. // if(/fontborder/.test(val)){
  10240. // node.setStyle('border','1px solid #000');
  10241. // if(node.attrs['class']){
  10242. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10243. // }else{
  10244. // node.setAttr('class')
  10245. // }
  10246. // }
  10247. // }
  10248. // });
  10249. });
  10250. // me.addOutputRule(function(root){
  10251. // utils.each(root.getNodesByTagName('span'), function (node) {
  10252. // var val;
  10253. // if(val = node.getStyle('text-decoration')){
  10254. // if(/line-through/.test(val)){
  10255. // if(node.attrs['class']){
  10256. // node.attrs['class'] += ' fontstrikethrough';
  10257. // }else{
  10258. // node.setAttr('class','fontstrikethrough')
  10259. // }
  10260. // }
  10261. //
  10262. // node.setStyle('text-decoration')
  10263. // }
  10264. // if(val = node.getStyle('border')){
  10265. // if(/1px/.test(val) && /solid/.test(val)){
  10266. // if(node.attrs['class']){
  10267. // node.attrs['class'] += ' fontborder';
  10268. //
  10269. // }else{
  10270. // node.setAttr('class','fontborder')
  10271. // }
  10272. // }
  10273. // node.setStyle('border')
  10274. //
  10275. // }
  10276. // });
  10277. // });
  10278. for (var p in fonts) {
  10279. (function (cmd, style) {
  10280. UE.commands[cmd] = {
  10281. execCommand: function (cmdName, value) {
  10282. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10283. cmdName == 'fontborder' ? '1px solid #000' :
  10284. 'line-through');
  10285. var me = this,
  10286. range = this.selection.getRange(),
  10287. text;
  10288. if (value == 'default') {
  10289. if (range.collapsed) {
  10290. text = me.document.createTextNode('font');
  10291. range.insertNode(text).select();
  10292. }
  10293. me.execCommand('removeFormat', 'span,a', style);
  10294. if (text) {
  10295. range.setStartBefore(text).collapse(true);
  10296. domUtils.remove(text);
  10297. }
  10298. mergesibling(range,cmdName,value);
  10299. range.select()
  10300. } else {
  10301. if (!range.collapsed) {
  10302. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10303. me.execCommand('removeFormat', 'span,a', style);
  10304. }
  10305. range = me.selection.getRange();
  10306. range.applyInlineStyle('span', {'style': style + ':' + value});
  10307. mergesibling(range, cmdName,value);
  10308. range.select();
  10309. } else {
  10310. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10311. text = me.document.createTextNode('font');
  10312. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10313. //for ie hack when enter
  10314. range.insertNode(text);
  10315. if (needCmd[cmd]) {
  10316. range.selectNode(text).select();
  10317. me.execCommand('removeFormat', 'span,a', style, null);
  10318. span = domUtils.findParentByTagName(text, 'span', true);
  10319. range.setStartBefore(text);
  10320. }
  10321. span && (span.style.cssText += ';' + style + ':' + value);
  10322. range.collapse(true).select();
  10323. } else {
  10324. range.insertNode(text);
  10325. range.selectNode(text).select();
  10326. span = range.document.createElement('span');
  10327. if (needCmd[cmd]) {
  10328. //a标签内的不处理跳过
  10329. if (domUtils.findParentByTagName(text, 'a', true)) {
  10330. range.setStartBefore(text).setCursor();
  10331. domUtils.remove(text);
  10332. return;
  10333. }
  10334. me.execCommand('removeFormat', 'span,a', style);
  10335. }
  10336. span.style.cssText = style + ':' + value;
  10337. text.parentNode.insertBefore(span, text);
  10338. //修复,span套span 但样式不继承的问题
  10339. if (!browser.ie || browser.ie && browser.version == 9) {
  10340. var spanParent = span.parentNode;
  10341. while (!domUtils.isBlockElm(spanParent)) {
  10342. if (spanParent.tagName == 'SPAN') {
  10343. //opera合并style不会加入";"
  10344. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10345. }
  10346. spanParent = spanParent.parentNode;
  10347. }
  10348. }
  10349. if (opera) {
  10350. setTimeout(function () {
  10351. range.setStart(span, 0).collapse(true);
  10352. mergesibling(range, cmdName,value);
  10353. range.select();
  10354. });
  10355. } else {
  10356. range.setStart(span, 0).collapse(true);
  10357. mergesibling(range,cmdName,value);
  10358. range.select();
  10359. }
  10360. //trace:981
  10361. //domUtils.mergeToParent(span)
  10362. }
  10363. domUtils.remove(text);
  10364. }
  10365. }
  10366. return true;
  10367. },
  10368. queryCommandValue: function (cmdName) {
  10369. var startNode = this.selection.getStart();
  10370. //trace:946
  10371. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  10372. var tmpNode = startNode, value;
  10373. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  10374. if (tmpNode.nodeType == 1) {
  10375. value = domUtils.getComputedStyle(tmpNode, style);
  10376. if (value != 'none') {
  10377. return value;
  10378. }
  10379. }
  10380. tmpNode = tmpNode.parentNode;
  10381. }
  10382. return 'none';
  10383. }
  10384. if (cmdName == 'fontborder') {
  10385. var tmp = startNode, val;
  10386. while (tmp && dtd.$inline[tmp.tagName]) {
  10387. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  10388. if (/1px/.test(val) && /solid/.test(val)) {
  10389. return val;
  10390. }
  10391. }
  10392. tmp = tmp.parentNode;
  10393. }
  10394. return ''
  10395. }
  10396. if( cmdName == 'FontSize' ) {
  10397. var styleVal = domUtils.getComputedStyle(startNode, style),
  10398. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  10399. if( tmp ) {
  10400. return Math.floor( tmp[1] ) + tmp[2];
  10401. }
  10402. return styleVal;
  10403. }
  10404. return domUtils.getComputedStyle(startNode, style);
  10405. },
  10406. queryCommandState: function (cmdName) {
  10407. if (!needCmd[cmdName])
  10408. return 0;
  10409. var val = this.queryCommandValue(cmdName);
  10410. if (cmdName == 'fontborder') {
  10411. return /1px/.test(val) && /solid/.test(val)
  10412. } else {
  10413. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  10414. }
  10415. }
  10416. };
  10417. })(p, fonts[p]);
  10418. }
  10419. };
  10420. /**
  10421. * 超链接
  10422. * @file
  10423. * @since 1.2.6.1
  10424. */
  10425. /**
  10426. * 插入超链接
  10427. * @command link
  10428. * @method execCommand
  10429. * @param { String } cmd 命令字符串
  10430. * @param { Object } options 设置自定义属性,例如:url、title、target
  10431. * @example
  10432. * ```javascript
  10433. * editor.execCommand( 'link', '{
  10434. * url:'ueditor.baidu.com',
  10435. * title:'ueditor',
  10436. * target:'_blank'
  10437. * }' );
  10438. * ```
  10439. */
  10440. /**
  10441. * 返回当前选中的第一个超链接节点
  10442. * @command link
  10443. * @method queryCommandValue
  10444. * @param { String } cmd 命令字符串
  10445. * @return { Element } 超链接节点
  10446. * @example
  10447. * ```javascript
  10448. * editor.queryCommandValue( 'link' );
  10449. * ```
  10450. */
  10451. /**
  10452. * 取消超链接
  10453. * @command unlink
  10454. * @method execCommand
  10455. * @param { String } cmd 命令字符串
  10456. * @example
  10457. * ```javascript
  10458. * editor.execCommand( 'unlink');
  10459. * ```
  10460. */
  10461. UE.plugins['link'] = function(){
  10462. function optimize( range ) {
  10463. var start = range.startContainer,end = range.endContainer;
  10464. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  10465. range.setStartBefore( start );
  10466. }
  10467. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  10468. range.setEndAfter( end );
  10469. }
  10470. }
  10471. UE.commands['unlink'] = {
  10472. execCommand : function() {
  10473. var range = this.selection.getRange(),
  10474. bookmark;
  10475. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  10476. return;
  10477. }
  10478. bookmark = range.createBookmark();
  10479. optimize( range );
  10480. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  10481. },
  10482. queryCommandState : function(){
  10483. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  10484. }
  10485. };
  10486. function doLink(range,opt,me){
  10487. var rngClone = range.cloneRange(),
  10488. link = me.queryCommandValue('link');
  10489. optimize( range = range.adjustmentBoundary() );
  10490. var start = range.startContainer;
  10491. if(start.nodeType == 1 && link){
  10492. start = start.childNodes[range.startOffset];
  10493. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  10494. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  10495. }
  10496. }
  10497. if( !rngClone.collapsed || link){
  10498. range.removeInlineStyle( 'a' );
  10499. rngClone = range.cloneRange();
  10500. }
  10501. if ( rngClone.collapsed ) {
  10502. var a = range.document.createElement( 'a'),
  10503. text = '';
  10504. if(opt.textValue){
  10505. text = utils.html(opt.textValue);
  10506. delete opt.textValue;
  10507. }else{
  10508. text = utils.html(opt.href);
  10509. }
  10510. domUtils.setAttributes( a, opt );
  10511. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  10512. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  10513. range.setStartAfter(start).collapse(true);
  10514. }
  10515. a[browser.ie ? 'innerText' : 'textContent'] = text;
  10516. range.insertNode(a).selectNode( a );
  10517. } else {
  10518. range.applyInlineStyle( 'a', opt );
  10519. }
  10520. }
  10521. UE.commands['link'] = {
  10522. execCommand : function( cmdName, opt ) {
  10523. var range;
  10524. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  10525. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  10526. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  10527. doLink(range=this.selection.getRange(),opt,this);
  10528. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  10529. range.collapse().select(true);
  10530. },
  10531. queryCommandValue : function() {
  10532. var range = this.selection.getRange(),
  10533. node;
  10534. if ( range.collapsed ) {
  10535. // node = this.selection.getStart();
  10536. //在ie下getstart()取值偏上了
  10537. node = range.startContainer;
  10538. node = node.nodeType == 1 ? node : node.parentNode;
  10539. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  10540. return node;
  10541. }
  10542. } else {
  10543. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  10544. range.shrinkBoundary();
  10545. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  10546. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  10547. common = range.getCommonAncestor();
  10548. node = domUtils.findParentByTagName( common, 'a', true );
  10549. if ( !node && common.nodeType == 1){
  10550. var as = common.getElementsByTagName( 'a' ),
  10551. ps,pe;
  10552. for ( var i = 0,ci; ci = as[i++]; ) {
  10553. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  10554. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  10555. &&
  10556. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  10557. ) {
  10558. node = ci;
  10559. break;
  10560. }
  10561. }
  10562. }
  10563. return node;
  10564. }
  10565. },
  10566. queryCommandState : function() {
  10567. //判断如果是视频的话连接不可用
  10568. //fix 853
  10569. var img = this.selection.getRange().getClosedNode(),
  10570. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  10571. return flag ? -1 : 0;
  10572. }
  10573. };
  10574. };
  10575. ///import core
  10576. ///import plugins\inserthtml.js
  10577. ///commands 插入框架
  10578. ///commandsName InsertFrame
  10579. ///commandsTitle 插入Iframe
  10580. ///commandsDialog dialogs\insertframe
  10581. UE.plugins['insertframe'] = function() {
  10582. var me =this;
  10583. function deleteIframe(){
  10584. me._iframe && delete me._iframe;
  10585. }
  10586. me.addListener("selectionchange",function(){
  10587. deleteIframe();
  10588. });
  10589. };
  10590. ///import core
  10591. ///commands 涂鸦
  10592. ///commandsName Scrawl
  10593. ///commandsTitle 涂鸦
  10594. ///commandsDialog dialogs\scrawl
  10595. UE.commands['scrawl'] = {
  10596. queryCommandState : function(){
  10597. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  10598. }
  10599. };
  10600. /**
  10601. * 清除格式
  10602. * @file
  10603. * @since 1.2.6.1
  10604. */
  10605. /**
  10606. * 清除文字样式
  10607. * @command removeformat
  10608. * @method execCommand
  10609. * @param { String } cmd 命令字符串
  10610. * @param {String} tags 以逗号隔开的标签。如:strong
  10611. * @param {String} style 样式如:color
  10612. * @param {String} attrs 属性如:width
  10613. * @example
  10614. * ```javascript
  10615. * editor.execCommand( 'removeformat', 'strong','color','width' );
  10616. * ```
  10617. */
  10618. UE.plugins['removeformat'] = function(){
  10619. var me = this;
  10620. me.setOpt({
  10621. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  10622. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  10623. });
  10624. me.commands['removeformat'] = {
  10625. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  10626. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  10627. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  10628. range = new dom.Range( this.document ),
  10629. bookmark,node,parent,
  10630. filter = function( node ) {
  10631. return node.nodeType == 1;
  10632. };
  10633. function isRedundantSpan (node) {
  10634. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  10635. return 0;
  10636. }
  10637. if (browser.ie) {
  10638. //ie 下判断实效,所以只能简单用style来判断
  10639. //return node.style.cssText == '' ? 1 : 0;
  10640. var attrs = node.attributes;
  10641. if ( attrs.length ) {
  10642. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  10643. if ( attrs[i].specified ) {
  10644. return 0;
  10645. }
  10646. }
  10647. return 1;
  10648. }
  10649. }
  10650. return !node.attributes.length;
  10651. }
  10652. function doRemove( range ) {
  10653. var bookmark1 = range.createBookmark();
  10654. if ( range.collapsed ) {
  10655. range.enlarge( true );
  10656. }
  10657. //不能把a标签切了
  10658. if(!notIncludeA){
  10659. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  10660. if(aNode){
  10661. range.setStartBefore(aNode);
  10662. }
  10663. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  10664. if(aNode){
  10665. range.setEndAfter(aNode);
  10666. }
  10667. }
  10668. bookmark = range.createBookmark();
  10669. node = bookmark.start;
  10670. //切开始
  10671. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  10672. domUtils.breakParent( node, parent );
  10673. domUtils.clearEmptySibling( node );
  10674. }
  10675. if ( bookmark.end ) {
  10676. //切结束
  10677. node = bookmark.end;
  10678. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  10679. domUtils.breakParent( node, parent );
  10680. domUtils.clearEmptySibling( node );
  10681. }
  10682. //开始去除样式
  10683. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  10684. next;
  10685. while ( current ) {
  10686. if ( current == bookmark.end ) {
  10687. break;
  10688. }
  10689. next = domUtils.getNextDomNode( current, true, filter );
  10690. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  10691. if ( tagReg.test( current.tagName ) ) {
  10692. if ( style ) {
  10693. domUtils.removeStyle( current, style );
  10694. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  10695. domUtils.remove( current, true );
  10696. }
  10697. } else {
  10698. domUtils.remove( current, true );
  10699. }
  10700. } else {
  10701. //trace:939 不能把list上的样式去掉
  10702. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  10703. domUtils.removeAttributes( current, removeFormatAttributes );
  10704. if ( isRedundantSpan( current ) ){
  10705. domUtils.remove( current, true );
  10706. }
  10707. }
  10708. }
  10709. }
  10710. current = next;
  10711. }
  10712. }
  10713. //trace:1035
  10714. //trace:1096 不能把td上的样式去掉,比如边框
  10715. var pN = bookmark.start.parentNode;
  10716. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  10717. domUtils.removeAttributes( pN,removeFormatAttributes );
  10718. }
  10719. pN = bookmark.end.parentNode;
  10720. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  10721. domUtils.removeAttributes( pN,removeFormatAttributes );
  10722. }
  10723. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  10724. //清除冗余的代码 <b><bookmark></b>
  10725. var node = range.startContainer,
  10726. tmp,
  10727. collapsed = range.collapsed;
  10728. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  10729. tmp = node.parentNode;
  10730. range.setStartBefore(node);
  10731. //trace:937
  10732. //更新结束边界
  10733. if(range.startContainer === range.endContainer){
  10734. range.endOffset--;
  10735. }
  10736. domUtils.remove(node);
  10737. node = tmp;
  10738. }
  10739. if(!collapsed){
  10740. node = range.endContainer;
  10741. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  10742. tmp = node.parentNode;
  10743. range.setEndBefore(node);
  10744. domUtils.remove(node);
  10745. node = tmp;
  10746. }
  10747. }
  10748. }
  10749. range = this.selection.getRange();
  10750. doRemove( range );
  10751. range.select();
  10752. }
  10753. };
  10754. };
  10755. /**
  10756. * 添加引用
  10757. * @file
  10758. * @since 1.2.6.1
  10759. */
  10760. /**
  10761. * 添加引用
  10762. * @command blockquote
  10763. * @method execCommand
  10764. * @param { String } cmd 命令字符串
  10765. * @example
  10766. * ```javascript
  10767. * editor.execCommand( 'blockquote' );
  10768. * ```
  10769. */
  10770. /**
  10771. * 添加引用
  10772. * @command blockquote
  10773. * @method execCommand
  10774. * @param { String } cmd 命令字符串
  10775. * @param { Object } attrs 节点属性
  10776. * @example
  10777. * ```javascript
  10778. * editor.execCommand( 'blockquote',{
  10779. * style: "color: red;"
  10780. * } );
  10781. * ```
  10782. */
  10783. UE.plugins['blockquote'] = function(){
  10784. var me = this;
  10785. function getObj(editor){
  10786. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  10787. }
  10788. me.commands['blockquote'] = {
  10789. execCommand : function( cmdName, attrs ) {
  10790. var range = this.selection.getRange(),
  10791. obj = getObj(this),
  10792. blockquote = dtd.blockquote,
  10793. bookmark = range.createBookmark();
  10794. if ( obj ) {
  10795. var start = range.startContainer,
  10796. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  10797. end = range.endContainer,
  10798. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  10799. //处理一下li
  10800. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  10801. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  10802. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  10803. domUtils.remove(obj,true);
  10804. }else{
  10805. domUtils.breakParent(startBlock,obj);
  10806. }
  10807. if(startBlock !== endBlock){
  10808. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  10809. if(obj){
  10810. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  10811. obj.parentNode && domUtils.remove(obj,true);
  10812. }else{
  10813. domUtils.breakParent(endBlock,obj);
  10814. }
  10815. }
  10816. }
  10817. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  10818. for(var i=0,bi;bi=blockquotes[i++];){
  10819. if(!bi.childNodes.length){
  10820. domUtils.remove(bi);
  10821. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  10822. domUtils.remove(bi,true);
  10823. }
  10824. }
  10825. } else {
  10826. var tmpRange = range.cloneRange(),
  10827. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  10828. preNode = node,
  10829. doEnd = 1;
  10830. //调整开始
  10831. while ( 1 ) {
  10832. if ( domUtils.isBody(node) ) {
  10833. if ( preNode !== node ) {
  10834. if ( range.collapsed ) {
  10835. tmpRange.selectNode( preNode );
  10836. doEnd = 0;
  10837. } else {
  10838. tmpRange.setStartBefore( preNode );
  10839. }
  10840. }else{
  10841. tmpRange.setStart(node,0);
  10842. }
  10843. break;
  10844. }
  10845. if ( !blockquote[node.tagName] ) {
  10846. if ( range.collapsed ) {
  10847. tmpRange.selectNode( preNode );
  10848. } else{
  10849. tmpRange.setStartBefore( preNode);
  10850. }
  10851. break;
  10852. }
  10853. preNode = node;
  10854. node = node.parentNode;
  10855. }
  10856. //调整结束
  10857. if ( doEnd ) {
  10858. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  10859. while ( 1 ) {
  10860. if ( domUtils.isBody( node ) ) {
  10861. if ( preNode !== node ) {
  10862. tmpRange.setEndAfter( preNode );
  10863. } else {
  10864. tmpRange.setEnd( node, node.childNodes.length );
  10865. }
  10866. break;
  10867. }
  10868. if ( !blockquote[node.tagName] ) {
  10869. tmpRange.setEndAfter( preNode );
  10870. break;
  10871. }
  10872. preNode = node;
  10873. node = node.parentNode;
  10874. }
  10875. }
  10876. node = range.document.createElement( 'blockquote' );
  10877. domUtils.setAttributes( node, attrs );
  10878. node.appendChild( tmpRange.extractContents() );
  10879. tmpRange.insertNode( node );
  10880. //去除重复的
  10881. var childs = domUtils.getElementsByTagName(node,'blockquote');
  10882. for(var i=0,ci;ci=childs[i++];){
  10883. if(ci.parentNode){
  10884. domUtils.remove(ci,true);
  10885. }
  10886. }
  10887. }
  10888. range.moveToBookmark( bookmark ).select();
  10889. },
  10890. queryCommandState : function() {
  10891. return getObj(this) ? 1 : 0;
  10892. }
  10893. };
  10894. };
  10895. /**
  10896. * 大小写转换
  10897. * @file
  10898. * @since 1.2.6.1
  10899. */
  10900. /**
  10901. * 把选区内文本变大写,与“tolowercase”命令互斥
  10902. * @command touppercase
  10903. * @method execCommand
  10904. * @param { String } cmd 命令字符串
  10905. * @example
  10906. * ```javascript
  10907. * editor.execCommand( 'touppercase' );
  10908. * ```
  10909. */
  10910. /**
  10911. * 把选区内文本变小写,与“touppercase”命令互斥
  10912. * @command tolowercase
  10913. * @method execCommand
  10914. * @param { String } cmd 命令字符串
  10915. * @example
  10916. * ```javascript
  10917. * editor.execCommand( 'tolowercase' );
  10918. * ```
  10919. */
  10920. UE.commands['touppercase'] =
  10921. UE.commands['tolowercase'] = {
  10922. execCommand:function (cmd) {
  10923. var me = this;
  10924. var rng = me.selection.getRange();
  10925. if(rng.collapsed){
  10926. return rng;
  10927. }
  10928. var bk = rng.createBookmark(),
  10929. bkEnd = bk.end,
  10930. filterFn = function( node ) {
  10931. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  10932. },
  10933. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  10934. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  10935. if ( curNode.nodeType == 3 ) {
  10936. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  10937. }
  10938. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  10939. if(curNode === bkEnd){
  10940. break;
  10941. }
  10942. }
  10943. rng.moveToBookmark(bk).select();
  10944. }
  10945. };
  10946. /**
  10947. * 首行缩进
  10948. * @file
  10949. * @since 1.2.6.1
  10950. */
  10951. /**
  10952. * 缩进
  10953. * @command indent
  10954. * @method execCommand
  10955. * @param { String } cmd 命令字符串
  10956. * @example
  10957. * ```javascript
  10958. * editor.execCommand( 'indent' );
  10959. * ```
  10960. */
  10961. UE.commands['indent'] = {
  10962. execCommand : function() {
  10963. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  10964. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  10965. },
  10966. queryCommandState : function() {
  10967. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  10968. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  10969. }
  10970. };
  10971. /**
  10972. * 打印
  10973. * @file
  10974. * @since 1.2.6.1
  10975. */
  10976. /**
  10977. * 打印
  10978. * @command print
  10979. * @method execCommand
  10980. * @param { String } cmd 命令字符串
  10981. * @example
  10982. * ```javascript
  10983. * editor.execCommand( 'print' );
  10984. * ```
  10985. */
  10986. UE.commands['print'] = {
  10987. execCommand : function(){
  10988. this.window.print();
  10989. },
  10990. notNeedUndo : 1
  10991. };
  10992. /**
  10993. * 全选
  10994. * @file
  10995. * @since 1.2.6.1
  10996. */
  10997. /**
  10998. * 选中所有内容
  10999. * @command selectall
  11000. * @method execCommand
  11001. * @param { String } cmd 命令字符串
  11002. * @example
  11003. * ```javascript
  11004. * editor.execCommand( 'selectall' );
  11005. * ```
  11006. */
  11007. UE.plugins['selectall'] = function(){
  11008. var me = this;
  11009. me.commands['selectall'] = {
  11010. execCommand : function(){
  11011. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11012. var me = this,body = me.body,
  11013. range = me.selection.getRange();
  11014. range.selectNodeContents(body);
  11015. if(domUtils.isEmptyBlock(body)){
  11016. //opera不能自动合并到元素的里边,要手动处理一下
  11017. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11018. range.setStartAtFirst(body.firstChild);
  11019. }
  11020. range.collapse(true);
  11021. }
  11022. range.select(true);
  11023. },
  11024. notNeedUndo : 1
  11025. };
  11026. //快捷键
  11027. me.addshortcutkey({
  11028. "selectAll" : "ctrl+65"
  11029. });
  11030. };
  11031. /**
  11032. * 段落样式
  11033. * @file
  11034. * @since 1.2.6.1
  11035. */
  11036. /**
  11037. * 段落格式
  11038. * @command paragraph
  11039. * @method execCommand
  11040. * @param { String } cmd 命令字符串
  11041. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11042. * @param {Object} attrs 标签的属性
  11043. * @example
  11044. * ```javascript
  11045. * editor.execCommand( 'Paragraph','h1','{
  11046. * class:'test'
  11047. * }' );
  11048. * ```
  11049. */
  11050. /**
  11051. * 返回选区内节点标签名
  11052. * @command paragraph
  11053. * @method queryCommandValue
  11054. * @param { String } cmd 命令字符串
  11055. * @return { String } 节点标签名
  11056. * @example
  11057. * ```javascript
  11058. * editor.queryCommandValue( 'Paragraph' );
  11059. * ```
  11060. */
  11061. UE.plugins['paragraph'] = function() {
  11062. var me = this,
  11063. block = domUtils.isBlockElm,
  11064. notExchange = ['TD','LI','PRE'],
  11065. doParagraph = function(range,style,attrs,sourceCmdName){
  11066. var bookmark = range.createBookmark(),
  11067. filterFn = function( node ) {
  11068. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11069. },
  11070. para;
  11071. range.enlarge( true );
  11072. var bookmark2 = range.createBookmark(),
  11073. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11074. tmpRange = range.cloneRange(),
  11075. tmpNode;
  11076. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11077. if ( current.nodeType == 3 || !block( current ) ) {
  11078. tmpRange.setStartBefore( current );
  11079. while ( current && current !== bookmark2.end && !block( current ) ) {
  11080. tmpNode = current;
  11081. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11082. return !block( node );
  11083. } );
  11084. }
  11085. tmpRange.setEndAfter( tmpNode );
  11086. para = range.document.createElement( style );
  11087. if(attrs){
  11088. domUtils.setAttributes(para,attrs);
  11089. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11090. para.style.cssText = attrs.style;
  11091. }
  11092. }
  11093. para.appendChild( tmpRange.extractContents() );
  11094. //需要内容占位
  11095. if(domUtils.isEmptyNode(para)){
  11096. domUtils.fillChar(range.document,para);
  11097. }
  11098. tmpRange.insertNode( para );
  11099. var parent = para.parentNode;
  11100. //如果para上一级是一个block元素且不是body,td就删除它
  11101. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11102. //存储dir,style
  11103. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11104. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11105. //trace:1070
  11106. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11107. //trace:1030
  11108. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11109. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11110. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11111. }
  11112. //trace:1706 选择的就是h1-6要删除
  11113. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11114. domUtils.setAttributes(parent,attrs);
  11115. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11116. parent.style.cssText = attrs.style;
  11117. }
  11118. domUtils.remove(para,true);
  11119. para = parent;
  11120. }else{
  11121. domUtils.remove( para.parentNode, true );
  11122. }
  11123. }
  11124. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11125. current = parent;
  11126. }else{
  11127. current = para;
  11128. }
  11129. current = domUtils.getNextDomNode( current, false, filterFn );
  11130. } else {
  11131. current = domUtils.getNextDomNode( current, true, filterFn );
  11132. }
  11133. }
  11134. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11135. };
  11136. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11137. me.commands['paragraph'] = {
  11138. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11139. var range = this.selection.getRange();
  11140. //闭合时单独处理
  11141. if(range.collapsed){
  11142. var txt = this.document.createTextNode('p');
  11143. range.insertNode(txt);
  11144. //去掉冗余的fillchar
  11145. if(browser.ie){
  11146. var node = txt.previousSibling;
  11147. if(node && domUtils.isWhitespace(node)){
  11148. domUtils.remove(node);
  11149. }
  11150. node = txt.nextSibling;
  11151. if(node && domUtils.isWhitespace(node)){
  11152. domUtils.remove(node);
  11153. }
  11154. }
  11155. }
  11156. range = doParagraph(range,style,attrs,sourceCmdName);
  11157. if(txt){
  11158. range.setStartBefore(txt).collapse(true);
  11159. pN = txt.parentNode;
  11160. domUtils.remove(txt);
  11161. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11162. domUtils.fillNode(this.document,pN);
  11163. }
  11164. }
  11165. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11166. var child = range.startContainer.childNodes[range.startOffset];
  11167. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11168. range.setStart(child,0).collapse(true);
  11169. }
  11170. }
  11171. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11172. range.select();
  11173. return true;
  11174. },
  11175. queryCommandValue : function() {
  11176. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11177. return node ? node.tagName.toLowerCase() : '';
  11178. }
  11179. };
  11180. };
  11181. /**
  11182. * 设置文字输入的方向的插件
  11183. * @file
  11184. * @since 1.2.6.1
  11185. */
  11186. (function() {
  11187. var block = domUtils.isBlockElm ,
  11188. getObj = function(editor){
  11189. // var startNode = editor.selection.getStart(),
  11190. // parents;
  11191. // if ( startNode ) {
  11192. // //查找所有的是block的父亲节点
  11193. // parents = domUtils.findParents( startNode, true, block, true );
  11194. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11195. // if ( ci.getAttribute( 'dir' ) ) {
  11196. // return ci;
  11197. // }
  11198. // }
  11199. // }
  11200. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n.getAttribute('dir')});
  11201. },
  11202. doDirectionality = function(range,editor,forward){
  11203. var bookmark,
  11204. filterFn = function( node ) {
  11205. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11206. },
  11207. obj = getObj( editor );
  11208. if ( obj && range.collapsed ) {
  11209. obj.setAttribute( 'dir', forward );
  11210. return range;
  11211. }
  11212. bookmark = range.createBookmark();
  11213. range.enlarge( true );
  11214. var bookmark2 = range.createBookmark(),
  11215. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11216. tmpRange = range.cloneRange(),
  11217. tmpNode;
  11218. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11219. if ( current.nodeType == 3 || !block( current ) ) {
  11220. tmpRange.setStartBefore( current );
  11221. while ( current && current !== bookmark2.end && !block( current ) ) {
  11222. tmpNode = current;
  11223. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11224. return !block( node );
  11225. } );
  11226. }
  11227. tmpRange.setEndAfter( tmpNode );
  11228. var common = tmpRange.getCommonAncestor();
  11229. if ( !domUtils.isBody( common ) && block( common ) ) {
  11230. //遍历到了block节点
  11231. common.setAttribute( 'dir', forward );
  11232. current = common;
  11233. } else {
  11234. //没有遍历到,添加一个block节点
  11235. var p = range.document.createElement( 'p' );
  11236. p.setAttribute( 'dir', forward );
  11237. var frag = tmpRange.extractContents();
  11238. p.appendChild( frag );
  11239. tmpRange.insertNode( p );
  11240. current = p;
  11241. }
  11242. current = domUtils.getNextDomNode( current, false, filterFn );
  11243. } else {
  11244. current = domUtils.getNextDomNode( current, true, filterFn );
  11245. }
  11246. }
  11247. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11248. };
  11249. /**
  11250. * 文字输入方向
  11251. * @command directionality
  11252. * @method execCommand
  11253. * @param { String } cmdName 命令字符串
  11254. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11255. * @example
  11256. * ```javascript
  11257. * editor.execCommand( 'directionality', 'ltr');
  11258. * ```
  11259. */
  11260. /**
  11261. * 查询当前选区的文字输入方向
  11262. * @command directionality
  11263. * @method queryCommandValue
  11264. * @param { String } cmdName 命令字符串
  11265. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11266. * @example
  11267. * ```javascript
  11268. * editor.queryCommandValue( 'directionality');
  11269. * ```
  11270. */
  11271. UE.commands['directionality'] = {
  11272. execCommand : function( cmdName,forward ) {
  11273. var range = this.selection.getRange();
  11274. //闭合时单独处理
  11275. if(range.collapsed){
  11276. var txt = this.document.createTextNode('d');
  11277. range.insertNode(txt);
  11278. }
  11279. doDirectionality(range,this,forward);
  11280. if(txt){
  11281. range.setStartBefore(txt).collapse(true);
  11282. domUtils.remove(txt);
  11283. }
  11284. range.select();
  11285. return true;
  11286. },
  11287. queryCommandValue : function() {
  11288. var node = getObj(this);
  11289. return node ? node.getAttribute('dir') : 'ltr';
  11290. }
  11291. };
  11292. })();
  11293. /**
  11294. * 插入分割线插件
  11295. * @file
  11296. * @since 1.2.6.1
  11297. */
  11298. /**
  11299. * 插入分割线
  11300. * @command horizontal
  11301. * @method execCommand
  11302. * @param { String } cmdName 命令字符串
  11303. * @example
  11304. * ```javascript
  11305. * editor.execCommand( 'horizontal' );
  11306. * ```
  11307. */
  11308. UE.plugins['horizontal'] = function(){
  11309. var me = this;
  11310. me.commands['horizontal'] = {
  11311. execCommand : function( cmdName ) {
  11312. var me = this;
  11313. if(me.queryCommandState(cmdName)!==-1){
  11314. me.execCommand('insertHtml','<hr>');
  11315. var range = me.selection.getRange(),
  11316. start = range.startContainer;
  11317. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  11318. var tmp;
  11319. if(tmp = start.childNodes[range.startOffset - 1]){
  11320. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  11321. if(me.options.enterTag == 'p'){
  11322. tmp = me.document.createElement('p');
  11323. range.insertNode(tmp);
  11324. range.setStart(tmp,0).setCursor();
  11325. }else{
  11326. tmp = me.document.createElement('br');
  11327. range.insertNode(tmp);
  11328. range.setStartBefore(tmp).setCursor();
  11329. }
  11330. }
  11331. }
  11332. }
  11333. return true;
  11334. }
  11335. },
  11336. //边界在table里不能加分隔线
  11337. queryCommandState : function() {
  11338. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  11339. }
  11340. };
  11341. // me.addListener('delkeyup',function(){
  11342. // var rng = this.selection.getRange();
  11343. // if(browser.ie && browser.version > 8){
  11344. // rng.txtToElmBoundary(true);
  11345. // if(domUtils.isStartInblock(rng)){
  11346. // var tmpNode = rng.startContainer;
  11347. // var pre = tmpNode.previousSibling;
  11348. // if(pre && domUtils.isTagNode(pre,'hr')){
  11349. // domUtils.remove(pre);
  11350. // rng.select();
  11351. // return;
  11352. // }
  11353. // }
  11354. // }
  11355. // if(domUtils.isBody(rng.startContainer)){
  11356. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  11357. // if(hr && hr.nodeName == 'HR'){
  11358. // var next = hr.nextSibling;
  11359. // if(next){
  11360. // rng.setStart(next,0)
  11361. // }else if(hr.previousSibling){
  11362. // rng.setStartAtLast(hr.previousSibling)
  11363. // }else{
  11364. // var p = this.document.createElement('p');
  11365. // hr.parentNode.insertBefore(p,hr);
  11366. // domUtils.fillNode(this.document,p);
  11367. // rng.setStart(p,0);
  11368. // }
  11369. // domUtils.remove(hr);
  11370. // rng.setCursor(false,true);
  11371. // }
  11372. // }
  11373. // })
  11374. me.addListener('delkeydown',function(name,evt){
  11375. var rng = this.selection.getRange();
  11376. rng.txtToElmBoundary(true);
  11377. if(domUtils.isStartInblock(rng)){
  11378. var tmpNode = rng.startContainer;
  11379. var pre = tmpNode.previousSibling;
  11380. if(pre && domUtils.isTagNode(pre,'hr')){
  11381. domUtils.remove(pre);
  11382. rng.select();
  11383. domUtils.preventDefault(evt);
  11384. return true;
  11385. }
  11386. }
  11387. })
  11388. };
  11389. /**
  11390. * 插入时间和日期
  11391. * @file
  11392. * @since 1.2.6.1
  11393. */
  11394. /**
  11395. * 插入时间,默认格式:12:59:59
  11396. * @command time
  11397. * @method execCommand
  11398. * @param { String } cmd 命令字符串
  11399. * @example
  11400. * ```javascript
  11401. * editor.execCommand( 'time');
  11402. * ```
  11403. */
  11404. /**
  11405. * 插入日期,默认格式:2013-08-30
  11406. * @command date
  11407. * @method execCommand
  11408. * @param { String } cmd 命令字符串
  11409. * @example
  11410. * ```javascript
  11411. * editor.execCommand( 'date');
  11412. * ```
  11413. */
  11414. UE.commands['time'] = UE.commands["date"] = {
  11415. execCommand : function(cmd, format){
  11416. var date = new Date;
  11417. function formatTime(date, format) {
  11418. var hh = ('0' + date.getHours()).slice(-2),
  11419. ii = ('0' + date.getMinutes()).slice(-2),
  11420. ss = ('0' + date.getSeconds()).slice(-2);
  11421. format = format || 'hh:ii:ss';
  11422. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  11423. }
  11424. function formatDate(date, format) {
  11425. var yyyy = ('000' + date.getFullYear()).slice(-4),
  11426. yy = yyyy.slice(-2),
  11427. mm = ('0' + (date.getMonth()+1)).slice(-2),
  11428. dd = ('0' + date.getDate()).slice(-2);
  11429. format = format || 'yyyy-mm-dd';
  11430. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  11431. }
  11432. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  11433. }
  11434. };
  11435. /**
  11436. * 段前段后间距插件
  11437. * @file
  11438. * @since 1.2.6.1
  11439. */
  11440. /**
  11441. * 设置段间距
  11442. * @command rowspacing
  11443. * @method execCommand
  11444. * @param { String } cmd 命令字符串
  11445. * @param { String } value 段间距的值,以px为单位
  11446. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  11447. * @example
  11448. * ```javascript
  11449. * editor.execCommand( 'rowspacing', '10', 'top' );
  11450. * ```
  11451. */
  11452. UE.plugins['rowspacing'] = function(){
  11453. var me = this;
  11454. me.setOpt({
  11455. 'rowspacingtop':['5', '10', '15', '20', '25'],
  11456. 'rowspacingbottom':['5', '10', '15', '20', '25']
  11457. });
  11458. me.commands['rowspacing'] = {
  11459. execCommand : function( cmdName,value,dir ) {
  11460. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  11461. return true;
  11462. },
  11463. queryCommandValue : function(cmdName,dir) {
  11464. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  11465. value;
  11466. //trace:1026
  11467. if(pN){
  11468. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  11469. return !value ? 0 : value;
  11470. }
  11471. return 0;
  11472. }
  11473. };
  11474. };
  11475. /**
  11476. * 设置行内间距
  11477. * @file
  11478. * @since 1.2.6.1
  11479. */
  11480. UE.plugins['lineheight'] = function(){
  11481. var me = this;
  11482. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  11483. /**
  11484. * 行距
  11485. * @command lineheight
  11486. * @method execCommand
  11487. * @param { String } cmdName 命令字符串
  11488. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  11489. * @example
  11490. * ```javascript
  11491. * editor.execCommand( 'lineheight', 1.5);
  11492. * ```
  11493. */
  11494. /**
  11495. * 查询当前选区内容的行高大小
  11496. * @command lineheight
  11497. * @method queryCommandValue
  11498. * @param { String } cmd 命令字符串
  11499. * @return { String } 返回当前行高大小
  11500. * @example
  11501. * ```javascript
  11502. * editor.queryCommandValue( 'lineheight' );
  11503. * ```
  11504. */
  11505. me.commands['lineheight'] = {
  11506. execCommand : function( cmdName,value ) {
  11507. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  11508. return true;
  11509. },
  11510. queryCommandValue : function() {
  11511. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  11512. if(pN){
  11513. var value = domUtils.getComputedStyle(pN,'line-height');
  11514. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  11515. }
  11516. }
  11517. };
  11518. };
  11519. /**
  11520. * 插入代码插件
  11521. * @file
  11522. * @since 1.2.6.1
  11523. */
  11524. UE.plugins['insertcode'] = function() {
  11525. var me = this;
  11526. me.ready(function(){
  11527. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  11528. me.document)
  11529. });
  11530. me.setOpt('insertcode',{
  11531. 'as3':'ActionScript3',
  11532. 'bash':'Bash/Shell',
  11533. 'cpp':'C/C++',
  11534. 'css':'Css',
  11535. 'cf':'CodeFunction',
  11536. 'c#':'C#',
  11537. 'delphi':'Delphi',
  11538. 'diff':'Diff',
  11539. 'erlang':'Erlang',
  11540. 'groovy':'Groovy',
  11541. 'html':'Html',
  11542. 'java':'Java',
  11543. 'jfx':'JavaFx',
  11544. 'js':'Javascript',
  11545. 'pl':'Perl',
  11546. 'php':'Php',
  11547. 'plain':'Plain Text',
  11548. 'ps':'PowerShell',
  11549. 'python':'Python',
  11550. 'ruby':'Ruby',
  11551. 'scala':'Scala',
  11552. 'sql':'Sql',
  11553. 'vb':'Vb',
  11554. 'xml':'Xml'
  11555. });
  11556. /**
  11557. * 插入代码
  11558. * @command insertcode
  11559. * @method execCommand
  11560. * @param { String } cmd 命令字符串
  11561. * @param { String } lang 插入代码的语言
  11562. * @example
  11563. * ```javascript
  11564. * editor.execCommand( 'insertcode', 'javascript' );
  11565. * ```
  11566. */
  11567. /**
  11568. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  11569. * @command insertcode
  11570. * @method queryCommandValue
  11571. * @param { String } cmd 命令字符串
  11572. * @return { String } 返回代码的语言
  11573. * @example
  11574. * ```javascript
  11575. * editor.queryCommandValue( 'insertcode' );
  11576. * ```
  11577. */
  11578. me.commands['insertcode'] = {
  11579. execCommand : function(cmd,lang){
  11580. var me = this,
  11581. rng = me.selection.getRange(),
  11582. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11583. if(pre){
  11584. pre.className = 'brush:'+lang+';toolbar:false;';
  11585. }else{
  11586. var code = '';
  11587. if(rng.collapsed){
  11588. code = browser.ie? (browser.version > 8 ? '' : '&nbsp;'):'<br/>';
  11589. }else{
  11590. var frag = rng.extractContents();
  11591. var div = me.document.createElement('div');
  11592. div.appendChild(frag);
  11593. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  11594. if(browser.ie && browser.version > 8){
  11595. if(node.type =='element'){
  11596. if(node.tagName == 'br'){
  11597. code += '\n'
  11598. }else if(!dtd.$empty[node.tagName]){
  11599. utils.each(node.children,function(cn){
  11600. if(cn.type =='element'){
  11601. if(cn.tagName == 'br'){
  11602. code += '\n'
  11603. }else if(!dtd.$empty[node.tagName]){
  11604. code += cn.innerText();
  11605. }
  11606. }else{
  11607. code += cn.data
  11608. }
  11609. })
  11610. if(!/\n$/.test(code)){
  11611. code += '\n';
  11612. }
  11613. }
  11614. }else{
  11615. code += node.data + '\n'
  11616. }
  11617. if(!node.nextSibling() && /\n$/.test(code)){
  11618. code = code.replace(/\n$/,'');
  11619. }
  11620. }else{
  11621. if(browser.ie){
  11622. if(node.type =='element'){
  11623. if(node.tagName == 'br'){
  11624. code += '<br>'
  11625. }else if(!dtd.$empty[node.tagName]){
  11626. utils.each(node.children,function(cn){
  11627. if(cn.type =='element'){
  11628. if(cn.tagName == 'br'){
  11629. code += '<br>'
  11630. }else if(!dtd.$empty[node.tagName]){
  11631. code += cn.innerText();
  11632. }
  11633. }else{
  11634. code += cn.data
  11635. }
  11636. });
  11637. if(!/br>$/.test(code)){
  11638. code += '<br>';
  11639. }
  11640. }
  11641. }else{
  11642. code += node.data + '<br>'
  11643. }
  11644. if(!node.nextSibling() && /<br>$/.test(code)){
  11645. code = code.replace(/<br>$/,'');
  11646. }
  11647. }else{
  11648. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  11649. if(!/br\/?\s*>$/.test(code)){
  11650. if(!node.nextSibling())
  11651. return;
  11652. code += '<br>'
  11653. }
  11654. }
  11655. }
  11656. });
  11657. }
  11658. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  11659. pre = me.document.getElementById('coder');
  11660. domUtils.removeAttributes(pre,'id');
  11661. var tmpNode = pre.previousSibling;
  11662. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  11663. domUtils.remove(tmpNode)
  11664. }
  11665. var rng = me.selection.getRange();
  11666. if(domUtils.isEmptyBlock(pre)){
  11667. rng.setStart(pre,0).setCursor(false,true)
  11668. }else{
  11669. rng.selectNodeContents(pre).select()
  11670. }
  11671. }
  11672. },
  11673. queryCommandValue : function(){
  11674. var path = this.selection.getStartElementPath();
  11675. var lang = '';
  11676. utils.each(path,function(node){
  11677. if(node.nodeName =='PRE'){
  11678. var match = node.className.match(/brush:([^;]+)/);
  11679. lang = match && match[1] ? match[1] : '';
  11680. return false;
  11681. }
  11682. });
  11683. return lang;
  11684. }
  11685. };
  11686. me.addInputRule(function(root){
  11687. utils.each(root.getNodesByTagName('pre'),function(pre){
  11688. var brs = pre.getNodesByTagName('br');
  11689. if(brs.length){
  11690. browser.ie && browser.version > 8 && utils.each(brs,function(br){
  11691. var txt = UE.uNode.createText('\n');
  11692. br.parentNode.insertBefore(txt,br);
  11693. br.parentNode.removeChild(br);
  11694. });
  11695. return;
  11696. }
  11697. if(browser.ie && browser.version > 8)
  11698. return;
  11699. var code = pre.innerText().split(/\n/);
  11700. pre.innerHTML('');
  11701. utils.each(code,function(c){
  11702. if(c.length){
  11703. pre.appendChild(UE.uNode.createText(c));
  11704. }
  11705. pre.appendChild(UE.uNode.createElement('br'))
  11706. })
  11707. })
  11708. });
  11709. me.addOutputRule(function(root){
  11710. utils.each(root.getNodesByTagName('pre'),function(pre){
  11711. var code = '';
  11712. utils.each(pre.children,function(n){
  11713. if(n.type == 'text'){
  11714. //在ie下文本内容有可能末尾带有\n要去掉
  11715. //trace:3396
  11716. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  11717. }else{
  11718. if(n.tagName == 'br'){
  11719. code += '\n'
  11720. }else{
  11721. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  11722. }
  11723. }
  11724. });
  11725. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  11726. })
  11727. });
  11728. //不需要判断highlight的command列表
  11729. me.notNeedCodeQuery ={
  11730. help:1,
  11731. undo:1,
  11732. redo:1,
  11733. source:1,
  11734. print:1,
  11735. searchreplace:1,
  11736. fullscreen:1,
  11737. preview:1,
  11738. insertparagraph:1,
  11739. elementpath:1,
  11740. insertcode:1,
  11741. inserthtml:1,
  11742. selectall:1
  11743. };
  11744. //将queyCommamndState重置
  11745. var orgQuery = me.queryCommandState;
  11746. me.queryCommandState = function(cmd){
  11747. var me = this;
  11748. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  11749. return -1;
  11750. }
  11751. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  11752. };
  11753. me.addListener('beforeenterkeydown',function(){
  11754. var rng = me.selection.getRange();
  11755. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11756. if(pre){
  11757. me.fireEvent('saveScene');
  11758. if(!rng.collapsed){
  11759. rng.deleteContents();
  11760. }
  11761. if(!browser.ie || browser.ie9above){
  11762. var tmpNode = me.document.createElement('br'),pre;
  11763. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  11764. var next = tmpNode.nextSibling;
  11765. if(!next && (!browser.ie || browser.version > 10)){
  11766. rng.insertNode(tmpNode.cloneNode(false));
  11767. }else{
  11768. rng.setStartAfter(tmpNode);
  11769. }
  11770. pre = tmpNode.previousSibling;
  11771. var tmp;
  11772. while(pre ){
  11773. tmp = pre;
  11774. pre = pre.previousSibling;
  11775. if(!pre || pre.nodeName == 'BR'){
  11776. pre = tmp;
  11777. break;
  11778. }
  11779. }
  11780. if(pre){
  11781. var str = '';
  11782. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  11783. str += pre.nodeValue;
  11784. pre = pre.nextSibling;
  11785. }
  11786. if(pre.nodeName != 'BR'){
  11787. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  11788. if(match && match[1]){
  11789. str += match[1]
  11790. }
  11791. }
  11792. if(str){
  11793. str = me.document.createTextNode(str);
  11794. rng.insertNode(str).setStartAfter(str);
  11795. }
  11796. }
  11797. rng.collapse(true).select(true);
  11798. }else{
  11799. if(browser.version > 8){
  11800. var txt = me.document.createTextNode('\n');
  11801. var start = rng.startContainer;
  11802. if(rng.startOffset == 0){
  11803. var preNode = start.previousSibling;
  11804. if(preNode){
  11805. rng.insertNode(txt);
  11806. var fillchar = me.document.createTextNode(' ');
  11807. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  11808. }
  11809. }else{
  11810. rng.insertNode(txt).setStartAfter(txt);
  11811. var fillchar = me.document.createTextNode(' ');
  11812. start = rng.startContainer.childNodes[rng.startOffset];
  11813. if(start && !/^\n/.test(start.nodeValue)){
  11814. rng.setStartBefore(txt)
  11815. }
  11816. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  11817. }
  11818. }else{
  11819. var tmpNode = me.document.createElement('br');
  11820. rng.insertNode(tmpNode);
  11821. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  11822. rng.setStartAfter(tmpNode);
  11823. pre = tmpNode.previousSibling;
  11824. var tmp;
  11825. while(pre ){
  11826. tmp = pre;
  11827. pre = pre.previousSibling;
  11828. if(!pre || pre.nodeName == 'BR'){
  11829. pre = tmp;
  11830. break;
  11831. }
  11832. }
  11833. if(pre){
  11834. var str = '';
  11835. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  11836. str += pre.nodeValue;
  11837. pre = pre.nextSibling;
  11838. }
  11839. if(pre.nodeName != 'BR'){
  11840. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  11841. if(match && match[1]){
  11842. str += match[1]
  11843. }
  11844. }
  11845. str = me.document.createTextNode(str);
  11846. rng.insertNode(str).setStartAfter(str);
  11847. }
  11848. rng.collapse(true).select();
  11849. }
  11850. }
  11851. me.fireEvent('saveScene');
  11852. return true;
  11853. }
  11854. });
  11855. me.addListener('tabkeydown',function(cmd,evt){
  11856. var rng = me.selection.getRange();
  11857. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11858. if(pre){
  11859. me.fireEvent('saveScene');
  11860. if(evt.shiftKey){
  11861. }else{
  11862. if(!rng.collapsed){
  11863. var bk = rng.createBookmark();
  11864. var start = bk.start.previousSibling;
  11865. while(start){
  11866. if(pre.firstChild === start && !domUtils.isBr(start)){
  11867. pre.insertBefore(me.document.createTextNode(' '),start);
  11868. break;
  11869. }
  11870. if(domUtils.isBr(start)){
  11871. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  11872. break;
  11873. }
  11874. start = start.previousSibling;
  11875. }
  11876. var end = bk.end;
  11877. start = bk.start.nextSibling;
  11878. if(pre.firstChild === bk.start){
  11879. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  11880. }
  11881. while(start && start !== end){
  11882. if(domUtils.isBr(start) && start.nextSibling){
  11883. if(start.nextSibling === end){
  11884. break;
  11885. }
  11886. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  11887. }
  11888. start = start.nextSibling;
  11889. }
  11890. rng.moveToBookmark(bk).select();
  11891. }else{
  11892. var tmpNode = me.document.createTextNode(' ');
  11893. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  11894. }
  11895. }
  11896. me.fireEvent('saveScene');
  11897. return true;
  11898. }
  11899. });
  11900. me.addListener('beforeinserthtml',function(evtName,html){
  11901. var me = this,
  11902. rng = me.selection.getRange(),
  11903. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  11904. if(pre){
  11905. if(!rng.collapsed){
  11906. rng.deleteContents()
  11907. }
  11908. var htmlstr = '';
  11909. if(browser.ie && browser.version > 8){
  11910. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  11911. if(node.type =='element'){
  11912. if(node.tagName == 'br'){
  11913. htmlstr += '\n'
  11914. }else if(!dtd.$empty[node.tagName]){
  11915. utils.each(node.children,function(cn){
  11916. if(cn.type =='element'){
  11917. if(cn.tagName == 'br'){
  11918. htmlstr += '\n'
  11919. }else if(!dtd.$empty[node.tagName]){
  11920. htmlstr += cn.innerText();
  11921. }
  11922. }else{
  11923. htmlstr += cn.data
  11924. }
  11925. })
  11926. if(!/\n$/.test(htmlstr)){
  11927. htmlstr += '\n';
  11928. }
  11929. }
  11930. }else{
  11931. htmlstr += node.data + '\n'
  11932. }
  11933. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  11934. htmlstr = htmlstr.replace(/\n$/,'');
  11935. }
  11936. });
  11937. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  11938. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  11939. }else{
  11940. var frag = me.document.createDocumentFragment();
  11941. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  11942. if(node.type =='element'){
  11943. if(node.tagName == 'br'){
  11944. frag.appendChild(me.document.createElement('br'))
  11945. }else if(!dtd.$empty[node.tagName]){
  11946. utils.each(node.children,function(cn){
  11947. if(cn.type =='element'){
  11948. if(cn.tagName == 'br'){
  11949. frag.appendChild(me.document.createElement('br'))
  11950. }else if(!dtd.$empty[node.tagName]){
  11951. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  11952. }
  11953. }else{
  11954. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  11955. }
  11956. })
  11957. if(frag.lastChild.nodeName != 'BR'){
  11958. frag.appendChild(me.document.createElement('br'))
  11959. }
  11960. }
  11961. }else{
  11962. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  11963. }
  11964. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  11965. frag.removeChild(frag.lastChild)
  11966. }
  11967. });
  11968. rng.insertNode(frag).select();
  11969. }
  11970. return true;
  11971. }
  11972. });
  11973. //方向键的处理
  11974. me.addListener('keydown',function(cmd,evt){
  11975. var me = this,keyCode = evt.keyCode || evt.which;
  11976. if(keyCode == 40){
  11977. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  11978. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  11979. var last = pre.lastChild
  11980. while(last && last.nodeName == 'BR'){
  11981. last = last.previousSibling;
  11982. }
  11983. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  11984. me.execCommand('insertparagraph');
  11985. domUtils.preventDefault(evt)
  11986. }
  11987. }
  11988. }
  11989. });
  11990. //trace:3395
  11991. me.addListener('delkeydown',function(type,evt){
  11992. var rng = this.selection.getRange();
  11993. rng.txtToElmBoundary(true);
  11994. var start = rng.startContainer;
  11995. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  11996. var p = me.document.createElement('p');
  11997. domUtils.fillNode(me.document,p);
  11998. start.parentNode.insertBefore(p,start);
  11999. domUtils.remove(start);
  12000. rng.setStart(p,0).setCursor(false,true);
  12001. domUtils.preventDefault(evt);
  12002. return true;
  12003. }
  12004. })
  12005. };
  12006. /**
  12007. * 清空文档插件
  12008. * @file
  12009. * @since 1.2.6.1
  12010. */
  12011. /**
  12012. * 清空文档
  12013. * @command cleardoc
  12014. * @method execCommand
  12015. * @param { String } cmd 命令字符串
  12016. * @example
  12017. * ```javascript
  12018. * //editor 是编辑器实例
  12019. * editor.execCommand('cleardoc');
  12020. * ```
  12021. */
  12022. UE.commands['cleardoc'] = {
  12023. execCommand : function( cmdName) {
  12024. var me = this,
  12025. enterTag = me.options.enterTag,
  12026. range = me.selection.getRange();
  12027. if(enterTag == "br"){
  12028. me.body.innerHTML = "<br/>";
  12029. range.setStart(me.body,0).setCursor();
  12030. }else{
  12031. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12032. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12033. }
  12034. setTimeout(function(){
  12035. me.fireEvent("clearDoc");
  12036. },0);
  12037. }
  12038. };
  12039. /**
  12040. * 锚点插件,为UEditor提供插入锚点支持
  12041. * @file
  12042. * @since 1.2.6.1
  12043. */
  12044. UE.plugin.register('anchor', function (){
  12045. return {
  12046. bindEvents:{
  12047. 'ready':function(){
  12048. utils.cssRule('anchor',
  12049. '.anchorclass{background: url(\''
  12050. + this.options.themePath
  12051. + 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;}',
  12052. this.document);
  12053. }
  12054. },
  12055. outputRule: function(root){
  12056. utils.each(root.getNodesByTagName('img'),function(a){
  12057. var val;
  12058. if(val = a.getAttr('anchorname')){
  12059. a.tagName = 'a';
  12060. a.setAttr({
  12061. anchorname : '',
  12062. name : val,
  12063. 'class' : ''
  12064. })
  12065. }
  12066. })
  12067. },
  12068. inputRule:function(root){
  12069. utils.each(root.getNodesByTagName('a'),function(a){
  12070. var val;
  12071. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12072. a.tagName = 'img';
  12073. a.setAttr({
  12074. anchorname :a.getAttr('name'),
  12075. 'class' : 'anchorclass'
  12076. });
  12077. a.setAttr('name')
  12078. }
  12079. })
  12080. },
  12081. commands:{
  12082. /**
  12083. * 插入锚点
  12084. * @command anchor
  12085. * @method execCommand
  12086. * @param { String } cmd 命令字符串
  12087. * @param { String } name 锚点名称字符串
  12088. * @example
  12089. * ```javascript
  12090. * //editor 是编辑器实例
  12091. * editor.execCommand('anchor', 'anchor1');
  12092. * ```
  12093. */
  12094. 'anchor':{
  12095. execCommand:function (cmd, name) {
  12096. var range = this.selection.getRange(),img = range.getClosedNode();
  12097. if (img && img.getAttribute('anchorname')) {
  12098. if (name) {
  12099. img.setAttribute('anchorname', name);
  12100. } else {
  12101. range.setStartBefore(img).setCursor();
  12102. domUtils.remove(img);
  12103. }
  12104. } else {
  12105. if (name) {
  12106. //只在选区的开始插入
  12107. var anchor = this.document.createElement('img');
  12108. range.collapse(true);
  12109. domUtils.setAttributes(anchor,{
  12110. 'anchorname':name,
  12111. 'class':'anchorclass'
  12112. });
  12113. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12114. }
  12115. }
  12116. }
  12117. }
  12118. }
  12119. }
  12120. });
  12121. ///import core
  12122. ///commands 字数统计
  12123. ///commandsName WordCount,wordCount
  12124. ///commandsTitle 字数统计
  12125. /*
  12126. * Created by JetBrains WebStorm.
  12127. * User: taoqili
  12128. * Date: 11-9-7
  12129. * Time: 下午8:18
  12130. * To change this template use File | Settings | File Templates.
  12131. */
  12132. UE.plugins['wordcount'] = function(){
  12133. var me = this;
  12134. me.setOpt('wordCount',true);
  12135. me.addListener('contentchange',function(){
  12136. me.fireEvent('wordcount');
  12137. });
  12138. var timer;
  12139. me.addListener('ready',function(){
  12140. var me = this;
  12141. domUtils.on(me.body,"keyup",function(evt){
  12142. var code = evt.keyCode||evt.which,
  12143. //忽略的按键,ctr,alt,shift,方向键
  12144. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12145. if(code in ignores) return;
  12146. clearTimeout(timer);
  12147. timer = setTimeout(function(){
  12148. me.fireEvent('wordcount');
  12149. },200)
  12150. })
  12151. });
  12152. };
  12153. /**
  12154. * 分页功能插件
  12155. * @file
  12156. * @since 1.2.6.1
  12157. */
  12158. UE.plugins['pagebreak'] = function () {
  12159. var me = this,
  12160. notBreakTags = ['td'];
  12161. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12162. function fillNode(node){
  12163. if(domUtils.isEmptyBlock(node)){
  12164. var firstChild = node.firstChild,tmpNode;
  12165. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12166. tmpNode = firstChild;
  12167. firstChild = firstChild.firstChild;
  12168. }
  12169. !tmpNode && (tmpNode = node);
  12170. domUtils.fillNode(me.document,tmpNode);
  12171. }
  12172. }
  12173. //分页符样式添加
  12174. me.ready(function(){
  12175. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12176. });
  12177. function isHr(node){
  12178. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12179. }
  12180. me.addInputRule(function(root){
  12181. root.traversal(function(node){
  12182. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12183. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12184. node.parentNode.insertBefore(hr,node);
  12185. node.parentNode.removeChild(node)
  12186. }
  12187. })
  12188. });
  12189. me.addOutputRule(function(node){
  12190. utils.each(node.getNodesByTagName('hr'),function(n){
  12191. if(n.getAttr('class') == 'pagebreak'){
  12192. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12193. n.parentNode.insertBefore(txt,n);
  12194. n.parentNode.removeChild(n);
  12195. }
  12196. })
  12197. });
  12198. /**
  12199. * 插入分页符
  12200. * @command pagebreak
  12201. * @method execCommand
  12202. * @param { String } cmd 命令字符串
  12203. * @remind 在表格中插入分页符会把表格切分成两部分
  12204. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12205. * 以便于提交数据到服务器端后处理分页。
  12206. * @example
  12207. * ```javascript
  12208. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12209. * ```
  12210. */
  12211. me.commands['pagebreak'] = {
  12212. execCommand:function () {
  12213. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12214. domUtils.setAttributes(hr,{
  12215. 'class' : 'pagebreak',
  12216. noshade:"noshade",
  12217. size:"5"
  12218. });
  12219. domUtils.unSelectable(hr);
  12220. //table单独处理
  12221. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12222. parents = [], pN;
  12223. if (node) {
  12224. switch (node.tagName) {
  12225. case 'TD':
  12226. pN = node.parentNode;
  12227. if (!pN.previousSibling) {
  12228. var table = domUtils.findParentByTagName(pN, 'table');
  12229. // var tableWrapDiv = table.parentNode;
  12230. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12231. // && tableWrapDiv.tagName == 'DIV'
  12232. // && tableWrapDiv.getAttribute('dropdrag')
  12233. // ){
  12234. // domUtils.remove(tableWrapDiv,true);
  12235. // }
  12236. table.parentNode.insertBefore(hr, table);
  12237. parents = domUtils.findParents(hr, true);
  12238. } else {
  12239. pN.parentNode.insertBefore(hr, pN);
  12240. parents = domUtils.findParents(hr);
  12241. }
  12242. pN = parents[1];
  12243. if (hr !== pN) {
  12244. domUtils.breakParent(hr, pN);
  12245. }
  12246. //table要重写绑定一下拖拽
  12247. me.fireEvent('afteradjusttable',me.document);
  12248. }
  12249. } else {
  12250. if (!range.collapsed) {
  12251. range.deleteContents();
  12252. var start = range.startContainer;
  12253. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12254. range.setStartBefore(start).collapse(true);
  12255. domUtils.remove(start);
  12256. start = range.startContainer;
  12257. }
  12258. }
  12259. range.insertNode(hr);
  12260. var pN = hr.parentNode, nextNode;
  12261. while (!domUtils.isBody(pN)) {
  12262. domUtils.breakParent(hr, pN);
  12263. nextNode = hr.nextSibling;
  12264. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12265. domUtils.remove(nextNode);
  12266. }
  12267. pN = hr.parentNode;
  12268. }
  12269. nextNode = hr.nextSibling;
  12270. var pre = hr.previousSibling;
  12271. if(isHr(pre)){
  12272. domUtils.remove(pre);
  12273. }else{
  12274. pre && fillNode(pre);
  12275. }
  12276. if(!nextNode){
  12277. var p = me.document.createElement('p');
  12278. hr.parentNode.appendChild(p);
  12279. domUtils.fillNode(me.document,p);
  12280. range.setStart(p,0).collapse(true);
  12281. }else{
  12282. if(isHr(nextNode)){
  12283. domUtils.remove(nextNode);
  12284. }else{
  12285. fillNode(nextNode);
  12286. }
  12287. range.setEndAfter(hr).collapse(false);
  12288. }
  12289. range.select(true);
  12290. }
  12291. }
  12292. };
  12293. };
  12294. ///import core
  12295. ///commands 本地图片引导上传
  12296. ///commandsName WordImage
  12297. ///commandsTitle 本地图片引导上传
  12298. ///commandsDialog dialogs\wordimage
  12299. UE.plugin.register('wordimage',function(){
  12300. var me = this,
  12301. images = [];
  12302. return {
  12303. commands : {
  12304. 'wordimage':{
  12305. execCommand:function () {
  12306. var images = domUtils.getElementsByTagName(me.body, "img");
  12307. var urlList = [];
  12308. for (var i = 0, ci; ci = images[i++];) {
  12309. var url = ci.getAttribute("word_img");
  12310. url && urlList.push(url);
  12311. }
  12312. return urlList;
  12313. },
  12314. queryCommandState:function () {
  12315. images = domUtils.getElementsByTagName(me.body, "img");
  12316. for (var i = 0, ci; ci = images[i++];) {
  12317. if (ci.getAttribute("word_img")) {
  12318. return 1;
  12319. }
  12320. }
  12321. return -1;
  12322. },
  12323. notNeedUndo:true
  12324. }
  12325. },
  12326. inputRule : function (root) {
  12327. utils.each(root.getNodesByTagName('img'), function (img) {
  12328. var attrs = img.attrs,
  12329. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  12330. opt = me.options,
  12331. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  12332. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  12333. img.setAttr({
  12334. width:attrs.width,
  12335. height:attrs.height,
  12336. alt:attrs.alt,
  12337. word_img: attrs.src,
  12338. src:src,
  12339. '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'
  12340. })
  12341. }
  12342. })
  12343. }
  12344. }
  12345. });
  12346. UE.plugins['dragdrop'] = function (){
  12347. var me = this;
  12348. me.ready(function(){
  12349. domUtils.on(this.body,'dragend',function(){
  12350. var rng = me.selection.getRange();
  12351. var node = rng.getClosedNode()||me.selection.getStart();
  12352. if(node && node.tagName == 'IMG'){
  12353. var pre = node.previousSibling,next;
  12354. while(next = node.nextSibling){
  12355. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  12356. domUtils.remove(next)
  12357. }else{
  12358. break;
  12359. }
  12360. }
  12361. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  12362. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  12363. pre.appendChild(node);
  12364. domUtils.moveChild(next,pre);
  12365. domUtils.remove(next);
  12366. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  12367. next.insertBefore(node,next.firstChild);
  12368. }
  12369. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  12370. domUtils.remove(pre)
  12371. }
  12372. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  12373. domUtils.remove(next)
  12374. }
  12375. rng.selectNode(node).select();
  12376. me.fireEvent('saveScene');
  12377. }
  12378. }
  12379. })
  12380. });
  12381. me.addListener('keyup', function(type, evt) {
  12382. var keyCode = evt.keyCode || evt.which;
  12383. if (keyCode == 13) {
  12384. var rng = me.selection.getRange(),node;
  12385. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  12386. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  12387. domUtils.removeStyle(node,'text-align')
  12388. }
  12389. }
  12390. }
  12391. })
  12392. };
  12393. /**
  12394. * undo redo
  12395. * @file
  12396. * @since 1.2.6.1
  12397. */
  12398. /**
  12399. * 撤销上一次执行的命令
  12400. * @command undo
  12401. * @method execCommand
  12402. * @param { String } cmd 命令字符串
  12403. * @example
  12404. * ```javascript
  12405. * editor.execCommand( 'undo' );
  12406. * ```
  12407. */
  12408. /**
  12409. * 重做上一次执行的命令
  12410. * @command redo
  12411. * @method execCommand
  12412. * @param { String } cmd 命令字符串
  12413. * @example
  12414. * ```javascript
  12415. * editor.execCommand( 'redo' );
  12416. * ```
  12417. */
  12418. UE.plugins['undo'] = function () {
  12419. var saveSceneTimer;
  12420. var me = this,
  12421. maxUndoCount = me.options.maxUndoCount || 20,
  12422. maxInputCount = me.options.maxInputCount || 20,
  12423. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  12424. var noNeedFillCharTags = {
  12425. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  12426. };
  12427. var orgState = me.options.autoClearEmptyNode;
  12428. function compareAddr(indexA, indexB) {
  12429. if (indexA.length != indexB.length)
  12430. return 0;
  12431. for (var i = 0, l = indexA.length; i < l; i++) {
  12432. if (indexA[i] != indexB[i])
  12433. return 0
  12434. }
  12435. return 1;
  12436. }
  12437. function compareRangeAddress(rngAddrA, rngAddrB) {
  12438. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  12439. return 0;
  12440. }
  12441. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  12442. return 0;
  12443. }
  12444. return 1;
  12445. }
  12446. function UndoManager() {
  12447. this.list = [];
  12448. this.index = 0;
  12449. this.hasUndo = false;
  12450. this.hasRedo = false;
  12451. this.undo = function () {
  12452. if (this.hasUndo) {
  12453. if (!this.list[this.index - 1] && this.list.length == 1) {
  12454. this.reset();
  12455. return;
  12456. }
  12457. while (this.list[this.index].content == this.list[this.index - 1].content) {
  12458. this.index--;
  12459. if (this.index == 0) {
  12460. return this.restore(0);
  12461. }
  12462. }
  12463. this.restore(--this.index);
  12464. }
  12465. };
  12466. this.redo = function () {
  12467. if (this.hasRedo) {
  12468. while (this.list[this.index].content == this.list[this.index + 1].content) {
  12469. this.index++;
  12470. if (this.index == this.list.length - 1) {
  12471. return this.restore(this.index);
  12472. }
  12473. }
  12474. this.restore(++this.index);
  12475. }
  12476. };
  12477. this.restore = function () {
  12478. var me = this.editor;
  12479. var scene = this.list[this.index];
  12480. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  12481. me.options.autoClearEmptyNode = false;
  12482. me.filterInputRule(root);
  12483. me.options.autoClearEmptyNode = orgState;
  12484. //trace:873
  12485. //去掉展位符
  12486. me.document.body.innerHTML = root.toHtml();
  12487. me.fireEvent('afterscencerestore');
  12488. //处理undo后空格不展位的问题
  12489. if (browser.ie) {
  12490. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  12491. if(domUtils.isEmptyNode(node)){
  12492. domUtils.fillNode(me.document, node);
  12493. }
  12494. })
  12495. }
  12496. try{
  12497. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  12498. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  12499. }catch(e){}
  12500. this.update();
  12501. this.clearKey();
  12502. //不能把自己reset了
  12503. me.fireEvent('reset', true);
  12504. };
  12505. this.getScene = function () {
  12506. var me = this.editor;
  12507. var rng = me.selection.getRange(),
  12508. rngAddress = rng.createAddress(false,true);
  12509. me.fireEvent('beforegetscene');
  12510. var root = UE.htmlparser(me.body.innerHTML);
  12511. me.options.autoClearEmptyNode = false;
  12512. me.filterOutputRule(root);
  12513. me.options.autoClearEmptyNode = orgState;
  12514. var cont = root.toHtml();
  12515. //trace:3461
  12516. //这个会引起回退时导致空格丢失的情况
  12517. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  12518. me.fireEvent('aftergetscene');
  12519. return {
  12520. address:rngAddress,
  12521. content:cont
  12522. }
  12523. };
  12524. this.save = function (notCompareRange,notSetCursor) {
  12525. clearTimeout(saveSceneTimer);
  12526. var currentScene = this.getScene(notSetCursor),
  12527. lastScene = this.list[this.index];
  12528. //内容相同位置相同不存
  12529. if (lastScene && lastScene.content == currentScene.content &&
  12530. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  12531. ) {
  12532. return;
  12533. }
  12534. this.list = this.list.slice(0, this.index + 1);
  12535. this.list.push(currentScene);
  12536. //如果大于最大数量了,就把最前的剔除
  12537. if (this.list.length > maxUndoCount) {
  12538. this.list.shift();
  12539. }
  12540. this.index = this.list.length - 1;
  12541. this.clearKey();
  12542. //跟新undo/redo状态
  12543. this.update();
  12544. };
  12545. this.update = function () {
  12546. this.hasRedo = !!this.list[this.index + 1];
  12547. this.hasUndo = !!this.list[this.index - 1];
  12548. };
  12549. this.reset = function () {
  12550. this.list = [];
  12551. this.index = 0;
  12552. this.hasUndo = false;
  12553. this.hasRedo = false;
  12554. this.clearKey();
  12555. };
  12556. this.clearKey = function () {
  12557. keycont = 0;
  12558. lastKeyCode = null;
  12559. };
  12560. }
  12561. me.undoManger = new UndoManager();
  12562. me.undoManger.editor = me;
  12563. function saveScene() {
  12564. this.undoManger.save();
  12565. }
  12566. me.addListener('saveScene', function () {
  12567. var args = Array.prototype.splice.call(arguments,1);
  12568. this.undoManger.save.apply(this.undoManger,args);
  12569. });
  12570. // me.addListener('beforeexeccommand', saveScene);
  12571. // me.addListener('afterexeccommand', saveScene);
  12572. me.addListener('reset', function (type, exclude) {
  12573. if (!exclude) {
  12574. this.undoManger.reset();
  12575. }
  12576. });
  12577. me.commands['redo'] = me.commands['undo'] = {
  12578. execCommand:function (cmdName) {
  12579. this.undoManger[cmdName]();
  12580. },
  12581. queryCommandState:function (cmdName) {
  12582. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  12583. },
  12584. notNeedUndo:1
  12585. };
  12586. var keys = {
  12587. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  12588. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  12589. 37:1, 38:1, 39:1, 40:1
  12590. },
  12591. keycont = 0,
  12592. lastKeyCode;
  12593. //输入法状态下不计算字符数
  12594. var inputType = false;
  12595. me.addListener('ready', function () {
  12596. domUtils.on(this.body, 'compositionstart', function () {
  12597. inputType = true;
  12598. });
  12599. domUtils.on(this.body, 'compositionend', function () {
  12600. inputType = false;
  12601. })
  12602. });
  12603. //快捷键
  12604. me.addshortcutkey({
  12605. "Undo":"ctrl+90", //undo
  12606. "Redo":"ctrl+89" //redo
  12607. });
  12608. var isCollapsed = true;
  12609. me.addListener('keydown', function (type, evt) {
  12610. var me = this;
  12611. var keyCode = evt.keyCode || evt.which;
  12612. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  12613. if (inputType)
  12614. return;
  12615. if(!me.selection.getRange().collapsed){
  12616. me.undoManger.save(false,true);
  12617. isCollapsed = false;
  12618. return;
  12619. }
  12620. if (me.undoManger.list.length == 0) {
  12621. me.undoManger.save(true);
  12622. }
  12623. clearTimeout(saveSceneTimer);
  12624. function save(cont){
  12625. if (cont.selection.getRange().collapsed)
  12626. cont.fireEvent('contentchange');
  12627. cont.undoManger.save(false,true);
  12628. cont.fireEvent('selectionchange');
  12629. }
  12630. saveSceneTimer = setTimeout(function(){
  12631. if(inputType){
  12632. var interalTimer = setInterval(function(){
  12633. if(!inputType){
  12634. save(me);
  12635. clearInterval(interalTimer)
  12636. }
  12637. },300)
  12638. return;
  12639. }
  12640. save(me);
  12641. },200);
  12642. lastKeyCode = keyCode;
  12643. keycont++;
  12644. if (keycont >= maxInputCount ) {
  12645. save(me)
  12646. }
  12647. }
  12648. });
  12649. me.addListener('keyup', function (type, evt) {
  12650. var keyCode = evt.keyCode || evt.which;
  12651. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  12652. if (inputType)
  12653. return;
  12654. if(!isCollapsed){
  12655. this.undoManger.save(false,true);
  12656. isCollapsed = true;
  12657. }
  12658. }
  12659. });
  12660. //扩展实例,添加关闭和开启命令undo
  12661. me.stopCmdUndo = function(){
  12662. me.__hasEnterExecCommand = true;
  12663. };
  12664. me.startCmdUndo = function(){
  12665. me.__hasEnterExecCommand = false;
  12666. }
  12667. };
  12668. ///import core
  12669. ///import plugins/inserthtml.js
  12670. ///import plugins/undo.js
  12671. ///import plugins/serialize.js
  12672. ///commands 粘贴
  12673. ///commandsName PastePlain
  12674. ///commandsTitle 纯文本粘贴模式
  12675. /*
  12676. ** @description 粘贴
  12677. * @author zhanyi
  12678. */
  12679. UE.plugins['paste'] = function () {
  12680. function getClipboardData(callback) {
  12681. var doc = this.document;
  12682. if (doc.getElementById('baidu_pastebin')) {
  12683. return;
  12684. }
  12685. var range = this.selection.getRange(),
  12686. bk = range.createBookmark(),
  12687. //创建剪贴的容器div
  12688. pastebin = doc.createElement('div');
  12689. pastebin.id = 'baidu_pastebin';
  12690. // Safari 要求div必须有内容,才能粘贴内容进来
  12691. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  12692. doc.body.appendChild(pastebin);
  12693. //trace:717 隐藏的span不能得到top
  12694. //bk.start.innerHTML = '&nbsp;';
  12695. bk.start.style.display = '';
  12696. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  12697. //要在现在光标平行的位置加入,否则会出现跳动的问题
  12698. domUtils.getXY(bk.start).y + 'px';
  12699. range.selectNodeContents(pastebin).select(true);
  12700. setTimeout(function () {
  12701. if (browser.webkit) {
  12702. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  12703. if (domUtils.isEmptyNode(pi)) {
  12704. domUtils.remove(pi);
  12705. } else {
  12706. pastebin = pi;
  12707. break;
  12708. }
  12709. }
  12710. }
  12711. try {
  12712. pastebin.parentNode.removeChild(pastebin);
  12713. } catch (e) {
  12714. }
  12715. range.moveToBookmark(bk).select(true);
  12716. callback(pastebin);
  12717. }, 0);
  12718. }
  12719. var me = this;
  12720. var txtContent, htmlContent, address;
  12721. function filter(div) {
  12722. var html;
  12723. if (div.firstChild) {
  12724. //去掉cut中添加的边界值
  12725. var nodes = domUtils.getElementsByTagName(div, 'span');
  12726. for (var i = 0, ni; ni = nodes[i++];) {
  12727. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  12728. domUtils.remove(ni);
  12729. }
  12730. }
  12731. if (browser.webkit) {
  12732. var brs = div.querySelectorAll('div br');
  12733. for (var i = 0, bi; bi = brs[i++];) {
  12734. var pN = bi.parentNode;
  12735. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  12736. pN.innerHTML = '<p><br/></p>';
  12737. domUtils.remove(pN);
  12738. }
  12739. }
  12740. var divs = div.querySelectorAll('#baidu_pastebin');
  12741. for (var i = 0, di; di = divs[i++];) {
  12742. var tmpP = me.document.createElement('p');
  12743. di.parentNode.insertBefore(tmpP, di);
  12744. while (di.firstChild) {
  12745. tmpP.appendChild(di.firstChild);
  12746. }
  12747. domUtils.remove(di);
  12748. }
  12749. var metas = div.querySelectorAll('meta');
  12750. for (var i = 0, ci; ci = metas[i++];) {
  12751. domUtils.remove(ci);
  12752. }
  12753. var brs = div.querySelectorAll('br');
  12754. for (i = 0; ci = brs[i++];) {
  12755. if (/^apple-/i.test(ci.className)) {
  12756. domUtils.remove(ci);
  12757. }
  12758. }
  12759. }
  12760. if (browser.gecko) {
  12761. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  12762. for (i = 0; ci = dirtyNodes[i++];) {
  12763. ci.removeAttribute('_moz_dirty');
  12764. }
  12765. }
  12766. if (!browser.ie) {
  12767. var spans = div.querySelectorAll('span.Apple-style-span');
  12768. for (var i = 0, ci; ci = spans[i++];) {
  12769. domUtils.remove(ci, true);
  12770. }
  12771. }
  12772. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  12773. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  12774. //过滤word粘贴过来的冗余属性
  12775. html = UE.filterWord(html);
  12776. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  12777. var root = UE.htmlparser(html);
  12778. //如果给了过滤规则就先进行过滤
  12779. if (me.options.filterRules) {
  12780. UE.filterNode(root, me.options.filterRules);
  12781. }
  12782. //执行默认的处理
  12783. me.filterInputRule(root);
  12784. //针对chrome的处理
  12785. if (browser.webkit) {
  12786. var br = root.lastChild();
  12787. if (br && br.type == 'element' && br.tagName == 'br') {
  12788. root.removeChild(br)
  12789. }
  12790. utils.each(me.body.querySelectorAll('div'), function (node) {
  12791. if (domUtils.isEmptyBlock(node)) {
  12792. domUtils.remove(node,true)
  12793. }
  12794. })
  12795. }
  12796. html = {'html': root.toHtml()};
  12797. me.fireEvent('beforepaste', html, root);
  12798. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  12799. if(!html.html){
  12800. return;
  12801. }
  12802. root = UE.htmlparser(html.html,true);
  12803. //如果开启了纯文本模式
  12804. if (me.queryCommandState('pasteplain') === 1) {
  12805. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  12806. } else {
  12807. //文本模式
  12808. UE.filterNode(root, me.options.filterTxtRules);
  12809. txtContent = root.toHtml();
  12810. //完全模式
  12811. htmlContent = html.html;
  12812. address = me.selection.getRange().createAddress(true);
  12813. me.execCommand('insertHtml', htmlContent, true);
  12814. }
  12815. me.fireEvent("afterpaste", html);
  12816. }
  12817. }
  12818. me.addListener('pasteTransfer', function (cmd, plainType) {
  12819. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  12820. var range = me.selection.getRange();
  12821. range.moveToAddress(address, true);
  12822. if (!range.collapsed) {
  12823. while (!domUtils.isBody(range.startContainer)
  12824. ) {
  12825. var start = range.startContainer;
  12826. if(start.nodeType == 1){
  12827. start = start.childNodes[range.startOffset];
  12828. if(!start){
  12829. range.setStartBefore(range.startContainer);
  12830. continue;
  12831. }
  12832. var pre = start.previousSibling;
  12833. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12834. range.setStartBefore(pre)
  12835. }
  12836. }
  12837. if(range.startOffset == 0){
  12838. range.setStartBefore(range.startContainer);
  12839. }else{
  12840. break;
  12841. }
  12842. }
  12843. while (!domUtils.isBody(range.endContainer)
  12844. ) {
  12845. var end = range.endContainer;
  12846. if(end.nodeType == 1){
  12847. end = end.childNodes[range.endOffset];
  12848. if(!end){
  12849. range.setEndAfter(range.endContainer);
  12850. continue;
  12851. }
  12852. var next = end.nextSibling;
  12853. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  12854. range.setEndAfter(next)
  12855. }
  12856. }
  12857. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  12858. range.setEndAfter(range.endContainer);
  12859. }else{
  12860. break;
  12861. }
  12862. }
  12863. }
  12864. range.deleteContents();
  12865. range.select(true);
  12866. me.__hasEnterExecCommand = true;
  12867. var html = htmlContent;
  12868. if (plainType === 2) {
  12869. html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  12870. tagName = tagName.toLowerCase();
  12871. if ({img: 1}[tagName]) {
  12872. return a;
  12873. }
  12874. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  12875. if ({
  12876. 'src': 1,
  12877. 'href': 1,
  12878. 'name': 1
  12879. }[atr.toLowerCase()]) {
  12880. return atr + '=' + val + ' '
  12881. }
  12882. return ''
  12883. });
  12884. if ({
  12885. 'span': 1,
  12886. 'div': 1
  12887. }[tagName]) {
  12888. return ''
  12889. } else {
  12890. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  12891. }
  12892. });
  12893. } else if (plainType) {
  12894. html = txtContent;
  12895. }
  12896. me.execCommand('inserthtml', html, true);
  12897. me.__hasEnterExecCommand = false;
  12898. var rng = me.selection.getRange();
  12899. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  12900. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  12901. ) {
  12902. rng.setStartBefore(rng.startContainer);
  12903. }
  12904. var tmpAddress = rng.createAddress(true);
  12905. address.endAddress = tmpAddress.startAddress;
  12906. }
  12907. });
  12908. me.addListener('ready', function () {
  12909. domUtils.on(me.body, 'cut', function () {
  12910. var range = me.selection.getRange();
  12911. if (!range.collapsed && me.undoManger) {
  12912. me.undoManger.save();
  12913. }
  12914. });
  12915. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  12916. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  12917. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  12918. return;
  12919. }
  12920. getClipboardData.call(me, function (div) {
  12921. filter(div);
  12922. });
  12923. });
  12924. });
  12925. };
  12926. /**
  12927. * 有序列表,无序列表插件
  12928. * @file
  12929. * @since 1.2.6.1
  12930. */
  12931. UE.plugins['list'] = function () {
  12932. var me = this,
  12933. notExchange = {
  12934. 'TD':1,
  12935. 'PRE':1,
  12936. 'BLOCKQUOTE':1
  12937. };
  12938. var customStyle = {
  12939. 'cn' : 'cn-1-',
  12940. 'cn1' : 'cn-2-',
  12941. 'cn2' : 'cn-3-',
  12942. 'num': 'num-1-',
  12943. 'num1' : 'num-2-',
  12944. 'num2' : 'num-3-',
  12945. 'dash' : 'dash',
  12946. 'dot':'dot'
  12947. };
  12948. me.setOpt( {
  12949. 'autoTransWordToList':false,
  12950. 'insertorderedlist':{
  12951. 'num':'',
  12952. 'num1':'',
  12953. 'num2':'',
  12954. 'cn':'',
  12955. 'cn1':'',
  12956. 'cn2':'',
  12957. 'decimal':'',
  12958. 'lower-alpha':'',
  12959. 'lower-roman':'',
  12960. 'upper-alpha':'',
  12961. 'upper-roman':''
  12962. },
  12963. 'insertunorderedlist':{
  12964. 'circle':'',
  12965. 'disc':'',
  12966. 'square':'',
  12967. 'dash' : '',
  12968. 'dot':''
  12969. },
  12970. listDefaultPaddingLeft : '30',
  12971. listiconpath : 'http://bs.baidu.com/listicon/',
  12972. maxListLevel : -1//-1不限制
  12973. } );
  12974. function listToArray(list){
  12975. var arr = [];
  12976. for(var p in list){
  12977. arr.push(p)
  12978. }
  12979. return arr;
  12980. }
  12981. var listStyle = {
  12982. 'OL':listToArray(me.options.insertorderedlist),
  12983. 'UL':listToArray(me.options.insertunorderedlist)
  12984. };
  12985. var liiconpath = me.options.listiconpath;
  12986. //根据用户配置,调整customStyle
  12987. for(var s in customStyle){
  12988. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  12989. delete customStyle[s];
  12990. }
  12991. }
  12992. me.ready(function () {
  12993. var customCss = [];
  12994. for(var p in customStyle){
  12995. if(p == 'dash' || p == 'dot'){
  12996. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  12997. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  12998. }else{
  12999. for(var i= 0;i<99;i++){
  13000. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  13001. }
  13002. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13003. }
  13004. switch(p){
  13005. case 'cn':
  13006. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  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 'cn1':
  13011. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13012. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13013. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13014. break;
  13015. case 'cn2':
  13016. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13017. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13018. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13019. break;
  13020. case 'num':
  13021. case 'num1':
  13022. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13023. break;
  13024. case 'num2':
  13025. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13026. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13027. break;
  13028. case 'dash':
  13029. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13030. break;
  13031. case 'dot':
  13032. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13033. }
  13034. }
  13035. customCss.push('.list-paddingleft-1{padding-left:0}');
  13036. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13037. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13038. //如果不给宽度会在自定应样式里出现滚动条
  13039. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13040. });
  13041. //单独处理剪切的问题
  13042. me.ready(function(){
  13043. domUtils.on(me.body,'cut',function(){
  13044. setTimeout(function(){
  13045. var rng = me.selection.getRange(),li;
  13046. //trace:3416
  13047. if(!rng.collapsed){
  13048. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13049. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13050. var pn = li.parentNode,node;
  13051. if(node = pn.previousSibling){
  13052. domUtils.remove(pn);
  13053. rng.setStartAtLast(node).collapse(true);
  13054. rng.select(true);
  13055. }else if(node = pn.nextSibling){
  13056. domUtils.remove(pn);
  13057. rng.setStartAtFirst(node).collapse(true);
  13058. rng.select(true);
  13059. }else{
  13060. var tmpNode = me.document.createElement('p');
  13061. domUtils.fillNode(me.document,tmpNode);
  13062. pn.parentNode.insertBefore(tmpNode,pn);
  13063. domUtils.remove(pn);
  13064. rng.setStart(tmpNode,0).collapse(true);
  13065. rng.select(true);
  13066. }
  13067. }
  13068. }
  13069. }
  13070. })
  13071. })
  13072. });
  13073. function getStyle(node){
  13074. var cls = node.className;
  13075. if(domUtils.hasClass(node,/custom_/)){
  13076. return cls.match(/custom_(\w+)/)[1]
  13077. }
  13078. return domUtils.getStyle(node, 'list-style-type')
  13079. }
  13080. me.addListener('beforepaste',function(type,html){
  13081. var me = this,
  13082. rng = me.selection.getRange(),li;
  13083. var root = UE.htmlparser(html.html,true);
  13084. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13085. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13086. utils.each(root.getNodesByTagName(tagName),function(n){
  13087. n.tagName = list.tagName;
  13088. n.setAttr();
  13089. if(n.parentNode === root){
  13090. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13091. }else{
  13092. var className = n.parentNode.getAttr('class');
  13093. if(className && /custom_/.test(className)){
  13094. type = className.match(/custom_(\w+)/)[1]
  13095. }else{
  13096. type = n.parentNode.getStyle('list-style-type');
  13097. }
  13098. if(!type){
  13099. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13100. }
  13101. }
  13102. var index = utils.indexOf(listStyle[list.tagName], type);
  13103. if(n.parentNode !== root)
  13104. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13105. var currentStyle = listStyle[list.tagName][index];
  13106. if(customStyle[currentStyle]){
  13107. n.setAttr('class', 'custom_' + currentStyle)
  13108. }else{
  13109. n.setStyle('list-style-type',currentStyle)
  13110. }
  13111. })
  13112. }
  13113. html.html = root.toHtml();
  13114. });
  13115. //进入编辑器的li要套p标签
  13116. me.addInputRule(function(root){
  13117. utils.each(root.getNodesByTagName('li'),function(li){
  13118. var tmpP = UE.uNode.createElement('p');
  13119. for(var i= 0,ci;ci=li.children[i];){
  13120. if(ci.type == 'text' || dtd.p[ci.tagName]){
  13121. tmpP.appendChild(ci);
  13122. }else{
  13123. if(tmpP.firstChild()){
  13124. li.insertBefore(tmpP,ci);
  13125. tmpP = UE.uNode.createElement('p');
  13126. i = i + 2;
  13127. }else{
  13128. i++;
  13129. }
  13130. }
  13131. }
  13132. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  13133. li.appendChild(tmpP);
  13134. }
  13135. //trace:3357
  13136. //p不能为空
  13137. if (!tmpP.firstChild()) {
  13138. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  13139. }
  13140. //去掉末尾的空白
  13141. var p = li.firstChild();
  13142. var lastChild = p.lastChild();
  13143. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  13144. p.removeChild(lastChild)
  13145. }
  13146. });
  13147. if(me.options.autoTransWordToList){
  13148. var orderlisttype = {
  13149. 'num1':/^\d+\)/,
  13150. 'decimal':/^\d+\./,
  13151. 'lower-alpha':/^[a-z]+\)/,
  13152. 'upper-alpha':/^[A-Z]+\./,
  13153. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  13154. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  13155. },
  13156. unorderlisttype = {
  13157. 'square':'n'
  13158. };
  13159. function checkListType(content,container){
  13160. var span = container.firstChild();
  13161. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  13162. for(var p in unorderlisttype){
  13163. if(unorderlisttype[p] == span.data){
  13164. return p
  13165. }
  13166. }
  13167. return 'disc'
  13168. }
  13169. for(var p in orderlisttype){
  13170. if(orderlisttype[p].test(content)){
  13171. return p;
  13172. }
  13173. }
  13174. }
  13175. utils.each(root.getNodesByTagName('p'),function(node){
  13176. if(node.getAttr('class') != 'MsoListParagraph'){
  13177. return
  13178. }
  13179. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  13180. node.setStyle('margin','');
  13181. node.setStyle('margin-left','');
  13182. node.setAttr('class','');
  13183. function appendLi(list,p,type){
  13184. if(list.tagName == 'ol'){
  13185. if(browser.ie){
  13186. var first = p.firstChild();
  13187. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  13188. p.removeChild(first);
  13189. }
  13190. }else{
  13191. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  13192. }
  13193. }else{
  13194. p.removeChild(p.firstChild())
  13195. }
  13196. var li = UE.uNode.createElement('li');
  13197. li.appendChild(p);
  13198. list.appendChild(li);
  13199. }
  13200. var tmp = node,type,cacheNode = node;
  13201. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  13202. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  13203. if(customStyle[type]){
  13204. list.setAttr('class','custom_'+type)
  13205. }else{
  13206. list.setStyle('list-style-type',type)
  13207. }
  13208. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  13209. tmp = node.nextSibling();
  13210. if(!tmp){
  13211. node.parentNode.insertBefore(list,node)
  13212. }
  13213. appendLi(list,node,type);
  13214. node = tmp;
  13215. }
  13216. if(!list.parentNode && node && node.parentNode){
  13217. node.parentNode.insertBefore(list,node)
  13218. }
  13219. }
  13220. var span = cacheNode.firstChild();
  13221. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  13222. span.parentNode.removeChild(span)
  13223. }
  13224. })
  13225. }
  13226. });
  13227. //调整索引标签
  13228. me.addListener('contentchange',function(){
  13229. adjustListStyle(me.document)
  13230. });
  13231. function adjustListStyle(doc,ignore){
  13232. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  13233. if(!domUtils.inDoc(node,doc))
  13234. return;
  13235. var parent = node.parentNode;
  13236. if(parent.tagName == node.tagName){
  13237. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  13238. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  13239. if(nodeStyleType == parentStyleType){
  13240. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  13241. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  13242. setListStyle(node,listStyle[node.tagName][styleIndex])
  13243. }
  13244. }
  13245. var index = 0,type = 2;
  13246. if( domUtils.hasClass(node,/custom_/)){
  13247. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  13248. type = 1;
  13249. }
  13250. }else{
  13251. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  13252. type = 3;
  13253. }
  13254. }
  13255. var style = domUtils.getStyle(node, 'list-style-type');
  13256. style && (node.style.cssText = 'list-style-type:' + style);
  13257. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  13258. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  13259. li.style.cssText && (li.style.cssText = '');
  13260. if(!li.firstChild){
  13261. domUtils.remove(li);
  13262. return;
  13263. }
  13264. if(li.parentNode !== node){
  13265. return;
  13266. }
  13267. index++;
  13268. if(domUtils.hasClass(node,/custom_/) ){
  13269. var paddingLeft = 1,currentStyle = getStyle(node);
  13270. if(node.tagName == 'OL'){
  13271. if(currentStyle){
  13272. switch(currentStyle){
  13273. case 'cn' :
  13274. case 'cn1':
  13275. case 'cn2':
  13276. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  13277. paddingLeft = 2
  13278. }else if(index > 20){
  13279. paddingLeft = 3
  13280. }
  13281. break;
  13282. case 'num2' :
  13283. if(index > 9){
  13284. paddingLeft = 2
  13285. }
  13286. }
  13287. }
  13288. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  13289. }else{
  13290. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  13291. }
  13292. }else{
  13293. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  13294. }
  13295. var className = li.getAttribute('class');
  13296. if(className !== null && !className.replace(/\s/g,'')){
  13297. domUtils.removeAttributes(li,'class')
  13298. }
  13299. });
  13300. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  13301. })
  13302. }
  13303. function adjustList(list, tag, style,ignoreEmpty) {
  13304. var nextList = list.nextSibling;
  13305. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  13306. domUtils.moveChild(nextList, list);
  13307. if (nextList.childNodes.length == 0) {
  13308. domUtils.remove(nextList);
  13309. }
  13310. }
  13311. if(nextList && domUtils.isFillChar(nextList)){
  13312. domUtils.remove(nextList);
  13313. }
  13314. var preList = list.previousSibling;
  13315. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  13316. domUtils.moveChild(list, preList);
  13317. }
  13318. if(preList && domUtils.isFillChar(preList)){
  13319. domUtils.remove(preList);
  13320. }
  13321. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  13322. if(getStyle(list)){
  13323. adjustListStyle(list.ownerDocument,true)
  13324. }
  13325. }
  13326. function setListStyle(list,style){
  13327. if(customStyle[style]){
  13328. list.className = 'custom_' + style;
  13329. }
  13330. try{
  13331. domUtils.setStyle(list, 'list-style-type', style);
  13332. }catch(e){}
  13333. }
  13334. function clearEmptySibling(node) {
  13335. var tmpNode = node.previousSibling;
  13336. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  13337. domUtils.remove(tmpNode);
  13338. }
  13339. tmpNode = node.nextSibling;
  13340. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  13341. domUtils.remove(tmpNode);
  13342. }
  13343. }
  13344. me.addListener('keydown', function (type, evt) {
  13345. function preventAndSave() {
  13346. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  13347. me.fireEvent('contentchange');
  13348. me.undoManger && me.undoManger.save();
  13349. }
  13350. function findList(node,filterFn){
  13351. while(node && !domUtils.isBody(node)){
  13352. if(filterFn(node)){
  13353. return null
  13354. }
  13355. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  13356. return node;
  13357. }
  13358. node = node.parentNode;
  13359. }
  13360. return null;
  13361. }
  13362. var keyCode = evt.keyCode || evt.which;
  13363. if (keyCode == 13 && !evt.shiftKey) {//回车
  13364. var rng = me.selection.getRange(),
  13365. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  13366. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  13367. if(parent && parent.tagName != 'PRE' && !li){
  13368. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  13369. if(/^\s*1\s*\.[^\d]/.test(html)){
  13370. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  13371. rng.setStartAtLast(parent).collapse(true).select();
  13372. me.__hasEnterExecCommand = true;
  13373. me.execCommand('insertorderedlist');
  13374. me.__hasEnterExecCommand = false;
  13375. }
  13376. }
  13377. var range = me.selection.getRange(),
  13378. start = findList(range.startContainer,function (node) {
  13379. return node.tagName == 'TABLE';
  13380. }),
  13381. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  13382. return node.tagName == 'TABLE';
  13383. });
  13384. if (start && end && start === end) {
  13385. if (!range.collapsed) {
  13386. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13387. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  13388. if (start && end && start === end) {
  13389. range.deleteContents();
  13390. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13391. if (li && domUtils.isEmptyBlock(li)) {
  13392. pre = li.previousSibling;
  13393. next = li.nextSibling;
  13394. p = me.document.createElement('p');
  13395. domUtils.fillNode(me.document, p);
  13396. parentList = li.parentNode;
  13397. if (pre && next) {
  13398. range.setStart(next, 0).collapse(true).select(true);
  13399. domUtils.remove(li);
  13400. } else {
  13401. if (!pre && !next || !pre) {
  13402. parentList.parentNode.insertBefore(p, parentList);
  13403. } else {
  13404. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  13405. }
  13406. domUtils.remove(li);
  13407. if (!parentList.firstChild) {
  13408. domUtils.remove(parentList);
  13409. }
  13410. range.setStart(p, 0).setCursor();
  13411. }
  13412. preventAndSave();
  13413. return;
  13414. }
  13415. } else {
  13416. var tmpRange = range.cloneRange(),
  13417. bk = tmpRange.collapse(false).createBookmark();
  13418. range.deleteContents();
  13419. tmpRange.moveToBookmark(bk);
  13420. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  13421. clearEmptySibling(li);
  13422. tmpRange.select();
  13423. preventAndSave();
  13424. return;
  13425. }
  13426. }
  13427. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13428. if (li) {
  13429. if (domUtils.isEmptyBlock(li)) {
  13430. bk = range.createBookmark();
  13431. var parentList = li.parentNode;
  13432. if (li !== parentList.lastChild) {
  13433. domUtils.breakParent(li, parentList);
  13434. clearEmptySibling(li);
  13435. } else {
  13436. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  13437. if (domUtils.isEmptyNode(parentList)) {
  13438. domUtils.remove(parentList);
  13439. }
  13440. }
  13441. //嵌套不处理
  13442. if (!dtd.$list[li.parentNode.tagName]) {
  13443. if (!domUtils.isBlockElm(li.firstChild)) {
  13444. p = me.document.createElement('p');
  13445. li.parentNode.insertBefore(p, li);
  13446. while (li.firstChild) {
  13447. p.appendChild(li.firstChild);
  13448. }
  13449. domUtils.remove(li);
  13450. } else {
  13451. domUtils.remove(li, true);
  13452. }
  13453. }
  13454. range.moveToBookmark(bk).select();
  13455. } else {
  13456. var first = li.firstChild;
  13457. if (!first || !domUtils.isBlockElm(first)) {
  13458. var p = me.document.createElement('p');
  13459. !li.firstChild && domUtils.fillNode(me.document, p);
  13460. while (li.firstChild) {
  13461. p.appendChild(li.firstChild);
  13462. }
  13463. li.appendChild(p);
  13464. first = p;
  13465. }
  13466. var span = me.document.createElement('span');
  13467. range.insertNode(span);
  13468. domUtils.breakParent(span, li);
  13469. var nextLi = span.nextSibling;
  13470. first = nextLi.firstChild;
  13471. if (!first) {
  13472. p = me.document.createElement('p');
  13473. domUtils.fillNode(me.document, p);
  13474. nextLi.appendChild(p);
  13475. first = p;
  13476. }
  13477. if (domUtils.isEmptyNode(first)) {
  13478. first.innerHTML = '';
  13479. domUtils.fillNode(me.document, first);
  13480. }
  13481. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  13482. domUtils.remove(span);
  13483. var pre = nextLi.previousSibling;
  13484. if (pre && domUtils.isEmptyBlock(pre)) {
  13485. pre.innerHTML = '<p></p>';
  13486. domUtils.fillNode(me.document, pre.firstChild);
  13487. }
  13488. }
  13489. // }
  13490. preventAndSave();
  13491. }
  13492. }
  13493. }
  13494. if (keyCode == 8) {
  13495. //修中ie中li下的问题
  13496. range = me.selection.getRange();
  13497. if (range.collapsed && domUtils.isStartInblock(range)) {
  13498. tmpRange = range.cloneRange().trimBoundary();
  13499. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13500. //要在li的最左边,才能处理
  13501. if (li && domUtils.isStartInblock(tmpRange)) {
  13502. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  13503. if (start && start !== li.firstChild) {
  13504. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  13505. domUtils.breakParent(start,parentList);
  13506. clearEmptySibling(start);
  13507. me.fireEvent('contentchange');
  13508. range.setStart(start,0).setCursor(false,true);
  13509. me.fireEvent('saveScene');
  13510. domUtils.preventDefault(evt);
  13511. return;
  13512. }
  13513. if (li && (pre = li.previousSibling)) {
  13514. if (keyCode == 46 && li.childNodes.length) {
  13515. return;
  13516. }
  13517. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  13518. if (dtd.$list[pre.tagName]) {
  13519. pre = pre.lastChild;
  13520. }
  13521. me.undoManger && me.undoManger.save();
  13522. first = li.firstChild;
  13523. if (domUtils.isBlockElm(first)) {
  13524. if (domUtils.isEmptyNode(first)) {
  13525. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  13526. pre.appendChild(first);
  13527. range.setStart(first, 0).setCursor(false, true);
  13528. //first不是唯一的节点
  13529. while (li.firstChild) {
  13530. pre.appendChild(li.firstChild);
  13531. }
  13532. } else {
  13533. span = me.document.createElement('span');
  13534. range.insertNode(span);
  13535. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  13536. if (domUtils.isEmptyBlock(pre)) {
  13537. pre.innerHTML = '';
  13538. }
  13539. domUtils.moveChild(li, pre);
  13540. range.setStartBefore(span).collapse(true).select(true);
  13541. domUtils.remove(span);
  13542. }
  13543. } else {
  13544. if (domUtils.isEmptyNode(li)) {
  13545. var p = me.document.createElement('p');
  13546. pre.appendChild(p);
  13547. range.setStart(p, 0).setCursor();
  13548. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  13549. } else {
  13550. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  13551. while (li.firstChild) {
  13552. pre.appendChild(li.firstChild);
  13553. }
  13554. }
  13555. }
  13556. domUtils.remove(li);
  13557. me.fireEvent('contentchange');
  13558. me.fireEvent('saveScene');
  13559. domUtils.preventDefault(evt);
  13560. return;
  13561. }
  13562. //trace:980
  13563. if (li && !li.previousSibling) {
  13564. var parentList = li.parentNode;
  13565. var bk = range.createBookmark();
  13566. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  13567. parentList.parentNode.insertBefore(li,parentList);
  13568. if(domUtils.isEmptyNode(parentList)){
  13569. domUtils.remove(parentList)
  13570. }
  13571. }else{
  13572. while(li.firstChild){
  13573. parentList.parentNode.insertBefore(li.firstChild,parentList);
  13574. }
  13575. domUtils.remove(li);
  13576. if(domUtils.isEmptyNode(parentList)){
  13577. domUtils.remove(parentList)
  13578. }
  13579. }
  13580. range.moveToBookmark(bk).setCursor(false,true);
  13581. me.fireEvent('contentchange');
  13582. me.fireEvent('saveScene');
  13583. domUtils.preventDefault(evt);
  13584. return;
  13585. }
  13586. }
  13587. }
  13588. }
  13589. });
  13590. me.addListener('keyup',function(type, evt){
  13591. var keyCode = evt.keyCode || evt.which;
  13592. if (keyCode == 8) {
  13593. var rng = me.selection.getRange(),list;
  13594. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  13595. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  13596. }
  13597. }
  13598. });
  13599. //处理tab键
  13600. me.addListener('tabkeydown',function(){
  13601. var range = me.selection.getRange();
  13602. //控制级数
  13603. function checkLevel(li){
  13604. if(me.options.maxListLevel != -1){
  13605. var level = li.parentNode,levelNum = 0;
  13606. while(/[ou]l/i.test(level.tagName)){
  13607. levelNum++;
  13608. level = level.parentNode;
  13609. }
  13610. if(levelNum >= me.options.maxListLevel){
  13611. return true;
  13612. }
  13613. }
  13614. }
  13615. //只以开始为准
  13616. //todo 后续改进
  13617. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  13618. if(li){
  13619. var bk;
  13620. if(range.collapsed){
  13621. if(checkLevel(li))
  13622. return true;
  13623. var parentLi = li.parentNode,
  13624. list = me.document.createElement(parentLi.tagName),
  13625. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  13626. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13627. var currentStyle = listStyle[list.tagName][index];
  13628. setListStyle(list,currentStyle);
  13629. if(domUtils.isStartInblock(range)){
  13630. me.fireEvent('saveScene');
  13631. bk = range.createBookmark();
  13632. parentLi.insertBefore(list, li);
  13633. list.appendChild(li);
  13634. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  13635. me.fireEvent('contentchange');
  13636. range.moveToBookmark(bk).select(true);
  13637. return true;
  13638. }
  13639. }else{
  13640. me.fireEvent('saveScene');
  13641. bk = range.createBookmark();
  13642. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  13643. if(domUtils.isTagNode(ci,'ol ul')){
  13644. closeList = ci;
  13645. break;
  13646. }
  13647. }
  13648. var current = li;
  13649. if(bk.end){
  13650. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  13651. if(checkLevel(current)){
  13652. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  13653. continue;
  13654. }
  13655. var parentLi = current.parentNode,
  13656. list = me.document.createElement(parentLi.tagName),
  13657. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  13658. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13659. var currentStyle = listStyle[list.tagName][currentIndex];
  13660. setListStyle(list,currentStyle);
  13661. parentLi.insertBefore(list, current);
  13662. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  13663. li = current.nextSibling;
  13664. list.appendChild(current);
  13665. if(!li || domUtils.isTagNode(li,'ol ul')){
  13666. if(li){
  13667. while(li = li.firstChild){
  13668. if(li.tagName == 'LI'){
  13669. break;
  13670. }
  13671. }
  13672. }else{
  13673. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  13674. }
  13675. break;
  13676. }
  13677. current = li;
  13678. }
  13679. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  13680. current = li;
  13681. }
  13682. }
  13683. me.fireEvent('contentchange');
  13684. range.moveToBookmark(bk).select();
  13685. return true;
  13686. }
  13687. }
  13688. });
  13689. function getLi(start){
  13690. while(start && !domUtils.isBody(start)){
  13691. if(start.nodeName == 'TABLE'){
  13692. return null;
  13693. }
  13694. if(start.nodeName == 'LI'){
  13695. return start
  13696. }
  13697. start = start.parentNode;
  13698. }
  13699. }
  13700. /**
  13701. * 有序列表,与“insertunorderedlist”命令互斥
  13702. * @command insertorderedlist
  13703. * @method execCommand
  13704. * @param { String } command 命令字符串
  13705. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  13706. * @example
  13707. * ```javascript
  13708. * editor.execCommand( 'insertunorderedlist','decimal');
  13709. * ```
  13710. */
  13711. /**
  13712. * 查询当前选区内容是否有序列表
  13713. * @command insertorderedlist
  13714. * @method queryCommandState
  13715. * @param { String } cmd 命令字符串
  13716. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  13717. * @example
  13718. * ```javascript
  13719. * editor.queryCommandState( 'insertorderedlist' );
  13720. * ```
  13721. */
  13722. /**
  13723. * 查询当前选区内容是否有序列表
  13724. * @command insertorderedlist
  13725. * @method queryCommandValue
  13726. * @param { String } cmd 命令字符串
  13727. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  13728. * @example
  13729. * ```javascript
  13730. * editor.queryCommandValue( 'insertorderedlist' );
  13731. * ```
  13732. */
  13733. /**
  13734. * 无序列表,与“insertorderedlist”命令互斥
  13735. * @command insertunorderedlist
  13736. * @method execCommand
  13737. * @param { String } command 命令字符串
  13738. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  13739. * @example
  13740. * ```javascript
  13741. * editor.execCommand( 'insertunorderedlist','circle');
  13742. * ```
  13743. */
  13744. /**
  13745. * 查询当前是否有word文档粘贴进来的图片
  13746. * @command insertunorderedlist
  13747. * @method insertunorderedlist
  13748. * @param { String } command 命令字符串
  13749. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  13750. * @example
  13751. * ```javascript
  13752. * editor.queryCommandState( 'insertunorderedlist' );
  13753. * ```
  13754. */
  13755. /**
  13756. * 查询当前选区内容是否有序列表
  13757. * @command insertunorderedlist
  13758. * @method queryCommandValue
  13759. * @param { String } command 命令字符串
  13760. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  13761. * @example
  13762. * ```javascript
  13763. * editor.queryCommandValue( 'insertunorderedlist' );
  13764. * ```
  13765. */
  13766. me.commands['insertorderedlist'] =
  13767. me.commands['insertunorderedlist'] = {
  13768. execCommand:function (command, style) {
  13769. if (!style) {
  13770. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  13771. }
  13772. var me = this,
  13773. range = this.selection.getRange(),
  13774. filterFn = function (node) {
  13775. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  13776. },
  13777. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  13778. frag = me.document.createDocumentFragment();
  13779. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  13780. //range.shrinkBoundary();//.adjustmentBoundary();
  13781. range.adjustmentBoundary().shrinkBoundary();
  13782. var bko = range.createBookmark(true),
  13783. start = getLi(me.document.getElementById(bko.start)),
  13784. modifyStart = 0,
  13785. end = getLi(me.document.getElementById(bko.end)),
  13786. modifyEnd = 0,
  13787. startParent, endParent,
  13788. list, tmp;
  13789. if (start || end) {
  13790. start && (startParent = start.parentNode);
  13791. if (!bko.end) {
  13792. end = start;
  13793. }
  13794. end && (endParent = end.parentNode);
  13795. if (startParent === endParent) {
  13796. while (start !== end) {
  13797. tmp = start;
  13798. start = start.nextSibling;
  13799. if (!domUtils.isBlockElm(tmp.firstChild)) {
  13800. var p = me.document.createElement('p');
  13801. while (tmp.firstChild) {
  13802. p.appendChild(tmp.firstChild);
  13803. }
  13804. tmp.appendChild(p);
  13805. }
  13806. frag.appendChild(tmp);
  13807. }
  13808. tmp = me.document.createElement('span');
  13809. startParent.insertBefore(tmp, end);
  13810. if (!domUtils.isBlockElm(end.firstChild)) {
  13811. p = me.document.createElement('p');
  13812. while (end.firstChild) {
  13813. p.appendChild(end.firstChild);
  13814. }
  13815. end.appendChild(p);
  13816. }
  13817. frag.appendChild(end);
  13818. domUtils.breakParent(tmp, startParent);
  13819. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  13820. domUtils.remove(tmp.previousSibling);
  13821. }
  13822. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  13823. domUtils.remove(tmp.nextSibling)
  13824. }
  13825. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  13826. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  13827. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  13828. if(domUtils.isTagNode(ci,'ol ul')){
  13829. // 删除时,子列表不处理
  13830. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  13831. // while(li.firstChild){
  13832. // tmpFrag.appendChild(li.firstChild);
  13833. // }
  13834. //
  13835. // });
  13836. tmpFrag.appendChild(ci);
  13837. }else{
  13838. while (ci.firstChild) {
  13839. tmpFrag.appendChild(ci.firstChild);
  13840. domUtils.remove(ci);
  13841. }
  13842. }
  13843. }
  13844. tmp.parentNode.insertBefore(tmpFrag, tmp);
  13845. } else {
  13846. list = me.document.createElement(tag);
  13847. setListStyle(list,style);
  13848. list.appendChild(frag);
  13849. tmp.parentNode.insertBefore(list, tmp);
  13850. }
  13851. domUtils.remove(tmp);
  13852. list && adjustList(list, tag, style);
  13853. range.moveToBookmark(bko).select();
  13854. return;
  13855. }
  13856. //开始
  13857. if (start) {
  13858. while (start) {
  13859. tmp = start.nextSibling;
  13860. if (domUtils.isTagNode(start, 'ol ul')) {
  13861. frag.appendChild(start);
  13862. } else {
  13863. var tmpfrag = me.document.createDocumentFragment(),
  13864. hasBlock = 0;
  13865. while (start.firstChild) {
  13866. if (domUtils.isBlockElm(start.firstChild)) {
  13867. hasBlock = 1;
  13868. }
  13869. tmpfrag.appendChild(start.firstChild);
  13870. }
  13871. if (!hasBlock) {
  13872. var tmpP = me.document.createElement('p');
  13873. tmpP.appendChild(tmpfrag);
  13874. frag.appendChild(tmpP);
  13875. } else {
  13876. frag.appendChild(tmpfrag);
  13877. }
  13878. domUtils.remove(start);
  13879. }
  13880. start = tmp;
  13881. }
  13882. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  13883. if (domUtils.isEmptyNode(startParent)) {
  13884. range.setStartBefore(startParent);
  13885. domUtils.remove(startParent);
  13886. } else {
  13887. range.setStartAfter(startParent);
  13888. }
  13889. modifyStart = 1;
  13890. }
  13891. if (end && domUtils.inDoc(endParent, me.document)) {
  13892. //结束
  13893. start = endParent.firstChild;
  13894. while (start && start !== end) {
  13895. tmp = start.nextSibling;
  13896. if (domUtils.isTagNode(start, 'ol ul')) {
  13897. frag.appendChild(start);
  13898. } else {
  13899. tmpfrag = me.document.createDocumentFragment();
  13900. hasBlock = 0;
  13901. while (start.firstChild) {
  13902. if (domUtils.isBlockElm(start.firstChild)) {
  13903. hasBlock = 1;
  13904. }
  13905. tmpfrag.appendChild(start.firstChild);
  13906. }
  13907. if (!hasBlock) {
  13908. tmpP = me.document.createElement('p');
  13909. tmpP.appendChild(tmpfrag);
  13910. frag.appendChild(tmpP);
  13911. } else {
  13912. frag.appendChild(tmpfrag);
  13913. }
  13914. domUtils.remove(start);
  13915. }
  13916. start = tmp;
  13917. }
  13918. var tmpDiv = domUtils.createElement(me.document, 'div', {
  13919. 'tmpDiv':1
  13920. });
  13921. domUtils.moveChild(end, tmpDiv);
  13922. frag.appendChild(tmpDiv);
  13923. domUtils.remove(end);
  13924. endParent.parentNode.insertBefore(frag, endParent);
  13925. range.setEndBefore(endParent);
  13926. if (domUtils.isEmptyNode(endParent)) {
  13927. domUtils.remove(endParent);
  13928. }
  13929. modifyEnd = 1;
  13930. }
  13931. }
  13932. if (!modifyStart) {
  13933. range.setStartBefore(me.document.getElementById(bko.start));
  13934. }
  13935. if (bko.end && !modifyEnd) {
  13936. range.setEndAfter(me.document.getElementById(bko.end));
  13937. }
  13938. range.enlarge(true, function (node) {
  13939. return notExchange[node.tagName];
  13940. });
  13941. frag = me.document.createDocumentFragment();
  13942. var bk = range.createBookmark(),
  13943. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  13944. tmpRange = range.cloneRange(),
  13945. tmpNode,
  13946. block = domUtils.isBlockElm;
  13947. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  13948. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  13949. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  13950. while (current.firstChild) {
  13951. frag.appendChild(current.firstChild);
  13952. }
  13953. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  13954. domUtils.remove(current);
  13955. current = tmpNode;
  13956. continue;
  13957. }
  13958. tmpNode = current;
  13959. tmpRange.setStartBefore(current);
  13960. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  13961. tmpNode = current;
  13962. current = domUtils.getNextDomNode(current, false, null, function (node) {
  13963. return !notExchange[node.tagName];
  13964. });
  13965. }
  13966. if (current && block(current)) {
  13967. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  13968. if (tmp && domUtils.isBookmarkNode(tmp)) {
  13969. current = domUtils.getNextDomNode(tmp, false, filterFn);
  13970. tmpNode = tmp;
  13971. }
  13972. }
  13973. tmpRange.setEndAfter(tmpNode);
  13974. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  13975. var li = range.document.createElement('li');
  13976. li.appendChild(tmpRange.extractContents());
  13977. if(domUtils.isEmptyNode(li)){
  13978. var tmpNode = range.document.createElement('p');
  13979. while(li.firstChild){
  13980. tmpNode.appendChild(li.firstChild)
  13981. }
  13982. li.appendChild(tmpNode);
  13983. }
  13984. frag.appendChild(li);
  13985. } else {
  13986. current = domUtils.getNextDomNode(current, true, filterFn);
  13987. }
  13988. }
  13989. range.moveToBookmark(bk).collapse(true);
  13990. list = me.document.createElement(tag);
  13991. setListStyle(list,style);
  13992. list.appendChild(frag);
  13993. range.insertNode(list);
  13994. //当前list上下看能否合并
  13995. adjustList(list, tag, style);
  13996. //去掉冗余的tmpDiv
  13997. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  13998. if (ci.getAttribute('tmpDiv')) {
  13999. domUtils.remove(ci, true)
  14000. }
  14001. }
  14002. range.moveToBookmark(bko).select();
  14003. },
  14004. queryCommandState:function (command) {
  14005. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14006. var path = this.selection.getStartElementPath();
  14007. for(var i= 0,ci;ci = path[i++];){
  14008. if(ci.nodeName == 'TABLE'){
  14009. return 0
  14010. }
  14011. if(tag == ci.nodeName.toLowerCase()){
  14012. return 1
  14013. };
  14014. }
  14015. return 0;
  14016. },
  14017. queryCommandValue:function (command) {
  14018. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14019. var path = this.selection.getStartElementPath(),
  14020. node;
  14021. for(var i= 0,ci;ci = path[i++];){
  14022. if(ci.nodeName == 'TABLE'){
  14023. node = null;
  14024. break;
  14025. }
  14026. if(tag == ci.nodeName.toLowerCase()){
  14027. node = ci;
  14028. break;
  14029. };
  14030. }
  14031. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14032. }
  14033. };
  14034. };
  14035. /**
  14036. * 源码编辑插件
  14037. * @file
  14038. * @since 1.2.6.1
  14039. */
  14040. (function (){
  14041. var sourceEditors = {
  14042. textarea: function (editor, holder){
  14043. var textarea = holder.ownerDocument.createElement('textarea');
  14044. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14045. // todo: IE下只有onresize属性可用... 很纠结
  14046. if (browser.ie && browser.version < 8) {
  14047. textarea.style.width = holder.offsetWidth + 'px';
  14048. textarea.style.height = holder.offsetHeight + 'px';
  14049. holder.onresize = function (){
  14050. textarea.style.width = holder.offsetWidth + 'px';
  14051. textarea.style.height = holder.offsetHeight + 'px';
  14052. };
  14053. }
  14054. holder.appendChild(textarea);
  14055. return {
  14056. setContent: function (content){
  14057. textarea.value = content;
  14058. },
  14059. getContent: function (){
  14060. return textarea.value;
  14061. },
  14062. select: function (){
  14063. var range;
  14064. if (browser.ie) {
  14065. range = textarea.createTextRange();
  14066. range.collapse(true);
  14067. range.select();
  14068. } else {
  14069. //todo: chrome下无法设置焦点
  14070. textarea.setSelectionRange(0, 0);
  14071. textarea.focus();
  14072. }
  14073. },
  14074. dispose: function (){
  14075. holder.removeChild(textarea);
  14076. // todo
  14077. holder.onresize = null;
  14078. textarea = null;
  14079. holder = null;
  14080. }
  14081. };
  14082. },
  14083. codemirror: function (editor, holder){
  14084. var codeEditor = window.CodeMirror(holder, {
  14085. mode: "text/html",
  14086. tabMode: "indent",
  14087. lineNumbers: true,
  14088. lineWrapping:true
  14089. });
  14090. var dom = codeEditor.getWrapperElement();
  14091. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  14092. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  14093. codeEditor.refresh();
  14094. return {
  14095. getCodeMirror:function(){
  14096. return codeEditor;
  14097. },
  14098. setContent: function (content){
  14099. codeEditor.setValue(content);
  14100. },
  14101. getContent: function (){
  14102. return codeEditor.getValue();
  14103. },
  14104. select: function (){
  14105. codeEditor.focus();
  14106. },
  14107. dispose: function (){
  14108. holder.removeChild(dom);
  14109. dom = null;
  14110. codeEditor = null;
  14111. }
  14112. };
  14113. }
  14114. };
  14115. UE.plugins['source'] = function (){
  14116. var me = this;
  14117. var opt = this.options;
  14118. var sourceMode = false;
  14119. var sourceEditor;
  14120. var orgSetContent;
  14121. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  14122. me.setOpt({
  14123. sourceEditorFirst:false
  14124. });
  14125. function createSourceEditor(holder){
  14126. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  14127. }
  14128. var bakCssText;
  14129. //解决在源码模式下getContent不能得到最新的内容问题
  14130. var oldGetContent,
  14131. bakAddress;
  14132. /**
  14133. * 切换源码模式和编辑模式
  14134. * @command source
  14135. * @method execCommand
  14136. * @param { String } cmd 命令字符串
  14137. * @example
  14138. * ```javascript
  14139. * editor.execCommand( 'source');
  14140. * ```
  14141. */
  14142. /**
  14143. * 查询当前编辑区域的状态是源码模式还是可视化模式
  14144. * @command source
  14145. * @method queryCommandState
  14146. * @param { String } cmd 命令字符串
  14147. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  14148. * @example
  14149. * ```javascript
  14150. * editor.queryCommandState( 'source' );
  14151. * ```
  14152. */
  14153. me.commands['source'] = {
  14154. execCommand: function (){
  14155. sourceMode = !sourceMode;
  14156. if (sourceMode) {
  14157. bakAddress = me.selection.getRange().createAddress(false,true);
  14158. me.undoManger && me.undoManger.save(true);
  14159. if(browser.gecko){
  14160. me.body.contentEditable = false;
  14161. }
  14162. bakCssText = me.iframe.style.cssText;
  14163. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  14164. me.fireEvent('beforegetcontent');
  14165. var root = UE.htmlparser(me.body.innerHTML);
  14166. me.filterOutputRule(root);
  14167. root.traversal(function (node) {
  14168. if (node.type == 'element') {
  14169. switch (node.tagName) {
  14170. case 'td':
  14171. case 'th':
  14172. case 'caption':
  14173. if(node.children && node.children.length == 1){
  14174. if(node.firstChild().tagName == 'br' ){
  14175. node.removeChild(node.firstChild())
  14176. }
  14177. };
  14178. break;
  14179. case 'pre':
  14180. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  14181. }
  14182. }
  14183. });
  14184. me.fireEvent('aftergetcontent');
  14185. var content = root.toHtml(true);
  14186. sourceEditor = createSourceEditor(me.iframe.parentNode);
  14187. sourceEditor.setContent(content);
  14188. orgSetContent = me.setContent;
  14189. me.setContent = function(html){
  14190. //这里暂时不触发事件,防止报错
  14191. var root = UE.htmlparser(html);
  14192. me.filterInputRule(root);
  14193. html = root.toHtml();
  14194. sourceEditor.setContent(html);
  14195. };
  14196. setTimeout(function (){
  14197. sourceEditor.select();
  14198. me.addListener('fullscreenchanged', function(){
  14199. try{
  14200. sourceEditor.getCodeMirror().refresh()
  14201. }catch(e){}
  14202. });
  14203. });
  14204. //重置getContent,源码模式下取值也能是最新的数据
  14205. oldGetContent = me.getContent;
  14206. me.getContent = function (){
  14207. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  14208. };
  14209. } else {
  14210. me.iframe.style.cssText = bakCssText;
  14211. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  14212. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  14213. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  14214. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  14215. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  14216. }
  14217. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  14218. });
  14219. me.setContent = orgSetContent;
  14220. me.setContent(cont);
  14221. sourceEditor.dispose();
  14222. sourceEditor = null;
  14223. //还原getContent方法
  14224. me.getContent = oldGetContent;
  14225. var first = me.body.firstChild;
  14226. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  14227. if(!first){
  14228. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  14229. first = me.body.firstChild;
  14230. }
  14231. //要在ifm为显示时ff才能取到selection,否则报错
  14232. //这里不能比较位置了
  14233. me.undoManger && me.undoManger.save(true);
  14234. if(browser.gecko){
  14235. var input = document.createElement('input');
  14236. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  14237. document.body.appendChild(input);
  14238. me.body.contentEditable = false;
  14239. setTimeout(function(){
  14240. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  14241. input.focus();
  14242. setTimeout(function(){
  14243. me.body.contentEditable = true;
  14244. me.selection.getRange().moveToAddress(bakAddress).select(true);
  14245. domUtils.remove(input);
  14246. });
  14247. });
  14248. }else{
  14249. //ie下有可能报错,比如在代码顶头的情况
  14250. try{
  14251. me.selection.getRange().moveToAddress(bakAddress).select(true);
  14252. }catch(e){}
  14253. }
  14254. }
  14255. this.fireEvent('sourcemodechanged', sourceMode);
  14256. },
  14257. queryCommandState: function (){
  14258. return sourceMode|0;
  14259. },
  14260. notNeedUndo : 1
  14261. };
  14262. var oldQueryCommandState = me.queryCommandState;
  14263. me.queryCommandState = function (cmdName){
  14264. cmdName = cmdName.toLowerCase();
  14265. if (sourceMode) {
  14266. //源码模式下可以开启的命令
  14267. return cmdName in {
  14268. 'source' : 1,
  14269. 'fullscreen' : 1
  14270. } ? 1 : -1
  14271. }
  14272. return oldQueryCommandState.apply(this, arguments);
  14273. };
  14274. if(opt.sourceEditor == "codemirror"){
  14275. me.addListener("ready",function(){
  14276. utils.loadFile(document,{
  14277. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  14278. tag : "script",
  14279. type : "text/javascript",
  14280. defer : "defer"
  14281. },function(){
  14282. if(opt.sourceEditorFirst){
  14283. setTimeout(function(){
  14284. me.execCommand("source");
  14285. },0);
  14286. }
  14287. });
  14288. utils.loadFile(document,{
  14289. tag : "link",
  14290. rel : "stylesheet",
  14291. type : "text/css",
  14292. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  14293. });
  14294. });
  14295. }
  14296. };
  14297. })();
  14298. ///import core
  14299. ///import plugins/undo.js
  14300. ///commands 设置回车标签p或br
  14301. ///commandsName EnterKey
  14302. ///commandsTitle 设置回车标签p或br
  14303. /*
  14304. * @description 处理回车
  14305. * @author zhanyi
  14306. */
  14307. UE.plugins['enterkey'] = function() {
  14308. var hTag,
  14309. me = this,
  14310. tag = me.options.enterTag;
  14311. me.addListener('keyup', function(type, evt) {
  14312. var keyCode = evt.keyCode || evt.which;
  14313. if (keyCode == 13) {
  14314. var range = me.selection.getRange(),
  14315. start = range.startContainer,
  14316. doSave;
  14317. //修正在h1-h6里边回车后不能嵌套p的问题
  14318. if (!browser.ie) {
  14319. if (/h\d/i.test(hTag)) {
  14320. if (browser.gecko) {
  14321. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  14322. if (!h) {
  14323. me.document.execCommand('formatBlock', false, '<p>');
  14324. doSave = 1;
  14325. }
  14326. } else {
  14327. //chrome remove div
  14328. if (start.nodeType == 1) {
  14329. var tmp = me.document.createTextNode(''),div;
  14330. range.insertNode(tmp);
  14331. div = domUtils.findParentByTagName(tmp, 'div', true);
  14332. if (div) {
  14333. var p = me.document.createElement('p');
  14334. while (div.firstChild) {
  14335. p.appendChild(div.firstChild);
  14336. }
  14337. div.parentNode.insertBefore(p, div);
  14338. domUtils.remove(div);
  14339. range.setStartBefore(tmp).setCursor();
  14340. doSave = 1;
  14341. }
  14342. domUtils.remove(tmp);
  14343. }
  14344. }
  14345. if (me.undoManger && doSave) {
  14346. me.undoManger.save();
  14347. }
  14348. }
  14349. //没有站位符,会出现多行的问题
  14350. browser.opera && range.select();
  14351. }else{
  14352. me.fireEvent('saveScene',true,true)
  14353. }
  14354. }
  14355. });
  14356. me.addListener('keydown', function(type, evt) {
  14357. var keyCode = evt.keyCode || evt.which;
  14358. if (keyCode == 13) {//回车
  14359. if(me.fireEvent('beforeenterkeydown')){
  14360. domUtils.preventDefault(evt);
  14361. return;
  14362. }
  14363. me.fireEvent('saveScene',true,true);
  14364. hTag = '';
  14365. var range = me.selection.getRange();
  14366. if (!range.collapsed) {
  14367. //跨td不能删
  14368. var start = range.startContainer,
  14369. end = range.endContainer,
  14370. startTd = domUtils.findParentByTagName(start, 'td', true),
  14371. endTd = domUtils.findParentByTagName(end, 'td', true);
  14372. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  14373. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  14374. return;
  14375. }
  14376. }
  14377. if (tag == 'p') {
  14378. if (!browser.ie) {
  14379. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  14380. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  14381. //trace:2431
  14382. if (!start && !browser.opera) {
  14383. me.document.execCommand('formatBlock', false, '<p>');
  14384. if (browser.gecko) {
  14385. range = me.selection.getRange();
  14386. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14387. start && domUtils.removeDirtyAttr(start);
  14388. }
  14389. } else {
  14390. hTag = start.tagName;
  14391. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  14392. }
  14393. }
  14394. } else {
  14395. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  14396. if (!range.collapsed) {
  14397. range.deleteContents();
  14398. start = range.startContainer;
  14399. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  14400. while (start.nodeType == 1) {
  14401. if (dtd.$empty[start.tagName]) {
  14402. range.setStartBefore(start).setCursor();
  14403. if (me.undoManger) {
  14404. me.undoManger.save();
  14405. }
  14406. return false;
  14407. }
  14408. if (!start.firstChild) {
  14409. var br = range.document.createElement('br');
  14410. start.appendChild(br);
  14411. range.setStart(start, 0).setCursor();
  14412. if (me.undoManger) {
  14413. me.undoManger.save();
  14414. }
  14415. return false;
  14416. }
  14417. start = start.firstChild;
  14418. }
  14419. if (start === range.startContainer.childNodes[range.startOffset]) {
  14420. br = range.document.createElement('br');
  14421. range.insertNode(br).setCursor();
  14422. } else {
  14423. range.setStart(start, 0).setCursor();
  14424. }
  14425. } else {
  14426. br = range.document.createElement('br');
  14427. range.insertNode(br).setStartAfter(br).setCursor();
  14428. }
  14429. } else {
  14430. br = range.document.createElement('br');
  14431. range.insertNode(br);
  14432. var parent = br.parentNode;
  14433. if (parent.lastChild === br) {
  14434. br.parentNode.insertBefore(br.cloneNode(true), br);
  14435. range.setStartBefore(br);
  14436. } else {
  14437. range.setStartAfter(br);
  14438. }
  14439. range.setCursor();
  14440. }
  14441. }
  14442. }
  14443. });
  14444. };
  14445. /*
  14446. * 处理特殊键的兼容性问题
  14447. */
  14448. UE.plugins['keystrokes'] = function() {
  14449. var me = this;
  14450. var collapsed = true;
  14451. me.addListener('keydown', function(type, evt) {
  14452. var keyCode = evt.keyCode || evt.which,
  14453. rng = me.selection.getRange();
  14454. //处理全选的情况
  14455. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  14456. || keyCode >= 48 && keyCode <= 57 ||
  14457. keyCode >= 96 && keyCode <= 111 || {
  14458. 13:1,
  14459. 8:1,
  14460. 46:1
  14461. }[keyCode])
  14462. ){
  14463. var tmpNode = rng.startContainer;
  14464. if(domUtils.isFillChar(tmpNode)){
  14465. rng.setStartBefore(tmpNode)
  14466. }
  14467. tmpNode = rng.endContainer;
  14468. if(domUtils.isFillChar(tmpNode)){
  14469. rng.setEndAfter(tmpNode)
  14470. }
  14471. rng.txtToElmBoundary();
  14472. //结束边界可能放到了br的前边,要把br包含进来
  14473. // x[xxx]<br/>
  14474. if(rng.endContainer && rng.endContainer.nodeType == 1){
  14475. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  14476. if(tmpNode && domUtils.isBr(tmpNode)){
  14477. rng.setEndAfter(tmpNode);
  14478. }
  14479. }
  14480. if(rng.startOffset == 0){
  14481. tmpNode = rng.startContainer;
  14482. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  14483. tmpNode = rng.endContainer;
  14484. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  14485. me.fireEvent('saveScene');
  14486. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  14487. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  14488. me._selectionChange();
  14489. return;
  14490. }
  14491. }
  14492. }
  14493. }
  14494. //处理backspace
  14495. if (keyCode == 8) {
  14496. rng = me.selection.getRange();
  14497. collapsed = rng.collapsed;
  14498. if(me.fireEvent('delkeydown',evt)){
  14499. return;
  14500. }
  14501. var start,end;
  14502. //避免按两次删除才能生效的问题
  14503. if(rng.collapsed && rng.inFillChar()){
  14504. start = rng.startContainer;
  14505. if(domUtils.isFillChar(start)){
  14506. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  14507. domUtils.remove(start)
  14508. }else{
  14509. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  14510. rng.startOffset--;
  14511. rng.collapse(true).select(true)
  14512. }
  14513. }
  14514. //解决选中control元素不能删除的问题
  14515. if (start = rng.getClosedNode()) {
  14516. me.fireEvent('saveScene');
  14517. rng.setStartBefore(start);
  14518. domUtils.remove(start);
  14519. rng.setCursor();
  14520. me.fireEvent('saveScene');
  14521. domUtils.preventDefault(evt);
  14522. return;
  14523. }
  14524. //阻止在table上的删除
  14525. if (!browser.ie) {
  14526. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  14527. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  14528. if (start && !end || !start && end || start !== end) {
  14529. evt.preventDefault();
  14530. return;
  14531. }
  14532. }
  14533. }
  14534. //处理tab键的逻辑
  14535. if (keyCode == 9) {
  14536. //不处理以下标签
  14537. var excludeTagNameForTabKey = {
  14538. 'ol' : 1,
  14539. 'ul' : 1,
  14540. 'table':1
  14541. };
  14542. //处理组件里的tab按下事件
  14543. if(me.fireEvent('tabkeydown',evt)){
  14544. domUtils.preventDefault(evt);
  14545. return;
  14546. }
  14547. var range = me.selection.getRange();
  14548. me.fireEvent('saveScene');
  14549. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  14550. txt += tabNode;
  14551. }
  14552. var span = me.document.createElement('span');
  14553. span.innerHTML = txt + domUtils.fillChar;
  14554. if (range.collapsed) {
  14555. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  14556. } else {
  14557. var filterFn = function(node) {
  14558. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  14559. };
  14560. //普通的情况
  14561. start = domUtils.findParent(range.startContainer, filterFn,true);
  14562. end = domUtils.findParent(range.endContainer, filterFn,true);
  14563. if (start && end && start === end) {
  14564. range.deleteContents();
  14565. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  14566. } else {
  14567. var bookmark = range.createBookmark();
  14568. range.enlarge(true);
  14569. var bookmark2 = range.createBookmark(),
  14570. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  14571. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  14572. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  14573. current = domUtils.getNextDomNode(current, false, filterFn);
  14574. }
  14575. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  14576. }
  14577. }
  14578. domUtils.preventDefault(evt)
  14579. }
  14580. //trace:1634
  14581. //ff的del键在容器空的时候,也会删除
  14582. if(browser.gecko && keyCode == 46){
  14583. range = me.selection.getRange();
  14584. if(range.collapsed){
  14585. start = range.startContainer;
  14586. if(domUtils.isEmptyBlock(start)){
  14587. var parent = start.parentNode;
  14588. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  14589. start = parent;
  14590. parent = parent.parentNode;
  14591. }
  14592. if(start === parent.lastChild)
  14593. evt.preventDefault();
  14594. return;
  14595. }
  14596. }
  14597. }
  14598. });
  14599. me.addListener('keyup', function(type, evt) {
  14600. var keyCode = evt.keyCode || evt.which,
  14601. rng,me = this;
  14602. if(keyCode == 8){
  14603. if(me.fireEvent('delkeyup')){
  14604. return;
  14605. }
  14606. rng = me.selection.getRange();
  14607. if(rng.collapsed){
  14608. var tmpNode,
  14609. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  14610. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  14611. if(domUtils.isEmptyBlock(tmpNode)){
  14612. var pre = tmpNode.previousSibling;
  14613. if(pre && pre.nodeName != 'TABLE'){
  14614. domUtils.remove(tmpNode);
  14615. rng.setStartAtLast(pre).setCursor(false,true);
  14616. return;
  14617. }else{
  14618. var next = tmpNode.nextSibling;
  14619. if(next && next.nodeName != 'TABLE'){
  14620. domUtils.remove(tmpNode);
  14621. rng.setStartAtFirst(next).setCursor(false,true);
  14622. return;
  14623. }
  14624. }
  14625. }
  14626. }
  14627. //处理当删除到body时,要重新给p标签展位
  14628. if(domUtils.isBody(rng.startContainer)){
  14629. var tmpNode = domUtils.createElement(me.document,'p',{
  14630. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  14631. });
  14632. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  14633. }
  14634. }
  14635. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  14636. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  14637. if(browser.ie){
  14638. var span = rng.document.createElement('span');
  14639. rng.insertNode(span).setStartBefore(span).collapse(true);
  14640. rng.select();
  14641. domUtils.remove(span)
  14642. }else{
  14643. rng.select()
  14644. }
  14645. }
  14646. }
  14647. })
  14648. };
  14649. ///import core
  14650. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  14651. ///commandsName FixImgClick
  14652. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  14653. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  14654. UE.plugins['fiximgclick'] = (function () {
  14655. function Scale() {
  14656. this.editor = null;
  14657. this.resizer = null;
  14658. this.cover = null;
  14659. this.doc = document;
  14660. this.prePos = {x: 0, y: 0};
  14661. this.startPos = {x: 0, y: 0};
  14662. }
  14663. (function () {
  14664. var rect = [
  14665. //[left, top, width, height]
  14666. [0, 0, -1, -1],
  14667. [0, 0, 0, -1],
  14668. [0, 0, 1, -1],
  14669. [0, 0, -1, 0],
  14670. [0, 0, 1, 0],
  14671. [0, 0, -1, 1],
  14672. [0, 0, 0, 1],
  14673. [0, 0, 1, 1]
  14674. ];
  14675. Scale.prototype = {
  14676. init: function (editor) {
  14677. var me = this;
  14678. me.editor = editor;
  14679. me.startPos = this.prePos = {x: 0, y: 0};
  14680. me.dragId = -1;
  14681. var hands = [],
  14682. cover = me.cover = document.createElement('div'),
  14683. resizer = me.resizer = document.createElement('div');
  14684. cover.id = me.editor.ui.id + '_imagescale_cover';
  14685. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  14686. domUtils.on(cover, 'mousedown click', function () {
  14687. me.hide();
  14688. });
  14689. for (i = 0; i < 8; i++) {
  14690. hands.push('<span class="edui-editor-scale-hand' + i + '"></span>');
  14691. }
  14692. resizer.id = me.editor.ui.id + '_imagescale';
  14693. resizer.className = 'edui-editor-scale';
  14694. resizer.innerHTML = hands.join('');
  14695. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  14696. me.editor.ui.getDom().appendChild(cover);
  14697. me.editor.ui.getDom().appendChild(resizer);
  14698. me.initStyle();
  14699. me.initEvents();
  14700. },
  14701. initStyle: function () {
  14702. utils.cssRule('imagescale', '.edui-editor-scale{position:absolute;border:1px solid #38B2CE;}' +
  14703. '.edui-editor-scale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  14704. + '.edui-editor-scale .edui-editor-scale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  14705. + '.edui-editor-scale .edui-editor-scale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  14706. + '.edui-editor-scale .edui-editor-scale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  14707. + '.edui-editor-scale .edui-editor-scale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  14708. + '.edui-editor-scale .edui-editor-scale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  14709. + '.edui-editor-scale .edui-editor-scale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  14710. + '.edui-editor-scale .edui-editor-scale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  14711. + '.edui-editor-scale .edui-editor-scale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  14712. },
  14713. initEvents: function () {
  14714. var me = this;
  14715. me.startPos.x = me.startPos.y = 0;
  14716. me.isDraging = false;
  14717. },
  14718. _eventHandler: function (e) {
  14719. var me = this;
  14720. switch (e.type) {
  14721. case 'mousedown':
  14722. var hand = e.target || e.srcElement, hand;
  14723. if (hand.className.indexOf('edui-editor-scale-hand') != -1 && me.dragId == -1) {
  14724. me.dragId = hand.className.slice(-1);
  14725. me.startPos.x = me.prePos.x = e.clientX;
  14726. me.startPos.y = me.prePos.y = e.clientY;
  14727. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  14728. }
  14729. break;
  14730. case 'mousemove':
  14731. if (me.dragId != -1) {
  14732. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  14733. me.prePos.x = e.clientX;
  14734. me.prePos.y = e.clientY;
  14735. me.updateTargetElement();
  14736. }
  14737. break;
  14738. case 'mouseup':
  14739. if (me.dragId != -1) {
  14740. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  14741. me.updateTargetElement();
  14742. if (me.target.parentNode) me.attachTo(me.target);
  14743. me.dragId = -1;
  14744. }
  14745. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  14746. me.editor.fireEvent('contentchange');
  14747. break;
  14748. default:
  14749. break;
  14750. }
  14751. },
  14752. updateTargetElement: function () {
  14753. var me = this,
  14754. targetPos;
  14755. domUtils.setStyles(me.target, {
  14756. 'width': me.resizer.style.width,
  14757. 'height': me.resizer.style.height
  14758. });
  14759. me.attachTo(me.target);
  14760. },
  14761. updateContainerStyle: function (dir, offset) {
  14762. var me = this,
  14763. dom = me.resizer, tmp;
  14764. if (rect[dir][0] != 0) {
  14765. tmp = parseInt(dom.style.left) + offset.x;
  14766. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  14767. }
  14768. if (rect[dir][1] != 0) {
  14769. tmp = parseInt(dom.style.top) + offset.y;
  14770. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  14771. }
  14772. if (rect[dir][2] != 0) {
  14773. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  14774. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  14775. }
  14776. if (rect[dir][3] != 0) {
  14777. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  14778. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  14779. }
  14780. },
  14781. _validScaledProp: function (prop, value) {
  14782. var ele = this.resizer,
  14783. wrap = document;
  14784. value = isNaN(value) ? 0 : value;
  14785. switch (prop) {
  14786. case 'left':
  14787. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  14788. case 'top':
  14789. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  14790. case 'width':
  14791. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  14792. case 'height':
  14793. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  14794. }
  14795. },
  14796. hideCover: function () {
  14797. this.cover.style.display = 'none';
  14798. },
  14799. showCover: function () {
  14800. var me = this,
  14801. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  14802. iframePos = domUtils.getXY(me.editor.iframe);
  14803. domUtils.setStyles(me.cover, {
  14804. 'width': me.editor.iframe.offsetWidth + 'px',
  14805. 'height': me.editor.iframe.offsetHeight + 'px',
  14806. 'top': iframePos.y - editorPos.y + 'px',
  14807. 'left': iframePos.x - editorPos.x + 'px',
  14808. 'position': 'absolute',
  14809. 'display': ''
  14810. })
  14811. },
  14812. show: function (targetObj) {
  14813. var me = this;
  14814. me.resizer.style.display = 'block';
  14815. if(targetObj) me.attachTo(targetObj);
  14816. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  14817. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  14818. me.showCover();
  14819. me.editor.fireEvent('afterscaleshow', me);
  14820. me.editor.fireEvent('saveScene');
  14821. },
  14822. hide: function () {
  14823. var me = this;
  14824. me.hideCover();
  14825. me.resizer.style.display = 'none';
  14826. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  14827. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  14828. me.editor.fireEvent('afterscalehide', me);
  14829. },
  14830. proxy: function( fn, context ) {
  14831. return function(e) {
  14832. return fn.apply( context || this, arguments);
  14833. };
  14834. },
  14835. attachTo: function (targetObj) {
  14836. var me = this,
  14837. target = me.target = targetObj,
  14838. resizer = this.resizer,
  14839. imgPos = domUtils.getXY(target),
  14840. iframePos = domUtils.getXY(me.editor.iframe),
  14841. editorPos = domUtils.getXY(resizer.parentNode);
  14842. domUtils.setStyles(resizer, {
  14843. 'width': target.width + 'px',
  14844. 'height': target.height + 'px',
  14845. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  14846. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  14847. });
  14848. }
  14849. }
  14850. })();
  14851. return function () {
  14852. var me = this,
  14853. imageScale;
  14854. me.setOpt('imageScaleEnabled', true);
  14855. if ( !browser.ie && me.options.imageScaleEnabled) {
  14856. me.addListener('click', function (type, e) {
  14857. var range = me.selection.getRange(),
  14858. img = range.getClosedNode();
  14859. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  14860. if (!imageScale) {
  14861. imageScale = new Scale();
  14862. imageScale.init(me);
  14863. me.ui.getDom().appendChild(imageScale.resizer);
  14864. var _keyDownHandler = function (e) {
  14865. imageScale.hide();
  14866. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  14867. }, _mouseDownHandler = function (e) {
  14868. var ele = e.target || e.srcElement;
  14869. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-scale') == -1)) {
  14870. _keyDownHandler(e);
  14871. }
  14872. }, timer;
  14873. me.addListener('afterscaleshow', function (e) {
  14874. me.addListener('beforekeydown', _keyDownHandler);
  14875. me.addListener('beforemousedown', _mouseDownHandler);
  14876. domUtils.on(document, 'keydown', _keyDownHandler);
  14877. domUtils.on(document,'mousedown', _mouseDownHandler);
  14878. me.selection.getNative().removeAllRanges();
  14879. });
  14880. me.addListener('afterscalehide', function (e) {
  14881. me.removeListener('beforekeydown', _keyDownHandler);
  14882. me.removeListener('beforemousedown', _mouseDownHandler);
  14883. domUtils.un(document, 'keydown', _keyDownHandler);
  14884. domUtils.un(document,'mousedown', _mouseDownHandler);
  14885. var target = imageScale.target;
  14886. if (target.parentNode) {
  14887. me.selection.getRange().selectNode(target).select();
  14888. }
  14889. });
  14890. //TODO 有iframe的情况,mousedown不能往下传。。
  14891. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  14892. me.selection.getNative().removeAllRanges();
  14893. var ele = e.target || e.srcElement;
  14894. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  14895. timer = setTimeout(function () {
  14896. imageScale.hide();
  14897. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  14898. }, 200);
  14899. }
  14900. });
  14901. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  14902. var ele = e.target || e.srcElement;
  14903. if (ele && ele.className.indexOf('edui-editor-scale-hand') == -1) {
  14904. clearTimeout(timer);
  14905. }
  14906. });
  14907. }
  14908. imageScale.show(img);
  14909. } else {
  14910. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  14911. }
  14912. });
  14913. }
  14914. if (browser.webkit) {
  14915. me.addListener('click', function (type, e) {
  14916. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  14917. var range = new dom.Range(me.document);
  14918. range.selectNode(e.target).select();
  14919. }
  14920. });
  14921. }
  14922. }
  14923. })();
  14924. ///import core
  14925. ///commands 为非ie浏览器自动添加a标签
  14926. ///commandsName AutoLink
  14927. ///commandsTitle 自动增加链接
  14928. /*
  14929. * @description 为非ie浏览器自动添加a标签
  14930. * @author zhanyi
  14931. */
  14932. UE.plugin.register('autolink',function(){
  14933. var cont = 0;
  14934. return !browser.ie ? {
  14935. bindEvents:{
  14936. 'reset' : function(){
  14937. cont = 0;
  14938. },
  14939. 'keydown':function(type, evt) {
  14940. var me = this;
  14941. var keyCode = evt.keyCode || evt.which;
  14942. if (keyCode == 32 || keyCode == 13) {
  14943. var sel = me.selection.getNative(),
  14944. range = sel.getRangeAt(0).cloneRange(),
  14945. offset,
  14946. charCode;
  14947. var start = range.startContainer;
  14948. while (start.nodeType == 1 && range.startOffset > 0) {
  14949. start = range.startContainer.childNodes[range.startOffset - 1];
  14950. if (!start){
  14951. break;
  14952. }
  14953. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  14954. range.collapse(true);
  14955. start = range.startContainer;
  14956. }
  14957. do{
  14958. if (range.startOffset == 0) {
  14959. start = range.startContainer.previousSibling;
  14960. while (start && start.nodeType == 1) {
  14961. start = start.lastChild;
  14962. }
  14963. if (!start || domUtils.isFillChar(start)){
  14964. break;
  14965. }
  14966. offset = start.nodeValue.length;
  14967. } else {
  14968. start = range.startContainer;
  14969. offset = range.startOffset;
  14970. }
  14971. range.setStart(start, offset - 1);
  14972. charCode = range.toString().charCodeAt(0);
  14973. } while (charCode != 160 && charCode != 32);
  14974. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  14975. while(range.toString().length){
  14976. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  14977. break;
  14978. }
  14979. try{
  14980. range.setStart(range.startContainer,range.startOffset+1);
  14981. }catch(e){
  14982. //trace:2121
  14983. var start = range.startContainer;
  14984. while(!(next = start.nextSibling)){
  14985. if(domUtils.isBody(start)){
  14986. return;
  14987. }
  14988. start = start.parentNode;
  14989. }
  14990. range.setStart(next,0);
  14991. }
  14992. }
  14993. //range的开始边界已经在a标签里的不再处理
  14994. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  14995. return;
  14996. }
  14997. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  14998. me.undoManger && me.undoManger.save();
  14999. a.appendChild(range.extractContents());
  15000. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  15001. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  15002. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  15003. a.setAttribute('_src',utils.html(href));
  15004. a.href = utils.html(href);
  15005. range.insertNode(a);
  15006. a.parentNode.insertBefore(text, a.nextSibling);
  15007. range.setStart(text, 0);
  15008. range.collapse(true);
  15009. sel.removeAllRanges();
  15010. sel.addRange(range);
  15011. me.undoManger && me.undoManger.save();
  15012. }
  15013. }
  15014. }
  15015. }
  15016. }:{}
  15017. },function(){
  15018. var keyCodes = {
  15019. 37:1, 38:1, 39:1, 40:1,
  15020. 13:1,32:1
  15021. };
  15022. function checkIsCludeLink(node){
  15023. if(node.nodeType == 3){
  15024. return null
  15025. }
  15026. if(node.nodeName == 'A'){
  15027. return node;
  15028. }
  15029. var lastChild = node.lastChild;
  15030. while(lastChild){
  15031. if(lastChild.nodeName == 'A'){
  15032. return lastChild;
  15033. }
  15034. if(lastChild.nodeType == 3){
  15035. if(domUtils.isWhitespace(lastChild)){
  15036. lastChild = lastChild.previousSibling;
  15037. continue;
  15038. }
  15039. return null
  15040. }
  15041. lastChild = lastChild.lastChild;
  15042. }
  15043. }
  15044. browser.ie && this.addListener('keyup',function(cmd,evt){
  15045. var me = this,keyCode = evt.keyCode;
  15046. if(keyCodes[keyCode]){
  15047. var rng = me.selection.getRange();
  15048. var start = rng.startContainer;
  15049. if(keyCode == 13){
  15050. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15051. start = start.parentNode;
  15052. }
  15053. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15054. var pre = start.previousSibling;
  15055. if(pre && pre.nodeType == 1){
  15056. var pre = checkIsCludeLink(pre);
  15057. if(pre && !pre.getAttribute('_href')){
  15058. domUtils.remove(pre,true);
  15059. }
  15060. }
  15061. }
  15062. }else if(keyCode == 32 ){
  15063. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15064. start = start.previousSibling;
  15065. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15066. domUtils.remove(start,true);
  15067. }
  15068. }
  15069. }else {
  15070. start = domUtils.findParentByTagName(start,'a',true);
  15071. if(start && !start.getAttribute('_href')){
  15072. var bk = rng.createBookmark();
  15073. domUtils.remove(start,true);
  15074. rng.moveToBookmark(bk).select(true)
  15075. }
  15076. }
  15077. }
  15078. });
  15079. }
  15080. );
  15081. ///import core
  15082. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  15083. ///commandsName AutoHeight,autoHeightEnabled
  15084. ///commandsTitle 自动增高
  15085. /*
  15086. * @description 自动伸展
  15087. * @author zhanyi
  15088. */
  15089. UE.plugins['autoheight'] = function () {
  15090. var me = this;
  15091. //提供开关,就算加载也可以关闭
  15092. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  15093. if (!me.autoHeightEnabled) {
  15094. return;
  15095. }
  15096. var bakOverflow,
  15097. lastHeight = 0,
  15098. options = me.options,
  15099. currentHeight,
  15100. timer;
  15101. function adjustHeight() {
  15102. var me = this;
  15103. clearTimeout(timer);
  15104. if(isFullscreen)return;
  15105. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  15106. timer = setTimeout(function(){
  15107. var node = me.body.lastChild;
  15108. while(node && node.nodeType != 1){
  15109. node = node.previousSibling;
  15110. }
  15111. if(node && node.nodeType == 1){
  15112. node.style.clear = 'both';
  15113. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  15114. if (currentHeight != lastHeight) {
  15115. me.setHeight(currentHeight,true);
  15116. lastHeight = currentHeight;
  15117. }
  15118. domUtils.removeStyle(node,'clear');
  15119. }
  15120. },50)
  15121. }
  15122. }
  15123. var isFullscreen;
  15124. me.addListener('fullscreenchanged',function(cmd,f){
  15125. isFullscreen = f
  15126. });
  15127. me.addListener('destroy', function () {
  15128. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  15129. });
  15130. me.enableAutoHeight = function () {
  15131. var me = this;
  15132. if (!me.autoHeightEnabled) {
  15133. return;
  15134. }
  15135. var doc = me.document;
  15136. me.autoHeightEnabled = true;
  15137. bakOverflow = doc.body.style.overflowY;
  15138. doc.body.style.overflowY = 'hidden';
  15139. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  15140. //ff不给事件算得不对
  15141. setTimeout(function () {
  15142. adjustHeight.call(me);
  15143. }, browser.gecko ? 100 : 0);
  15144. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  15145. };
  15146. me.disableAutoHeight = function () {
  15147. me.body.style.overflowY = bakOverflow || '';
  15148. me.removeListener('contentchange', adjustHeight);
  15149. me.removeListener('keyup', adjustHeight);
  15150. me.removeListener('mouseup', adjustHeight);
  15151. me.autoHeightEnabled = false;
  15152. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  15153. };
  15154. me.addListener('ready', function () {
  15155. me.enableAutoHeight();
  15156. //trace:1764
  15157. var timer;
  15158. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  15159. clearTimeout(timer);
  15160. timer = setTimeout(function () {
  15161. //trace:3681
  15162. adjustHeight.call(me);
  15163. }, 100);
  15164. });
  15165. });
  15166. };
  15167. ///import core
  15168. ///commands 悬浮工具栏
  15169. ///commandsName AutoFloat,autoFloatEnabled
  15170. ///commandsTitle 悬浮工具栏
  15171. /*
  15172. * modified by chengchao01
  15173. *
  15174. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  15175. */
  15176. UE.plugins['autofloat'] = function() {
  15177. var me = this,
  15178. lang = me.getLang();
  15179. me.setOpt({
  15180. topOffset:0
  15181. });
  15182. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  15183. topOffset = me.options.topOffset;
  15184. //如果不固定toolbar的位置,则直接退出
  15185. if(!optsAutoFloatEnabled){
  15186. return;
  15187. }
  15188. var uiUtils = UE.ui.uiUtils,
  15189. LteIE6 = browser.ie && browser.version <= 6,
  15190. quirks = browser.quirks;
  15191. function checkHasUI(){
  15192. if(!UE.ui){
  15193. alert(lang.autofloatMsg);
  15194. return 0;
  15195. }
  15196. return 1;
  15197. }
  15198. function fixIE6FixedPos(){
  15199. var docStyle = document.body.style;
  15200. docStyle.backgroundImage = 'url("about:blank")';
  15201. docStyle.backgroundAttachment = 'fixed';
  15202. }
  15203. var bakCssText,
  15204. placeHolder = document.createElement('div'),
  15205. toolbarBox,orgTop,
  15206. getPosition,
  15207. flag =true; //ie7模式下需要偏移
  15208. function setFloating(){
  15209. var toobarBoxPos = domUtils.getXY(toolbarBox),
  15210. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  15211. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  15212. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  15213. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  15214. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  15215. if (LteIE6 || (quirks && browser.ie)) {
  15216. if(toolbarBox.style.position != 'absolute'){
  15217. toolbarBox.style.position = 'absolute';
  15218. }
  15219. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  15220. } else {
  15221. if (browser.ie7Compat && flag) {
  15222. flag = false;
  15223. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  15224. }
  15225. if(toolbarBox.style.position != 'fixed'){
  15226. toolbarBox.style.position = 'fixed';
  15227. toolbarBox.style.top = topOffset +"px";
  15228. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  15229. }
  15230. }
  15231. }
  15232. function unsetFloating(){
  15233. flag = true;
  15234. if(placeHolder.parentNode){
  15235. placeHolder.parentNode.removeChild(placeHolder);
  15236. }
  15237. toolbarBox.style.cssText = bakCssText;
  15238. }
  15239. function updateFloating(){
  15240. var rect3 = getPosition(me.container);
  15241. var offset=me.options.toolbarTopOffset||0;
  15242. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  15243. setFloating();
  15244. }else{
  15245. unsetFloating();
  15246. }
  15247. }
  15248. var defer_updateFloating = utils.defer(function(){
  15249. updateFloating();
  15250. },browser.ie ? 200 : 100,true);
  15251. me.addListener('destroy',function(){
  15252. domUtils.un(window, ['scroll','resize'], updateFloating);
  15253. me.removeListener('keydown', defer_updateFloating);
  15254. });
  15255. me.addListener('ready', function(){
  15256. if(checkHasUI(me)){
  15257. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  15258. if(!me.ui){
  15259. return;
  15260. }
  15261. getPosition = uiUtils.getClientRect;
  15262. toolbarBox = me.ui.getDom('toolbarbox');
  15263. orgTop = getPosition(toolbarBox).top;
  15264. bakCssText = toolbarBox.style.cssText;
  15265. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  15266. if(LteIE6){
  15267. fixIE6FixedPos();
  15268. }
  15269. domUtils.on(window, ['scroll','resize'], updateFloating);
  15270. me.addListener('keydown', defer_updateFloating);
  15271. me.addListener('beforefullscreenchange', function (t, enabled){
  15272. if (enabled) {
  15273. unsetFloating();
  15274. }
  15275. });
  15276. me.addListener('fullscreenchanged', function (t, enabled){
  15277. if (!enabled) {
  15278. updateFloating();
  15279. }
  15280. });
  15281. me.addListener('sourcemodechanged', function (t, enabled){
  15282. setTimeout(function (){
  15283. updateFloating();
  15284. },0);
  15285. });
  15286. me.addListener("clearDoc",function(){
  15287. setTimeout(function(){
  15288. updateFloating();
  15289. },0);
  15290. })
  15291. }
  15292. });
  15293. };
  15294. /**
  15295. * 纯文本粘贴插件
  15296. * @file
  15297. * @since 1.2.6.1
  15298. */
  15299. UE.plugins['pasteplain'] = function(){
  15300. var me = this;
  15301. me.setOpt({
  15302. 'pasteplain':false,
  15303. 'filterTxtRules' : function(){
  15304. function transP(node){
  15305. node.tagName = 'p';
  15306. node.setStyle();
  15307. }
  15308. function removeNode(node){
  15309. node.parentNode.removeChild(node,true)
  15310. }
  15311. return {
  15312. //直接删除及其字节点内容
  15313. '-' : 'script style object iframe embed input select',
  15314. 'p': {$:{}},
  15315. 'br':{$:{}},
  15316. div: function (node) {
  15317. var tmpNode, p = UE.uNode.createElement('p');
  15318. while (tmpNode = node.firstChild()) {
  15319. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  15320. p.appendChild(tmpNode);
  15321. } else {
  15322. if (p.firstChild()) {
  15323. node.parentNode.insertBefore(p, node);
  15324. p = UE.uNode.createElement('p');
  15325. } else {
  15326. node.parentNode.insertBefore(tmpNode, node);
  15327. }
  15328. }
  15329. }
  15330. if (p.firstChild()) {
  15331. node.parentNode.insertBefore(p, node);
  15332. }
  15333. node.parentNode.removeChild(node);
  15334. },
  15335. ol: removeNode,
  15336. ul: removeNode,
  15337. dl:removeNode,
  15338. dt:removeNode,
  15339. dd:removeNode,
  15340. 'li':removeNode,
  15341. 'caption':transP,
  15342. 'th':transP,
  15343. 'tr':transP,
  15344. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  15345. 'td':function(node){
  15346. //没有内容的td直接删掉
  15347. var txt = !!node.innerText();
  15348. if(txt){
  15349. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  15350. }
  15351. node.parentNode.removeChild(node,node.innerText())
  15352. }
  15353. }
  15354. }()
  15355. });
  15356. //暂时这里支持一下老版本的属性
  15357. var pasteplain = me.options.pasteplain;
  15358. /**
  15359. * 启用或取消纯文本粘贴模式
  15360. * @command pasteplain
  15361. * @method execCommand
  15362. * @param { String } cmd 命令字符串
  15363. * @example
  15364. * ```javascript
  15365. * editor.queryCommandState( 'pasteplain' );
  15366. * ```
  15367. */
  15368. /**
  15369. * 查询当前是否处于纯文本粘贴模式
  15370. * @command pasteplain
  15371. * @method queryCommandState
  15372. * @param { String } cmd 命令字符串
  15373. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  15374. * @example
  15375. * ```javascript
  15376. * editor.queryCommandState( 'pasteplain' );
  15377. * ```
  15378. */
  15379. me.commands['pasteplain'] = {
  15380. queryCommandState: function (){
  15381. return pasteplain ? 1 : 0;
  15382. },
  15383. execCommand: function (){
  15384. pasteplain = !pasteplain|0;
  15385. },
  15386. notNeedUndo : 1
  15387. };
  15388. };
  15389. /**
  15390. * video插件, 为UEditor提供视频插入支持
  15391. * @file
  15392. * @since 1.2.6.1
  15393. */
  15394. UE.plugins['video'] = function (){
  15395. var me =this;
  15396. /*
  15397. * 创建插入视频字符窜
  15398. * @param url 视频地址
  15399. * @param width 视频宽度
  15400. * @param height 视频高度
  15401. * @param align 视频对齐
  15402. * @param toEmbed 是否以flash代替显示
  15403. * @param addParagraph 是否需要添加P 标签
  15404. */
  15405. function creatInsertStr(url,width,height,id,align,classname,type){
  15406. var str;
  15407. switch (type){
  15408. case 'image':
  15409. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname + '"' +
  15410. ' 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 + ';': '')+'" />'
  15411. break;
  15412. case 'embed':
  15413. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  15414. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  15415. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  15416. break;
  15417. case 'video':
  15418. var ext = url.substr(url.lastIndexOf('.') + 1);
  15419. if(ext == 'ogv') ext = 'ogg';
  15420. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + '" ' + (align ? ' style="float:' + align + '"': '') +
  15421. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  15422. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  15423. break;
  15424. }
  15425. return str;
  15426. }
  15427. function switchImgAndVideo(root,img2video){
  15428. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  15429. var className = node.getAttr('class');
  15430. if(className && className.indexOf('edui-faked-video') != -1){
  15431. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  15432. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  15433. }
  15434. if(className && className.indexOf('edui-upload-video') != -1){
  15435. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  15436. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  15437. }
  15438. })
  15439. }
  15440. me.addOutputRule(function(root){
  15441. switchImgAndVideo(root,true)
  15442. });
  15443. me.addInputRule(function(root){
  15444. switchImgAndVideo(root)
  15445. });
  15446. /**
  15447. * 插入视频
  15448. * @command insertvideo
  15449. * @method execCommand
  15450. * @param { String } cmd 命令字符串
  15451. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  15452. * @example
  15453. * ```javascript
  15454. *
  15455. * var videoAttr = {
  15456. * //视频地址
  15457. * url: 'http://www.youku.com/xxx',
  15458. * //视频宽高值, 单位px
  15459. * width: 200,
  15460. * height: 100
  15461. * };
  15462. *
  15463. * //editor 是编辑器实例
  15464. * //向编辑器插入单个视频
  15465. * editor.execCommand( 'insertvideo', videoAttr );
  15466. * ```
  15467. */
  15468. /**
  15469. * 插入视频
  15470. * @command insertvideo
  15471. * @method execCommand
  15472. * @param { String } cmd 命令字符串
  15473. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  15474. * @example
  15475. * ```javascript
  15476. *
  15477. * var videoAttr1 = {
  15478. * //视频地址
  15479. * url: 'http://www.youku.com/xxx',
  15480. * //视频宽高值, 单位px
  15481. * width: 200,
  15482. * height: 100
  15483. * },
  15484. * videoAttr2 = {
  15485. * //视频地址
  15486. * url: 'http://www.youku.com/xxx',
  15487. * //视频宽高值, 单位px
  15488. * width: 200,
  15489. * height: 100
  15490. * }
  15491. *
  15492. * //editor 是编辑器实例
  15493. * //该方法将会向编辑器内插入两个视频
  15494. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  15495. * ```
  15496. */
  15497. /**
  15498. * 查询当前光标所在处是否是一个视频
  15499. * @command insertvideo
  15500. * @method queryCommandState
  15501. * @param { String } cmd 需要查询的命令字符串
  15502. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  15503. * @example
  15504. * ```javascript
  15505. *
  15506. * //editor 是编辑器实例
  15507. * editor.queryCommandState( 'insertvideo' );
  15508. * ```
  15509. */
  15510. me.commands["insertvideo"] = {
  15511. execCommand: function (cmd, videoObjs, type){
  15512. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  15513. var html = [],id = 'tmpVedio', cl;
  15514. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  15515. vi = videoObjs[i];
  15516. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  15517. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  15518. }
  15519. me.execCommand("inserthtml",html.join(""),true);
  15520. var rng = this.selection.getRange();
  15521. for(var i= 0,len=videoObjs.length;i<len;i++){
  15522. var img = this.document.getElementById('tmpVedio'+i);
  15523. domUtils.removeAttributes(img,'id');
  15524. rng.selectNode(img).select();
  15525. me.execCommand('imagefloat',videoObjs[i].align)
  15526. }
  15527. },
  15528. queryCommandState : function(){
  15529. var img = me.selection.getRange().getClosedNode(),
  15530. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  15531. return flag ? 1 : 0;
  15532. }
  15533. };
  15534. };
  15535. /**
  15536. * Created with JetBrains WebStorm.
  15537. * User: taoqili
  15538. * Date: 13-1-18
  15539. * Time: 上午11:09
  15540. * To change this template use File | Settings | File Templates.
  15541. */
  15542. /**
  15543. * UE表格操作类
  15544. * @param table
  15545. * @constructor
  15546. */
  15547. (function () {
  15548. var UETable = UE.UETable = function (table) {
  15549. this.table = table;
  15550. this.indexTable = [];
  15551. this.selectedTds = [];
  15552. this.cellsRange = {};
  15553. this.update(table);
  15554. };
  15555. //===以下为静态工具方法===
  15556. UETable.removeSelectedClass = function (cells) {
  15557. utils.each(cells, function (cell) {
  15558. domUtils.removeClasses(cell, "selectTdClass");
  15559. })
  15560. };
  15561. UETable.addSelectedClass = function (cells) {
  15562. utils.each(cells, function (cell) {
  15563. domUtils.addClass(cell, "selectTdClass");
  15564. })
  15565. };
  15566. UETable.isEmptyBlock = function (node) {
  15567. var reg = new RegExp(domUtils.fillChar, 'g');
  15568. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  15569. return 0;
  15570. }
  15571. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  15572. if (node.getElementsByTagName(i).length) {
  15573. return 0;
  15574. }
  15575. }
  15576. return 1;
  15577. };
  15578. UETable.getWidth = function (cell) {
  15579. if (!cell)return 0;
  15580. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  15581. };
  15582. /**
  15583. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  15584. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  15585. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  15586. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  15587. */
  15588. UETable.getTableCellAlignState = function ( cells ) {
  15589. !utils.isArray( cells ) && ( cells = [cells] );
  15590. var result = {},
  15591. status = ['align', 'valign'],
  15592. tempStatus = null,
  15593. isSame = true;//状态是否相同
  15594. utils.each( cells, function( cellNode ){
  15595. utils.each( status, function( currentState ){
  15596. tempStatus = cellNode.getAttribute( currentState );
  15597. if( !result[ currentState ] && tempStatus ) {
  15598. result[ currentState ] = tempStatus;
  15599. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  15600. isSame = false;
  15601. return false;
  15602. }
  15603. } );
  15604. return isSame;
  15605. });
  15606. return isSame ? result : null;
  15607. };
  15608. /**
  15609. * 根据当前选区获取相关的table信息
  15610. * @return {Object}
  15611. */
  15612. UETable.getTableItemsByRange = function (editor) {
  15613. var start = editor.selection.getStart();
  15614. //ff下会选中bookmark
  15615. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 ) {
  15616. start = start.nextSibling;
  15617. }
  15618. //在table或者td边缘有可能存在选中tr的情况
  15619. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  15620. tr = cell && cell.parentNode,
  15621. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  15622. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  15623. return {
  15624. cell:cell,
  15625. tr:tr,
  15626. table:table,
  15627. caption:caption
  15628. }
  15629. };
  15630. UETable.getUETableBySelected = function (editor) {
  15631. var table = UETable.getTableItemsByRange(editor).table;
  15632. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  15633. return table.ueTable;
  15634. }
  15635. return null;
  15636. };
  15637. UETable.getDefaultValue = function (editor, table) {
  15638. var borderMap = {
  15639. thin:'0px',
  15640. medium:'1px',
  15641. thick:'2px'
  15642. },
  15643. tableBorder, tdPadding, tdBorder, tmpValue;
  15644. if (!table) {
  15645. table = editor.document.createElement('table');
  15646. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  15647. editor.body.appendChild(table);
  15648. var td = table.getElementsByTagName('td')[0];
  15649. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  15650. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15651. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  15652. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15653. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  15654. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15655. domUtils.remove(table);
  15656. return {
  15657. tableBorder:tableBorder,
  15658. tdPadding:tdPadding,
  15659. tdBorder:tdBorder
  15660. };
  15661. } else {
  15662. td = table.getElementsByTagName('td')[0];
  15663. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  15664. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15665. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  15666. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15667. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  15668. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  15669. return {
  15670. tableBorder:tableBorder,
  15671. tdPadding:tdPadding,
  15672. tdBorder:tdBorder
  15673. };
  15674. }
  15675. };
  15676. /**
  15677. * 根据当前点击的td或者table获取索引对象
  15678. * @param tdOrTable
  15679. */
  15680. UETable.getUETable = function (tdOrTable) {
  15681. var tag = tdOrTable.tagName.toLowerCase();
  15682. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  15683. if (!tdOrTable.ueTable) {
  15684. tdOrTable.ueTable = new UETable(tdOrTable);
  15685. }
  15686. return tdOrTable.ueTable;
  15687. };
  15688. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  15689. if (!cell || utils.isString(cell)) {
  15690. return this.table.ownerDocument.createElement(cell || 'td');
  15691. }
  15692. var flag = domUtils.hasClass(cell, "selectTdClass");
  15693. flag && domUtils.removeClasses(cell, "selectTdClass");
  15694. var tmpCell = cell.cloneNode(true);
  15695. if (ignoreMerge) {
  15696. tmpCell.rowSpan = tmpCell.colSpan = 1;
  15697. }
  15698. //去掉宽高
  15699. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  15700. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  15701. tmpCell.style.borderLeftStyle = "";
  15702. tmpCell.style.borderTopStyle = "";
  15703. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  15704. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  15705. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  15706. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  15707. flag && domUtils.addClass(cell, "selectTdClass");
  15708. return tmpCell;
  15709. }
  15710. UETable.prototype = {
  15711. getMaxRows:function () {
  15712. var rows = this.table.rows, maxLen = 1;
  15713. for (var i = 0, row; row = rows[i]; i++) {
  15714. var currentMax = 1;
  15715. for (var j = 0, cj; cj = row.cells[j++];) {
  15716. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  15717. }
  15718. maxLen = Math.max(currentMax + i, maxLen);
  15719. }
  15720. return maxLen;
  15721. },
  15722. /**
  15723. * 获取当前表格的最大列数
  15724. */
  15725. getMaxCols:function () {
  15726. var rows = this.table.rows, maxLen = 0, cellRows = {};
  15727. for (var i = 0, row; row = rows[i]; i++) {
  15728. var cellsNum = 0;
  15729. for (var j = 0, cj; cj = row.cells[j++];) {
  15730. cellsNum += (cj.colSpan || 1);
  15731. if (cj.rowSpan && cj.rowSpan > 1) {
  15732. for (var k = 1; k < cj.rowSpan; k++) {
  15733. if (!cellRows['row_' + (i + k)]) {
  15734. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  15735. } else {
  15736. cellRows['row_' + (i + k)]++
  15737. }
  15738. }
  15739. }
  15740. }
  15741. cellsNum += cellRows['row_' + i] || 0;
  15742. maxLen = Math.max(cellsNum, maxLen);
  15743. }
  15744. return maxLen;
  15745. },
  15746. getCellColIndex:function (cell) {
  15747. },
  15748. /**
  15749. * 获取当前cell旁边的单元格,
  15750. * @param cell
  15751. * @param right
  15752. */
  15753. getHSideCell:function (cell, right) {
  15754. try {
  15755. var cellInfo = this.getCellInfo(cell),
  15756. previewRowIndex, previewColIndex;
  15757. var len = this.selectedTds.length,
  15758. range = this.cellsRange;
  15759. //首行或者首列没有前置单元格
  15760. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  15761. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  15762. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  15763. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  15764. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  15765. } catch (e) {
  15766. showError(e);
  15767. }
  15768. },
  15769. getTabNextCell:function (cell, preRowIndex) {
  15770. var cellInfo = this.getCellInfo(cell),
  15771. rowIndex = preRowIndex || cellInfo.rowIndex,
  15772. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  15773. nextCell;
  15774. try {
  15775. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  15776. } catch (e) {
  15777. try {
  15778. rowIndex = rowIndex * 1 + 1;
  15779. colIndex = 0;
  15780. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  15781. } catch (e) {
  15782. }
  15783. }
  15784. return nextCell;
  15785. },
  15786. /**
  15787. * 获取视觉上的后置单元格
  15788. * @param cell
  15789. * @param bottom
  15790. */
  15791. getVSideCell:function (cell, bottom, ignoreRange) {
  15792. try {
  15793. var cellInfo = this.getCellInfo(cell),
  15794. nextRowIndex, nextColIndex;
  15795. var len = this.selectedTds.length && !ignoreRange,
  15796. range = this.cellsRange;
  15797. //末行或者末列没有后置单元格
  15798. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  15799. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  15800. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  15801. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  15802. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  15803. } catch (e) {
  15804. showError(e);
  15805. }
  15806. },
  15807. /**
  15808. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  15809. */
  15810. getSameEndPosCells:function (cell, xOrY) {
  15811. try {
  15812. var flag = (xOrY.toLowerCase() === "x"),
  15813. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  15814. rows = this.table.rows,
  15815. cells = null, returns = [];
  15816. for (var i = 0; i < this.rowsNum; i++) {
  15817. cells = rows[i].cells;
  15818. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  15819. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  15820. //对应行的td已经被上面行rowSpan了
  15821. if (tmpEnd > end && flag) break;
  15822. if (cell == tmpCell || end == tmpEnd) {
  15823. //只获取单一的单元格
  15824. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  15825. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  15826. returns.push(tmpCell);
  15827. }
  15828. if (flag) break;
  15829. }
  15830. }
  15831. }
  15832. return returns;
  15833. } catch (e) {
  15834. showError(e);
  15835. }
  15836. },
  15837. setCellContent:function (cell, content) {
  15838. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  15839. },
  15840. cloneCell:UETable.cloneCell,
  15841. /**
  15842. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  15843. */
  15844. getSameStartPosXCells:function (cell) {
  15845. try {
  15846. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  15847. rows = this.table.rows, cells , returns = [];
  15848. for (var i = 0; i < this.rowsNum; i++) {
  15849. cells = rows[i].cells;
  15850. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  15851. var tmpStart = domUtils.getXY(tmpCell).x;
  15852. if (tmpStart > start) break;
  15853. if (tmpStart == start && tmpCell.colSpan == 1) {
  15854. returns.push(tmpCell);
  15855. break;
  15856. }
  15857. }
  15858. }
  15859. return returns;
  15860. } catch (e) {
  15861. showError(e);
  15862. }
  15863. },
  15864. /**
  15865. * 更新table对应的索引表
  15866. */
  15867. update:function (table) {
  15868. this.table = table || this.table;
  15869. this.selectedTds = [];
  15870. this.cellsRange = {};
  15871. this.indexTable = [];
  15872. var rows = this.table.rows,
  15873. rowsNum = this.getMaxRows(),
  15874. dNum = rowsNum - rows.length,
  15875. colsNum = this.getMaxCols();
  15876. while (dNum--) {
  15877. this.table.insertRow(rows.length);
  15878. }
  15879. this.rowsNum = rowsNum;
  15880. this.colsNum = colsNum;
  15881. for (var i = 0, len = rows.length; i < len; i++) {
  15882. this.indexTable[i] = new Array(colsNum);
  15883. }
  15884. //填充索引表
  15885. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  15886. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  15887. //修正整行被rowSpan时导致的行数计算错误
  15888. if (cell.rowSpan > rowsNum) {
  15889. cell.rowSpan = rowsNum;
  15890. }
  15891. var colIndex = cellIndex,
  15892. rowSpan = cell.rowSpan || 1,
  15893. colSpan = cell.colSpan || 1;
  15894. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  15895. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  15896. for (var j = 0; j < rowSpan; j++) {
  15897. for (var k = 0; k < colSpan; k++) {
  15898. this.indexTable[rowIndex + j][colIndex + k] = {
  15899. rowIndex:rowIndex,
  15900. cellIndex:cellIndex,
  15901. colIndex:colIndex,
  15902. rowSpan:rowSpan,
  15903. colSpan:colSpan
  15904. }
  15905. }
  15906. }
  15907. }
  15908. }
  15909. //修复残缺td
  15910. for (j = 0; j < rowsNum; j++) {
  15911. for (k = 0; k < colsNum; k++) {
  15912. if (this.indexTable[j][k] === undefined) {
  15913. row = rows[j];
  15914. cell = row.cells[row.cells.length - 1];
  15915. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  15916. this.setCellContent(cell);
  15917. if (cell.colSpan !== 1)cell.colSpan = 1;
  15918. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  15919. row.appendChild(cell);
  15920. this.indexTable[j][k] = {
  15921. rowIndex:j,
  15922. cellIndex:cell.cellIndex,
  15923. colIndex:k,
  15924. rowSpan:1,
  15925. colSpan:1
  15926. }
  15927. }
  15928. }
  15929. }
  15930. //当框选后删除行或者列后撤销,需要重建选区。
  15931. var tds = domUtils.getElementsByTagName(this.table, "td"),
  15932. selectTds = [];
  15933. utils.each(tds, function (td) {
  15934. if (domUtils.hasClass(td, "selectTdClass")) {
  15935. selectTds.push(td);
  15936. }
  15937. });
  15938. if (selectTds.length) {
  15939. var start = selectTds[0],
  15940. end = selectTds[selectTds.length - 1],
  15941. startInfo = this.getCellInfo(start),
  15942. endInfo = this.getCellInfo(end);
  15943. this.selectedTds = selectTds;
  15944. this.cellsRange = {
  15945. beginRowIndex:startInfo.rowIndex,
  15946. beginColIndex:startInfo.colIndex,
  15947. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  15948. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  15949. };
  15950. }
  15951. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  15952. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  15953. domUtils.addClass(this.table.rows[0], "firstRow");
  15954. for(var i = 1; i< this.table.rows.length; i++) {
  15955. domUtils.removeClasses(this.table.rows[i], "firstRow");
  15956. }
  15957. }
  15958. },
  15959. /**
  15960. * 获取单元格的索引信息
  15961. */
  15962. getCellInfo:function (cell) {
  15963. if (!cell) return;
  15964. var cellIndex = cell.cellIndex,
  15965. rowIndex = cell.parentNode.rowIndex,
  15966. rowInfo = this.indexTable[rowIndex],
  15967. numCols = this.colsNum;
  15968. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  15969. var cellInfo = rowInfo[colIndex];
  15970. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  15971. return cellInfo;
  15972. }
  15973. }
  15974. },
  15975. /**
  15976. * 根据行列号获取单元格
  15977. */
  15978. getCell:function (rowIndex, cellIndex) {
  15979. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  15980. },
  15981. /**
  15982. * 删除单元格
  15983. */
  15984. deleteCell:function (cell, rowIndex) {
  15985. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  15986. var row = this.table.rows[rowIndex];
  15987. row.deleteCell(cell.cellIndex);
  15988. },
  15989. /**
  15990. * 根据始末两个单元格获取被框选的所有单元格范围
  15991. */
  15992. getCellsRange:function (cellA, cellB) {
  15993. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  15994. var tmpBeginRowIndex = beginRowIndex,
  15995. tmpBeginColIndex = beginColIndex,
  15996. tmpEndRowIndex = endRowIndex,
  15997. tmpEndColIndex = endColIndex,
  15998. cellInfo, colIndex, rowIndex;
  15999. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16000. if (beginRowIndex > 0) {
  16001. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16002. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16003. rowIndex = cellInfo.rowIndex;
  16004. if (rowIndex < beginRowIndex) {
  16005. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16006. }
  16007. }
  16008. }
  16009. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16010. if (endColIndex < me.colsNum) {
  16011. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16012. cellInfo = me.indexTable[rowIndex][endColIndex];
  16013. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16014. if (colIndex > endColIndex) {
  16015. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16016. }
  16017. }
  16018. }
  16019. // 检查是否有超出TableRange下边界的情况
  16020. if (endRowIndex < me.rowsNum) {
  16021. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16022. cellInfo = me.indexTable[endRowIndex][colIndex];
  16023. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16024. if (rowIndex > endRowIndex) {
  16025. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16026. }
  16027. }
  16028. }
  16029. // 检查是否有超出TableRange左边界的情况
  16030. if (beginColIndex > 0) {
  16031. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16032. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16033. colIndex = cellInfo.colIndex;
  16034. if (colIndex < beginColIndex) {
  16035. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16036. }
  16037. }
  16038. }
  16039. //递归调用直至所有完成所有框选单元格的扩展
  16040. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16041. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16042. } else {
  16043. // 不需要扩展TableRange的情况
  16044. return {
  16045. beginRowIndex:beginRowIndex,
  16046. beginColIndex:beginColIndex,
  16047. endRowIndex:endRowIndex,
  16048. endColIndex:endColIndex
  16049. };
  16050. }
  16051. }
  16052. try {
  16053. var me = this,
  16054. cellAInfo = me.getCellInfo(cellA);
  16055. if (cellA === cellB) {
  16056. return {
  16057. beginRowIndex:cellAInfo.rowIndex,
  16058. beginColIndex:cellAInfo.colIndex,
  16059. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16060. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16061. };
  16062. }
  16063. var cellBInfo = me.getCellInfo(cellB);
  16064. // 计算TableRange的四个边
  16065. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16066. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16067. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16068. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16069. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16070. } catch (e) {
  16071. //throw e;
  16072. }
  16073. },
  16074. /**
  16075. * 依据cellsRange获取对应的单元格集合
  16076. */
  16077. getCells:function (range) {
  16078. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16079. this.clearSelected();
  16080. var beginRowIndex = range.beginRowIndex,
  16081. beginColIndex = range.beginColIndex,
  16082. endRowIndex = range.endRowIndex,
  16083. endColIndex = range.endColIndex,
  16084. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16085. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16086. for (var j = beginColIndex; j <= endColIndex; j++) {
  16087. cellInfo = this.indexTable[i][j];
  16088. rowIndex = cellInfo.rowIndex;
  16089. colIndex = cellInfo.colIndex;
  16090. // 如果Cells里已经包含了此Cell则跳过
  16091. var key = rowIndex + '|' + colIndex;
  16092. if (tdHash[key]) continue;
  16093. tdHash[key] = 1;
  16094. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16095. return null;
  16096. }
  16097. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16098. }
  16099. }
  16100. return returnTds;
  16101. },
  16102. /**
  16103. * 清理已经选中的单元格
  16104. */
  16105. clearSelected:function () {
  16106. UETable.removeSelectedClass(this.selectedTds);
  16107. this.selectedTds = [];
  16108. this.cellsRange = {};
  16109. },
  16110. /**
  16111. * 根据range设置已经选中的单元格
  16112. */
  16113. setSelected:function (range) {
  16114. var cells = this.getCells(range);
  16115. UETable.addSelectedClass(cells);
  16116. this.selectedTds = cells;
  16117. this.cellsRange = range;
  16118. },
  16119. isFullRow:function () {
  16120. var range = this.cellsRange;
  16121. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16122. },
  16123. isFullCol:function () {
  16124. var range = this.cellsRange,
  16125. table = this.table,
  16126. ths = table.getElementsByTagName("th"),
  16127. rows = range.endRowIndex - range.beginRowIndex + 1;
  16128. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16129. },
  16130. /**
  16131. * 获取视觉上的前置单元格,默认是左边,top传入时
  16132. * @param cell
  16133. * @param top
  16134. */
  16135. getNextCell:function (cell, bottom, ignoreRange) {
  16136. try {
  16137. var cellInfo = this.getCellInfo(cell),
  16138. nextRowIndex, nextColIndex;
  16139. var len = this.selectedTds.length && !ignoreRange,
  16140. range = this.cellsRange;
  16141. //末行或者末列没有后置单元格
  16142. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16143. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16144. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16145. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16146. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16147. } catch (e) {
  16148. showError(e);
  16149. }
  16150. },
  16151. getPreviewCell:function (cell, top) {
  16152. try {
  16153. var cellInfo = this.getCellInfo(cell),
  16154. previewRowIndex, previewColIndex;
  16155. var len = this.selectedTds.length,
  16156. range = this.cellsRange;
  16157. //首行或者首列没有前置单元格
  16158. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16159. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  16160. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  16161. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16162. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  16163. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16164. } catch (e) {
  16165. showError(e);
  16166. }
  16167. },
  16168. /**
  16169. * 移动单元格中的内容
  16170. */
  16171. moveContent:function (cellTo, cellFrom) {
  16172. if (UETable.isEmptyBlock(cellFrom)) return;
  16173. if (UETable.isEmptyBlock(cellTo)) {
  16174. cellTo.innerHTML = cellFrom.innerHTML;
  16175. return;
  16176. }
  16177. var child = cellTo.lastChild;
  16178. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  16179. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  16180. }
  16181. while (child = cellFrom.firstChild) {
  16182. cellTo.appendChild(child);
  16183. }
  16184. },
  16185. /**
  16186. * 向右合并单元格
  16187. */
  16188. mergeRight:function (cell) {
  16189. var cellInfo = this.getCellInfo(cell),
  16190. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  16191. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  16192. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  16193. //合并
  16194. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  16195. //被合并的单元格不应存在宽度属性
  16196. cell.removeAttribute("width");
  16197. //移动内容
  16198. this.moveContent(cell, rightCell);
  16199. //删掉被合并的Cell
  16200. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  16201. this.update();
  16202. },
  16203. /**
  16204. * 向下合并单元格
  16205. */
  16206. mergeDown:function (cell) {
  16207. var cellInfo = this.getCellInfo(cell),
  16208. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  16209. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  16210. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  16211. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  16212. cell.removeAttribute("height");
  16213. this.moveContent(cell, downCell);
  16214. this.deleteCell(downCell, downCellInfo.rowIndex);
  16215. this.update();
  16216. },
  16217. /**
  16218. * 合并整个range中的内容
  16219. */
  16220. mergeRange:function () {
  16221. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  16222. var range = this.cellsRange,
  16223. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  16224. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  16225. var index = this.indexTable,
  16226. info = this.getCellInfo(leftTopCell);
  16227. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  16228. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  16229. }
  16230. // 删除剩余的Cells
  16231. var cells = this.getCells(range);
  16232. for(var i= 0,ci;ci=cells[i++];){
  16233. if (ci !== leftTopCell) {
  16234. this.moveContent(leftTopCell, ci);
  16235. this.deleteCell(ci);
  16236. }
  16237. }
  16238. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  16239. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  16240. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  16241. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  16242. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  16243. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  16244. leftTopCell.colSpan = 1;
  16245. }
  16246. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  16247. var rowIndex = leftTopCell.parentNode.rowIndex;
  16248. //解决IE下的表格操作问题
  16249. if( this.table.deleteRow ) {
  16250. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  16251. this.table.deleteRow(curIndex);
  16252. }
  16253. } else {
  16254. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  16255. var row = this.table.rows[rowIndex + 1];
  16256. row.parentNode.removeChild(row);
  16257. }
  16258. }
  16259. leftTopCell.rowSpan = 1;
  16260. }
  16261. this.update();
  16262. },
  16263. /**
  16264. * 插入一行单元格
  16265. */
  16266. insertRow:function (rowIndex, sourceCell) {
  16267. var numCols = this.colsNum,
  16268. table = this.table,
  16269. row = table.insertRow(rowIndex), cell,
  16270. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  16271. function replaceTdToTh(colIndex, cell, tableRow) {
  16272. if (colIndex == 0) {
  16273. var tr = tableRow.nextSibling || tableRow.previousSibling,
  16274. th = tr.cells[colIndex];
  16275. if (th.tagName == 'TH') {
  16276. th = cell.ownerDocument.createElement("th");
  16277. th.appendChild(cell.firstChild);
  16278. tableRow.insertBefore(th, cell);
  16279. domUtils.remove(cell)
  16280. }
  16281. }else{
  16282. if (cell.tagName == 'TH') {
  16283. var td = cell.ownerDocument.createElement("td");
  16284. td.appendChild(cell.firstChild);
  16285. tableRow.insertBefore(td, cell);
  16286. domUtils.remove(cell)
  16287. }
  16288. }
  16289. }
  16290. //首行直接插入,无需考虑部分单元格被rowspan的情况
  16291. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  16292. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  16293. cell = this.cloneCell(sourceCell, true);
  16294. this.setCellContent(cell);
  16295. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16296. row.appendChild(cell);
  16297. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  16298. }
  16299. } else {
  16300. var infoRow = this.indexTable[rowIndex],
  16301. cellIndex = 0;
  16302. for (colIndex = 0; colIndex < numCols; colIndex++) {
  16303. var cellInfo = infoRow[colIndex];
  16304. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  16305. if (cellInfo.rowIndex < rowIndex) {
  16306. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16307. cell.rowSpan = cellInfo.rowSpan + 1;
  16308. } else {
  16309. cell = this.cloneCell(sourceCell, true);
  16310. this.setCellContent(cell);
  16311. row.appendChild(cell);
  16312. }
  16313. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  16314. }
  16315. }
  16316. //框选时插入不触发contentchange,需要手动更新索引。
  16317. this.update();
  16318. return row;
  16319. },
  16320. /**
  16321. * 删除一行单元格
  16322. * @param rowIndex
  16323. */
  16324. deleteRow:function (rowIndex) {
  16325. var row = this.table.rows[rowIndex],
  16326. infoRow = this.indexTable[rowIndex],
  16327. colsNum = this.colsNum,
  16328. count = 0; //处理计数
  16329. for (var colIndex = 0; colIndex < colsNum;) {
  16330. var cellInfo = infoRow[colIndex],
  16331. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16332. if (cell.rowSpan > 1) {
  16333. if (cellInfo.rowIndex == rowIndex) {
  16334. var clone = cell.cloneNode(true);
  16335. clone.rowSpan = cell.rowSpan - 1;
  16336. clone.innerHTML = "";
  16337. cell.rowSpan = 1;
  16338. var nextRowIndex = rowIndex + 1,
  16339. nextRow = this.table.rows[nextRowIndex],
  16340. insertCellIndex,
  16341. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  16342. if (preMerged < colIndex) {
  16343. insertCellIndex = colIndex - preMerged - 1;
  16344. //nextRow.insertCell(insertCellIndex);
  16345. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  16346. } else {
  16347. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  16348. }
  16349. count += 1;
  16350. //cell.parentNode.removeChild(cell);
  16351. }
  16352. }
  16353. colIndex += cell.colSpan || 1;
  16354. }
  16355. var deleteTds = [], cacheMap = {};
  16356. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  16357. var tmpRowIndex = infoRow[colIndex].rowIndex,
  16358. tmpCellIndex = infoRow[colIndex].cellIndex,
  16359. key = tmpRowIndex + "_" + tmpCellIndex;
  16360. if (cacheMap[key])continue;
  16361. cacheMap[key] = 1;
  16362. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  16363. deleteTds.push(cell);
  16364. }
  16365. var mergeTds = [];
  16366. utils.each(deleteTds, function (td) {
  16367. if (td.rowSpan == 1) {
  16368. td.parentNode.removeChild(td);
  16369. } else {
  16370. mergeTds.push(td);
  16371. }
  16372. });
  16373. utils.each(mergeTds, function (td) {
  16374. td.rowSpan--;
  16375. });
  16376. row.parentNode.removeChild(row);
  16377. //浏览器方法本身存在bug,采用自定义方法删除
  16378. //this.table.deleteRow(rowIndex);
  16379. this.update();
  16380. },
  16381. insertCol:function (colIndex, sourceCell, defaultValue) {
  16382. var rowsNum = this.rowsNum,
  16383. rowIndex = 0,
  16384. tableRow, cell,
  16385. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  16386. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  16387. function replaceTdToTh(rowIndex, cell, tableRow) {
  16388. if (rowIndex == 0) {
  16389. var th = cell.nextSibling || cell.previousSibling;
  16390. if (th.tagName == 'TH') {
  16391. th = cell.ownerDocument.createElement("th");
  16392. th.appendChild(cell.firstChild);
  16393. tableRow.insertBefore(th, cell);
  16394. domUtils.remove(cell)
  16395. }
  16396. }else{
  16397. if (cell.tagName == 'TH') {
  16398. var td = cell.ownerDocument.createElement("td");
  16399. td.appendChild(cell.firstChild);
  16400. tableRow.insertBefore(td, cell);
  16401. domUtils.remove(cell)
  16402. }
  16403. }
  16404. }
  16405. var preCell;
  16406. if (colIndex == 0 || colIndex == this.colsNum) {
  16407. for (; rowIndex < rowsNum; rowIndex++) {
  16408. tableRow = this.table.rows[rowIndex];
  16409. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  16410. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  16411. this.setCellContent(cell);
  16412. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16413. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  16414. if (!colIndex) {
  16415. tableRow.insertBefore(cell, tableRow.cells[0]);
  16416. } else {
  16417. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  16418. }
  16419. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  16420. }
  16421. } else {
  16422. for (; rowIndex < rowsNum; rowIndex++) {
  16423. var cellInfo = this.indexTable[rowIndex][colIndex];
  16424. if (cellInfo.colIndex < colIndex) {
  16425. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16426. cell.colSpan = cellInfo.colSpan + 1;
  16427. } else {
  16428. tableRow = this.table.rows[rowIndex];
  16429. preCell = tableRow.cells[cellInfo.cellIndex];
  16430. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  16431. this.setCellContent(cell);
  16432. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16433. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  16434. //防止IE下报错
  16435. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  16436. }
  16437. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  16438. }
  16439. }
  16440. //框选时插入不触发contentchange,需要手动更新索引
  16441. this.update();
  16442. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  16443. },
  16444. updateWidth:function (width, defaultValue) {
  16445. var table = this.table,
  16446. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  16447. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  16448. table.setAttribute("width", tmpWidth);
  16449. return;
  16450. }
  16451. var tds = domUtils.getElementsByTagName(this.table, "td th");
  16452. utils.each(tds, function (td) {
  16453. td.setAttribute("width", width);
  16454. })
  16455. },
  16456. deleteCol:function (colIndex) {
  16457. var indexTable = this.indexTable,
  16458. tableRows = this.table.rows,
  16459. backTableWidth = this.table.getAttribute("width"),
  16460. backTdWidth = 0,
  16461. rowsNum = this.rowsNum,
  16462. cacheMap = {};
  16463. for (var rowIndex = 0; rowIndex < rowsNum;) {
  16464. var infoRow = indexTable[rowIndex],
  16465. cellInfo = infoRow[colIndex],
  16466. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  16467. // 跳过已经处理过的Cell
  16468. if (cacheMap[key])continue;
  16469. cacheMap[key] = 1;
  16470. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  16471. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  16472. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  16473. if (cell.colSpan > 1) {
  16474. cell.colSpan--;
  16475. } else {
  16476. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  16477. }
  16478. rowIndex += cellInfo.rowSpan || 1;
  16479. }
  16480. this.table.setAttribute("width", backTableWidth - backTdWidth);
  16481. this.update();
  16482. },
  16483. splitToCells:function (cell) {
  16484. var me = this,
  16485. cells = this.splitToRows(cell);
  16486. utils.each(cells, function (cell) {
  16487. me.splitToCols(cell);
  16488. })
  16489. },
  16490. splitToRows:function (cell) {
  16491. var cellInfo = this.getCellInfo(cell),
  16492. rowIndex = cellInfo.rowIndex,
  16493. colIndex = cellInfo.colIndex,
  16494. results = [];
  16495. // 修改Cell的rowSpan
  16496. cell.rowSpan = 1;
  16497. results.push(cell);
  16498. // 补齐单元格
  16499. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  16500. if (i == rowIndex)continue;
  16501. var tableRow = this.table.rows[i],
  16502. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  16503. tmpCell.colSpan = cellInfo.colSpan;
  16504. this.setCellContent(tmpCell);
  16505. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16506. tmpCell.setAttribute('align', cell.getAttribute('align'));
  16507. if (cell.style.cssText) {
  16508. tmpCell.style.cssText = cell.style.cssText;
  16509. }
  16510. results.push(tmpCell);
  16511. }
  16512. this.update();
  16513. return results;
  16514. },
  16515. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  16516. var indexRow = this.indexTable[rowIndex],
  16517. num = 0;
  16518. for (var i = 0; i < colIndex;) {
  16519. var colSpan = indexRow[i].colSpan,
  16520. tmpRowIndex = indexRow[i].rowIndex;
  16521. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  16522. i += colSpan;
  16523. }
  16524. return num;
  16525. },
  16526. splitToCols:function (cell) {
  16527. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  16528. cellInfo = this.getCellInfo(cell),
  16529. rowIndex = cellInfo.rowIndex,
  16530. colIndex = cellInfo.colIndex,
  16531. results = [];
  16532. // 修改Cell的rowSpan
  16533. cell.colSpan = 1;
  16534. cell.setAttribute("width", backWidth);
  16535. results.push(cell);
  16536. // 补齐单元格
  16537. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  16538. if (j == colIndex)continue;
  16539. var tableRow = this.table.rows[rowIndex],
  16540. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  16541. tmpCell.rowSpan = cellInfo.rowSpan;
  16542. this.setCellContent(tmpCell);
  16543. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16544. tmpCell.setAttribute('align', cell.getAttribute('align'));
  16545. tmpCell.setAttribute('width', backWidth);
  16546. if (cell.style.cssText) {
  16547. tmpCell.style.cssText = cell.style.cssText;
  16548. }
  16549. //处理th的情况
  16550. if (cell.tagName == 'TH') {
  16551. var th = cell.ownerDocument.createElement('th');
  16552. th.appendChild(tmpCell.firstChild);
  16553. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  16554. th.rowSpan = tmpCell.rowSpan;
  16555. tableRow.insertBefore(th, tmpCell);
  16556. domUtils.remove(tmpCell);
  16557. }
  16558. results.push(tmpCell);
  16559. }
  16560. this.update();
  16561. return results;
  16562. },
  16563. isLastCell:function (cell, rowsNum, colsNum) {
  16564. rowsNum = rowsNum || this.rowsNum;
  16565. colsNum = colsNum || this.colsNum;
  16566. var cellInfo = this.getCellInfo(cell);
  16567. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  16568. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  16569. },
  16570. getLastCell:function (cells) {
  16571. cells = cells || this.table.getElementsByTagName("td");
  16572. var firstInfo = this.getCellInfo(cells[0]);
  16573. var me = this, last = cells[0],
  16574. tr = last.parentNode,
  16575. cellsNum = 0, cols = 0, rows;
  16576. utils.each(cells, function (cell) {
  16577. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  16578. cellsNum += cell.rowSpan * cell.colSpan || 1;
  16579. });
  16580. rows = cellsNum / cols;
  16581. utils.each(cells, function (cell) {
  16582. if (me.isLastCell(cell, rows, cols)) {
  16583. last = cell;
  16584. return false;
  16585. }
  16586. });
  16587. return last;
  16588. },
  16589. selectRow:function (rowIndex) {
  16590. var indexRow = this.indexTable[rowIndex],
  16591. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  16592. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  16593. range = this.getCellsRange(start, end);
  16594. this.setSelected(range);
  16595. },
  16596. selectTable:function () {
  16597. var tds = this.table.getElementsByTagName("td"),
  16598. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  16599. this.setSelected(range);
  16600. },
  16601. setBackground:function (cells, value) {
  16602. if (typeof value === "string") {
  16603. utils.each(cells, function (cell) {
  16604. cell.style.backgroundColor = value;
  16605. })
  16606. } else if (typeof value === "object") {
  16607. value = utils.extend({
  16608. repeat:true,
  16609. colorList:["#ddd", "#fff"]
  16610. }, value);
  16611. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  16612. count = 0,
  16613. colors = value.colorList,
  16614. getColor = function (list, index, repeat) {
  16615. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  16616. };
  16617. for (var i = 0, cell; cell = cells[i++];) {
  16618. var cellInfo = this.getCellInfo(cell);
  16619. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  16620. }
  16621. }
  16622. },
  16623. removeBackground:function (cells) {
  16624. utils.each(cells, function (cell) {
  16625. cell.style.backgroundColor = "";
  16626. })
  16627. }
  16628. };
  16629. function showError(e) {
  16630. }
  16631. })();
  16632. /**
  16633. * Created with JetBrains PhpStorm.
  16634. * User: taoqili
  16635. * Date: 13-2-20
  16636. * Time: 下午6:25
  16637. * To change this template use File | Settings | File Templates.
  16638. */
  16639. ;
  16640. (function () {
  16641. var UT = UE.UETable,
  16642. getTableItemsByRange = function (editor) {
  16643. return UT.getTableItemsByRange(editor);
  16644. },
  16645. getUETableBySelected = function (editor) {
  16646. return UT.getUETableBySelected(editor)
  16647. },
  16648. getDefaultValue = function (editor, table) {
  16649. return UT.getDefaultValue(editor, table);
  16650. },
  16651. getUETable = function (tdOrTable) {
  16652. return UT.getUETable(tdOrTable);
  16653. };
  16654. UE.commands['inserttable'] = {
  16655. queryCommandState: function () {
  16656. return getTableItemsByRange(this).table ? -1 : 0;
  16657. },
  16658. execCommand: function (cmd, opt) {
  16659. function createTable(opt, tdWidth) {
  16660. var html = [],
  16661. rowsNum = opt.numRows,
  16662. colsNum = opt.numCols;
  16663. for (var r = 0; r < rowsNum; r++) {
  16664. html.push('<tr>');
  16665. for (var c = 0; c < colsNum; c++) {
  16666. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie ? domUtils.fillChar : '<br/>') + '</td>')
  16667. }
  16668. html.push('</tr>')
  16669. }
  16670. //禁止指定table-width
  16671. return '<table><tbody>' + html.join('') + '</tbody></table>'
  16672. }
  16673. if (!opt) {
  16674. opt = utils.extend({}, {
  16675. numCols: this.options.defaultCols,
  16676. numRows: this.options.defaultRows,
  16677. tdvalign: this.options.tdvalign
  16678. })
  16679. }
  16680. var me = this;
  16681. var range = this.selection.getRange(),
  16682. start = range.startContainer,
  16683. firstParentBlock = domUtils.findParent(start, function (node) {
  16684. return domUtils.isBlockElm(node);
  16685. }, true) || me.body;
  16686. var defaultValue = getDefaultValue(me),
  16687. tableWidth = firstParentBlock.offsetWidth,
  16688. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  16689. //todo其他属性
  16690. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  16691. me.execCommand("inserthtml", createTable(opt, tdWidth));
  16692. }
  16693. };
  16694. UE.commands['insertparagraphbeforetable'] = {
  16695. queryCommandState: function () {
  16696. return getTableItemsByRange(this).cell ? 0 : -1;
  16697. },
  16698. execCommand: function () {
  16699. var table = getTableItemsByRange(this).table;
  16700. if (table) {
  16701. var p = this.document.createElement("p");
  16702. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  16703. table.parentNode.insertBefore(p, table);
  16704. this.selection.getRange().setStart(p, 0).setCursor();
  16705. }
  16706. }
  16707. };
  16708. UE.commands['deletetable'] = {
  16709. queryCommandState: function () {
  16710. var rng = this.selection.getRange();
  16711. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  16712. },
  16713. execCommand: function (cmd, table) {
  16714. var rng = this.selection.getRange();
  16715. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  16716. if (table) {
  16717. var next = table.nextSibling;
  16718. if (!next) {
  16719. next = domUtils.createElement(this.document, 'p', {
  16720. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  16721. });
  16722. table.parentNode.insertBefore(next, table);
  16723. }
  16724. domUtils.remove(table);
  16725. rng = this.selection.getRange();
  16726. if (next.nodeType == 3) {
  16727. rng.setStartBefore(next)
  16728. } else {
  16729. rng.setStart(next, 0)
  16730. }
  16731. rng.setCursor(false, true)
  16732. this.fireEvent("tablehasdeleted")
  16733. }
  16734. }
  16735. };
  16736. UE.commands['cellalign'] = {
  16737. queryCommandState: function () {
  16738. return getSelectedArr(this).length ? 0 : -1
  16739. },
  16740. execCommand: function (cmd, align) {
  16741. var selectedTds = getSelectedArr(this);
  16742. if (selectedTds.length) {
  16743. for (var i = 0, ci; ci = selectedTds[i++];) {
  16744. ci.setAttribute('align', align);
  16745. }
  16746. }
  16747. }
  16748. };
  16749. UE.commands['cellvalign'] = {
  16750. queryCommandState: function () {
  16751. return getSelectedArr(this).length ? 0 : -1;
  16752. },
  16753. execCommand: function (cmd, valign) {
  16754. var selectedTds = getSelectedArr(this);
  16755. if (selectedTds.length) {
  16756. for (var i = 0, ci; ci = selectedTds[i++];) {
  16757. ci.setAttribute('vAlign', valign);
  16758. }
  16759. }
  16760. }
  16761. };
  16762. UE.commands['insertcaption'] = {
  16763. queryCommandState: function () {
  16764. var table = getTableItemsByRange(this).table;
  16765. if (table) {
  16766. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  16767. }
  16768. return -1;
  16769. },
  16770. execCommand: function () {
  16771. var table = getTableItemsByRange(this).table;
  16772. if (table) {
  16773. var caption = this.document.createElement('caption');
  16774. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  16775. table.insertBefore(caption, table.firstChild);
  16776. var range = this.selection.getRange();
  16777. range.setStart(caption, 0).setCursor();
  16778. }
  16779. }
  16780. };
  16781. UE.commands['deletecaption'] = {
  16782. queryCommandState: function () {
  16783. var rng = this.selection.getRange(),
  16784. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  16785. if (table) {
  16786. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  16787. }
  16788. return -1;
  16789. },
  16790. execCommand: function () {
  16791. var rng = this.selection.getRange(),
  16792. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  16793. if (table) {
  16794. domUtils.remove(table.getElementsByTagName('caption')[0]);
  16795. var range = this.selection.getRange();
  16796. range.setStart(table.rows[0].cells[0], 0).setCursor();
  16797. }
  16798. }
  16799. };
  16800. UE.commands['inserttitle'] = {
  16801. queryCommandState: function () {
  16802. var table = getTableItemsByRange(this).table;
  16803. if (table) {
  16804. var firstRow = table.rows[0];
  16805. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  16806. }
  16807. return -1;
  16808. },
  16809. execCommand: function () {
  16810. var table = getTableItemsByRange(this).table;
  16811. if (table) {
  16812. getUETable(table).insertRow(0, 'th');
  16813. }
  16814. var th = table.getElementsByTagName('th')[0];
  16815. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  16816. }
  16817. };
  16818. UE.commands['deletetitle'] = {
  16819. queryCommandState: function () {
  16820. var table = getTableItemsByRange(this).table;
  16821. if (table) {
  16822. var firstRow = table.rows[0];
  16823. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  16824. }
  16825. return -1;
  16826. },
  16827. execCommand: function () {
  16828. var table = getTableItemsByRange(this).table;
  16829. if (table) {
  16830. domUtils.remove(table.rows[0])
  16831. }
  16832. var td = table.getElementsByTagName('td')[0];
  16833. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  16834. }
  16835. };
  16836. UE.commands['inserttitlecol'] = {
  16837. queryCommandState: function () {
  16838. var table = getTableItemsByRange(this).table;
  16839. if (table) {
  16840. var lastRow = table.rows[table.rows.length-1];
  16841. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  16842. }
  16843. return -1;
  16844. },
  16845. execCommand: function (cmd) {
  16846. var table = getTableItemsByRange(this).table;
  16847. if (table) {
  16848. getUETable(table).insertCol(0, 'th');
  16849. }
  16850. resetTdWidth(table, this);
  16851. var th = table.getElementsByTagName('th')[0];
  16852. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  16853. }
  16854. };
  16855. UE.commands['deletetitlecol'] = {
  16856. queryCommandState: function () {
  16857. var table = getTableItemsByRange(this).table;
  16858. if (table) {
  16859. var lastRow = table.rows[table.rows.length-1];
  16860. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  16861. }
  16862. return -1;
  16863. },
  16864. execCommand: function () {
  16865. var table = getTableItemsByRange(this).table;
  16866. if (table) {
  16867. for(var i = 0; i< table.rows.length; i++ ){
  16868. domUtils.remove(table.rows[i].children[0])
  16869. }
  16870. }
  16871. resetTdWidth(table, this);
  16872. var td = table.getElementsByTagName('td')[0];
  16873. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  16874. }
  16875. };
  16876. UE.commands["mergeright"] = {
  16877. queryCommandState: function (cmd) {
  16878. var tableItems = getTableItemsByRange(this);
  16879. if (!tableItems.cell) return -1;
  16880. var ut = getUETable(tableItems.table);
  16881. if (ut.selectedTds.length) return -1;
  16882. var cellInfo = ut.getCellInfo(tableItems.cell),
  16883. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  16884. if (rightColIndex >= ut.colsNum) return -1;
  16885. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex];
  16886. return (rightCellInfo.rowIndex == cellInfo.rowIndex
  16887. && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  16888. },
  16889. execCommand: function (cmd) {
  16890. var rng = this.selection.getRange(),
  16891. bk = rng.createBookmark(true);
  16892. var cell = getTableItemsByRange(this).cell,
  16893. ut = getUETable(cell);
  16894. ut.mergeRight(cell);
  16895. rng.moveToBookmark(bk).select();
  16896. }
  16897. };
  16898. UE.commands["mergedown"] = {
  16899. queryCommandState: function (cmd) {
  16900. var tableItems = getTableItemsByRange(this),
  16901. cell = tableItems.cell;
  16902. if (!cell || cell.tagName == "TH") return -1;
  16903. var ut = getUETable(tableItems.table);
  16904. if (ut.selectedTds.length)return -1;
  16905. var cellInfo = ut.getCellInfo(tableItems.cell),
  16906. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  16907. // 如果处于最下边则不能f向右合并
  16908. if (downRowIndex >= ut.rowsNum) return -1;
  16909. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex];
  16910. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  16911. return (downCellInfo.colIndex == cellInfo.colIndex
  16912. && downCellInfo.colSpan == cellInfo.colSpan) && tableItems.cell.tagName !== 'TH' ? 0 : -1;
  16913. },
  16914. execCommand: function () {
  16915. var rng = this.selection.getRange(),
  16916. bk = rng.createBookmark(true);
  16917. var cell = getTableItemsByRange(this).cell,
  16918. ut = getUETable(cell);
  16919. ut.mergeDown(cell);
  16920. rng.moveToBookmark(bk).select();
  16921. }
  16922. };
  16923. UE.commands["mergecells"] = {
  16924. queryCommandState: function () {
  16925. return getUETableBySelected(this) ? 0 : -1;
  16926. },
  16927. execCommand: function () {
  16928. var ut = getUETableBySelected(this);
  16929. if (ut && ut.selectedTds.length) {
  16930. var cell = ut.selectedTds[0];
  16931. ut.mergeRange();
  16932. var rng = this.selection.getRange();
  16933. if (domUtils.isEmptyBlock(cell)) {
  16934. rng.setStart(cell, 0).collapse(true)
  16935. } else {
  16936. rng.selectNodeContents(cell)
  16937. }
  16938. rng.select();
  16939. }
  16940. }
  16941. };
  16942. UE.commands["insertrow"] = {
  16943. queryCommandState: function () {
  16944. var tableItems = getTableItemsByRange(this),
  16945. cell = tableItems.cell;
  16946. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  16947. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  16948. },
  16949. execCommand: function () {
  16950. var rng = this.selection.getRange(),
  16951. bk = rng.createBookmark(true);
  16952. var tableItems = getTableItemsByRange(this),
  16953. cell = tableItems.cell,
  16954. table = tableItems.table,
  16955. ut = getUETable(table),
  16956. cellInfo = ut.getCellInfo(cell);
  16957. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  16958. if (!ut.selectedTds.length) {
  16959. ut.insertRow(cellInfo.rowIndex, cell);
  16960. } else {
  16961. var range = ut.cellsRange;
  16962. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  16963. ut.insertRow(range.beginRowIndex, cell);
  16964. }
  16965. }
  16966. rng.moveToBookmark(bk).select();
  16967. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  16968. }
  16969. };
  16970. //后插入行
  16971. UE.commands["insertrownext"] = {
  16972. queryCommandState: function () {
  16973. var tableItems = getTableItemsByRange(this),
  16974. cell = tableItems.cell;
  16975. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  16976. },
  16977. execCommand: function () {
  16978. var rng = this.selection.getRange(),
  16979. bk = rng.createBookmark(true);
  16980. var tableItems = getTableItemsByRange(this),
  16981. cell = tableItems.cell,
  16982. table = tableItems.table,
  16983. ut = getUETable(table),
  16984. cellInfo = ut.getCellInfo(cell);
  16985. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  16986. if (!ut.selectedTds.length) {
  16987. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  16988. } else {
  16989. var range = ut.cellsRange;
  16990. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  16991. ut.insertRow(range.endRowIndex + 1, cell);
  16992. }
  16993. }
  16994. rng.moveToBookmark(bk).select();
  16995. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  16996. }
  16997. };
  16998. UE.commands["deleterow"] = {
  16999. queryCommandState: function () {
  17000. var tableItems = getTableItemsByRange(this);
  17001. if (!tableItems.cell) {
  17002. return -1;
  17003. }
  17004. },
  17005. execCommand: function () {
  17006. var cell = getTableItemsByRange(this).cell,
  17007. ut = getUETable(cell),
  17008. cellsRange = ut.cellsRange,
  17009. cellInfo = ut.getCellInfo(cell),
  17010. preCell = ut.getVSideCell(cell),
  17011. nextCell = ut.getVSideCell(cell, true),
  17012. rng = this.selection.getRange();
  17013. if (utils.isEmptyObject(cellsRange)) {
  17014. ut.deleteRow(cellInfo.rowIndex);
  17015. } else {
  17016. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17017. ut.deleteRow(cellsRange.beginRowIndex);
  17018. }
  17019. }
  17020. var table = ut.table;
  17021. if (!table.getElementsByTagName('td').length) {
  17022. var nextSibling = table.nextSibling;
  17023. domUtils.remove(table);
  17024. if (nextSibling) {
  17025. rng.setStart(nextSibling, 0).setCursor(false, true);
  17026. }
  17027. } else {
  17028. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17029. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17030. } else {
  17031. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17032. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17033. }
  17034. }
  17035. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17036. }
  17037. };
  17038. UE.commands["insertcol"] = {
  17039. queryCommandState: function (cmd) {
  17040. var tableItems = getTableItemsByRange(this),
  17041. cell = tableItems.cell;
  17042. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17043. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17044. },
  17045. execCommand: function (cmd) {
  17046. var rng = this.selection.getRange(),
  17047. bk = rng.createBookmark(true);
  17048. if (this.queryCommandState(cmd) == -1)return;
  17049. var cell = getTableItemsByRange(this).cell,
  17050. ut = getUETable(cell),
  17051. cellInfo = ut.getCellInfo(cell);
  17052. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17053. if (!ut.selectedTds.length) {
  17054. ut.insertCol(cellInfo.colIndex, cell);
  17055. } else {
  17056. var range = ut.cellsRange;
  17057. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17058. ut.insertCol(range.beginColIndex, cell);
  17059. }
  17060. }
  17061. rng.moveToBookmark(bk).select(true);
  17062. }
  17063. };
  17064. UE.commands["insertcolnext"] = {
  17065. queryCommandState: function () {
  17066. var tableItems = getTableItemsByRange(this),
  17067. cell = tableItems.cell;
  17068. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17069. },
  17070. execCommand: function () {
  17071. var rng = this.selection.getRange(),
  17072. bk = rng.createBookmark(true);
  17073. var cell = getTableItemsByRange(this).cell,
  17074. ut = getUETable(cell),
  17075. cellInfo = ut.getCellInfo(cell);
  17076. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17077. if (!ut.selectedTds.length) {
  17078. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17079. } else {
  17080. var range = ut.cellsRange;
  17081. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17082. ut.insertCol(range.endColIndex + 1, cell);
  17083. }
  17084. }
  17085. rng.moveToBookmark(bk).select();
  17086. }
  17087. };
  17088. UE.commands["deletecol"] = {
  17089. queryCommandState: function () {
  17090. var tableItems = getTableItemsByRange(this);
  17091. if (!tableItems.cell) return -1;
  17092. },
  17093. execCommand: function () {
  17094. var cell = getTableItemsByRange(this).cell,
  17095. ut = getUETable(cell),
  17096. range = ut.cellsRange,
  17097. cellInfo = ut.getCellInfo(cell),
  17098. preCell = ut.getHSideCell(cell),
  17099. nextCell = ut.getHSideCell(cell, true);
  17100. if (utils.isEmptyObject(range)) {
  17101. ut.deleteCol(cellInfo.colIndex);
  17102. } else {
  17103. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17104. ut.deleteCol(range.beginColIndex);
  17105. }
  17106. }
  17107. var table = ut.table,
  17108. rng = this.selection.getRange();
  17109. if (!table.getElementsByTagName('td').length) {
  17110. var nextSibling = table.nextSibling;
  17111. domUtils.remove(table);
  17112. if (nextSibling) {
  17113. rng.setStart(nextSibling, 0).setCursor(false, true);
  17114. }
  17115. } else {
  17116. if (domUtils.inDoc(cell, this.document)) {
  17117. rng.setStart(cell, 0).setCursor(false, true);
  17118. } else {
  17119. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17120. rng.selectNodeContents(nextCell).setCursor(false, true);
  17121. } else {
  17122. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17123. rng.selectNodeContents(preCell).setCursor(true, true);
  17124. }
  17125. }
  17126. }
  17127. }
  17128. }
  17129. };
  17130. UE.commands["splittocells"] = {
  17131. queryCommandState: function () {
  17132. var tableItems = getTableItemsByRange(this),
  17133. cell = tableItems.cell;
  17134. if (!cell) return -1;
  17135. var ut = getUETable(tableItems.table);
  17136. if (ut.selectedTds.length > 0) return -1;
  17137. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17138. },
  17139. execCommand: function () {
  17140. var rng = this.selection.getRange(),
  17141. bk = rng.createBookmark(true);
  17142. var cell = getTableItemsByRange(this).cell,
  17143. ut = getUETable(cell);
  17144. ut.splitToCells(cell);
  17145. rng.moveToBookmark(bk).select();
  17146. }
  17147. };
  17148. UE.commands["splittorows"] = {
  17149. queryCommandState: function () {
  17150. var tableItems = getTableItemsByRange(this),
  17151. cell = tableItems.cell;
  17152. if (!cell) return -1;
  17153. var ut = getUETable(tableItems.table);
  17154. if (ut.selectedTds.length > 0) return -1;
  17155. return cell && cell.rowSpan > 1 ? 0 : -1;
  17156. },
  17157. execCommand: function () {
  17158. var rng = this.selection.getRange(),
  17159. bk = rng.createBookmark(true);
  17160. var cell = getTableItemsByRange(this).cell,
  17161. ut = getUETable(cell);
  17162. ut.splitToRows(cell);
  17163. rng.moveToBookmark(bk).select();
  17164. }
  17165. };
  17166. UE.commands["splittocols"] = {
  17167. queryCommandState: function () {
  17168. var tableItems = getTableItemsByRange(this),
  17169. cell = tableItems.cell;
  17170. if (!cell) return -1;
  17171. var ut = getUETable(tableItems.table);
  17172. if (ut.selectedTds.length > 0) return -1;
  17173. return cell && cell.colSpan > 1 ? 0 : -1;
  17174. },
  17175. execCommand: function () {
  17176. var rng = this.selection.getRange(),
  17177. bk = rng.createBookmark(true);
  17178. var cell = getTableItemsByRange(this).cell,
  17179. ut = getUETable(cell);
  17180. ut.splitToCols(cell);
  17181. rng.moveToBookmark(bk).select();
  17182. }
  17183. };
  17184. UE.commands["adaptbytext"] =
  17185. UE.commands["adaptbywindow"] = {
  17186. queryCommandState: function () {
  17187. return getTableItemsByRange(this).table ? 0 : -1
  17188. },
  17189. execCommand: function (cmd) {
  17190. var tableItems = getTableItemsByRange(this),
  17191. table = tableItems.table;
  17192. if (table) {
  17193. if (cmd == 'adaptbywindow') {
  17194. resetTdWidth(table, this);
  17195. } else {
  17196. var cells = domUtils.getElementsByTagName(table, "td th");
  17197. utils.each(cells, function (cell) {
  17198. cell.removeAttribute("width");
  17199. });
  17200. table.removeAttribute("width");
  17201. }
  17202. }
  17203. }
  17204. };
  17205. //平均分配各列
  17206. UE.commands['averagedistributecol'] = {
  17207. queryCommandState: function () {
  17208. var ut = getUETableBySelected(this);
  17209. if (!ut) return -1;
  17210. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  17211. },
  17212. execCommand: function (cmd) {
  17213. var me = this,
  17214. ut = getUETableBySelected(me);
  17215. function getAverageWidth() {
  17216. var tb = ut.table,
  17217. averageWidth, sumWidth = 0, colsNum = 0,
  17218. tbAttr = getDefaultValue(me, tb);
  17219. if (ut.isFullRow()) {
  17220. sumWidth = tb.offsetWidth;
  17221. colsNum = ut.colsNum;
  17222. } else {
  17223. var begin = ut.cellsRange.beginColIndex,
  17224. end = ut.cellsRange.endColIndex,
  17225. node;
  17226. for (var i = begin; i <= end;) {
  17227. node = ut.selectedTds[i];
  17228. sumWidth += node.offsetWidth;
  17229. i += node.colSpan;
  17230. colsNum += 1;
  17231. }
  17232. }
  17233. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  17234. return averageWidth;
  17235. }
  17236. function setAverageWidth(averageWidth) {
  17237. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  17238. node.setAttribute("width", "");
  17239. });
  17240. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  17241. utils.each(cells, function (node) {
  17242. if (node.colSpan == 1) {
  17243. node.setAttribute("width", averageWidth);
  17244. }
  17245. });
  17246. }
  17247. if (ut && ut.selectedTds.length) {
  17248. setAverageWidth(getAverageWidth());
  17249. }
  17250. }
  17251. };
  17252. //平均分配各行
  17253. UE.commands['averagedistributerow'] = {
  17254. queryCommandState: function () {
  17255. var ut = getUETableBySelected(this);
  17256. if (!ut) return -1;
  17257. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  17258. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  17259. },
  17260. execCommand: function (cmd) {
  17261. var me = this,
  17262. ut = getUETableBySelected(me);
  17263. function getAverageHeight() {
  17264. var averageHeight, rowNum, sumHeight = 0,
  17265. tb = ut.table,
  17266. tbAttr = getDefaultValue(me, tb),
  17267. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  17268. if (ut.isFullCol()) {
  17269. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  17270. thArr = domUtils.getElementsByTagName(tb, "th"),
  17271. captionHeight, thHeight;
  17272. if (captionArr.length > 0) {
  17273. captionHeight = captionArr[0].offsetHeight;
  17274. }
  17275. if (thArr.length > 0) {
  17276. thHeight = thArr[0].offsetHeight;
  17277. }
  17278. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  17279. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  17280. } else {
  17281. var begin = ut.cellsRange.beginRowIndex,
  17282. end = ut.cellsRange.endRowIndex,
  17283. count = 0,
  17284. trs = domUtils.getElementsByTagName(tb, "tr");
  17285. for (var i = begin; i <= end; i++) {
  17286. sumHeight += trs[i].offsetHeight;
  17287. count += 1;
  17288. }
  17289. rowNum = count;
  17290. }
  17291. //ie8下是混杂模式
  17292. if (browser.ie && browser.version < 9) {
  17293. averageHeight = Math.ceil(sumHeight / rowNum);
  17294. } else {
  17295. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  17296. }
  17297. return averageHeight;
  17298. }
  17299. function setAverageHeight(averageHeight) {
  17300. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  17301. utils.each(cells, function (node) {
  17302. if (node.rowSpan == 1) {
  17303. node.setAttribute("height", averageHeight);
  17304. }
  17305. });
  17306. }
  17307. if (ut && ut.selectedTds.length) {
  17308. setAverageHeight(getAverageHeight());
  17309. }
  17310. }
  17311. };
  17312. //单元格对齐方式
  17313. UE.commands['cellalignment'] = {
  17314. queryCommandState: function () {
  17315. return getTableItemsByRange(this).table ? 0 : -1
  17316. },
  17317. execCommand: function (cmd, data) {
  17318. var me = this,
  17319. ut = getUETableBySelected(me);
  17320. if (!ut) {
  17321. var start = me.selection.getStart(),
  17322. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  17323. if (!/caption/ig.test(cell.tagName)) {
  17324. domUtils.setAttributes(cell, data);
  17325. } else {
  17326. cell.style.textAlign = data.align;
  17327. cell.style.verticalAlign = data.vAlign;
  17328. }
  17329. me.selection.getRange().setCursor(true);
  17330. } else {
  17331. utils.each(ut.selectedTds, function (cell) {
  17332. domUtils.setAttributes(cell, data);
  17333. });
  17334. }
  17335. },
  17336. /**
  17337. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  17338. * @see UE.UETable.getTableCellAlignState
  17339. */
  17340. queryCommandValue: function (cmd) {
  17341. var activeMenuCell = getTableItemsByRange( this).cell;
  17342. if( !activeMenuCell ) {
  17343. activeMenuCell = getSelectedArr(this)[0];
  17344. }
  17345. if (!activeMenuCell) {
  17346. return null;
  17347. } else {
  17348. //获取同时选中的其他单元格
  17349. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  17350. !cells.length && ( cells = activeMenuCell );
  17351. return UE.UETable.getTableCellAlignState(cells);
  17352. }
  17353. }
  17354. };
  17355. //表格对齐方式
  17356. UE.commands['tablealignment'] = {
  17357. queryCommandState: function () {
  17358. if (browser.ie && browser.version < 8) {
  17359. return -1;
  17360. }
  17361. return getTableItemsByRange(this).table ? 0 : -1
  17362. },
  17363. execCommand: function (cmd, value) {
  17364. var me = this,
  17365. start = me.selection.getStart(),
  17366. table = start && domUtils.findParentByTagName(start, ["table"], true);
  17367. if (table) {
  17368. table.setAttribute("align",value);
  17369. }
  17370. }
  17371. };
  17372. //表格属性
  17373. UE.commands['edittable'] = {
  17374. queryCommandState: function () {
  17375. return getTableItemsByRange(this).table ? 0 : -1
  17376. },
  17377. execCommand: function (cmd, color) {
  17378. var rng = this.selection.getRange(),
  17379. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17380. if (table) {
  17381. var arr = domUtils.getElementsByTagName(table, "td").concat(
  17382. domUtils.getElementsByTagName(table, "th"),
  17383. domUtils.getElementsByTagName(table, "caption")
  17384. );
  17385. utils.each(arr, function (node) {
  17386. node.style.borderColor = color;
  17387. });
  17388. }
  17389. }
  17390. };
  17391. //单元格属性
  17392. UE.commands['edittd'] = {
  17393. queryCommandState: function () {
  17394. return getTableItemsByRange(this).table ? 0 : -1
  17395. },
  17396. execCommand: function (cmd, bkColor) {
  17397. var me = this,
  17398. ut = getUETableBySelected(me);
  17399. if (!ut) {
  17400. var start = me.selection.getStart(),
  17401. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  17402. if (cell) {
  17403. cell.style.backgroundColor = bkColor;
  17404. }
  17405. } else {
  17406. utils.each(ut.selectedTds, function (cell) {
  17407. cell.style.backgroundColor = bkColor;
  17408. });
  17409. }
  17410. }
  17411. };
  17412. UE.commands["settablebackground"] = {
  17413. queryCommandState: function () {
  17414. return getSelectedArr(this).length > 1 ? 0 : -1;
  17415. },
  17416. execCommand: function (cmd, value) {
  17417. var cells, ut;
  17418. cells = getSelectedArr(this);
  17419. ut = getUETable(cells[0]);
  17420. ut.setBackground(cells, value);
  17421. }
  17422. };
  17423. UE.commands["cleartablebackground"] = {
  17424. queryCommandState: function () {
  17425. var cells = getSelectedArr(this);
  17426. if (!cells.length)return -1;
  17427. for (var i = 0, cell; cell = cells[i++];) {
  17428. if (cell.style.backgroundColor !== "") return 0;
  17429. }
  17430. return -1;
  17431. },
  17432. execCommand: function () {
  17433. var cells = getSelectedArr(this),
  17434. ut = getUETable(cells[0]);
  17435. ut.removeBackground(cells);
  17436. }
  17437. };
  17438. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  17439. queryCommandState: function (cmd) {
  17440. var table = getTableItemsByRange(this).table;
  17441. if (!table) return -1;
  17442. var interlaced = table.getAttribute("interlaced");
  17443. if (cmd == "interlacetable") {
  17444. //TODO 待定
  17445. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  17446. return (interlaced === "enabled") ? -1 : 0;
  17447. } else {
  17448. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  17449. }
  17450. },
  17451. execCommand: function (cmd, classList) {
  17452. var table = getTableItemsByRange(this).table;
  17453. if (cmd == "interlacetable") {
  17454. table.setAttribute("interlaced", "enabled");
  17455. this.fireEvent("interlacetable", table, classList);
  17456. } else {
  17457. table.setAttribute("interlaced", "disabled");
  17458. this.fireEvent("uninterlacetable", table);
  17459. }
  17460. }
  17461. };
  17462. UE.commands["setbordervisible"] = {
  17463. queryCommandState: function (cmd) {
  17464. var table = getTableItemsByRange(this).table;
  17465. if (!table) return -1;
  17466. return 0;
  17467. },
  17468. execCommand: function () {
  17469. var table = getTableItemsByRange(this).table;
  17470. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  17471. td.style.borderWidth = '1px';
  17472. td.style.borderStyle = 'solid';
  17473. })
  17474. }
  17475. };
  17476. function resetTdWidth(table, editor) {
  17477. var tds = domUtils.getElementsByTagName(table,'td th');
  17478. utils.each(tds, function (td) {
  17479. td.removeAttribute("width");
  17480. });
  17481. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  17482. var tdsWidths = [];
  17483. setTimeout(function () {
  17484. utils.each(tds, function (td) {
  17485. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  17486. })
  17487. utils.each(tds, function (td,i) {
  17488. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  17489. })
  17490. }, 0);
  17491. }
  17492. function getTableWidth(editor, needIEHack, defaultValue) {
  17493. var body = editor.body;
  17494. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  17495. }
  17496. function getSelectedArr(editor) {
  17497. var cell = getTableItemsByRange(editor).cell;
  17498. if (cell) {
  17499. var ut = getUETable(cell);
  17500. return ut.selectedTds.length ? ut.selectedTds : [cell];
  17501. } else {
  17502. return [];
  17503. }
  17504. }
  17505. })();
  17506. /**
  17507. * Created with JetBrains PhpStorm.
  17508. * User: taoqili
  17509. * Date: 12-10-12
  17510. * Time: 上午10:05
  17511. * To change this template use File | Settings | File Templates.
  17512. */
  17513. UE.plugins['table'] = function () {
  17514. var me = this,
  17515. tabTimer = null,
  17516. //拖动计时器
  17517. tableDragTimer = null,
  17518. //双击计时器
  17519. tableResizeTimer = null,
  17520. //单元格最小宽度
  17521. cellMinWidth = 5,
  17522. isInResizeBuffer = false,
  17523. //单元格边框大小
  17524. cellBorderWidth = 5,
  17525. //鼠标偏移距离
  17526. offsetOfTableCell = 10,
  17527. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  17528. singleClickState = 0,
  17529. userActionStatus = null,
  17530. //双击允许的时间范围
  17531. dblclickTime = 360,
  17532. UT = UE.UETable,
  17533. getUETable = function (tdOrTable) {
  17534. return UT.getUETable(tdOrTable);
  17535. },
  17536. getUETableBySelected = function (editor) {
  17537. return UT.getUETableBySelected(editor);
  17538. },
  17539. getDefaultValue = function (editor, table) {
  17540. return UT.getDefaultValue(editor, table);
  17541. },
  17542. removeSelectedClass = function (cells) {
  17543. return UT.removeSelectedClass(cells);
  17544. };
  17545. function showError(e) {
  17546. // throw e;
  17547. }
  17548. me.ready(function(){
  17549. var me = this;
  17550. var orgGetText = me.selection.getText;
  17551. me.selection.getText = function(){
  17552. var table = getUETableBySelected(me);
  17553. if(table){
  17554. var str = '';
  17555. utils.each(table.selectedTds,function(td){
  17556. str += td[browser.ie?'innerText':'textContent'];
  17557. })
  17558. return str;
  17559. }else{
  17560. return orgGetText.call(me.selection)
  17561. }
  17562. }
  17563. })
  17564. //处理拖动及框选相关方法
  17565. var startTd = null, //鼠标按下时的锚点td
  17566. currentTd = null, //当前鼠标经过时的td
  17567. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  17568. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  17569. dragButton = null,
  17570. dragOver = false,
  17571. dragLine = null, //模拟的拖动线
  17572. dragTd = null; //发生拖动的目标td
  17573. var mousedown = false,
  17574. //todo 判断混乱模式
  17575. needIEHack = true;
  17576. me.setOpt({
  17577. 'maxColNum':20,
  17578. 'maxRowNum':100,
  17579. 'defaultCols':5,
  17580. 'defaultRows':5,
  17581. 'tdvalign':'top',
  17582. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  17583. 'tableDragable':false,
  17584. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  17585. });
  17586. me.getUETable = getUETable;
  17587. var commands = {
  17588. 'deletetable':1,
  17589. 'inserttable':1,
  17590. 'cellvalign':1,
  17591. 'insertcaption':1,
  17592. 'deletecaption':1,
  17593. 'inserttitle':1,
  17594. 'deletetitle':1,
  17595. "mergeright":1,
  17596. "mergedown":1,
  17597. "mergecells":1,
  17598. "insertrow":1,
  17599. "insertrownext":1,
  17600. "deleterow":1,
  17601. "insertcol":1,
  17602. "insertcolnext":1,
  17603. "deletecol":1,
  17604. "splittocells":1,
  17605. "splittorows":1,
  17606. "splittocols":1,
  17607. "adaptbytext":1,
  17608. "adaptbywindow":1,
  17609. "adaptbycustomer":1,
  17610. "insertparagraph":1,
  17611. "insertparagraphbeforetable":1,
  17612. "averagedistributecol":1,
  17613. "averagedistributerow":1
  17614. };
  17615. me.ready(function () {
  17616. utils.cssRule('table',
  17617. //选中的td上的样式
  17618. '.selectTdClass{background-color:#edf5fa !important}' +
  17619. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  17620. //插入的表格的默认样式
  17621. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  17622. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  17623. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  17624. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  17625. 'table tr.firstRow th{border-top-width:2px;}' +
  17626. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  17627. 'td p{margin:0;padding:0;}', me.document);
  17628. var tableCopyList, isFullCol, isFullRow;
  17629. //注册del/backspace事件
  17630. me.addListener('keydown', function (cmd, evt) {
  17631. var me = this;
  17632. var keyCode = evt.keyCode || evt.which;
  17633. if (keyCode == 8) {
  17634. var ut = getUETableBySelected(me);
  17635. if (ut && ut.selectedTds.length) {
  17636. if (ut.isFullCol()) {
  17637. me.execCommand('deletecol')
  17638. } else if (ut.isFullRow()) {
  17639. me.execCommand('deleterow')
  17640. } else {
  17641. me.fireEvent('delcells');
  17642. }
  17643. domUtils.preventDefault(evt);
  17644. }
  17645. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  17646. range = me.selection.getRange();
  17647. if (range.collapsed && caption && isEmptyBlock(caption)) {
  17648. me.fireEvent('saveScene');
  17649. var table = caption.parentNode;
  17650. domUtils.remove(caption);
  17651. if (table) {
  17652. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  17653. }
  17654. me.fireEvent('saveScene');
  17655. }
  17656. }
  17657. if (keyCode == 46) {
  17658. ut = getUETableBySelected(me);
  17659. if (ut) {
  17660. me.fireEvent('saveScene');
  17661. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  17662. domUtils.fillNode(me.document, ci)
  17663. }
  17664. me.fireEvent('saveScene');
  17665. domUtils.preventDefault(evt);
  17666. }
  17667. }
  17668. if (keyCode == 13) {
  17669. var rng = me.selection.getRange(),
  17670. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  17671. if (caption) {
  17672. var table = domUtils.findParentByTagName(caption, 'table');
  17673. if (!rng.collapsed) {
  17674. rng.deleteContents();
  17675. me.fireEvent('saveScene');
  17676. } else {
  17677. if (caption) {
  17678. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  17679. }
  17680. }
  17681. domUtils.preventDefault(evt);
  17682. return;
  17683. }
  17684. if (rng.collapsed) {
  17685. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17686. if (table) {
  17687. var cell = table.rows[0].cells[0],
  17688. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  17689. preNode = table.previousSibling;
  17690. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  17691. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  17692. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  17693. me.execCommand('insertparagraphbeforetable');
  17694. domUtils.preventDefault(evt);
  17695. }
  17696. }
  17697. }
  17698. }
  17699. }
  17700. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  17701. tableCopyList = null;
  17702. var ut = getUETableBySelected(me);
  17703. if (ut) {
  17704. var tds = ut.selectedTds;
  17705. isFullCol = ut.isFullCol();
  17706. isFullRow = ut.isFullRow();
  17707. tableCopyList = [
  17708. [ut.cloneCell(tds[0],null,true)]
  17709. ];
  17710. for (var i = 1, ci; ci = tds[i]; i++) {
  17711. if (ci.parentNode !== tds[i - 1].parentNode) {
  17712. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  17713. } else {
  17714. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  17715. }
  17716. }
  17717. }
  17718. }
  17719. });
  17720. me.addListener("tablehasdeleted",function(){
  17721. toggleDraggableState(this, false, "", null);
  17722. if (dragButton)domUtils.remove(dragButton);
  17723. });
  17724. me.addListener('beforepaste', function (cmd, html) {
  17725. var me = this;
  17726. var rng = me.selection.getRange();
  17727. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  17728. var div = me.document.createElement("div");
  17729. div.innerHTML = html.html;
  17730. //trace:3729
  17731. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  17732. return;
  17733. }
  17734. var table = getUETableBySelected(me);
  17735. if (tableCopyList) {
  17736. me.fireEvent('saveScene');
  17737. var rng = me.selection.getRange();
  17738. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  17739. if (td) {
  17740. var ut = getUETable(td);
  17741. if (isFullRow) {
  17742. var rowIndex = ut.getCellInfo(td).rowIndex;
  17743. if (td.tagName == 'TH') {
  17744. rowIndex++;
  17745. }
  17746. for (var i = 0, ci; ci = tableCopyList[i++];) {
  17747. var tr = ut.insertRow(rowIndex++, "td");
  17748. for (var j = 0, cj; cj = ci[j]; j++) {
  17749. var cell = tr.cells[j];
  17750. if (!cell) {
  17751. cell = tr.insertCell(j)
  17752. }
  17753. cell.innerHTML = cj.innerHTML;
  17754. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  17755. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  17756. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  17757. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  17758. }
  17759. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  17760. if (!ci[j])
  17761. break;
  17762. cj.innerHTML = ci[j].innerHTML;
  17763. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  17764. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  17765. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  17766. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  17767. }
  17768. }
  17769. } else {
  17770. if (isFullCol) {
  17771. cellInfo = ut.getCellInfo(td);
  17772. var maxColNum = 0;
  17773. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  17774. maxColNum += cj.colSpan || 1;
  17775. }
  17776. me.__hasEnterExecCommand = true;
  17777. for (i = 0; i < maxColNum; i++) {
  17778. me.execCommand('insertcol');
  17779. }
  17780. me.__hasEnterExecCommand = false;
  17781. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  17782. if (td.tagName == 'TH') {
  17783. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  17784. }
  17785. }
  17786. for (var i = 0, ci; ci = tableCopyList[i++];) {
  17787. tmpNode = td;
  17788. for (var j = 0, cj; cj = ci[j++];) {
  17789. if (td) {
  17790. td.innerHTML = cj.innerHTML;
  17791. //todo 定制处理
  17792. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  17793. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  17794. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  17795. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  17796. preNode = td;
  17797. td = td.nextSibling;
  17798. } else {
  17799. var cloneTd = cj.cloneNode(true);
  17800. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  17801. preNode.parentNode.appendChild(cloneTd)
  17802. }
  17803. }
  17804. td = ut.getNextCell(tmpNode, true, true);
  17805. if (!tableCopyList[i])
  17806. break;
  17807. if (!td) {
  17808. var cellInfo = ut.getCellInfo(tmpNode);
  17809. ut.table.insertRow(ut.table.rows.length);
  17810. ut.update();
  17811. td = ut.getVSideCell(tmpNode, true);
  17812. }
  17813. }
  17814. }
  17815. ut.update();
  17816. } else {
  17817. table = me.document.createElement('table');
  17818. for (var i = 0, ci; ci = tableCopyList[i++];) {
  17819. var tr = table.insertRow(table.rows.length);
  17820. for (var j = 0, cj; cj = ci[j++];) {
  17821. cloneTd = UT.cloneCell(cj,null,true);
  17822. domUtils.removeAttributes(cloneTd, ['class']);
  17823. tr.appendChild(cloneTd)
  17824. }
  17825. if (j == 2 && cloneTd.rowSpan > 1) {
  17826. cloneTd.rowSpan = 1;
  17827. }
  17828. }
  17829. var defaultValue = getDefaultValue(me),
  17830. width = me.body.offsetWidth -
  17831. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  17832. me.execCommand('insertHTML', '<table ' +
  17833. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  17834. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  17835. }
  17836. me.fireEvent('contentchange');
  17837. me.fireEvent('saveScene');
  17838. html.html = '';
  17839. return true;
  17840. } else {
  17841. var div = me.document.createElement("div"), tables;
  17842. div.innerHTML = html.html;
  17843. tables = div.getElementsByTagName("table");
  17844. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  17845. utils.each(tables, function (t) {
  17846. domUtils.remove(t)
  17847. });
  17848. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  17849. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  17850. }
  17851. } else {
  17852. utils.each(tables, function (table) {
  17853. removeStyleSize(table, true);
  17854. domUtils.removeAttributes(table, ['style', 'border']);
  17855. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  17856. if (isEmptyBlock(td)) {
  17857. domUtils.fillNode(me.document, td);
  17858. }
  17859. removeStyleSize(td, true);
  17860. // domUtils.removeAttributes(td, ['style'])
  17861. });
  17862. });
  17863. }
  17864. html.html = div.innerHTML;
  17865. }
  17866. });
  17867. me.addListener('afterpaste', function () {
  17868. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  17869. if (table.offsetWidth > me.body.offsetWidth) {
  17870. var defaultValue = getDefaultValue(me, table);
  17871. 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'
  17872. }
  17873. })
  17874. });
  17875. me.addListener('blur', function () {
  17876. tableCopyList = null;
  17877. });
  17878. var timer;
  17879. me.addListener('keydown', function () {
  17880. clearTimeout(timer);
  17881. timer = setTimeout(function () {
  17882. var rng = me.selection.getRange(),
  17883. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  17884. if (cell) {
  17885. var table = cell.parentNode.parentNode.parentNode;
  17886. if (table.offsetWidth > table.getAttribute("width")) {
  17887. cell.style.wordBreak = "break-all";
  17888. }
  17889. }
  17890. }, 100);
  17891. });
  17892. me.addListener("selectionchange", function () {
  17893. toggleDraggableState(me, false, "", null);
  17894. });
  17895. //内容变化时触发索引更新
  17896. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  17897. me.addListener("contentchange", function () {
  17898. var me = this;
  17899. //尽可能排除一些不需要更新的状况
  17900. hideDragLine(me);
  17901. if (getUETableBySelected(me))return;
  17902. var rng = me.selection.getRange();
  17903. var start = rng.startContainer;
  17904. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  17905. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  17906. if (me.fireEvent("excludetable", table) === true) return;
  17907. table.ueTable = new UT(table);
  17908. //trace:3742
  17909. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  17910. //
  17911. // if (domUtils.isEmptyBlock(td) && td !== start) {
  17912. // domUtils.fillNode(me.document, td);
  17913. // if (browser.ie && browser.version == 6) {
  17914. // td.innerHTML = '&nbsp;'
  17915. // }
  17916. // }
  17917. // });
  17918. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  17919. // if (domUtils.isEmptyBlock(th) && th !== start) {
  17920. // domUtils.fillNode(me.document, th);
  17921. // if (browser.ie && browser.version == 6) {
  17922. // th.innerHTML = '&nbsp;'
  17923. // }
  17924. // }
  17925. // });
  17926. table.onmouseover = function () {
  17927. me.fireEvent('tablemouseover', table);
  17928. };
  17929. table.onmousemove = function () {
  17930. me.fireEvent('tablemousemove', table);
  17931. me.options.tableDragable && toggleDragButton(true, this, me);
  17932. utils.defer(function(){
  17933. me.fireEvent('contentchange',50)
  17934. },true)
  17935. };
  17936. table.onmouseout = function () {
  17937. me.fireEvent('tablemouseout', table);
  17938. toggleDraggableState(me, false, "", null);
  17939. hideDragLine(me);
  17940. };
  17941. table.onclick = function (evt) {
  17942. evt = me.window.event || evt;
  17943. var target = getParentTdOrTh(evt.target || evt.srcElement);
  17944. if (!target)return;
  17945. var ut = getUETable(target),
  17946. table = ut.table,
  17947. cellInfo = ut.getCellInfo(target),
  17948. cellsRange,
  17949. rng = me.selection.getRange();
  17950. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  17951. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  17952. // ut.setSelected(cellsRange);
  17953. // return;
  17954. // }
  17955. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  17956. //
  17957. // return;
  17958. // }
  17959. if (inTableSide(table, target, evt, true)) {
  17960. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  17961. if (evt.shiftKey && ut.selectedTds.length) {
  17962. if (ut.selectedTds[0] !== endTdCol) {
  17963. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  17964. ut.setSelected(cellsRange);
  17965. } else {
  17966. rng && rng.selectNodeContents(endTdCol).select();
  17967. }
  17968. } else {
  17969. if (target !== endTdCol) {
  17970. cellsRange = ut.getCellsRange(target, endTdCol);
  17971. ut.setSelected(cellsRange);
  17972. } else {
  17973. rng && rng.selectNodeContents(endTdCol).select();
  17974. }
  17975. }
  17976. return;
  17977. }
  17978. if (inTableSide(table, target, evt)) {
  17979. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  17980. if (evt.shiftKey && ut.selectedTds.length) {
  17981. if (ut.selectedTds[0] !== endTdRow) {
  17982. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  17983. ut.setSelected(cellsRange);
  17984. } else {
  17985. rng && rng.selectNodeContents(endTdRow).select();
  17986. }
  17987. } else {
  17988. if (target !== endTdRow) {
  17989. cellsRange = ut.getCellsRange(target, endTdRow);
  17990. ut.setSelected(cellsRange);
  17991. } else {
  17992. rng && rng.selectNodeContents(endTdRow).select();
  17993. }
  17994. }
  17995. }
  17996. };
  17997. });
  17998. switchBorderColor(me, true);
  17999. });
  18000. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18001. domUtils.on(me.document, "mouseout", function (evt) {
  18002. var target = evt.target || evt.srcElement;
  18003. if (target.tagName == "TABLE") {
  18004. toggleDraggableState(me, false, "", null);
  18005. }
  18006. });
  18007. /**
  18008. * 表格隔行变色
  18009. */
  18010. me.addListener("interlacetable",function(type,table,classList){
  18011. if(!table) return;
  18012. var me = this,
  18013. rows = table.rows,
  18014. len = rows.length,
  18015. getClass = function(list,index,repeat){
  18016. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18017. };
  18018. for(var i = 0;i<len;i++){
  18019. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18020. }
  18021. });
  18022. me.addListener("uninterlacetable",function(type,table){
  18023. if(!table) return;
  18024. var me = this,
  18025. rows = table.rows,
  18026. classList = me.options.classList,
  18027. len = rows.length;
  18028. for(var i = 0;i<len;i++){
  18029. domUtils.removeClasses( rows[i], classList );
  18030. }
  18031. });
  18032. me.addListener("mousedown", mouseDownEvent);
  18033. me.addListener("mouseup", mouseUpEvent);
  18034. //拖动的时候不出发mouseup
  18035. domUtils.on( me.body, 'dragstart', function( evt ){
  18036. mouseUpEvent.call( me, 'dragstart', evt );
  18037. });
  18038. var currentRowIndex = 0;
  18039. me.addListener("mousedown", function () {
  18040. currentRowIndex = 0;
  18041. });
  18042. me.addListener('tabkeydown', function () {
  18043. var range = this.selection.getRange(),
  18044. common = range.getCommonAncestor(true, true),
  18045. table = domUtils.findParentByTagName(common, 'table');
  18046. if (table) {
  18047. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18048. var cell = domUtils.getElementsByTagName(table, 'th td');
  18049. if (cell && cell.length) {
  18050. range.setStart(cell[0], 0).setCursor(false, true)
  18051. }
  18052. } else {
  18053. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18054. ua = getUETable(cell);
  18055. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18056. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18057. if (nextCell) {
  18058. if (isEmptyBlock(nextCell)) {
  18059. range.setStart(nextCell, 0).setCursor(false, true)
  18060. } else {
  18061. range.selectNodeContents(nextCell).select()
  18062. }
  18063. } else {
  18064. me.fireEvent('saveScene');
  18065. me.__hasEnterExecCommand = true;
  18066. this.execCommand('insertrownext');
  18067. me.__hasEnterExecCommand = false;
  18068. range = this.selection.getRange();
  18069. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18070. me.fireEvent('saveScene');
  18071. }
  18072. }
  18073. return true;
  18074. }
  18075. });
  18076. browser.ie && me.addListener('selectionchange', function () {
  18077. toggleDraggableState(this, false, "", null);
  18078. });
  18079. me.addListener("keydown", function (type, evt) {
  18080. var me = this;
  18081. //处理在表格的最后一个输入tab产生新的表格
  18082. var keyCode = evt.keyCode || evt.which;
  18083. if (keyCode == 8 || keyCode == 46) {
  18084. return;
  18085. }
  18086. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18087. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18088. var ut = getUETableBySelected(me);
  18089. if (!ut) return;
  18090. notCtrlKey && ut.clearSelected();
  18091. });
  18092. me.addListener("beforegetcontent", function () {
  18093. switchBorderColor(this, false);
  18094. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18095. if (domUtils.isEmptyNode(ci)) {
  18096. ci.innerHTML = '&nbsp;'
  18097. }
  18098. });
  18099. });
  18100. me.addListener("aftergetcontent", function () {
  18101. switchBorderColor(this, true);
  18102. });
  18103. me.addListener("getAllHtml", function () {
  18104. removeSelectedClass(me.document.getElementsByTagName("td"));
  18105. });
  18106. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18107. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18108. if (!fullscreen) {
  18109. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18110. tables = domUtils.getElementsByTagName(this.body, "table");
  18111. utils.each(tables, function (table) {
  18112. if (table.offsetWidth < me.body.offsetWidth) return false;
  18113. var tds = domUtils.getElementsByTagName(table, "td"),
  18114. backWidths = [];
  18115. utils.each(tds, function (td) {
  18116. backWidths.push(td.offsetWidth);
  18117. });
  18118. for (var i = 0, td; td = tds[i]; i++) {
  18119. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18120. }
  18121. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18122. });
  18123. }
  18124. });
  18125. //重写execCommand命令,用于处理框选时的处理
  18126. var oldExecCommand = me.execCommand;
  18127. me.execCommand = function (cmd, datatat) {
  18128. var me = this,
  18129. args = arguments;
  18130. cmd = cmd.toLowerCase();
  18131. var ut = getUETableBySelected(me), tds,
  18132. range = new dom.Range(me.document),
  18133. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18134. result;
  18135. if (!cmdFun) return;
  18136. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18137. me.__hasEnterExecCommand = true;
  18138. me.fireEvent("beforeexeccommand", cmd);
  18139. tds = ut.selectedTds;
  18140. var lastState = -2, lastValue = -2, value, state;
  18141. for (var i = 0, td; td = tds[i]; i++) {
  18142. if (isEmptyBlock(td)) {
  18143. range.setStart(td, 0).setCursor(false, true)
  18144. } else {
  18145. range.selectNode(td).select(true);
  18146. }
  18147. state = me.queryCommandState(cmd);
  18148. value = me.queryCommandValue(cmd);
  18149. if (state != -1) {
  18150. if (lastState !== state || lastValue !== value) {
  18151. me._ignoreContentChange = true;
  18152. result = oldExecCommand.apply(me, arguments);
  18153. me._ignoreContentChange = false;
  18154. }
  18155. lastState = me.queryCommandState(cmd);
  18156. lastValue = me.queryCommandValue(cmd);
  18157. if (domUtils.isEmptyBlock(td)) {
  18158. domUtils.fillNode(me.document, td)
  18159. }
  18160. }
  18161. }
  18162. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  18163. me.fireEvent('contentchange');
  18164. me.fireEvent("afterexeccommand", cmd);
  18165. me.__hasEnterExecCommand = false;
  18166. me._selectionChange();
  18167. } else {
  18168. result = oldExecCommand.apply(me, arguments);
  18169. }
  18170. return result;
  18171. };
  18172. });
  18173. /**
  18174. * 删除obj的宽高style,改成属性宽高
  18175. * @param obj
  18176. * @param replaceToProperty
  18177. */
  18178. function removeStyleSize(obj, replaceToProperty) {
  18179. removeStyle(obj, "width", true);
  18180. removeStyle(obj, "height", true);
  18181. }
  18182. function removeStyle(obj, styleName, replaceToProperty) {
  18183. if (obj.style[styleName]) {
  18184. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  18185. obj.style[styleName] = "";
  18186. }
  18187. }
  18188. function getParentTdOrTh(ele) {
  18189. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  18190. var td;
  18191. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  18192. return null;
  18193. }
  18194. function isEmptyBlock(node) {
  18195. var reg = new RegExp(domUtils.fillChar, 'g');
  18196. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  18197. return 0;
  18198. }
  18199. for (var n in dtd.$isNotEmpty) {
  18200. if (node.getElementsByTagName(n).length) {
  18201. return 0;
  18202. }
  18203. }
  18204. return 1;
  18205. }
  18206. function mouseCoords(evt) {
  18207. if (evt.pageX || evt.pageY) {
  18208. return { x:evt.pageX, y:evt.pageY };
  18209. }
  18210. return {
  18211. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  18212. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  18213. };
  18214. }
  18215. function mouseMoveEvent(evt) {
  18216. if( isEditorDisabled() ) {
  18217. return;
  18218. }
  18219. try {
  18220. //普通状态下鼠标移动
  18221. var target = getParentTdOrTh(evt.target || evt.srcElement),
  18222. pos;
  18223. //区分用户的行为是拖动还是双击
  18224. if( isInResizeBuffer ) {
  18225. me.body.style.webkitUserSelect = 'none';
  18226. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  18227. clearTableDragTimer();
  18228. isInResizeBuffer = false;
  18229. singleClickState = 0;
  18230. //drag action
  18231. tableBorderDrag(evt);
  18232. }
  18233. }
  18234. //修改单元格大小时的鼠标移动
  18235. if (onDrag && dragTd) {
  18236. singleClickState = 0;
  18237. me.body.style.webkitUserSelect = 'none';
  18238. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  18239. pos = mouseCoords(evt);
  18240. toggleDraggableState(me, true, onDrag, pos, target);
  18241. if (onDrag == "h") {
  18242. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  18243. } else if (onDrag == "v") {
  18244. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  18245. }
  18246. return;
  18247. }
  18248. //当鼠标处于table上时,修改移动过程中的光标状态
  18249. if (target) {
  18250. //针对使用table作为容器的组件不触发拖拽效果
  18251. if (me.fireEvent('excludetable', target) === true)
  18252. return;
  18253. pos = mouseCoords(evt);
  18254. var state = getRelation(target, pos),
  18255. table = domUtils.findParentByTagName(target, "table", true);
  18256. if (inTableSide(table, target, evt, true)) {
  18257. if (me.fireEvent("excludetable", table) === true) return;
  18258. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  18259. } else if (inTableSide(table, target, evt)) {
  18260. if (me.fireEvent("excludetable", table) === true) return;
  18261. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  18262. } else {
  18263. me.body.style.cursor = "text";
  18264. var curCell = target;
  18265. if (/\d/.test(state)) {
  18266. state = state.replace(/\d/, '');
  18267. target = getUETable(target).getPreviewCell(target, state == "v");
  18268. }
  18269. //位于第一行的顶部或者第一列的左边时不可拖动
  18270. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  18271. }
  18272. } else {
  18273. toggleDragButton(false, table, me);
  18274. }
  18275. } catch (e) {
  18276. showError(e);
  18277. }
  18278. }
  18279. var dragButtonTimer;
  18280. function toggleDragButton(show, table, editor) {
  18281. if (!show) {
  18282. if (dragOver)return;
  18283. dragButtonTimer = setTimeout(function () {
  18284. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  18285. }, 2000);
  18286. } else {
  18287. createDragButton(table, editor);
  18288. }
  18289. }
  18290. function createDragButton(table, editor) {
  18291. var pos = domUtils.getXY(table),
  18292. doc = table.ownerDocument;
  18293. if (dragButton && dragButton.parentNode)return dragButton;
  18294. dragButton = doc.createElement("div");
  18295. dragButton.contentEditable = false;
  18296. dragButton.innerHTML = "";
  18297. 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;";
  18298. domUtils.unSelectable(dragButton);
  18299. dragButton.onmouseover = function (evt) {
  18300. dragOver = true;
  18301. };
  18302. dragButton.onmouseout = function (evt) {
  18303. dragOver = false;
  18304. };
  18305. domUtils.on(dragButton, 'click', function (type, evt) {
  18306. doClick(evt, this);
  18307. });
  18308. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  18309. doDblClick(evt);
  18310. });
  18311. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  18312. domUtils.preventDefault(evt);
  18313. });
  18314. var timer;
  18315. function doClick(evt, button) {
  18316. // 部分浏览器下需要清理
  18317. clearTimeout(timer);
  18318. timer = setTimeout(function () {
  18319. editor.fireEvent("tableClicked", table, button);
  18320. }, 300);
  18321. }
  18322. function doDblClick(evt) {
  18323. clearTimeout(timer);
  18324. var ut = getUETable(table),
  18325. start = table.rows[0].cells[0],
  18326. end = ut.getLastCell(),
  18327. range = ut.getCellsRange(start, end);
  18328. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  18329. ut.setSelected(range);
  18330. }
  18331. doc.body.appendChild(dragButton);
  18332. }
  18333. // function inPosition(table, pos) {
  18334. // var tablePos = domUtils.getXY(table),
  18335. // width = table.offsetWidth,
  18336. // height = table.offsetHeight;
  18337. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  18338. // return "topLeft";
  18339. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  18340. // return "bottomRight";
  18341. // }
  18342. // }
  18343. function inTableSide(table, cell, evt, top) {
  18344. var pos = mouseCoords(evt),
  18345. state = getRelation(cell, pos);
  18346. if (top) {
  18347. var caption = table.getElementsByTagName("caption")[0],
  18348. capHeight = caption ? caption.offsetHeight : 0;
  18349. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  18350. } else {
  18351. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  18352. }
  18353. }
  18354. /**
  18355. * 获取拖动时允许的X轴坐标
  18356. * @param dragTd
  18357. * @param evt
  18358. */
  18359. function getPermissionX(dragTd, evt) {
  18360. var ut = getUETable(dragTd);
  18361. if (ut) {
  18362. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  18363. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  18364. mouseX = mouseCoords(evt).x,
  18365. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  18366. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  18367. left += cellMinWidth;
  18368. right -= cellMinWidth;
  18369. return mouseX < left ? left : mouseX > right ? right : mouseX;
  18370. }
  18371. }
  18372. /**
  18373. * 获取拖动时允许的Y轴坐标
  18374. */
  18375. function getPermissionY(dragTd, evt) {
  18376. try {
  18377. var top = domUtils.getXY(dragTd).y,
  18378. mousePosY = mouseCoords(evt).y;
  18379. return mousePosY < top ? top : mousePosY;
  18380. } catch (e) {
  18381. showError(e);
  18382. }
  18383. }
  18384. /**
  18385. * 移动状态切换
  18386. */
  18387. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  18388. try {
  18389. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  18390. if (browser.ie) {
  18391. if (dir && !mousedown && !getUETableBySelected(editor)) {
  18392. getDragLine(editor, editor.document);
  18393. showDragLineAt(dir, cell);
  18394. } else {
  18395. hideDragLine(editor)
  18396. }
  18397. }
  18398. onBorder = draggable;
  18399. } catch (e) {
  18400. showError(e);
  18401. }
  18402. }
  18403. /**
  18404. * 获取与UETable相关的resize line
  18405. * @param uetable UETable对象
  18406. */
  18407. function getResizeLineByUETable() {
  18408. var lineId = '_UETableResizeLine',
  18409. line = this.document.getElementById( lineId );
  18410. if( !line ) {
  18411. line = this.document.createElement("div");
  18412. line.id = lineId;
  18413. line.contnetEditable = false;
  18414. line.setAttribute("unselectable", "on");
  18415. var styles = {
  18416. width: 2*cellBorderWidth + 1 + 'px',
  18417. position: 'absolute',
  18418. 'z-index': 100000,
  18419. cursor: 'col-resize',
  18420. background: 'red',
  18421. display: 'none'
  18422. };
  18423. //切换状态
  18424. line.onmouseout = function(){
  18425. this.style.display = 'none';
  18426. };
  18427. utils.extend( line.style, styles );
  18428. this.document.body.appendChild( line );
  18429. }
  18430. return line;
  18431. }
  18432. /**
  18433. * 更新resize-line
  18434. */
  18435. function updateResizeLine( cell, uetable ) {
  18436. var line = getResizeLineByUETable.call( this ),
  18437. table = uetable.table,
  18438. styles = {
  18439. top: domUtils.getXY( table ).y + 'px',
  18440. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  18441. display: 'block',
  18442. height: table.offsetHeight + 'px'
  18443. };
  18444. utils.extend( line.style, styles );
  18445. }
  18446. /**
  18447. * 显示resize-line
  18448. */
  18449. function showResizeLine( cell ) {
  18450. var uetable = getUETable( cell );
  18451. updateResizeLine.call( this, cell, uetable );
  18452. }
  18453. /**
  18454. * 获取鼠标与当前单元格的相对位置
  18455. * @param ele
  18456. * @param mousePos
  18457. */
  18458. function getRelation(ele, mousePos) {
  18459. var elePos = domUtils.getXY(ele);
  18460. if( !elePos ) {
  18461. return '';
  18462. }
  18463. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  18464. return "h";
  18465. }
  18466. if (mousePos.x - elePos.x < cellBorderWidth) {
  18467. return 'h1'
  18468. }
  18469. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  18470. return "v";
  18471. }
  18472. if (mousePos.y - elePos.y < cellBorderWidth) {
  18473. return 'v1'
  18474. }
  18475. return '';
  18476. }
  18477. function mouseDownEvent(type, evt) {
  18478. if( isEditorDisabled() ) {
  18479. return ;
  18480. }
  18481. userActionStatus = {
  18482. x: evt.clientX,
  18483. y: evt.clientY
  18484. };
  18485. //右键菜单单独处理
  18486. if (evt.button == 2) {
  18487. var ut = getUETableBySelected(me),
  18488. flag = false;
  18489. if (ut) {
  18490. var td = getTargetTd(me, evt);
  18491. utils.each(ut.selectedTds, function (ti) {
  18492. if (ti === td) {
  18493. flag = true;
  18494. }
  18495. });
  18496. if (!flag) {
  18497. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  18498. ut.clearSelected()
  18499. } else {
  18500. td = ut.selectedTds[0];
  18501. setTimeout(function () {
  18502. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  18503. }, 0);
  18504. }
  18505. }
  18506. } else {
  18507. tableClickHander( evt );
  18508. }
  18509. }
  18510. //清除表格的计时器
  18511. function clearTableTimer() {
  18512. tabTimer && clearTimeout( tabTimer );
  18513. tabTimer = null;
  18514. }
  18515. //双击收缩
  18516. function tableDbclickHandler(evt) {
  18517. singleClickState = 0;
  18518. evt = evt || me.window.event;
  18519. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18520. if (target) {
  18521. var h;
  18522. if (h = getRelation(target, mouseCoords(evt))) {
  18523. hideDragLine( me );
  18524. if (h == 'h1') {
  18525. h = 'h';
  18526. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  18527. me.execCommand('adaptbywindow');
  18528. } else {
  18529. target = getUETable(target).getPreviewCell(target);
  18530. if (target) {
  18531. var rng = me.selection.getRange();
  18532. rng.selectNodeContents(target).setCursor(true, true)
  18533. }
  18534. }
  18535. }
  18536. if (h == 'h') {
  18537. var ut = getUETable(target),
  18538. table = ut.table,
  18539. cells = getCellsByMoveBorder( target, table, true );
  18540. cells = extractArray( cells, 'left' );
  18541. ut.width = ut.offsetWidth;
  18542. var oldWidth = [],
  18543. newWidth = [];
  18544. utils.each( cells, function( cell ){
  18545. oldWidth.push( cell.offsetWidth );
  18546. } );
  18547. utils.each( cells, function( cell ){
  18548. cell.removeAttribute("width");
  18549. } );
  18550. window.setTimeout( function(){
  18551. //是否允许改变
  18552. var changeable = true;
  18553. utils.each( cells, function( cell, index ){
  18554. var width = cell.offsetWidth;
  18555. if( width > oldWidth[index] ) {
  18556. changeable = false;
  18557. return false;
  18558. }
  18559. newWidth.push( width );
  18560. } );
  18561. var change = changeable ? newWidth : oldWidth;
  18562. utils.each( cells, function( cell, index ){
  18563. cell.width = change[index] - getTabcellSpace();
  18564. } );
  18565. }, 0 );
  18566. // minWidth -= cellMinWidth;
  18567. //
  18568. // table.removeAttribute("width");
  18569. // utils.each(cells, function (cell) {
  18570. // cell.style.width = "";
  18571. // cell.width -= minWidth;
  18572. // });
  18573. }
  18574. }
  18575. }
  18576. }
  18577. function tableClickHander( evt ) {
  18578. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  18579. //trace:3113
  18580. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  18581. utils.each(me.document.getElementsByTagName('table'), function (t) {
  18582. t.ueTable = null;
  18583. });
  18584. startTd = getTargetTd(me, evt);
  18585. if( !startTd ) return;
  18586. var table = domUtils.findParentByTagName(startTd, "table", true);
  18587. ut = getUETable(table);
  18588. ut && ut.clearSelected();
  18589. //判断当前鼠标状态
  18590. if (!onBorder) {
  18591. me.document.body.style.webkitUserSelect = '';
  18592. mousedown = true;
  18593. me.addListener('mouseover', mouseOverEvent);
  18594. } else {
  18595. //边框上的动作处理
  18596. borderActionHandler( evt );
  18597. }
  18598. }
  18599. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  18600. function borderActionHandler( evt ) {
  18601. if ( browser.ie ) {
  18602. evt = reconstruct(evt );
  18603. }
  18604. clearTableDragTimer();
  18605. //是否正在等待resize的缓冲中
  18606. isInResizeBuffer = true;
  18607. tableDragTimer = setTimeout(function(){
  18608. tableBorderDrag( evt );
  18609. }, dblclickTime);
  18610. }
  18611. function extractArray( originArr, key ) {
  18612. var result = [],
  18613. tmp = null;
  18614. for( var i = 0, len = originArr.length; i<len; i++ ) {
  18615. tmp = originArr[ i ][ key ];
  18616. if( tmp ) {
  18617. result.push( tmp );
  18618. }
  18619. }
  18620. return result;
  18621. }
  18622. function clearTableDragTimer() {
  18623. tableDragTimer && clearTimeout(tableDragTimer);
  18624. tableDragTimer = null;
  18625. }
  18626. function reconstruct( obj ) {
  18627. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  18628. newObj = {};
  18629. if( obj ) {
  18630. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  18631. val=obj[ key ];
  18632. val && (newObj[ key ] = val);
  18633. }
  18634. }
  18635. return newObj;
  18636. }
  18637. //边框拖动
  18638. function tableBorderDrag( evt ) {
  18639. isInResizeBuffer = false;
  18640. if( !startTd ) return;
  18641. var state = Math.abs( userActionStatus.x - evt.clientX ) >= Math.abs( userActionStatus.y - evt.clientY ) ? 'h' : 'v';
  18642. // var state = getRelation(startTd, mouseCoords(evt));
  18643. if (/\d/.test(state)) {
  18644. state = state.replace(/\d/, '');
  18645. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  18646. }
  18647. hideDragLine(me);
  18648. getDragLine(me, me.document);
  18649. me.fireEvent('saveScene');
  18650. showDragLineAt(state, startTd);
  18651. mousedown = true;
  18652. //拖动开始
  18653. onDrag = state;
  18654. dragTd = startTd;
  18655. }
  18656. function mouseUpEvent(type, evt) {
  18657. if( isEditorDisabled() ) {
  18658. return ;
  18659. }
  18660. clearTableDragTimer();
  18661. isInResizeBuffer = false;
  18662. if( onBorder ) {
  18663. singleClickState = ++singleClickState % 3;
  18664. userActionStatus = {
  18665. x: evt.clientX,
  18666. y: evt.clientY
  18667. };
  18668. tableResizeTimer = setTimeout(function(){
  18669. singleClickState > 0 && singleClickState--;
  18670. }, dblclickTime );
  18671. if( singleClickState === 2 ) {
  18672. singleClickState = 0;
  18673. tableDbclickHandler(evt);
  18674. return;
  18675. }
  18676. }
  18677. if (evt.button == 2)return;
  18678. var me = this;
  18679. //清除表格上原生跨选问题
  18680. var range = me.selection.getRange(),
  18681. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  18682. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  18683. if (start || end) {
  18684. if (start === end) {
  18685. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  18686. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  18687. if (start !== end) {
  18688. me.selection.clearRange()
  18689. }
  18690. } else {
  18691. me.selection.clearRange()
  18692. }
  18693. }
  18694. mousedown = false;
  18695. me.document.body.style.webkitUserSelect = '';
  18696. //拖拽状态下的mouseUP
  18697. if ( onDrag && dragTd ) {
  18698. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  18699. singleClickState = 0;
  18700. dragLine = me.document.getElementById('ue_tableDragLine');
  18701. var dragTdPos = domUtils.getXY(dragTd),
  18702. dragLinePos = domUtils.getXY(dragLine);
  18703. switch (onDrag) {
  18704. case "h":
  18705. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  18706. break;
  18707. case "v":
  18708. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  18709. break;
  18710. default:
  18711. }
  18712. onDrag = "";
  18713. dragTd = null;
  18714. hideDragLine(me);
  18715. me.fireEvent('saveScene');
  18716. return;
  18717. }
  18718. //正常状态下的mouseup
  18719. if (!startTd) {
  18720. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  18721. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  18722. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  18723. if (me.fireEvent("excludetable", target) === true) return;
  18724. range = new dom.Range(me.document);
  18725. range.setStart(target, 0).setCursor(false, true);
  18726. }
  18727. } else {
  18728. var ut = getUETable(startTd),
  18729. cell = ut ? ut.selectedTds[0] : null;
  18730. if (cell) {
  18731. range = new dom.Range(me.document);
  18732. if (domUtils.isEmptyBlock(cell)) {
  18733. range.setStart(cell, 0).setCursor(false, true);
  18734. } else {
  18735. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  18736. }
  18737. } else {
  18738. range = me.selection.getRange().shrinkBoundary();
  18739. if (!range.collapsed) {
  18740. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  18741. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  18742. //在table里边的不能清除
  18743. if (start && !end || !start && end || start && end && start !== end) {
  18744. range.setCursor(false, true);
  18745. }
  18746. }
  18747. }
  18748. startTd = null;
  18749. me.removeListener('mouseover', mouseOverEvent);
  18750. }
  18751. me._selectionChange(250, evt);
  18752. }
  18753. function mouseOverEvent(type, evt) {
  18754. if( isEditorDisabled() ) {
  18755. return;
  18756. }
  18757. var me = this,
  18758. tar = evt.target || evt.srcElement;
  18759. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  18760. //需要判断两个TD是否位于同一个表格内
  18761. if (startTd && currentTd &&
  18762. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  18763. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  18764. var ut = getUETable(currentTd);
  18765. if (startTd != currentTd) {
  18766. me.document.body.style.webkitUserSelect = 'none';
  18767. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  18768. var range = ut.getCellsRange(startTd, currentTd);
  18769. ut.setSelected(range);
  18770. } else {
  18771. me.document.body.style.webkitUserSelect = '';
  18772. ut.clearSelected();
  18773. }
  18774. }
  18775. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  18776. }
  18777. function setCellHeight(cell, height, backHeight) {
  18778. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  18779. tmpHeight = backHeight + height;
  18780. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  18781. if (cell.style.height) cell.style.height = "";
  18782. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  18783. }
  18784. function getWidth(cell) {
  18785. if (!cell)return 0;
  18786. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  18787. }
  18788. function changeColWidth(cell, changeValue) {
  18789. var ut = getUETable(cell);
  18790. if (ut) {
  18791. //根据当前移动的边框获取相关的单元格
  18792. var table = ut.table,
  18793. cells = getCellsByMoveBorder( cell, table );
  18794. table.style.width = "";
  18795. table.removeAttribute("width");
  18796. //修正改变量
  18797. changeValue = correctChangeValue( changeValue, cell, cells );
  18798. if (cell.nextSibling) {
  18799. var i=0;
  18800. utils.each( cells, function( cellGroup ){
  18801. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  18802. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  18803. } );
  18804. } else {
  18805. utils.each( cells, function( cellGroup ){
  18806. cellGroup.left.width -= -changeValue;
  18807. } );
  18808. }
  18809. }
  18810. }
  18811. function isEditorDisabled() {
  18812. return me.body.contentEditable === "false";
  18813. }
  18814. function changeRowHeight(td, changeValue) {
  18815. if (Math.abs(changeValue) < 10) return;
  18816. var ut = getUETable(td);
  18817. if (ut) {
  18818. var cells = ut.getSameEndPosCells(td, "y"),
  18819. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  18820. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  18821. for (var i = 0, cell; cell = cells[i++];) {
  18822. setCellHeight(cell, changeValue, backHeight);
  18823. }
  18824. }
  18825. }
  18826. /**
  18827. * 获取调整单元格大小的相关单元格
  18828. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  18829. */
  18830. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  18831. if( !table ) {
  18832. table = domUtils.findParentByTagName( cell, 'table' );
  18833. }
  18834. if( !table ) {
  18835. return null;
  18836. }
  18837. //获取到该单元格所在行的序列号
  18838. var index = domUtils.getNodeIndex( cell ),
  18839. temp = cell,
  18840. rows = table.rows,
  18841. colIndex = 0;
  18842. while( temp ) {
  18843. //获取到当前单元格在未发生单元格合并时的序列
  18844. if( temp.nodeType === 1 ) {
  18845. colIndex += (temp.colSpan || 1);
  18846. }
  18847. temp = temp.previousSibling;
  18848. }
  18849. temp = null;
  18850. //记录想关的单元格
  18851. var borderCells = [];
  18852. utils.each(rows, function( tabRow ){
  18853. var cells = tabRow.cells,
  18854. currIndex = 0;
  18855. utils.each( cells, function( tabCell ){
  18856. currIndex += (tabCell.colSpan || 1);
  18857. if( currIndex === colIndex ) {
  18858. borderCells.push({
  18859. left: tabCell,
  18860. right: tabCell.nextSibling || null
  18861. });
  18862. return false;
  18863. } else if( currIndex > colIndex ) {
  18864. if( isContainMergeCell ) {
  18865. borderCells.push({
  18866. left: tabCell
  18867. });
  18868. }
  18869. return false;
  18870. }
  18871. } );
  18872. });
  18873. return borderCells;
  18874. }
  18875. /**
  18876. * 通过给定的单元格集合获取最小的单元格width
  18877. */
  18878. function getMinWidthByTableCells( cells ) {
  18879. var minWidth = Number.MAX_VALUE;
  18880. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  18881. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  18882. }
  18883. return minWidth;
  18884. }
  18885. function correctChangeValue( changeValue, relatedCell, cells ) {
  18886. //为单元格的paading预留空间
  18887. changeValue -= getTabcellSpace();
  18888. if( changeValue < 0 ) {
  18889. return 0;
  18890. }
  18891. changeValue -= getTableCellWidth( relatedCell );
  18892. //确定方向
  18893. var direction = changeValue < 0 ? 'left':'right';
  18894. changeValue = Math.abs(changeValue);
  18895. //只关心非最后一个单元格就可以
  18896. utils.each( cells, function( cellGroup ){
  18897. var curCell = cellGroup[direction];
  18898. //为单元格保留最小空间
  18899. if( curCell ) {
  18900. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  18901. }
  18902. } );
  18903. //修正越界
  18904. changeValue = changeValue < 0 ? 0 : changeValue;
  18905. return direction === 'left' ? -changeValue : changeValue;
  18906. }
  18907. function getTableCellWidth( cell ) {
  18908. var width = 0,
  18909. //偏移纠正量
  18910. offset = 0,
  18911. width = cell.offsetWidth - getTabcellSpace();
  18912. //最后一个节点纠正一下
  18913. if( !cell.nextSibling ) {
  18914. width -= getTableCellOffset( cell );
  18915. }
  18916. width = width < 0 ? 0 : width;
  18917. try {
  18918. cell.width = width;
  18919. } catch(e) {
  18920. }
  18921. return width;
  18922. }
  18923. /**
  18924. * 获取单元格所在表格的最末单元格的偏移量
  18925. */
  18926. function getTableCellOffset( cell ) {
  18927. tab = domUtils.findParentByTagName( cell, "table", false);
  18928. if( tab.offsetVal === undefined ) {
  18929. var prev = cell.previousSibling;
  18930. if( prev ) {
  18931. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  18932. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  18933. } else {
  18934. tab.offsetVal = 0;
  18935. }
  18936. }
  18937. return tab.offsetVal;
  18938. }
  18939. function getTabcellSpace() {
  18940. if( UT.tabcellSpace === undefined ) {
  18941. var cell = null,
  18942. tab = me.document.createElement("table"),
  18943. tbody = me.document.createElement("tbody"),
  18944. trow = me.document.createElement("tr"),
  18945. tabcell = me.document.createElement("td"),
  18946. mirror = null;
  18947. tabcell.style.cssText = 'border: 0;';
  18948. tabcell.width = 1;
  18949. trow.appendChild( tabcell );
  18950. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  18951. tbody.appendChild( trow );
  18952. tab.appendChild( tbody );
  18953. tab.style.cssText = "visibility: hidden;";
  18954. me.body.appendChild( tab );
  18955. UT.paddingSpace = tabcell.offsetWidth - 1;
  18956. var tmpTabWidth = tab.offsetWidth;
  18957. tabcell.style.cssText = '';
  18958. mirror.style.cssText = '';
  18959. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  18960. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  18961. me.body.removeChild( tab );
  18962. }
  18963. getTabcellSpace = function(){ return UT.tabcellSpace; };
  18964. return UT.tabcellSpace;
  18965. }
  18966. function getDragLine(editor, doc) {
  18967. if (mousedown)return;
  18968. dragLine = editor.document.createElement("div");
  18969. domUtils.setAttributes(dragLine, {
  18970. id:"ue_tableDragLine",
  18971. unselectable:'on',
  18972. contenteditable:false,
  18973. 'onresizestart':'return false',
  18974. 'ondragstart':'return false',
  18975. 'onselectstart':'return false',
  18976. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  18977. });
  18978. editor.body.appendChild(dragLine);
  18979. }
  18980. function hideDragLine(editor) {
  18981. if (mousedown)return;
  18982. var line;
  18983. while (line = editor.document.getElementById('ue_tableDragLine')) {
  18984. domUtils.remove(line)
  18985. }
  18986. }
  18987. /**
  18988. * 依据state(v|h)在cell位置显示横线
  18989. * @param state
  18990. * @param cell
  18991. */
  18992. function showDragLineAt(state, cell) {
  18993. if (!cell) return;
  18994. var table = domUtils.findParentByTagName(cell, "table"),
  18995. caption = table.getElementsByTagName('caption'),
  18996. width = table.offsetWidth,
  18997. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  18998. tablePos = domUtils.getXY(table),
  18999. cellPos = domUtils.getXY(cell), css;
  19000. switch (state) {
  19001. case "h":
  19002. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19003. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19004. break;
  19005. case "v":
  19006. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19007. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19008. 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)';
  19009. break;
  19010. default:
  19011. }
  19012. }
  19013. /**
  19014. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19015. * @param editor
  19016. * @param flag
  19017. */
  19018. function switchBorderColor(editor, flag) {
  19019. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19020. for (var i = 0, node; node = tableArr[i++];) {
  19021. var td = domUtils.getElementsByTagName(node, "td");
  19022. if (td[0]) {
  19023. if (flag) {
  19024. color = (td[0].style.borderColor).replace(/\s/g, "");
  19025. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19026. domUtils.addClass(node, "noBorderTable")
  19027. } else {
  19028. domUtils.removeClasses(node, "noBorderTable")
  19029. }
  19030. }
  19031. }
  19032. }
  19033. function getTableWidth(editor, needIEHack, defaultValue) {
  19034. var body = editor.body;
  19035. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19036. }
  19037. /**
  19038. * 获取当前拖动的单元格
  19039. */
  19040. function getTargetTd(editor, evt) {
  19041. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19042. dir = null;
  19043. if( !target ) {
  19044. return null;
  19045. }
  19046. dir = getRelation( target, mouseCoords( evt ) );
  19047. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19048. if( !target ) {
  19049. return null;
  19050. }
  19051. if( dir === 'h1' && target.previousSibling ) {
  19052. var position = domUtils.getXY( target),
  19053. cellWidth = target.offsetWidth;
  19054. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19055. target = target.previousSibling;
  19056. }
  19057. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19058. var position = domUtils.getXY( target),
  19059. cellHeight = target.offsetHeight;
  19060. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19061. target = target.parentNode.previousSibling.firstChild;
  19062. }
  19063. }
  19064. //排除了非td内部以及用于代码高亮部分的td
  19065. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19066. }
  19067. };
  19068. /**
  19069. * Created with JetBrains PhpStorm.
  19070. * User: Jinqn
  19071. * Date: 13-10-12
  19072. * Time: 上午10:20
  19073. * To change this template use File | Settings | File Templates.
  19074. */
  19075. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19076. var table = this.table,
  19077. rows = table.rows,
  19078. trArray = [],
  19079. flag = rows[0].cells[0].tagName === "TH",
  19080. lastRowIndex = 0;
  19081. if(this.selectedTds.length){
  19082. var range = this.cellsRange,
  19083. len = range.endRowIndex + 1;
  19084. for (var i = range.beginRowIndex; i < len; i++) {
  19085. trArray[i] = rows[i];
  19086. }
  19087. trArray.splice(0,range.beginRowIndex);
  19088. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19089. }else{
  19090. for (var i = 0,len = rows.length; i < len; i++) {
  19091. trArray[i] = rows[i];
  19092. }
  19093. }
  19094. var Fn = {
  19095. 'reversecurrent': function(td1,td2){
  19096. return 1;
  19097. },
  19098. 'orderbyasc': function(td1,td2){
  19099. var value1 = td1.innerText||td1.textContent,
  19100. value2 = td2.innerText||td2.textContent;
  19101. return value1.localeCompare(value2);
  19102. },
  19103. 'reversebyasc': function(td1,td2){
  19104. var value1 = td1.innerHTML,
  19105. value2 = td2.innerHTML;
  19106. return value2.localeCompare(value1);
  19107. },
  19108. 'orderbynum': function(td1,td2){
  19109. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19110. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19111. if(value1) value1 = +value1[0];
  19112. if(value2) value2 = +value2[0];
  19113. return (value1||0) - (value2||0);
  19114. },
  19115. 'reversebynum': function(td1,td2){
  19116. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19117. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19118. if(value1) value1 = +value1[0];
  19119. if(value2) value2 = +value2[0];
  19120. return (value2||0) - (value1||0);
  19121. }
  19122. };
  19123. //对表格设置排序的标记data-sort-type
  19124. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19125. //th不参与排序
  19126. flag && trArray.splice(0, 1);
  19127. trArray = utils.sort(trArray,function (tr1, tr2) {
  19128. var result;
  19129. if (compareFn && typeof compareFn === "function") {
  19130. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19131. } else if (compareFn && typeof compareFn === "number") {
  19132. result = 1;
  19133. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  19134. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19135. } else {
  19136. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19137. }
  19138. return result;
  19139. });
  19140. var fragment = table.ownerDocument.createDocumentFragment();
  19141. for (var j = 0, len = trArray.length; j < len; j++) {
  19142. fragment.appendChild(trArray[j]);
  19143. }
  19144. var tbody = table.getElementsByTagName("tbody")[0];
  19145. if(!lastRowIndex){
  19146. tbody.appendChild(fragment);
  19147. }else{
  19148. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  19149. }
  19150. };
  19151. UE.plugins['tablesort'] = function () {
  19152. var me = this,
  19153. UT = UE.UETable,
  19154. getUETable = function (tdOrTable) {
  19155. return UT.getUETable(tdOrTable);
  19156. },
  19157. getTableItemsByRange = function (editor) {
  19158. return UT.getTableItemsByRange(editor);
  19159. };
  19160. me.ready(function () {
  19161. //添加表格可排序的样式
  19162. utils.cssRule('tablesort',
  19163. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  19164. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  19165. me.document);
  19166. //做单元格合并操作时,清除可排序标识
  19167. me.addListener("afterexeccommand", function (type, cmd) {
  19168. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  19169. this.execCommand('disablesort');
  19170. }
  19171. });
  19172. });
  19173. //表格排序
  19174. UE.commands['sorttable'] = {
  19175. queryCommandState: function () {
  19176. var me = this,
  19177. tableItems = getTableItemsByRange(me);
  19178. if (!tableItems.cell) return -1;
  19179. var table = tableItems.table,
  19180. cells = table.getElementsByTagName("td");
  19181. for (var i = 0, cell; cell = cells[i++];) {
  19182. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  19183. }
  19184. return 0;
  19185. },
  19186. execCommand: function (cmd, fn) {
  19187. var me = this,
  19188. range = me.selection.getRange(),
  19189. bk = range.createBookmark(true),
  19190. tableItems = getTableItemsByRange(me),
  19191. cell = tableItems.cell,
  19192. ut = getUETable(tableItems.table),
  19193. cellInfo = ut.getCellInfo(cell);
  19194. ut.sortTable(cellInfo.cellIndex, fn);
  19195. range.moveToBookmark(bk);
  19196. try{
  19197. range.select();
  19198. }catch(e){}
  19199. }
  19200. };
  19201. //设置表格可排序,清除表格可排序
  19202. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  19203. queryCommandState: function (cmd) {
  19204. var table = getTableItemsByRange(this).table;
  19205. if(table && cmd=='enablesort') {
  19206. var cells = domUtils.getElementsByTagName(table, 'th td');
  19207. for(var i = 0; i<cells.length; i++) {
  19208. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  19209. }
  19210. }
  19211. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  19212. },
  19213. execCommand: function (cmd) {
  19214. var table = getTableItemsByRange(this).table;
  19215. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  19216. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  19217. }
  19218. };
  19219. };
  19220. ///import core
  19221. ///commands 右键菜单
  19222. ///commandsName ContextMenu
  19223. ///commandsTitle 右键菜单
  19224. /*
  19225. * 右键菜单
  19226. * @function
  19227. * @name baidu.editor.plugins.contextmenu
  19228. * @author zhanyi
  19229. */
  19230. UE.plugins['contextmenu'] = function () {
  19231. var me = this,
  19232. lang = me.getLang( "contextMenu" ),
  19233. menu,
  19234. items = me.options.contextMenu || [
  19235. {label:lang['selectall'], cmdName:'selectall'},
  19236. {
  19237. label:lang.cleardoc,
  19238. cmdName:'cleardoc',
  19239. exec:function () {
  19240. if ( confirm( lang.confirmclear ) ) {
  19241. this.execCommand( 'cleardoc' );
  19242. }
  19243. }
  19244. },
  19245. '-',
  19246. {
  19247. label:lang.unlink,
  19248. cmdName:'unlink'
  19249. },
  19250. '-',
  19251. {
  19252. group:lang.paragraph,
  19253. icon:'justifyjustify',
  19254. subMenu:[
  19255. {
  19256. label:lang.justifyleft,
  19257. cmdName:'justify',
  19258. value:'left'
  19259. },
  19260. {
  19261. label:lang.justifyright,
  19262. cmdName:'justify',
  19263. value:'right'
  19264. },
  19265. {
  19266. label:lang.justifycenter,
  19267. cmdName:'justify',
  19268. value:'center'
  19269. },
  19270. {
  19271. label:lang.justifyjustify,
  19272. cmdName:'justify',
  19273. value:'justify'
  19274. }
  19275. ]
  19276. },
  19277. '-',
  19278. {
  19279. group:lang.table,
  19280. icon:'table',
  19281. subMenu:[
  19282. {
  19283. label:lang.inserttable,
  19284. cmdName:'inserttable'
  19285. },
  19286. {
  19287. label:lang.deletetable,
  19288. cmdName:'deletetable'
  19289. },
  19290. '-',
  19291. {
  19292. label:lang.deleterow,
  19293. cmdName:'deleterow'
  19294. },
  19295. {
  19296. label:lang.deletecol,
  19297. cmdName:'deletecol'
  19298. },
  19299. {
  19300. label:lang.insertcol,
  19301. cmdName:'insertcol'
  19302. },
  19303. {
  19304. label:lang.insertcolnext,
  19305. cmdName:'insertcolnext'
  19306. },
  19307. {
  19308. label:lang.insertrow,
  19309. cmdName:'insertrow'
  19310. },
  19311. {
  19312. label:lang.insertrownext,
  19313. cmdName:'insertrownext'
  19314. },
  19315. '-',
  19316. {
  19317. label:lang.insertcaption,
  19318. cmdName:'insertcaption'
  19319. },
  19320. {
  19321. label:lang.deletecaption,
  19322. cmdName:'deletecaption'
  19323. },
  19324. {
  19325. label:lang.inserttitle,
  19326. cmdName:'inserttitle'
  19327. },
  19328. {
  19329. label:lang.deletetitle,
  19330. cmdName:'deletetitle'
  19331. },
  19332. {
  19333. label:lang.inserttitlecol,
  19334. cmdName:'inserttitlecol'
  19335. },
  19336. {
  19337. label:lang.deletetitlecol,
  19338. cmdName:'deletetitlecol'
  19339. },
  19340. '-',
  19341. {
  19342. label:lang.mergecells,
  19343. cmdName:'mergecells'
  19344. },
  19345. {
  19346. label:lang.mergeright,
  19347. cmdName:'mergeright'
  19348. },
  19349. {
  19350. label:lang.mergedown,
  19351. cmdName:'mergedown'
  19352. },
  19353. '-',
  19354. {
  19355. label:lang.splittorows,
  19356. cmdName:'splittorows'
  19357. },
  19358. {
  19359. label:lang.splittocols,
  19360. cmdName:'splittocols'
  19361. },
  19362. {
  19363. label:lang.splittocells,
  19364. cmdName:'splittocells'
  19365. },
  19366. '-',
  19367. {
  19368. label:lang.averageDiseRow,
  19369. cmdName:'averagedistributerow'
  19370. },
  19371. {
  19372. label:lang.averageDisCol,
  19373. cmdName:'averagedistributecol'
  19374. },
  19375. '-',
  19376. {
  19377. label:lang.edittd,
  19378. cmdName:'edittd',
  19379. exec:function () {
  19380. if ( UE.ui['edittd'] ) {
  19381. new UE.ui['edittd']( this );
  19382. }
  19383. this.getDialog('edittd').open();
  19384. }
  19385. },
  19386. {
  19387. label:lang.edittable,
  19388. cmdName:'edittable',
  19389. exec:function () {
  19390. if ( UE.ui['edittable'] ) {
  19391. new UE.ui['edittable']( this );
  19392. }
  19393. this.getDialog('edittable').open();
  19394. }
  19395. },
  19396. {
  19397. label:lang.setbordervisible,
  19398. cmdName:'setbordervisible'
  19399. }
  19400. ]
  19401. },
  19402. {
  19403. group:lang.tablesort,
  19404. icon:'tablesort',
  19405. subMenu:[
  19406. {
  19407. label:lang.enablesort,
  19408. cmdName:'enablesort'
  19409. },
  19410. {
  19411. label:lang.disablesort,
  19412. cmdName:'disablesort'
  19413. },
  19414. '-',
  19415. {
  19416. label:lang.reversecurrent,
  19417. cmdName:'sorttable',
  19418. value:'reversecurrent'
  19419. },
  19420. {
  19421. label:lang.orderbyasc,
  19422. cmdName:'sorttable',
  19423. value:'orderbyasc'
  19424. },
  19425. {
  19426. label:lang.reversebyasc,
  19427. cmdName:'sorttable',
  19428. value:'reversebyasc'
  19429. },
  19430. {
  19431. label:lang.orderbynum,
  19432. cmdName:'sorttable',
  19433. value:'orderbynum'
  19434. },
  19435. {
  19436. label:lang.reversebynum,
  19437. cmdName:'sorttable',
  19438. value:'reversebynum'
  19439. }
  19440. ]
  19441. },
  19442. {
  19443. group:lang.borderbk,
  19444. icon:'borderBack',
  19445. subMenu:[
  19446. {
  19447. label:lang.setcolor,
  19448. cmdName:"interlacetable",
  19449. exec:function(){
  19450. this.execCommand("interlacetable");
  19451. }
  19452. },
  19453. {
  19454. label:lang.unsetcolor,
  19455. cmdName:"uninterlacetable",
  19456. exec:function(){
  19457. this.execCommand("uninterlacetable");
  19458. }
  19459. },
  19460. {
  19461. label:lang.setbackground,
  19462. cmdName:"settablebackground",
  19463. exec:function(){
  19464. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  19465. }
  19466. },
  19467. {
  19468. label:lang.unsetbackground,
  19469. cmdName:"cleartablebackground",
  19470. exec:function(){
  19471. this.execCommand("cleartablebackground");
  19472. }
  19473. },
  19474. {
  19475. label:lang.redandblue,
  19476. cmdName:"settablebackground",
  19477. exec:function(){
  19478. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  19479. }
  19480. },
  19481. {
  19482. label:lang.threecolorgradient,
  19483. cmdName:"settablebackground",
  19484. exec:function(){
  19485. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  19486. }
  19487. }
  19488. ]
  19489. },
  19490. {
  19491. group:lang.aligntd,
  19492. icon:'aligntd',
  19493. subMenu:[
  19494. {
  19495. cmdName:'cellalignment',
  19496. value:{align:'left',vAlign:'top'}
  19497. },
  19498. {
  19499. cmdName:'cellalignment',
  19500. value:{align:'center',vAlign:'top'}
  19501. },
  19502. {
  19503. cmdName:'cellalignment',
  19504. value:{align:'right',vAlign:'top'}
  19505. },
  19506. {
  19507. cmdName:'cellalignment',
  19508. value:{align:'left',vAlign:'middle'}
  19509. },
  19510. {
  19511. cmdName:'cellalignment',
  19512. value:{align:'center',vAlign:'middle'}
  19513. },
  19514. {
  19515. cmdName:'cellalignment',
  19516. value:{align:'right',vAlign:'middle'}
  19517. },
  19518. {
  19519. cmdName:'cellalignment',
  19520. value:{align:'left',vAlign:'bottom'}
  19521. },
  19522. {
  19523. cmdName:'cellalignment',
  19524. value:{align:'center',vAlign:'bottom'}
  19525. },
  19526. {
  19527. cmdName:'cellalignment',
  19528. value:{align:'right',vAlign:'bottom'}
  19529. }
  19530. ]
  19531. },
  19532. {
  19533. group:lang.aligntable,
  19534. icon:'aligntable',
  19535. subMenu:[
  19536. {
  19537. cmdName:'tablealignment',
  19538. className: 'left',
  19539. label:lang.tableleft,
  19540. value:"left"
  19541. },
  19542. {
  19543. cmdName:'tablealignment',
  19544. className: 'center',
  19545. label:lang.tablecenter,
  19546. value:"center"
  19547. },
  19548. {
  19549. cmdName:'tablealignment',
  19550. className: 'right',
  19551. label:lang.tableright,
  19552. value:"right"
  19553. }
  19554. ]
  19555. },
  19556. '-',
  19557. {
  19558. label:lang.insertparagraphbefore,
  19559. cmdName:'insertparagraph',
  19560. value:true
  19561. },
  19562. {
  19563. label:lang.insertparagraphafter,
  19564. cmdName:'insertparagraph'
  19565. },
  19566. {
  19567. label:lang['copy'],
  19568. cmdName:'copy',
  19569. exec:function () {
  19570. alert( lang.copymsg );
  19571. },
  19572. query:function () {
  19573. return 0;
  19574. }
  19575. },
  19576. {
  19577. label:lang['paste'],
  19578. cmdName:'paste',
  19579. exec:function () {
  19580. alert( lang.pastemsg );
  19581. },
  19582. query:function () {
  19583. return 0;
  19584. }
  19585. }
  19586. ];
  19587. if ( !items.length ) {
  19588. return;
  19589. }
  19590. var uiUtils = UE.ui.uiUtils;
  19591. me.addListener( 'contextmenu', function ( type, evt ) {
  19592. var offset = uiUtils.getViewportOffsetByEvent( evt );
  19593. me.fireEvent( 'beforeselectionchange' );
  19594. if ( menu ) {
  19595. menu.destroy();
  19596. }
  19597. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  19598. var last;
  19599. (function ( item ) {
  19600. if ( item == '-' ) {
  19601. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  19602. contextItems.push( '-' );
  19603. }
  19604. } else if ( item.hasOwnProperty( "group" ) ) {
  19605. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  19606. (function ( subItem ) {
  19607. if ( subItem == '-' ) {
  19608. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  19609. subMenu.push( '-' );
  19610. }else{
  19611. subMenu.splice(subMenu.length-1);
  19612. }
  19613. } else {
  19614. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  19615. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  19616. subMenu.push( {
  19617. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  19618. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  19619. onclick:subItem.exec ? function () {
  19620. subItem.exec.call( me );
  19621. } : function () {
  19622. me.execCommand( subItem.cmdName, subItem.value );
  19623. }
  19624. } );
  19625. }
  19626. }
  19627. })( cj );
  19628. }
  19629. if ( subMenu.length ) {
  19630. function getLabel(){
  19631. switch (item.icon){
  19632. case "table":
  19633. return me.getLang( "contextMenu.table" );
  19634. case "justifyjustify":
  19635. return me.getLang( "contextMenu.paragraph" );
  19636. case "aligntd":
  19637. return me.getLang("contextMenu.aligntd");
  19638. case "aligntable":
  19639. return me.getLang("contextMenu.aligntable");
  19640. case "tablesort":
  19641. return lang.tablesort;
  19642. case "borderBack":
  19643. return lang.borderbk;
  19644. default :
  19645. return '';
  19646. }
  19647. }
  19648. contextItems.push( {
  19649. //todo 修正成自动获取方式
  19650. 'label':getLabel(),
  19651. className:'edui-for-' + item.icon,
  19652. 'subMenu':{
  19653. items:subMenu,
  19654. editor:me
  19655. }
  19656. } );
  19657. }
  19658. } else {
  19659. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  19660. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  19661. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  19662. contextItems.push( {
  19663. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  19664. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  19665. onclick:item.exec ? function () {
  19666. item.exec.call( me );
  19667. } : function () {
  19668. me.execCommand( item.cmdName, item.value );
  19669. }
  19670. } );
  19671. }
  19672. }
  19673. })( ti );
  19674. }
  19675. if ( contextItems[contextItems.length - 1] == '-' ) {
  19676. contextItems.pop();
  19677. }
  19678. menu = new UE.ui.Menu( {
  19679. items:contextItems,
  19680. className:"edui-contextmenu",
  19681. editor:me
  19682. } );
  19683. menu.render();
  19684. menu.showAt( offset );
  19685. me.fireEvent("aftershowcontextmenu",menu);
  19686. domUtils.preventDefault( evt );
  19687. if ( browser.ie ) {
  19688. var ieRange;
  19689. try {
  19690. ieRange = me.selection.getNative().createRange();
  19691. } catch ( e ) {
  19692. return;
  19693. }
  19694. if ( ieRange.item ) {
  19695. var range = new dom.Range( me.document );
  19696. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  19697. }
  19698. }
  19699. } );
  19700. };
  19701. ///import core
  19702. ///commands 弹出菜单
  19703. // commandsName popupmenu
  19704. ///commandsTitle 弹出菜单
  19705. /*
  19706. * 弹出菜单
  19707. * @function
  19708. * @name baidu.editor.plugins.popupmenu
  19709. * @author xuheng
  19710. */
  19711. UE.plugins['shortcutmenu'] = function () {
  19712. var me = this,
  19713. menu,
  19714. items = me.options.shortcutMenu || [];
  19715. if (!items.length) {
  19716. return;
  19717. }
  19718. me.addListener ('contextmenu mouseup' , function (type , e) {
  19719. var me = this,
  19720. customEvt = {
  19721. type : type ,
  19722. target : e.target || e.srcElement ,
  19723. screenX : e.screenX ,
  19724. screenY : e.screenY ,
  19725. clientX : e.clientX ,
  19726. clientY : e.clientY
  19727. };
  19728. setTimeout (function () {
  19729. var rng = me.selection.getRange ();
  19730. if (rng.collapsed === false || type == "contextmenu") {
  19731. if (!menu) {
  19732. menu = new baidu.editor.ui.ShortCutMenu ({
  19733. editor : me ,
  19734. items : items ,
  19735. theme : me.options.theme ,
  19736. className : 'edui-shortcutmenu'
  19737. });
  19738. menu.render ();
  19739. me.fireEvent ("afterrendershortcutmenu" , menu);
  19740. }
  19741. menu.show (customEvt , !!UE.plugins['contextmenu']);
  19742. }
  19743. });
  19744. if (type == 'contextmenu') {
  19745. domUtils.preventDefault (e);
  19746. if (browser.ie9below) {
  19747. var ieRange;
  19748. try {
  19749. ieRange = me.selection.getNative().createRange();
  19750. } catch (e) {
  19751. return;
  19752. }
  19753. if (ieRange.item) {
  19754. var range = new dom.Range (me.document);
  19755. range.selectNode (ieRange.item (0)).select (true , true);
  19756. }
  19757. }
  19758. }
  19759. });
  19760. me.addListener ('keydown' , function (type) {
  19761. if (type == "keydown") {
  19762. menu && !menu.isHidden && menu.hide ();
  19763. }
  19764. });
  19765. };
  19766. /**
  19767. * B、I、sub、super命令支持
  19768. * @file
  19769. * @since 1.2.6.1
  19770. */
  19771. UE.plugins['basestyle'] = function(){
  19772. /**
  19773. * 字体加粗
  19774. * @command bold
  19775. * @param { String } cmd 命令字符串
  19776. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  19777. * @method execCommand
  19778. * @example
  19779. * ```javascript
  19780. * //editor是编辑器实例
  19781. * //对当前选中的文本内容执行加粗操作
  19782. * //第一次执行, 文本内容加粗
  19783. * editor.execCommand( 'bold' );
  19784. *
  19785. * //第二次执行, 文本内容取消加粗
  19786. * editor.execCommand( 'bold' );
  19787. * ```
  19788. */
  19789. /**
  19790. * 字体倾斜
  19791. * @command italic
  19792. * @method execCommand
  19793. * @param { String } cmd 命令字符串
  19794. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  19795. * @example
  19796. * ```javascript
  19797. * //editor是编辑器实例
  19798. * //对当前选中的文本内容执行斜体操作
  19799. * //第一次操作, 文本内容将变成斜体
  19800. * editor.execCommand( 'italic' );
  19801. *
  19802. * //再次对同一文本内容执行, 则文本内容将恢复正常
  19803. * editor.execCommand( 'italic' );
  19804. * ```
  19805. */
  19806. /**
  19807. * 下标文本,与“superscript”命令互斥
  19808. * @command subscript
  19809. * @method execCommand
  19810. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  19811. * @param { String } cmd 命令字符串
  19812. * @example
  19813. * ```javascript
  19814. * //editor是编辑器实例
  19815. * //对当前选中的文本内容执行下标操作
  19816. * //第一次操作, 文本内容将变成下标文本
  19817. * editor.execCommand( 'subscript' );
  19818. *
  19819. * //再次对同一文本内容执行, 则文本内容将恢复正常
  19820. * editor.execCommand( 'subscript' );
  19821. * ```
  19822. */
  19823. /**
  19824. * 上标文本,与“subscript”命令互斥
  19825. * @command superscript
  19826. * @method execCommand
  19827. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  19828. * @param { String } cmd 命令字符串
  19829. * @example
  19830. * ```javascript
  19831. * //editor是编辑器实例
  19832. * //对当前选中的文本内容执行上标操作
  19833. * //第一次操作, 文本内容将变成上标文本
  19834. * editor.execCommand( 'superscript' );
  19835. *
  19836. * //再次对同一文本内容执行, 则文本内容将恢复正常
  19837. * editor.execCommand( 'superscript' );
  19838. * ```
  19839. */
  19840. var basestyles = {
  19841. 'bold':['strong','b'],
  19842. 'italic':['em','i'],
  19843. 'subscript':['sub'],
  19844. 'superscript':['sup']
  19845. },
  19846. getObj = function(editor,tagNames){
  19847. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  19848. },
  19849. me = this;
  19850. //添加快捷键
  19851. me.addshortcutkey({
  19852. "Bold" : "ctrl+66",//^B
  19853. "Italic" : "ctrl+73", //^I
  19854. "Underline" : "ctrl+85"//^U
  19855. });
  19856. me.addInputRule(function(root){
  19857. utils.each(root.getNodesByTagName('b i'),function(node){
  19858. switch (node.tagName){
  19859. case 'b':
  19860. node.tagName = 'strong';
  19861. break;
  19862. case 'i':
  19863. node.tagName = 'em';
  19864. }
  19865. });
  19866. });
  19867. for ( var style in basestyles ) {
  19868. (function( cmd, tagNames ) {
  19869. me.commands[cmd] = {
  19870. execCommand : function( cmdName ) {
  19871. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  19872. if ( range.collapsed ) {
  19873. if ( obj ) {
  19874. var tmpText = me.document.createTextNode('');
  19875. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  19876. range.setStartBefore(tmpText);
  19877. domUtils.remove(tmpText);
  19878. } else {
  19879. var tmpNode = range.document.createElement( tagNames[0] );
  19880. if(cmdName == 'superscript' || cmdName == 'subscript'){
  19881. tmpText = me.document.createTextNode('');
  19882. range.insertNode(tmpText)
  19883. .removeInlineStyle(['sub','sup'])
  19884. .setStartBefore(tmpText)
  19885. .collapse(true);
  19886. }
  19887. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  19888. }
  19889. range.collapse( true );
  19890. } else {
  19891. if(cmdName == 'superscript' || cmdName == 'subscript'){
  19892. if(!obj || obj.tagName.toLowerCase() != cmdName){
  19893. range.removeInlineStyle(['sub','sup']);
  19894. }
  19895. }
  19896. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  19897. }
  19898. range.select();
  19899. },
  19900. queryCommandState : function() {
  19901. return getObj(this,tagNames) ? 1 : 0;
  19902. }
  19903. };
  19904. })( style, basestyles[style] );
  19905. }
  19906. };
  19907. /**
  19908. * 选取路径命令
  19909. * @file
  19910. */
  19911. UE.plugins['elementpath'] = function(){
  19912. var currentLevel,
  19913. tagNames,
  19914. me = this;
  19915. me.setOpt('elementPathEnabled',true);
  19916. if(!me.options.elementPathEnabled){
  19917. return;
  19918. }
  19919. me.commands['elementpath'] = {
  19920. execCommand : function( cmdName, level ) {
  19921. var start = tagNames[level],
  19922. range = me.selection.getRange();
  19923. currentLevel = level*1;
  19924. range.selectNode(start).select();
  19925. },
  19926. queryCommandValue : function() {
  19927. //产生一个副本,不能修改原来的startElementPath;
  19928. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  19929. names = [];
  19930. tagNames = parents;
  19931. for(var i=0,ci;ci=parents[i];i++){
  19932. if(ci.nodeType == 3) {
  19933. continue;
  19934. }
  19935. var name = ci.tagName.toLowerCase();
  19936. if(name == 'img' && ci.getAttribute('anchorname')){
  19937. name = 'anchor';
  19938. }
  19939. names[i] = name;
  19940. if(currentLevel == i){
  19941. currentLevel = -1;
  19942. break;
  19943. }
  19944. }
  19945. return names;
  19946. }
  19947. };
  19948. };
  19949. /**
  19950. * 格式刷,只格式inline的
  19951. * @file
  19952. * @since 1.2.6.1
  19953. */
  19954. /**
  19955. * 格式刷
  19956. * @command formatmatch
  19957. * @method execCommand
  19958. * @remind 该操作不能复制段落格式
  19959. * @param { String } cmd 命令字符串
  19960. * @example
  19961. * ```javascript
  19962. * //editor是编辑器实例
  19963. * //获取格式刷
  19964. * editor.execCommand( 'formatmatch' );
  19965. * ```
  19966. */
  19967. UE.plugins['formatmatch'] = function(){
  19968. var me = this,
  19969. list = [],img,
  19970. flag = 0;
  19971. me.addListener('reset',function(){
  19972. list = [];
  19973. flag = 0;
  19974. });
  19975. function addList(type,evt){
  19976. if(browser.webkit){
  19977. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  19978. }
  19979. function addFormat(range){
  19980. if(text){
  19981. range.selectNode(text);
  19982. }
  19983. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  19984. }
  19985. me.undoManger && me.undoManger.save();
  19986. var range = me.selection.getRange(),
  19987. imgT = target || range.getClosedNode();
  19988. if(img && imgT && imgT.tagName == 'IMG'){
  19989. //trace:964
  19990. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  19991. img = null;
  19992. }else{
  19993. if(!img){
  19994. var collapsed = range.collapsed;
  19995. if(collapsed){
  19996. var text = me.document.createTextNode('match');
  19997. range.insertNode(text).select();
  19998. }
  19999. me.__hasEnterExecCommand = true;
  20000. //不能把block上的属性干掉
  20001. //trace:1553
  20002. var removeFormatAttributes = me.options.removeFormatAttributes;
  20003. me.options.removeFormatAttributes = '';
  20004. me.execCommand('removeformat');
  20005. me.options.removeFormatAttributes = removeFormatAttributes;
  20006. me.__hasEnterExecCommand = false;
  20007. //trace:969
  20008. range = me.selection.getRange();
  20009. if(list.length){
  20010. addFormat(range);
  20011. }
  20012. if(text){
  20013. range.setStartBefore(text).collapse(true);
  20014. }
  20015. range.select();
  20016. text && domUtils.remove(text);
  20017. }
  20018. }
  20019. me.undoManger && me.undoManger.save();
  20020. me.removeListener('mouseup',addList);
  20021. flag = 0;
  20022. }
  20023. me.commands['formatmatch'] = {
  20024. execCommand : function( cmdName ) {
  20025. if(flag){
  20026. flag = 0;
  20027. list = [];
  20028. me.removeListener('mouseup',addList);
  20029. return;
  20030. }
  20031. var range = me.selection.getRange();
  20032. img = range.getClosedNode();
  20033. if(!img || img.tagName != 'IMG'){
  20034. range.collapse(true).shrinkBoundary();
  20035. var start = range.startContainer;
  20036. list = domUtils.findParents(start,true,function(node){
  20037. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20038. });
  20039. //a不能加入格式刷, 并且克隆节点
  20040. for(var i=0,ci;ci=list[i];i++){
  20041. if(ci.tagName == 'A'){
  20042. list.splice(i,1);
  20043. break;
  20044. }
  20045. }
  20046. }
  20047. me.addListener('mouseup',addList);
  20048. flag = 1;
  20049. },
  20050. queryCommandState : function() {
  20051. return flag;
  20052. },
  20053. notNeedUndo : 1
  20054. };
  20055. };
  20056. ///import core
  20057. ///commands 查找替换
  20058. ///commandsName SearchReplace
  20059. ///commandsTitle 查询替换
  20060. ///commandsDialog dialogs\searchreplace
  20061. /*
  20062. * @description 查找替换
  20063. * @author zhanyi
  20064. */
  20065. UE.plugin.register('searchreplace',function(){
  20066. var me = this;
  20067. function findTextInString(textContent,opt,currentIndex){
  20068. var str = opt.searchStr;
  20069. if(opt.dir == -1){
  20070. textContent = textContent.split('').reverse().join('');
  20071. str = str.split('').reverse().join('');
  20072. currentIndex = textContent.length - currentIndex;
  20073. }
  20074. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20075. while(match = reg.exec(textContent)){
  20076. if(match.index >= currentIndex){
  20077. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20078. }
  20079. }
  20080. return -1
  20081. }
  20082. function findTextBlockElm(node,currentIndex,opt){
  20083. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20084. if(domUtils.isBody(node)){
  20085. node = node.firstChild;
  20086. }
  20087. var first = 1;
  20088. while(node){
  20089. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20090. index = findTextInString(textContent,opt,currentIndex );
  20091. first = 0;
  20092. if(index!=-1){
  20093. return {
  20094. 'node':node,
  20095. 'index':index
  20096. }
  20097. }
  20098. node = domUtils[methodName](node);
  20099. if(node){
  20100. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20101. }
  20102. }
  20103. }
  20104. function findNTextInBlockElm(node,index,str){
  20105. var currentIndex = 0,
  20106. currentNode = node.firstChild,
  20107. currentNodeLength = 0,
  20108. result;
  20109. while(currentNode){
  20110. if(currentNode.nodeType == 3){
  20111. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20112. currentIndex += currentNodeLength;
  20113. if(currentIndex >= index){
  20114. return {
  20115. 'node':currentNode,
  20116. 'index': currentNodeLength - (currentIndex - index)
  20117. }
  20118. }
  20119. }else if(!dtd.$empty[currentNode.tagName]){
  20120. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  20121. currentIndex += currentNodeLength;
  20122. if(currentIndex >= index){
  20123. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  20124. if(result){
  20125. return result;
  20126. }
  20127. }
  20128. }
  20129. currentNode = domUtils.getNextDomNode(currentNode);
  20130. }
  20131. }
  20132. function searchReplace(me,opt){
  20133. var rng = me.selection.getRange(),
  20134. startBlockNode,
  20135. searchStr = opt.searchStr,
  20136. span = me.document.createElement('span');
  20137. span.innerHTML = '$$ueditor_searchreplace_key$$';
  20138. //判断是不是第一次选中
  20139. if(!rng.collapsed){
  20140. rng.select();
  20141. var rngText = me.selection.getText();
  20142. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  20143. if(opt.replaceStr != undefined){
  20144. replaceText(rng,opt.replaceStr);
  20145. rng.select();
  20146. return true;
  20147. }else{
  20148. rng.collapse(opt.dir == -1)
  20149. }
  20150. }
  20151. }
  20152. rng.insertNode(span);
  20153. rng.enlargeToBlockElm(true);
  20154. startBlockNode = rng.startContainer;
  20155. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  20156. rng.setStartBefore(span);
  20157. domUtils.remove(span);
  20158. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  20159. if(result){
  20160. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  20161. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  20162. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  20163. if(opt.replaceStr !== undefined){
  20164. replaceText(rng,opt.replaceStr)
  20165. }
  20166. rng.select();
  20167. return true;
  20168. }else{
  20169. rng.setCursor()
  20170. }
  20171. }
  20172. function replaceText(rng,str){
  20173. me.fireEvent('saveScene');
  20174. str = me.document.createTextNode(str);
  20175. rng.deleteContents().insertNode(str);
  20176. me.fireEvent('saveScene');
  20177. }
  20178. return {
  20179. commands:{
  20180. 'searchreplace':{
  20181. execCommand:function(cmdName,opt){
  20182. utils.extend(opt,{
  20183. all : false,
  20184. casesensitive : false,
  20185. dir : 1
  20186. },true);
  20187. var num = 0;
  20188. if(opt.all){
  20189. var rng = me.selection.getRange(),
  20190. first = me.body.firstChild;
  20191. if(first && first.nodeType == 1){
  20192. rng.setStart(first,0)
  20193. }else if(first.nodeType == 3){
  20194. rng.setStartBefore(first)
  20195. }
  20196. rng.collapse(true).select(true);
  20197. while(searchReplace(this,opt)){
  20198. num++;
  20199. }
  20200. }else{
  20201. if(searchReplace(this,opt)){
  20202. num++
  20203. }
  20204. }
  20205. return num;
  20206. },
  20207. notNeedUndo:1
  20208. }
  20209. }
  20210. }
  20211. });
  20212. /**
  20213. * 自定义样式
  20214. * @file
  20215. * @since 1.2.6.1
  20216. */
  20217. /**
  20218. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  20219. * @command customstyle
  20220. * @method execCommand
  20221. * @param { String } cmd 命令字符串
  20222. * @example
  20223. * ```javascript
  20224. * editor.execCommand( 'customstyle' );
  20225. * ```
  20226. */
  20227. UE.plugins['customstyle'] = function() {
  20228. var me = this;
  20229. me.setOpt({ 'customstyle':[
  20230. {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;'},
  20231. {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;'},
  20232. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  20233. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  20234. ]});
  20235. me.commands['customstyle'] = {
  20236. execCommand : function(cmdName, obj) {
  20237. var me = this,
  20238. tagName = obj.tag,
  20239. node = domUtils.findParent(me.selection.getStart(), function(node) {
  20240. return node.getAttribute('label');
  20241. }, true),
  20242. range,bk,tmpObj = {};
  20243. for (var p in obj) {
  20244. if(obj[p]!==undefined)
  20245. tmpObj[p] = obj[p];
  20246. }
  20247. delete tmpObj.tag;
  20248. if (node && node.getAttribute('label') == obj.label) {
  20249. range = this.selection.getRange();
  20250. bk = range.createBookmark();
  20251. if (range.collapsed) {
  20252. //trace:1732 删掉自定义标签,要有p来回填站位
  20253. if(dtd.$block[node.tagName]){
  20254. var fillNode = me.document.createElement('p');
  20255. domUtils.moveChild(node, fillNode);
  20256. node.parentNode.insertBefore(fillNode, node);
  20257. domUtils.remove(node);
  20258. }else{
  20259. domUtils.remove(node,true);
  20260. }
  20261. } else {
  20262. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  20263. nodes = domUtils.getElementsByTagName(common, tagName);
  20264. if(new RegExp(tagName,'i').test(common.tagName)){
  20265. nodes.push(common);
  20266. }
  20267. for (var i = 0,ni; ni = nodes[i++];) {
  20268. if (ni.getAttribute('label') == obj.label) {
  20269. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  20270. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  20271. &&
  20272. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  20273. )
  20274. if (dtd.$block[tagName]) {
  20275. var fillNode = me.document.createElement('p');
  20276. domUtils.moveChild(ni, fillNode);
  20277. ni.parentNode.insertBefore(fillNode, ni);
  20278. }
  20279. domUtils.remove(ni, true);
  20280. }
  20281. }
  20282. node = domUtils.findParent(common, function(node) {
  20283. return node.getAttribute('label') == obj.label;
  20284. }, true);
  20285. if (node) {
  20286. domUtils.remove(node, true);
  20287. }
  20288. }
  20289. range.moveToBookmark(bk).select();
  20290. } else {
  20291. if (dtd.$block[tagName]) {
  20292. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  20293. range = me.selection.getRange();
  20294. if (!range.collapsed) {
  20295. range.collapse();
  20296. node = domUtils.findParent(me.selection.getStart(), function(node) {
  20297. return node.getAttribute('label') == obj.label;
  20298. }, true);
  20299. var pNode = me.document.createElement('p');
  20300. domUtils.insertAfter(node, pNode);
  20301. domUtils.fillNode(me.document, pNode);
  20302. range.setStart(pNode, 0).setCursor();
  20303. }
  20304. } else {
  20305. range = me.selection.getRange();
  20306. if (range.collapsed) {
  20307. node = me.document.createElement(tagName);
  20308. domUtils.setAttributes(node, tmpObj);
  20309. range.insertNode(node).setStart(node, 0).setCursor();
  20310. return;
  20311. }
  20312. bk = range.createBookmark();
  20313. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  20314. }
  20315. }
  20316. },
  20317. queryCommandValue : function() {
  20318. var parent = domUtils.filterNodeList(
  20319. this.selection.getStartElementPath(),
  20320. function(node){return node.getAttribute('label')}
  20321. );
  20322. return parent ? parent.getAttribute('label') : '';
  20323. }
  20324. };
  20325. //当去掉customstyle是,如果是块元素,用p代替
  20326. me.addListener('keyup', function(type, evt) {
  20327. var keyCode = evt.keyCode || evt.which;
  20328. if (keyCode == 32 || keyCode == 13) {
  20329. var range = me.selection.getRange();
  20330. if (range.collapsed) {
  20331. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  20332. return node.getAttribute('label');
  20333. }, true);
  20334. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  20335. var p = me.document.createElement('p');
  20336. domUtils.insertAfter(node, p);
  20337. domUtils.fillNode(me.document, p);
  20338. domUtils.remove(node);
  20339. range.setStart(p, 0).setCursor();
  20340. }
  20341. }
  20342. }
  20343. });
  20344. };
  20345. ///import core
  20346. ///commands 远程图片抓取
  20347. ///commandsName catchRemoteImage,catchremoteimageenable
  20348. ///commandsTitle 远程图片抓取
  20349. /*
  20350. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  20351. *
  20352. */
  20353. UE.plugins['catchremoteimage'] = function () {
  20354. if (this.options.catchRemoteImageEnable===false){
  20355. return;
  20356. }
  20357. var me = this;
  20358. this.setOpt({
  20359. localDomain:["127.0.0.1","localhost","img.baidu.com"],
  20360. separater:'ue_separate_ue',
  20361. catchFieldName:"upfile",
  20362. catchRemoteImageEnable:true
  20363. });
  20364. var ajax = UE.ajax,
  20365. localDomain = me.options.localDomain ,
  20366. catcherUrl = me.options.catcherUrl,
  20367. separater = me.options.separater;
  20368. function catchremoteimage(imgs, callbacks) {
  20369. var submitStr = imgs.join(separater);
  20370. var tmpOption = {
  20371. timeout:60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  20372. onsuccess:callbacks["success"],
  20373. onerror:callbacks["error"]
  20374. };
  20375. tmpOption[me.options.catchFieldName] = submitStr;
  20376. ajax.request(catcherUrl, tmpOption);
  20377. }
  20378. me.addListener("afterpaste", function () {
  20379. me.fireEvent("catchRemoteImage");
  20380. });
  20381. me.addListener("catchRemoteImage", function () {
  20382. var remoteImages = [];
  20383. var imgs = domUtils.getElementsByTagName(me.document, "img");
  20384. var test = function (src,urls) {
  20385. for (var j = 0, url; url = urls[j++];) {
  20386. if (src.indexOf(url) !== -1) {
  20387. return true;
  20388. }
  20389. }
  20390. return false;
  20391. };
  20392. for (var i = 0, ci; ci = imgs[i++];) {
  20393. if (ci.getAttribute("word_img")){
  20394. continue;
  20395. }
  20396. var src = ci.getAttribute("_src") || ci.src || "";
  20397. if (/^(https?|ftp):/i.test(src) && !test(src,localDomain)) {
  20398. remoteImages.push(src);
  20399. }
  20400. }
  20401. if (remoteImages.length) {
  20402. catchremoteimage(remoteImages, {
  20403. //成功抓取
  20404. success:function (xhr) {
  20405. try {
  20406. var info = eval("(" + xhr.responseText + ")");
  20407. } catch (e) {
  20408. return;
  20409. }
  20410. var srcUrls = info.srcUrl.split(separater),
  20411. urls = info.url.split(separater);
  20412. for (var i = 0, ci; ci = imgs[i++];) {
  20413. var src = ci.getAttribute("_src") || ci.src || "";
  20414. for (var j = 0, cj; cj = srcUrls[j++];) {
  20415. var url = urls[j - 1];
  20416. if (src == cj && url != "error") { //抓取失败时不做替换处理
  20417. //地址修正
  20418. var newSrc = me.options.catcherPath + url;
  20419. domUtils.setAttributes(ci, {
  20420. "src":newSrc,
  20421. "_src":newSrc
  20422. });
  20423. break;
  20424. }
  20425. }
  20426. }
  20427. me.fireEvent('catchremotesuccess')
  20428. },
  20429. //回调失败,本次请求超时
  20430. error:function () {
  20431. me.fireEvent("catchremoteerror");
  20432. }
  20433. });
  20434. }
  20435. });
  20436. };
  20437. ///import core
  20438. ///import plugins\inserthtml.js
  20439. ///import plugins\image.js
  20440. ///commandsName snapscreen
  20441. ///commandsTitle 截屏
  20442. /*
  20443. * 截屏插件
  20444. */
  20445. UE.plugins['snapscreen'] = function(){
  20446. var me = this,
  20447. doc,
  20448. snapplugin;
  20449. me.setOpt({
  20450. snapscreenServerPort: location.port //屏幕截图的server端端口
  20451. ,snapscreenImgAlign: '' //截图的图片默认的排版方式
  20452. ,snapscreenHost: location.hostname //屏幕截图的server端文件所在的网站地址或者ip,请不要加http://
  20453. });
  20454. me.commands['snapscreen'] = {
  20455. execCommand: function(){
  20456. var me = this,lang = me.getLang("snapScreen_plugin");
  20457. if(!snapplugin){
  20458. var container = me.container;
  20459. doc = container.ownerDocument || container.document;
  20460. snapplugin = doc.createElement("object");
  20461. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  20462. return;
  20463. }
  20464. snapplugin.style.cssText = "position:absolute;left:-9999px;";
  20465. snapplugin.setAttribute("width","0");
  20466. snapplugin.setAttribute("height","0");
  20467. container.appendChild(snapplugin);
  20468. }
  20469. var editorOptions = me.options;
  20470. var onSuccess = function(rs){
  20471. try{
  20472. rs = eval("("+ rs +")");
  20473. }catch(e){
  20474. alert(lang.callBackErrorMsg);
  20475. return;
  20476. }
  20477. if(rs.state != 'SUCCESS'){
  20478. alert(rs.state);
  20479. return;
  20480. }
  20481. me.execCommand('insertimage', {
  20482. src: editorOptions.snapscreenPath + rs.url,
  20483. floatStyle: editorOptions.snapscreenImgAlign,
  20484. _src:editorOptions.snapscreenPath + rs.url
  20485. });
  20486. };
  20487. var onStartUpload = function(){
  20488. //开始截图上传
  20489. };
  20490. var onError = function(){
  20491. alert(lang.uploadErrorMsg);
  20492. };
  20493. try{
  20494. var port = editorOptions.snapscreenServerPort + '';
  20495. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.split( editorOptions.snapscreenHost );
  20496. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl[1] || editorOptions.snapscreenServerUrl[0];
  20497. if( editorOptions.snapscreenServerUrl.indexOf(":"+port) === 0 ) {
  20498. editorOptions.snapscreenServerUrl = editorOptions.snapscreenServerUrl.substring( port.length+1 );
  20499. }
  20500. var ret =snapplugin.saveSnapshot(editorOptions.snapscreenHost, editorOptions.snapscreenServerUrl, port);
  20501. onSuccess(ret);
  20502. }catch(e){
  20503. me.ui._dialogs['snapscreenDialog'].open();
  20504. }
  20505. }
  20506. };
  20507. }
  20508. /**
  20509. * 插入段落
  20510. * @file
  20511. * @since 1.2.6.1
  20512. */
  20513. /**
  20514. * 插入段落
  20515. * @command insertparagraph
  20516. * @method execCommand
  20517. * @param { String } cmd 命令字符串
  20518. * @example
  20519. * ```javascript
  20520. * //editor是编辑器实例
  20521. * editor.execCommand( 'insertparagraph' );
  20522. * ```
  20523. */
  20524. UE.commands['insertparagraph'] = {
  20525. execCommand : function( cmdName,front) {
  20526. var me = this,
  20527. range = me.selection.getRange(),
  20528. start = range.startContainer,tmpNode;
  20529. while(start ){
  20530. if(domUtils.isBody(start)){
  20531. break;
  20532. }
  20533. tmpNode = start;
  20534. start = start.parentNode;
  20535. }
  20536. if(tmpNode){
  20537. var p = me.document.createElement('p');
  20538. if(front){
  20539. tmpNode.parentNode.insertBefore(p,tmpNode)
  20540. }else{
  20541. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  20542. }
  20543. domUtils.fillNode(me.document,p);
  20544. range.setStart(p,0).setCursor(false,true);
  20545. }
  20546. }
  20547. };
  20548. /**
  20549. * 百度应用
  20550. * @file
  20551. * @since 1.2.6.1
  20552. */
  20553. /**
  20554. * 插入百度应用
  20555. * @command webapp
  20556. * @method execCommand
  20557. * @remind 需要百度APPKey
  20558. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  20559. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  20560. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  20561. * @example
  20562. * ```javascript
  20563. * //editor是编辑器实例
  20564. * //在编辑器里插入一个“植物大战僵尸”的APP
  20565. * editor.execCommand( 'webapp' , {
  20566. * title: '植物大战僵尸',
  20567. * width: 560,
  20568. * height: 465,
  20569. * logo: '应用展示的图片',
  20570. * url: '百度应用的地址'
  20571. * } );
  20572. * ```
  20573. */
  20574. //UE.plugins['webapp'] = function () {
  20575. // var me = this;
  20576. // function createInsertStr( obj, toIframe, addParagraph ) {
  20577. // return !toIframe ?
  20578. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  20579. // ' 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 + '" />' +
  20580. // (addParagraph ? '</p>' : '')
  20581. // :
  20582. // '<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>';
  20583. // }
  20584. //
  20585. // function switchImgAndIframe( img2frame ) {
  20586. // var tmpdiv,
  20587. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  20588. // for ( var i = 0, node; node = nodes[i++]; ) {
  20589. // if ( node.className != "edui-faked-webapp" ){
  20590. // continue;
  20591. // }
  20592. // tmpdiv = me.document.createElement( "div" );
  20593. // 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 );
  20594. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  20595. // }
  20596. // }
  20597. //
  20598. // me.addListener( "beforegetcontent", function () {
  20599. // switchImgAndIframe( true );
  20600. // } );
  20601. // me.addListener( 'aftersetcontent', function () {
  20602. // switchImgAndIframe( false );
  20603. // } );
  20604. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  20605. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  20606. // return;
  20607. // }
  20608. // switchImgAndIframe( false );
  20609. // } );
  20610. //
  20611. // me.commands['webapp'] = {
  20612. // execCommand:function ( cmd, obj ) {
  20613. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  20614. // }
  20615. // };
  20616. //};
  20617. UE.plugin.register('webapp', function (){
  20618. var me = this;
  20619. function createInsertStr(obj,toEmbed){
  20620. return !toEmbed ?
  20621. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  20622. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  20623. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  20624. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  20625. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  20626. '/>'
  20627. :
  20628. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  20629. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  20630. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  20631. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  20632. }
  20633. return {
  20634. outputRule: function(root){
  20635. utils.each(root.getNodesByTagName('img'),function(node){
  20636. var html;
  20637. if(node.getAttr('class') == 'edui-faked-webapp'){
  20638. html = createInsertStr({
  20639. title:node.getAttr('title'),
  20640. 'width':node.getAttr('width'),
  20641. 'height':node.getAttr('height'),
  20642. 'align':node.getAttr('align'),
  20643. 'cssfloat':node.getStyle('float'),
  20644. 'url':node.getAttr("_url"),
  20645. 'logo':node.getAttr('_logo_url')
  20646. },true);
  20647. var embed = UE.uNode.createElement(html);
  20648. node.parentNode.replaceChild(embed,node);
  20649. }
  20650. })
  20651. },
  20652. inputRule:function(root){
  20653. utils.each(root.getNodesByTagName('iframe'),function(node){
  20654. if(node.getAttr('class') == 'edui-faked-webapp'){
  20655. var img = UE.uNode.createElement(createInsertStr({
  20656. title:node.getAttr('title'),
  20657. 'width':node.getAttr('width'),
  20658. 'height':node.getAttr('height'),
  20659. 'align':node.getAttr('align'),
  20660. 'cssfloat':node.getStyle('float'),
  20661. 'url':node.getAttr("src"),
  20662. 'logo':node.getAttr('logo_url')
  20663. }));
  20664. node.parentNode.replaceChild(img,node);
  20665. }
  20666. })
  20667. },
  20668. commands:{
  20669. /**
  20670. * 插入百度应用
  20671. * @command webapp
  20672. * @method execCommand
  20673. * @remind 需要百度APPKey
  20674. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  20675. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  20676. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  20677. * @example
  20678. * ```javascript
  20679. * //editor是编辑器实例
  20680. * //在编辑器里插入一个“植物大战僵尸”的APP
  20681. * editor.execCommand( 'webapp' , {
  20682. * title: '植物大战僵尸',
  20683. * width: 560,
  20684. * height: 465,
  20685. * logo: '应用展示的图片',
  20686. * url: '百度应用的地址'
  20687. * } );
  20688. * ```
  20689. */
  20690. 'webapp':{
  20691. execCommand:function (cmd, obj) {
  20692. var me = this,
  20693. str = createInsertStr(utils.extend(obj,{
  20694. align:'none'
  20695. }), false);
  20696. me.execCommand("inserthtml",str);
  20697. },
  20698. queryCommandState:function () {
  20699. var me = this,
  20700. img = me.selection.getRange().getClosedNode(),
  20701. flag = img && (img.className == "edui-faked-webapp");
  20702. return flag ? 1 : 0;
  20703. }
  20704. }
  20705. }
  20706. }
  20707. });
  20708. ///import core
  20709. ///import plugins\inserthtml.js
  20710. ///import plugins\cleardoc.js
  20711. ///commands 模板
  20712. ///commandsName template
  20713. ///commandsTitle 模板
  20714. ///commandsDialog dialogs\template
  20715. UE.plugins['template'] = function () {
  20716. UE.commands['template'] = {
  20717. execCommand:function (cmd, obj) {
  20718. obj.html && this.execCommand("inserthtml", obj.html);
  20719. }
  20720. };
  20721. this.addListener("click", function (type, evt) {
  20722. var el = evt.target || evt.srcElement,
  20723. range = this.selection.getRange();
  20724. var tnode = domUtils.findParent(el, function (node) {
  20725. if (node.className && domUtils.hasClass(node, "ue_t")) {
  20726. return node;
  20727. }
  20728. }, true);
  20729. tnode && range.selectNode(tnode).shrinkBoundary().select();
  20730. });
  20731. this.addListener("keydown", function (type, evt) {
  20732. var range = this.selection.getRange();
  20733. if (!range.collapsed) {
  20734. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  20735. var tnode = domUtils.findParent(range.startContainer, function (node) {
  20736. if (node.className && domUtils.hasClass(node, "ue_t")) {
  20737. return node;
  20738. }
  20739. }, true);
  20740. if (tnode) {
  20741. domUtils.removeClasses(tnode, ["ue_t"]);
  20742. }
  20743. }
  20744. }
  20745. });
  20746. };
  20747. /**
  20748. * 插入音乐命令
  20749. * @file
  20750. */
  20751. UE.plugin.register('music', function (){
  20752. var me = this;
  20753. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  20754. return !toEmbed ?
  20755. '<img ' +
  20756. (align && !cssfloat? 'align="' + align + '"' : '') +
  20757. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  20758. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  20759. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  20760. :
  20761. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  20762. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  20763. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  20764. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  20765. }
  20766. return {
  20767. outputRule: function(root){
  20768. utils.each(root.getNodesByTagName('img'),function(node){
  20769. var html;
  20770. if(node.getAttr('class') == 'edui-faked-music'){
  20771. var cssfloat = node.getStyle('float');
  20772. var align = node.getAttr('align');
  20773. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  20774. var embed = UE.uNode.createElement(html);
  20775. node.parentNode.replaceChild(embed,node);
  20776. }
  20777. })
  20778. },
  20779. inputRule:function(root){
  20780. utils.each(root.getNodesByTagName('embed'),function(node){
  20781. if(node.getAttr('class') == 'edui-faked-music'){
  20782. var cssfloat = node.getStyle('float');
  20783. var align = node.getAttr('align');
  20784. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  20785. var img = UE.uNode.createElement(html);
  20786. node.parentNode.replaceChild(img,node);
  20787. }
  20788. })
  20789. },
  20790. commands:{
  20791. /**
  20792. * 插入音乐
  20793. * @command music
  20794. * @method execCommand
  20795. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  20796. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  20797. * @example
  20798. * ```javascript
  20799. * //editor是编辑器实例
  20800. * //在编辑器里插入一个“植物大战僵尸”的APP
  20801. * editor.execCommand( 'music' , {
  20802. * width: 400,
  20803. * height: 95,
  20804. * align: "center",
  20805. * url: "音乐地址"
  20806. * } );
  20807. * ```
  20808. */
  20809. 'music':{
  20810. execCommand:function (cmd, musicObj) {
  20811. var me = this,
  20812. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  20813. me.execCommand("inserthtml",str);
  20814. },
  20815. queryCommandState:function () {
  20816. var me = this,
  20817. img = me.selection.getRange().getClosedNode(),
  20818. flag = img && (img.className == "edui-faked-music");
  20819. return flag ? 1 : 0;
  20820. }
  20821. }
  20822. }
  20823. }
  20824. });
  20825. /**
  20826. * @description
  20827. * 1.拖放文件到编辑区域,自动上传并插入到选区
  20828. * 2.插入粘贴板的图片,自动上传并插入到选区
  20829. * @author Jinqn
  20830. * @date 2013-10-14
  20831. */
  20832. UE.plugin.register('autoupload', function (){
  20833. var me = this;
  20834. var sendAndInsertImage = function (file, editor) {
  20835. //模拟数据
  20836. var fd = new FormData();
  20837. fd.append(editor.options.imageFieldName || 'upfile', file, file.name || ('blob.' + file.type.substr('image/'.length)));
  20838. fd.append('type', 'ajax');
  20839. var xhr = new XMLHttpRequest();
  20840. xhr.open("post", me.options.imageUrl, true);
  20841. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  20842. xhr.addEventListener('load', function (e) {
  20843. try{
  20844. var json = (new Function("return " + e.target.response))(),
  20845. picLink = me.options.imagePath + json.url;
  20846. editor.execCommand('insertimage', {
  20847. src: picLink,
  20848. _src: picLink
  20849. });
  20850. }catch(er){ }
  20851. });
  20852. xhr.send(fd);
  20853. };
  20854. function getPasteImage(e){
  20855. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  20856. }
  20857. function getDropImage(e){
  20858. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  20859. }
  20860. return {
  20861. bindEvents:{
  20862. //插入粘贴板的图片,拖放插入图片
  20863. 'ready':function(e){
  20864. if(window.FormData && window.FileReader) {
  20865. domUtils.on(me.body, 'paste drop', function(e){
  20866. var hasImg = false,
  20867. items;
  20868. //获取粘贴板文件列表或者拖放文件列表
  20869. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  20870. if(items){
  20871. var len = items.length,
  20872. file;
  20873. while (len--){
  20874. file = items[len];
  20875. if(file.getAsFile) file = file.getAsFile();
  20876. if(file && file.size > 0 && /image\/\w+/i.test(file.type) ) {
  20877. sendAndInsertImage(file, me);
  20878. hasImg = true;
  20879. }
  20880. }
  20881. hasImg && e.preventDefault();
  20882. }
  20883. });
  20884. //取消拖放图片时出现的文字光标位置提示
  20885. domUtils.on(me.body, 'dragover', function (e) {
  20886. if(e.dataTransfer.types[0] == 'Files') {
  20887. e.preventDefault();
  20888. }
  20889. });
  20890. }
  20891. }
  20892. }
  20893. }
  20894. });
  20895. UE.plugin.register('autosave', function (){
  20896. var me = this,
  20897. //无限循环保护
  20898. lastSaveTime = new Date(),
  20899. //最小保存间隔时间
  20900. MIN_TIME = 20,
  20901. //auto save key
  20902. saveKey = null;
  20903. //存储媒介封装
  20904. var LocalStorage = UE.LocalStorage = ( function () {
  20905. var storage = window.localStorage || getUserData() || null,
  20906. LOCAL_FILE = "localStorage";
  20907. return {
  20908. saveLocalData: function ( key, data ) {
  20909. if ( storage && data) {
  20910. storage.setItem( key, data );
  20911. return true;
  20912. }
  20913. return false;
  20914. },
  20915. getLocalData: function ( key ) {
  20916. if ( storage ) {
  20917. return storage.getItem( key );
  20918. }
  20919. return null;
  20920. },
  20921. removeItem: function ( key ) {
  20922. storage && storage.removeItem( key );
  20923. }
  20924. };
  20925. function getUserData () {
  20926. var container = document.createElement( "div" );
  20927. container.style.display = "none";
  20928. if( !container.addBehavior ) {
  20929. return null;
  20930. }
  20931. container.addBehavior("#default#userdata");
  20932. return {
  20933. getItem: function ( key ) {
  20934. var result = null;
  20935. try {
  20936. document.body.appendChild( container );
  20937. container.load( LOCAL_FILE );
  20938. result = container.getAttribute( key );
  20939. document.body.removeChild( container );
  20940. } catch ( e ) {
  20941. }
  20942. return result;
  20943. },
  20944. setItem: function ( key, value ) {
  20945. document.body.appendChild( container );
  20946. container.setAttribute( key, value );
  20947. container.save( LOCAL_FILE );
  20948. document.body.removeChild( container );
  20949. },
  20950. // 暂时没有用到
  20951. // clear: function () {
  20952. //
  20953. // var expiresTime = new Date();
  20954. // expiresTime.setFullYear( expiresTime.getFullYear() - 1 );
  20955. // document.body.appendChild( container );
  20956. // container.expires = expiresTime.toUTCString();
  20957. // container.save( LOCAL_FILE );
  20958. // document.body.removeChild( container );
  20959. //
  20960. // },
  20961. removeItem: function ( key ) {
  20962. document.body.appendChild( container );
  20963. container.removeAttribute( key );
  20964. container.save( LOCAL_FILE );
  20965. document.body.removeChild( container );
  20966. }
  20967. };
  20968. }
  20969. } )();
  20970. function save ( editor ) {
  20971. var saveData = null;
  20972. if ( new Date() - lastSaveTime < MIN_TIME ) {
  20973. return;
  20974. }
  20975. if ( !editor.hasContents() ) {
  20976. //这里不能调用命令来删除, 会造成事件死循环
  20977. saveKey && LocalStorage.removeItem( saveKey );
  20978. return;
  20979. }
  20980. lastSaveTime = new Date();
  20981. editor._saveFlag = null;
  20982. saveData = me.body.innerHTML;
  20983. if ( editor.fireEvent( "beforeautosave", {
  20984. content: saveData
  20985. } ) === false ) {
  20986. return;
  20987. }
  20988. LocalStorage.saveLocalData( saveKey, saveData );
  20989. editor.fireEvent( "afterautosave", {
  20990. content: saveData
  20991. } );
  20992. }
  20993. return {
  20994. defaultOptions: {
  20995. //默认间隔时间
  20996. saveInterval: 500
  20997. },
  20998. bindEvents:{
  20999. 'ready':function(){
  21000. var _suffix = "-drafts-data",
  21001. key = null;
  21002. if ( me.key ) {
  21003. key = me.key + _suffix;
  21004. } else {
  21005. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21006. }
  21007. //页面地址+编辑器ID 保持唯一
  21008. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21009. },
  21010. 'contentchange': function () {
  21011. if ( !saveKey ) {
  21012. return;
  21013. }
  21014. if ( me._saveFlag ) {
  21015. window.clearTimeout( me._saveFlag );
  21016. }
  21017. if ( me.options.saveInterval > 0 ) {
  21018. me._saveFlag = window.setTimeout( function () {
  21019. save( me );
  21020. }, me.options.saveInterval );
  21021. } else {
  21022. save(me);
  21023. }
  21024. }
  21025. },
  21026. commands:{
  21027. 'clearlocaldata':{
  21028. execCommand:function (cmd, name) {
  21029. if ( saveKey && LocalStorage.getLocalData( saveKey ) ) {
  21030. LocalStorage.removeItem( saveKey )
  21031. }
  21032. },
  21033. notNeedUndo: true,
  21034. ignoreContentChange:true
  21035. },
  21036. 'getlocaldata':{
  21037. execCommand:function (cmd, name) {
  21038. return saveKey ? LocalStorage.getLocalData( saveKey ) || '' : '';
  21039. },
  21040. notNeedUndo: true,
  21041. ignoreContentChange:true
  21042. },
  21043. 'drafts':{
  21044. execCommand:function (cmd, name) {
  21045. if ( saveKey ) {
  21046. me.body.innerHTML = LocalStorage.getLocalData( saveKey ) || '<p>'+(browser.ie ? '&nbsp;' : '<br/>')+'</p>';
  21047. me.focus(true);
  21048. }
  21049. },
  21050. queryCommandState: function () {
  21051. return saveKey ? ( LocalStorage.getLocalData( saveKey ) === null ? -1 : 0 ) : -1;
  21052. },
  21053. notNeedUndo: true,
  21054. ignoreContentChange:true
  21055. }
  21056. }
  21057. }
  21058. });
  21059. UE.plugin.register('charts', function (){
  21060. var me = this;
  21061. return {
  21062. bindEvents: {
  21063. 'chartserror': function () {
  21064. }
  21065. },
  21066. commands:{
  21067. 'charts': {
  21068. execCommand: function ( cmd, data ) {
  21069. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  21070. flagText = [],
  21071. config = {};
  21072. if ( !tableNode ) {
  21073. return false;
  21074. }
  21075. if ( !validData( tableNode ) ) {
  21076. me.fireEvent( "chartserror" );
  21077. return false;
  21078. }
  21079. config.title = data.title || '';
  21080. config.subTitle = data.subTitle || '';
  21081. config.xTitle = data.xTitle || '';
  21082. config.yTitle = data.yTitle || '';
  21083. config.suffix = data.suffix || '';
  21084. config.tip = data.tip || '';
  21085. //数据对齐方式
  21086. config.dataFormat = data.tableDataFormat || '';
  21087. //图表类型
  21088. config.chartType = data.chartType || 0;
  21089. for ( var key in config ) {
  21090. if ( !config.hasOwnProperty( key ) ) {
  21091. continue;
  21092. }
  21093. flagText.push( key+":"+config[ key ] );
  21094. }
  21095. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  21096. domUtils.addClass( tableNode, "edui-charts-table" );
  21097. },
  21098. queryCommandState: function ( cmd, name ) {
  21099. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  21100. return tableNode && validData( tableNode ) ? 0 : -1;
  21101. }
  21102. }
  21103. },
  21104. inputRule:function(root){
  21105. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  21106. if ( tableNode.getAttr("data-chart") !== undefined ) {
  21107. tableNode.setAttr("style");
  21108. }
  21109. })
  21110. },
  21111. outputRule:function(root){
  21112. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  21113. if ( tableNode.getAttr("data-chart") !== undefined ) {
  21114. tableNode.setAttr("style", "display: none;");
  21115. }
  21116. })
  21117. }
  21118. }
  21119. function validData ( table ) {
  21120. var firstRows = null,
  21121. cellCount = 0;
  21122. //行数不够
  21123. if ( table.rows.length < 2 ) {
  21124. return false;
  21125. }
  21126. //列数不够
  21127. if ( table.rows[0].cells.length < 2 ) {
  21128. return false;
  21129. }
  21130. //第一行所有cell必须是th
  21131. firstRows = table.rows[ 0 ].cells;
  21132. cellCount = firstRows.length;
  21133. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  21134. if ( cell.tagName.toLowerCase() !== 'th' ) {
  21135. return false;
  21136. }
  21137. }
  21138. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  21139. //每行单元格数不匹配, 返回false
  21140. if ( row.cells.length != cellCount ) {
  21141. return false;
  21142. }
  21143. //第一列不是th也返回false
  21144. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  21145. return false;
  21146. }
  21147. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  21148. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  21149. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  21150. //必须是数字
  21151. if ( !/^\d*\.?\d+$/.test( value ) ) {
  21152. return false;
  21153. }
  21154. }
  21155. }
  21156. return true;
  21157. }
  21158. });
  21159. /**
  21160. * 目录大纲支持插件
  21161. * @file
  21162. * @since 1.3.0
  21163. */
  21164. UE.plugin.register('section', function (){
  21165. /* 目录节点对象 */
  21166. function Section(option){
  21167. this.tag = '';
  21168. this.level = -1,
  21169. this.dom = null;
  21170. this.nextSection = null;
  21171. this.previousSection = null;
  21172. this.parentSection = null;
  21173. this.startAddress = [];
  21174. this.endAddress = [];
  21175. this.children = [];
  21176. }
  21177. function getSection(option) {
  21178. var section = new Section();
  21179. return utils.extend(section, option);
  21180. }
  21181. function getNodeFromAddress(startAddress, root) {
  21182. var current = root;
  21183. for(var i = 0;i < startAddress.length; i++) {
  21184. if(!current.childNodes) return null;
  21185. current = current.childNodes[startAddress[i]];
  21186. }
  21187. return current;
  21188. }
  21189. var me = this;
  21190. return {
  21191. bindMultiEvents:{
  21192. type: 'aftersetcontent afterscencerestore',
  21193. handler: function(){
  21194. me.fireEvent('updateSections');
  21195. }
  21196. },
  21197. bindEvents:{
  21198. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  21199. 'ready': function (){
  21200. me.fireEvent('updateSections');
  21201. domUtils.on(me.body, 'drop paste', function(){
  21202. me.fireEvent('updateSections');
  21203. });
  21204. },
  21205. /* 执行paragraph命令之后 */
  21206. 'afterexeccommand': function (type, cmd) {
  21207. if(cmd == 'paragraph') {
  21208. me.fireEvent('updateSections');
  21209. }
  21210. },
  21211. /* 部分键盘操作,触发updateSections事件 */
  21212. 'keyup': function (type, e) {
  21213. var me = this,
  21214. range = me.selection.getRange();
  21215. if(range.collapsed != true) {
  21216. me.fireEvent('updateSections');
  21217. } else {
  21218. var keyCode = e.keyCode || e.which;
  21219. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  21220. me.fireEvent('updateSections');
  21221. }
  21222. }
  21223. }
  21224. },
  21225. commands:{
  21226. 'getsections': {
  21227. execCommand: function (cmd, levels) {
  21228. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  21229. for (var i = 0; i < levelFn.length; i++) {
  21230. if (typeof levelFn[i] == 'string') {
  21231. levelFn[i] = function(fn){
  21232. return function(node){
  21233. return node.tagName == fn.toUpperCase()
  21234. };
  21235. }(levelFn[i]);
  21236. } else if (typeof levelFn[i] != 'function') {
  21237. levelFn[i] = function (node) {
  21238. return null;
  21239. }
  21240. }
  21241. }
  21242. function getSectionLevel(node) {
  21243. for (var i = 0; i < levelFn.length; i++) {
  21244. if (levelFn[i](node)) return i;
  21245. }
  21246. return -1;
  21247. }
  21248. var me = this,
  21249. Directory = getSection({'level':-1, 'title':'root'}),
  21250. previous = Directory;
  21251. function traversal(node, Directory) {
  21252. var level,
  21253. tmpSection = null,
  21254. parent,
  21255. child,
  21256. children = node.childNodes;
  21257. for (var i = 0, len = children.length; i < len; i++) {
  21258. child = children[i];
  21259. level = getSectionLevel(child);
  21260. if (level >= 0) {
  21261. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  21262. current = getSection({
  21263. 'tag': child.tagName,
  21264. 'title': child.innerText || child.textContent || '',
  21265. 'level': level,
  21266. 'dom': child,
  21267. 'startAddress': utils.clone(address, []),
  21268. 'endAddress': utils.clone(address, []),
  21269. 'children': []
  21270. });
  21271. previous.nextSection = current;
  21272. current.previousSection = previous;
  21273. parent = previous;
  21274. while(level <= parent.level){
  21275. parent = parent.parentSection;
  21276. }
  21277. current.parentSection = parent;
  21278. parent.children.push(current);
  21279. tmpSection = previous = current;
  21280. } else {
  21281. child.nodeType === 1 && traversal(child, Directory);
  21282. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  21283. }
  21284. }
  21285. }
  21286. traversal(me.body, Directory);
  21287. return Directory;
  21288. },
  21289. notNeedUndo: true
  21290. },
  21291. 'movesection': {
  21292. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  21293. var me = this,
  21294. targetAddress,
  21295. target;
  21296. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  21297. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  21298. target = getNodeFromAddress(targetAddress, me.body);
  21299. /* 判断目标地址是否被源章节包含 */
  21300. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  21301. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  21302. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  21303. current,
  21304. nextNode;
  21305. if(isAfter) {
  21306. current = endNode;
  21307. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  21308. nextNode = current.previousSibling;
  21309. domUtils.insertAfter(target, current);
  21310. if(current == startNode) break;
  21311. current = nextNode;
  21312. }
  21313. } else {
  21314. current = startNode;
  21315. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  21316. nextNode = current.nextSibling;
  21317. target.parentNode.insertBefore(current, target);
  21318. if(current == endNode) break;
  21319. current = nextNode;
  21320. }
  21321. }
  21322. me.fireEvent('updateSections');
  21323. /* 获取地址的包含关系 */
  21324. function isContainsAddress(startAddress, endAddress, addressTarget){
  21325. var isAfterStartAddress = false,
  21326. isBeforeEndAddress = false;
  21327. for(var i = 0; i< startAddress.length; i++){
  21328. if(i >= addressTarget.length) break;
  21329. if(addressTarget[i] > startAddress[i]) {
  21330. isAfterStartAddress = true;
  21331. break;
  21332. } else if(addressTarget[i] < startAddress[i]) {
  21333. break;
  21334. }
  21335. }
  21336. for(var i = 0; i< endAddress.length; i++){
  21337. if(i >= addressTarget.length) break;
  21338. if(addressTarget[i] < startAddress[i]) {
  21339. isBeforeEndAddress = true;
  21340. break;
  21341. } else if(addressTarget[i] > startAddress[i]) {
  21342. break;
  21343. }
  21344. }
  21345. return isAfterStartAddress && isBeforeEndAddress;
  21346. }
  21347. }
  21348. },
  21349. 'deletesection': {
  21350. execCommand: function (cmd, section, keepChildren) {
  21351. var me = this;
  21352. if(!section) return;
  21353. function getNodeFromAddress(startAddress) {
  21354. var current = me.body;
  21355. for(var i = 0;i < startAddress.length; i++) {
  21356. if(!current.childNodes) return null;
  21357. current = current.childNodes[startAddress[i]];
  21358. }
  21359. return current;
  21360. }
  21361. var startNode = getNodeFromAddress(section.startAddress),
  21362. endNode = getNodeFromAddress(section.endAddress),
  21363. current = startNode,
  21364. nextNode;
  21365. if(!keepChildren) {
  21366. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  21367. nextNode = current.nextSibling;
  21368. domUtils.remove(current);
  21369. current = nextNode;
  21370. }
  21371. } else {
  21372. domUtils.remove(current);
  21373. }
  21374. me.fireEvent('updateSections');
  21375. }
  21376. },
  21377. 'selectsection': {
  21378. execCommand: function (cmd, section) {
  21379. if(!section && !section.dom) return false;
  21380. var me = this,
  21381. range = me.selection.getRange(),
  21382. address = {
  21383. 'startAddress':utils.clone(section.startAddress, []),
  21384. 'endAddress':utils.clone(section.endAddress, [])
  21385. };
  21386. address.endAddress[address.endAddress.length - 1]++;
  21387. range.moveToAddress(address).select().scrollToView();
  21388. return true;
  21389. },
  21390. notNeedUndo: true
  21391. },
  21392. 'scrolltosection': {
  21393. execCommand: function (cmd, section) {
  21394. if(!section && !section.dom) return false;
  21395. var me = this,
  21396. range = me.selection.getRange(),
  21397. address = {
  21398. 'startAddress':section.startAddress,
  21399. 'endAddress':section.endAddress
  21400. };
  21401. address.endAddress[address.endAddress.length - 1]++;
  21402. range.moveToAddress(address).scrollToView();
  21403. return true;
  21404. },
  21405. notNeedUndo: true
  21406. }
  21407. }
  21408. }
  21409. });
  21410. var baidu = baidu || {};
  21411. baidu.editor = baidu.editor || {};
  21412. baidu.editor.ui = {};
  21413. (function (){
  21414. var browser = baidu.editor.browser,
  21415. domUtils = baidu.editor.dom.domUtils;
  21416. var magic = '$EDITORUI';
  21417. var root = window[magic] = {};
  21418. var uidMagic = 'ID' + magic;
  21419. var uidCount = 0;
  21420. var uiUtils = baidu.editor.ui.uiUtils = {
  21421. uid: function (obj){
  21422. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  21423. },
  21424. hook: function ( fn, callback ) {
  21425. var dg;
  21426. if (fn && fn._callbacks) {
  21427. dg = fn;
  21428. } else {
  21429. dg = function (){
  21430. var q;
  21431. if (fn) {
  21432. q = fn.apply(this, arguments);
  21433. }
  21434. var callbacks = dg._callbacks;
  21435. var k = callbacks.length;
  21436. while (k --) {
  21437. var r = callbacks[k].apply(this, arguments);
  21438. if (q === undefined) {
  21439. q = r;
  21440. }
  21441. }
  21442. return q;
  21443. };
  21444. dg._callbacks = [];
  21445. }
  21446. dg._callbacks.push(callback);
  21447. return dg;
  21448. },
  21449. createElementByHtml: function (html){
  21450. var el = document.createElement('div');
  21451. el.innerHTML = html;
  21452. el = el.firstChild;
  21453. el.parentNode.removeChild(el);
  21454. return el;
  21455. },
  21456. getViewportElement: function (){
  21457. return (browser.ie && browser.quirks) ?
  21458. document.body : document.documentElement;
  21459. },
  21460. getClientRect: function (element){
  21461. var bcr;
  21462. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  21463. try{
  21464. bcr = element.getBoundingClientRect();
  21465. }catch(e){
  21466. bcr={left:0,top:0,height:0,width:0}
  21467. }
  21468. var rect = {
  21469. left: Math.round(bcr.left),
  21470. top: Math.round(bcr.top),
  21471. height: Math.round(bcr.bottom - bcr.top),
  21472. width: Math.round(bcr.right - bcr.left)
  21473. };
  21474. var doc;
  21475. while ((doc = element.ownerDocument) !== document &&
  21476. (element = domUtils.getWindow(doc).frameElement)) {
  21477. bcr = element.getBoundingClientRect();
  21478. rect.left += bcr.left;
  21479. rect.top += bcr.top;
  21480. }
  21481. rect.bottom = rect.top + rect.height;
  21482. rect.right = rect.left + rect.width;
  21483. return rect;
  21484. },
  21485. getViewportRect: function (){
  21486. var viewportEl = uiUtils.getViewportElement();
  21487. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  21488. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  21489. return {
  21490. left: 0,
  21491. top: 0,
  21492. height: height,
  21493. width: width,
  21494. bottom: height,
  21495. right: width
  21496. };
  21497. },
  21498. setViewportOffset: function (element, offset){
  21499. var rect;
  21500. var fixedLayer = uiUtils.getFixedLayer();
  21501. if (element.parentNode === fixedLayer) {
  21502. element.style.left = offset.left + 'px';
  21503. element.style.top = offset.top + 'px';
  21504. } else {
  21505. domUtils.setViewportOffset(element, offset);
  21506. }
  21507. },
  21508. getEventOffset: function (evt){
  21509. var el = evt.target || evt.srcElement;
  21510. var rect = uiUtils.getClientRect(el);
  21511. var offset = uiUtils.getViewportOffsetByEvent(evt);
  21512. return {
  21513. left: offset.left - rect.left,
  21514. top: offset.top - rect.top
  21515. };
  21516. },
  21517. getViewportOffsetByEvent: function (evt){
  21518. var el = evt.target || evt.srcElement;
  21519. var frameEl = domUtils.getWindow(el).frameElement;
  21520. var offset = {
  21521. left: evt.clientX,
  21522. top: evt.clientY
  21523. };
  21524. if (frameEl && el.ownerDocument !== document) {
  21525. var rect = uiUtils.getClientRect(frameEl);
  21526. offset.left += rect.left;
  21527. offset.top += rect.top;
  21528. }
  21529. return offset;
  21530. },
  21531. setGlobal: function (id, obj){
  21532. root[id] = obj;
  21533. return magic + '["' + id + '"]';
  21534. },
  21535. unsetGlobal: function (id){
  21536. delete root[id];
  21537. },
  21538. copyAttributes: function (tgt, src){
  21539. var attributes = src.attributes;
  21540. var k = attributes.length;
  21541. while (k --) {
  21542. var attrNode = attributes[k];
  21543. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  21544. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  21545. }
  21546. }
  21547. if (src.className) {
  21548. domUtils.addClass(tgt,src.className);
  21549. }
  21550. if (src.style.cssText) {
  21551. tgt.style.cssText += ';' + src.style.cssText;
  21552. }
  21553. },
  21554. removeStyle: function (el, styleName){
  21555. if (el.style.removeProperty) {
  21556. el.style.removeProperty(styleName);
  21557. } else if (el.style.removeAttribute) {
  21558. el.style.removeAttribute(styleName);
  21559. } else throw '';
  21560. },
  21561. contains: function (elA, elB){
  21562. return elA && elB && (elA === elB ? false : (
  21563. elA.contains ? elA.contains(elB) :
  21564. elA.compareDocumentPosition(elB) & 16
  21565. ));
  21566. },
  21567. startDrag: function (evt, callbacks,doc){
  21568. var doc = doc || document;
  21569. var startX = evt.clientX;
  21570. var startY = evt.clientY;
  21571. function handleMouseMove(evt){
  21572. var x = evt.clientX - startX;
  21573. var y = evt.clientY - startY;
  21574. callbacks.ondragmove(x, y,evt);
  21575. if (evt.stopPropagation) {
  21576. evt.stopPropagation();
  21577. } else {
  21578. evt.cancelBubble = true;
  21579. }
  21580. }
  21581. if (doc.addEventListener) {
  21582. function handleMouseUp(evt){
  21583. doc.removeEventListener('mousemove', handleMouseMove, true);
  21584. doc.removeEventListener('mouseup', handleMouseUp, true);
  21585. window.removeEventListener('mouseup', handleMouseUp, true);
  21586. callbacks.ondragstop();
  21587. }
  21588. doc.addEventListener('mousemove', handleMouseMove, true);
  21589. doc.addEventListener('mouseup', handleMouseUp, true);
  21590. window.addEventListener('mouseup', handleMouseUp, true);
  21591. evt.preventDefault();
  21592. } else {
  21593. var elm = evt.srcElement;
  21594. elm.setCapture();
  21595. function releaseCaptrue(){
  21596. elm.releaseCapture();
  21597. elm.detachEvent('onmousemove', handleMouseMove);
  21598. elm.detachEvent('onmouseup', releaseCaptrue);
  21599. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  21600. callbacks.ondragstop();
  21601. }
  21602. elm.attachEvent('onmousemove', handleMouseMove);
  21603. elm.attachEvent('onmouseup', releaseCaptrue);
  21604. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  21605. evt.returnValue = false;
  21606. }
  21607. callbacks.ondragstart();
  21608. },
  21609. getFixedLayer: function (){
  21610. var layer = document.getElementById('edui_fixedlayer');
  21611. if (layer == null) {
  21612. layer = document.createElement('div');
  21613. layer.id = 'edui_fixedlayer';
  21614. document.body.appendChild(layer);
  21615. if (browser.ie && browser.version <= 8) {
  21616. layer.style.position = 'absolute';
  21617. bindFixedLayer();
  21618. setTimeout(updateFixedOffset);
  21619. } else {
  21620. layer.style.position = 'fixed';
  21621. }
  21622. layer.style.left = '0';
  21623. layer.style.top = '0';
  21624. layer.style.width = '0';
  21625. layer.style.height = '0';
  21626. }
  21627. return layer;
  21628. },
  21629. makeUnselectable: function (element){
  21630. if (browser.opera || (browser.ie && browser.version < 9)) {
  21631. element.unselectable = 'on';
  21632. if (element.hasChildNodes()) {
  21633. for (var i=0; i<element.childNodes.length; i++) {
  21634. if (element.childNodes[i].nodeType == 1) {
  21635. uiUtils.makeUnselectable(element.childNodes[i]);
  21636. }
  21637. }
  21638. }
  21639. } else {
  21640. if (element.style.MozUserSelect !== undefined) {
  21641. element.style.MozUserSelect = 'none';
  21642. } else if (element.style.WebkitUserSelect !== undefined) {
  21643. element.style.WebkitUserSelect = 'none';
  21644. } else if (element.style.KhtmlUserSelect !== undefined) {
  21645. element.style.KhtmlUserSelect = 'none';
  21646. }
  21647. }
  21648. }
  21649. };
  21650. function updateFixedOffset(){
  21651. var layer = document.getElementById('edui_fixedlayer');
  21652. uiUtils.setViewportOffset(layer, {
  21653. left: 0,
  21654. top: 0
  21655. });
  21656. // layer.style.display = 'none';
  21657. // layer.style.display = 'block';
  21658. //#trace: 1354
  21659. // setTimeout(updateFixedOffset);
  21660. }
  21661. function bindFixedLayer(adjOffset){
  21662. domUtils.on(window, 'scroll', updateFixedOffset);
  21663. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  21664. }
  21665. })();
  21666. (function () {
  21667. var utils = baidu.editor.utils,
  21668. uiUtils = baidu.editor.ui.uiUtils,
  21669. EventBase = baidu.editor.EventBase,
  21670. UIBase = baidu.editor.ui.UIBase = function () {
  21671. };
  21672. UIBase.prototype = {
  21673. className:'',
  21674. uiName:'',
  21675. initOptions:function (options) {
  21676. var me = this;
  21677. for (var k in options) {
  21678. me[k] = options[k];
  21679. }
  21680. this.id = this.id || 'edui' + uiUtils.uid();
  21681. },
  21682. initUIBase:function () {
  21683. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  21684. },
  21685. render:function (holder) {
  21686. var html = this.renderHtml();
  21687. var el = uiUtils.createElementByHtml(html);
  21688. //by xuheng 给每个node添加class
  21689. var list = domUtils.getElementsByTagName(el, "*");
  21690. var theme = "edui-" + (this.theme || this.editor.options.theme);
  21691. var layer = document.getElementById('edui_fixedlayer');
  21692. for (var i = 0, node; node = list[i++];) {
  21693. domUtils.addClass(node, theme);
  21694. }
  21695. domUtils.addClass(el, theme);
  21696. if(layer){
  21697. layer.className="";
  21698. domUtils.addClass(layer,theme);
  21699. }
  21700. var seatEl = this.getDom();
  21701. if (seatEl != null) {
  21702. seatEl.parentNode.replaceChild(el, seatEl);
  21703. uiUtils.copyAttributes(el, seatEl);
  21704. } else {
  21705. if (typeof holder == 'string') {
  21706. holder = document.getElementById(holder);
  21707. }
  21708. holder = holder || uiUtils.getFixedLayer();
  21709. domUtils.addClass(holder, theme);
  21710. holder.appendChild(el);
  21711. }
  21712. this.postRender();
  21713. },
  21714. getDom:function (name) {
  21715. if (!name) {
  21716. return document.getElementById(this.id);
  21717. } else {
  21718. return document.getElementById(this.id + '_' + name);
  21719. }
  21720. },
  21721. postRender:function () {
  21722. this.fireEvent('postrender');
  21723. },
  21724. getHtmlTpl:function () {
  21725. return '';
  21726. },
  21727. formatHtml:function (tpl) {
  21728. var prefix = 'edui-' + this.uiName;
  21729. return (tpl
  21730. .replace(/##/g, this.id)
  21731. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  21732. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  21733. .replace(/\$\$/g, this._globalKey));
  21734. },
  21735. renderHtml:function () {
  21736. return this.formatHtml(this.getHtmlTpl());
  21737. },
  21738. dispose:function () {
  21739. var box = this.getDom();
  21740. if (box) baidu.editor.dom.domUtils.remove(box);
  21741. uiUtils.unsetGlobal(this.id);
  21742. }
  21743. };
  21744. utils.inherits(UIBase, EventBase);
  21745. })();
  21746. (function (){
  21747. var utils = baidu.editor.utils,
  21748. UIBase = baidu.editor.ui.UIBase,
  21749. Separator = baidu.editor.ui.Separator = function (options){
  21750. this.initOptions(options);
  21751. this.initSeparator();
  21752. };
  21753. Separator.prototype = {
  21754. uiName: 'separator',
  21755. initSeparator: function (){
  21756. this.initUIBase();
  21757. },
  21758. getHtmlTpl: function (){
  21759. return '<div id="##" class="edui-box %%"></div>';
  21760. }
  21761. };
  21762. utils.inherits(Separator, UIBase);
  21763. })();
  21764. ///import core
  21765. ///import uicore
  21766. (function (){
  21767. var utils = baidu.editor.utils,
  21768. domUtils = baidu.editor.dom.domUtils,
  21769. UIBase = baidu.editor.ui.UIBase,
  21770. uiUtils = baidu.editor.ui.uiUtils;
  21771. var Mask = baidu.editor.ui.Mask = function (options){
  21772. this.initOptions(options);
  21773. this.initUIBase();
  21774. };
  21775. Mask.prototype = {
  21776. getHtmlTpl: function (){
  21777. return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>';
  21778. },
  21779. postRender: function (){
  21780. var me = this;
  21781. domUtils.on(window, 'resize', function (){
  21782. setTimeout(function (){
  21783. if (!me.isHidden()) {
  21784. me._fill();
  21785. }
  21786. });
  21787. });
  21788. },
  21789. show: function (zIndex){
  21790. this._fill();
  21791. this.getDom().style.display = '';
  21792. this.getDom().style.zIndex = zIndex;
  21793. },
  21794. hide: function (){
  21795. this.getDom().style.display = 'none';
  21796. this.getDom().style.zIndex = '';
  21797. },
  21798. isHidden: function (){
  21799. return this.getDom().style.display == 'none';
  21800. },
  21801. _onMouseDown: function (){
  21802. return false;
  21803. },
  21804. _fill: function (){
  21805. var el = this.getDom();
  21806. var vpRect = uiUtils.getViewportRect();
  21807. el.style.width = vpRect.width + 'px';
  21808. el.style.height = vpRect.height + 'px';
  21809. }
  21810. };
  21811. utils.inherits(Mask, UIBase);
  21812. })();
  21813. ///import core
  21814. ///import uicore
  21815. (function () {
  21816. var utils = baidu.editor.utils,
  21817. uiUtils = baidu.editor.ui.uiUtils,
  21818. domUtils = baidu.editor.dom.domUtils,
  21819. UIBase = baidu.editor.ui.UIBase,
  21820. Popup = baidu.editor.ui.Popup = function (options){
  21821. this.initOptions(options);
  21822. this.initPopup();
  21823. };
  21824. var allPopups = [];
  21825. function closeAllPopup( evt,el ){
  21826. for ( var i = 0; i < allPopups.length; i++ ) {
  21827. var pop = allPopups[i];
  21828. if (!pop.isHidden()) {
  21829. if (pop.queryAutoHide(el) !== false) {
  21830. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  21831. pop.hide();
  21832. }
  21833. }
  21834. }
  21835. if(allPopups.length)
  21836. pop.editor.fireEvent("afterhidepop");
  21837. }
  21838. Popup.postHide = closeAllPopup;
  21839. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  21840. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  21841. Popup.prototype = {
  21842. SHADOW_RADIUS: 5,
  21843. content: null,
  21844. _hidden: false,
  21845. autoRender: true,
  21846. canSideLeft: true,
  21847. canSideUp: true,
  21848. initPopup: function (){
  21849. this.initUIBase();
  21850. allPopups.push( this );
  21851. },
  21852. getHtmlTpl: function (){
  21853. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  21854. ' <div id="##_body" class="edui-popup-body">' +
  21855. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  21856. ' <div class="edui-shadow"></div>' +
  21857. ' <div id="##_content" class="edui-popup-content">' +
  21858. this.getContentHtmlTpl() +
  21859. ' </div>' +
  21860. ' </div>' +
  21861. '</div>';
  21862. },
  21863. getContentHtmlTpl: function (){
  21864. if(this.content){
  21865. if (typeof this.content == 'string') {
  21866. return this.content;
  21867. }
  21868. return this.content.renderHtml();
  21869. }else{
  21870. return ''
  21871. }
  21872. },
  21873. _UIBase_postRender: UIBase.prototype.postRender,
  21874. postRender: function (){
  21875. if (this.content instanceof UIBase) {
  21876. this.content.postRender();
  21877. }
  21878. //捕获鼠标滚轮
  21879. if( this.captureWheel && !this.captured ) {
  21880. this.captured = true;
  21881. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  21882. _height = this.getDom().offsetHeight,
  21883. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  21884. content = this.getDom('content'),
  21885. ifr = this.getDom('body').getElementsByTagName('iframe'),
  21886. me = this;
  21887. ifr.length && ( ifr = ifr[0] );
  21888. while( _top + _height > winHeight ) {
  21889. _height -= 30;
  21890. content.style.height = _height + 'px';
  21891. //同步更改iframe高度
  21892. ifr && ( ifr.style.height = _height + 'px' );
  21893. }
  21894. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  21895. if( window.XMLHttpRequest ) {
  21896. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  21897. if(e.preventDefault) {
  21898. e.preventDefault();
  21899. } else {
  21900. e.returnValue = false;
  21901. }
  21902. if( e.wheelDelta ) {
  21903. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  21904. } else {
  21905. content.scrollTop -= ( e.detail / -3 )*60;
  21906. }
  21907. });
  21908. } else {
  21909. //ie6
  21910. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  21911. e.returnValue = false;
  21912. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  21913. });
  21914. }
  21915. }
  21916. this.fireEvent('postRenderAfter');
  21917. this.hide(true);
  21918. this._UIBase_postRender();
  21919. },
  21920. _doAutoRender: function (){
  21921. if (!this.getDom() && this.autoRender) {
  21922. this.render();
  21923. }
  21924. },
  21925. mesureSize: function (){
  21926. var box = this.getDom('content');
  21927. return uiUtils.getClientRect(box);
  21928. },
  21929. fitSize: function (){
  21930. if( this.captureWheel && this.sized ) {
  21931. return this.__size;
  21932. }
  21933. this.sized = true;
  21934. var popBodyEl = this.getDom('body');
  21935. popBodyEl.style.width = '';
  21936. popBodyEl.style.height = '';
  21937. var size = this.mesureSize();
  21938. if( this.captureWheel ) {
  21939. popBodyEl.style.width = -(-20 -size.width) + 'px';
  21940. var height = parseInt( this.getDom('content').style.height, 10 );
  21941. !window.isNaN( height ) && ( size.height = height );
  21942. } else {
  21943. popBodyEl.style.width = size.width + 'px';
  21944. }
  21945. popBodyEl.style.height = size.height + 'px';
  21946. this.__size = size;
  21947. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  21948. return size;
  21949. },
  21950. showAnchor: function ( element, hoz ){
  21951. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  21952. },
  21953. showAnchorRect: function ( rect, hoz, adj ){
  21954. this._doAutoRender();
  21955. var vpRect = uiUtils.getViewportRect();
  21956. this._show();
  21957. var popSize = this.fitSize();
  21958. var sideLeft, sideUp, left, top;
  21959. if (hoz) {
  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.left - popSize.width : rect.right);
  21963. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  21964. } else {
  21965. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  21966. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  21967. left = (sideLeft ? rect.right - popSize.width : rect.left);
  21968. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  21969. }
  21970. var popEl = this.getDom();
  21971. uiUtils.setViewportOffset(popEl, {
  21972. left: left,
  21973. top: top
  21974. });
  21975. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  21976. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  21977. if(this.editor){
  21978. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  21979. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  21980. }
  21981. },
  21982. showAt: function (offset) {
  21983. var left = offset.left;
  21984. var top = offset.top;
  21985. var rect = {
  21986. left: left,
  21987. top: top,
  21988. right: left,
  21989. bottom: top,
  21990. height: 0,
  21991. width: 0
  21992. };
  21993. this.showAnchorRect(rect, false, true);
  21994. },
  21995. _show: function (){
  21996. if (this._hidden) {
  21997. var box = this.getDom();
  21998. box.style.display = '';
  21999. this._hidden = false;
  22000. // if (box.setActive) {
  22001. // box.setActive();
  22002. // }
  22003. this.fireEvent('show');
  22004. }
  22005. },
  22006. isHidden: function (){
  22007. return this._hidden;
  22008. },
  22009. show: function (){
  22010. this._doAutoRender();
  22011. this._show();
  22012. },
  22013. hide: function (notNofity){
  22014. if (!this._hidden && this.getDom()) {
  22015. this.getDom().style.display = 'none';
  22016. this._hidden = true;
  22017. if (!notNofity) {
  22018. this.fireEvent('hide');
  22019. }
  22020. }
  22021. },
  22022. queryAutoHide: function (el){
  22023. return !el || !uiUtils.contains(this.getDom(), el);
  22024. }
  22025. };
  22026. utils.inherits(Popup, UIBase);
  22027. domUtils.on( document, 'mousedown', function ( evt ) {
  22028. var el = evt.target || evt.srcElement;
  22029. closeAllPopup( evt,el );
  22030. } );
  22031. domUtils.on( window, 'scroll', function (evt,el) {
  22032. closeAllPopup( evt,el );
  22033. } );
  22034. })();
  22035. ///import core
  22036. ///import uicore
  22037. (function (){
  22038. var utils = baidu.editor.utils,
  22039. UIBase = baidu.editor.ui.UIBase,
  22040. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  22041. this.initOptions(options);
  22042. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  22043. this.initUIBase();
  22044. };
  22045. ColorPicker.prototype = {
  22046. getHtmlTpl: function (){
  22047. return genColorPicker(this.noColorText,this.editor);
  22048. },
  22049. _onTableClick: function (evt){
  22050. var tgt = evt.target || evt.srcElement;
  22051. var color = tgt.getAttribute('data-color');
  22052. if (color) {
  22053. this.fireEvent('pickcolor', color);
  22054. }
  22055. },
  22056. _onTableOver: function (evt){
  22057. var tgt = evt.target || evt.srcElement;
  22058. var color = tgt.getAttribute('data-color');
  22059. if (color) {
  22060. this.getDom('preview').style.backgroundColor = color;
  22061. }
  22062. },
  22063. _onTableOut: function (){
  22064. this.getDom('preview').style.backgroundColor = '';
  22065. },
  22066. _onPickNoColor: function (){
  22067. this.fireEvent('picknocolor');
  22068. }
  22069. };
  22070. utils.inherits(ColorPicker, UIBase);
  22071. var COLORS = (
  22072. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  22073. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  22074. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  22075. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  22076. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  22077. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  22078. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  22079. function genColorPicker(noColorText,editor){
  22080. var html = '<div id="##" class="edui-colorpicker %%">' +
  22081. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  22082. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  22083. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  22084. '</div>' +
  22085. '<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">' +
  22086. '<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>'+
  22087. '<tr class="edui-colorpicker-tablefirstrow" >';
  22088. for (var i=0; i<COLORS.length; i++) {
  22089. if (i && i%10 === 0) {
  22090. 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"':'')+'>';
  22091. }
  22092. 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"' +
  22093. ' data-color="#'+ COLORS[i] +'"'+
  22094. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  22095. (i<10 || i>=60?'border-width:1px;':
  22096. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  22097. 'border-width:0 1px 0 1px;')+
  22098. '"' +
  22099. '></a></td>':'';
  22100. }
  22101. html += '</tr></table></div>';
  22102. return html;
  22103. }
  22104. })();
  22105. ///import core
  22106. ///import uicore
  22107. (function (){
  22108. var utils = baidu.editor.utils,
  22109. uiUtils = baidu.editor.ui.uiUtils,
  22110. UIBase = baidu.editor.ui.UIBase;
  22111. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  22112. this.initOptions(options);
  22113. this.initTablePicker();
  22114. };
  22115. TablePicker.prototype = {
  22116. defaultNumRows: 10,
  22117. defaultNumCols: 10,
  22118. maxNumRows: 20,
  22119. maxNumCols: 20,
  22120. numRows: 10,
  22121. numCols: 10,
  22122. lengthOfCellSide: 22,
  22123. initTablePicker: function (){
  22124. this.initUIBase();
  22125. },
  22126. getHtmlTpl: function (){
  22127. var me = this;
  22128. return '<div id="##" class="edui-tablepicker %%">' +
  22129. '<div class="edui-tablepicker-body">' +
  22130. '<div class="edui-infoarea">' +
  22131. '<span id="##_label" class="edui-label"></span>' +
  22132. '</div>' +
  22133. '<div class="edui-pickarea"' +
  22134. ' onmousemove="$$._onMouseMove(event, this);"' +
  22135. ' onmouseover="$$._onMouseOver(event, this);"' +
  22136. ' onmouseout="$$._onMouseOut(event, this);"' +
  22137. ' onclick="$$._onClick(event, this);"' +
  22138. '>' +
  22139. '<div id="##_overlay" class="edui-overlay"></div>' +
  22140. '</div>' +
  22141. '</div>' +
  22142. '</div>';
  22143. },
  22144. _UIBase_render: UIBase.prototype.render,
  22145. render: function (holder){
  22146. this._UIBase_render(holder);
  22147. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  22148. },
  22149. _track: function (numCols, numRows){
  22150. var style = this.getDom('overlay').style;
  22151. var sideLen = this.lengthOfCellSide;
  22152. style.width = numCols * sideLen + 'px';
  22153. style.height = numRows * sideLen + 'px';
  22154. var label = this.getDom('label');
  22155. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  22156. this.numCols = numCols;
  22157. this.numRows = numRows;
  22158. },
  22159. _onMouseOver: function (evt, el){
  22160. var rel = evt.relatedTarget || evt.fromElement;
  22161. if (!uiUtils.contains(el, rel) && el !== rel) {
  22162. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  22163. this.getDom('overlay').style.visibility = '';
  22164. }
  22165. },
  22166. _onMouseOut: function (evt, el){
  22167. var rel = evt.relatedTarget || evt.toElement;
  22168. if (!uiUtils.contains(el, rel) && el !== rel) {
  22169. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  22170. this.getDom('overlay').style.visibility = 'hidden';
  22171. }
  22172. },
  22173. _onMouseMove: function (evt, el){
  22174. var style = this.getDom('overlay').style;
  22175. var offset = uiUtils.getEventOffset(evt);
  22176. var sideLen = this.lengthOfCellSide;
  22177. var numCols = Math.ceil(offset.left / sideLen);
  22178. var numRows = Math.ceil(offset.top / sideLen);
  22179. this._track(numCols, numRows);
  22180. },
  22181. _onClick: function (){
  22182. this.fireEvent('picktable', this.numCols, this.numRows);
  22183. }
  22184. };
  22185. utils.inherits(TablePicker, UIBase);
  22186. })();
  22187. (function (){
  22188. var browser = baidu.editor.browser,
  22189. domUtils = baidu.editor.dom.domUtils,
  22190. uiUtils = baidu.editor.ui.uiUtils;
  22191. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  22192. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  22193. ( browser.ie ? (
  22194. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  22195. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  22196. : (
  22197. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  22198. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  22199. baidu.editor.ui.Stateful = {
  22200. alwalysHoverable: false,
  22201. target:null,//目标元素和this指向dom不一样
  22202. Stateful_init: function (){
  22203. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  22204. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  22205. },
  22206. Stateful_getHtmlTpl: function (){
  22207. var tpl = this._Stateful_dGetHtmlTpl();
  22208. // 使用function避免$转义
  22209. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  22210. },
  22211. Stateful_onMouseEnter: function (evt, el){
  22212. this.target=el;
  22213. if (!this.isDisabled() || this.alwalysHoverable) {
  22214. this.addState('hover');
  22215. this.fireEvent('over');
  22216. }
  22217. },
  22218. Stateful_onMouseLeave: function (evt, el){
  22219. if (!this.isDisabled() || this.alwalysHoverable) {
  22220. this.removeState('hover');
  22221. this.removeState('active');
  22222. this.fireEvent('out');
  22223. }
  22224. },
  22225. Stateful_onMouseOver: function (evt, el){
  22226. var rel = evt.relatedTarget;
  22227. if (!uiUtils.contains(el, rel) && el !== rel) {
  22228. this.Stateful_onMouseEnter(evt, el);
  22229. }
  22230. },
  22231. Stateful_onMouseOut: function (evt, el){
  22232. var rel = evt.relatedTarget;
  22233. if (!uiUtils.contains(el, rel) && el !== rel) {
  22234. this.Stateful_onMouseLeave(evt, el);
  22235. }
  22236. },
  22237. Stateful_onMouseDown: function (evt, el){
  22238. if (!this.isDisabled()) {
  22239. this.addState('active');
  22240. }
  22241. },
  22242. Stateful_onMouseUp: function (evt, el){
  22243. if (!this.isDisabled()) {
  22244. this.removeState('active');
  22245. }
  22246. },
  22247. Stateful_postRender: function (){
  22248. if (this.disabled && !this.hasState('disabled')) {
  22249. this.addState('disabled');
  22250. }
  22251. },
  22252. hasState: function (state){
  22253. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  22254. },
  22255. addState: function (state){
  22256. if (!this.hasState(state)) {
  22257. this.getStateDom().className += ' edui-state-' + state;
  22258. }
  22259. },
  22260. removeState: function (state){
  22261. if (this.hasState(state)) {
  22262. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  22263. }
  22264. },
  22265. getStateDom: function (){
  22266. return this.getDom('state');
  22267. },
  22268. isChecked: function (){
  22269. return this.hasState('checked');
  22270. },
  22271. setChecked: function (checked){
  22272. if (!this.isDisabled() && checked) {
  22273. this.addState('checked');
  22274. } else {
  22275. this.removeState('checked');
  22276. }
  22277. },
  22278. isDisabled: function (){
  22279. return this.hasState('disabled');
  22280. },
  22281. setDisabled: function (disabled){
  22282. if (disabled) {
  22283. this.removeState('hover');
  22284. this.removeState('checked');
  22285. this.removeState('active');
  22286. this.addState('disabled');
  22287. } else {
  22288. this.removeState('disabled');
  22289. }
  22290. }
  22291. };
  22292. })();
  22293. ///import core
  22294. ///import uicore
  22295. ///import ui/stateful.js
  22296. (function (){
  22297. var utils = baidu.editor.utils,
  22298. UIBase = baidu.editor.ui.UIBase,
  22299. Stateful = baidu.editor.ui.Stateful,
  22300. Button = baidu.editor.ui.Button = function (options){
  22301. this.initOptions(options);
  22302. this.initButton();
  22303. };
  22304. Button.prototype = {
  22305. uiName: 'button',
  22306. label: '',
  22307. title: '',
  22308. showIcon: true,
  22309. showText: true,
  22310. initButton: function (){
  22311. this.initUIBase();
  22312. this.Stateful_init();
  22313. },
  22314. getHtmlTpl: function (){
  22315. return '<div id="##" class="edui-box %%">' +
  22316. '<div id="##_state" stateful>' +
  22317. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  22318. ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' +
  22319. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  22320. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  22321. '</div>' +
  22322. '</div>' +
  22323. '</div></div>';
  22324. },
  22325. postRender: function (){
  22326. this.Stateful_postRender();
  22327. this.setDisabled(this.disabled)
  22328. },
  22329. _onClick: function (){
  22330. if (!this.isDisabled()) {
  22331. this.fireEvent('click');
  22332. }
  22333. }
  22334. };
  22335. utils.inherits(Button, UIBase);
  22336. utils.extend(Button.prototype, Stateful);
  22337. })();
  22338. ///import core
  22339. ///import uicore
  22340. ///import ui/stateful.js
  22341. (function (){
  22342. var utils = baidu.editor.utils,
  22343. uiUtils = baidu.editor.ui.uiUtils,
  22344. domUtils = baidu.editor.dom.domUtils,
  22345. UIBase = baidu.editor.ui.UIBase,
  22346. Stateful = baidu.editor.ui.Stateful,
  22347. SplitButton = baidu.editor.ui.SplitButton = function (options){
  22348. this.initOptions(options);
  22349. this.initSplitButton();
  22350. };
  22351. SplitButton.prototype = {
  22352. popup: null,
  22353. uiName: 'splitbutton',
  22354. title: '',
  22355. initSplitButton: function (){
  22356. this.initUIBase();
  22357. this.Stateful_init();
  22358. var me = this;
  22359. if (this.popup != null) {
  22360. var popup = this.popup;
  22361. this.popup = null;
  22362. this.setPopup(popup);
  22363. }
  22364. },
  22365. _UIBase_postRender: UIBase.prototype.postRender,
  22366. postRender: function (){
  22367. this.Stateful_postRender();
  22368. this._UIBase_postRender();
  22369. },
  22370. setPopup: function (popup){
  22371. if (this.popup === popup) return;
  22372. if (this.popup != null) {
  22373. this.popup.dispose();
  22374. }
  22375. popup.addListener('show', utils.bind(this._onPopupShow, this));
  22376. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  22377. popup.addListener('postrender', utils.bind(function (){
  22378. popup.getDom('body').appendChild(
  22379. uiUtils.createElementByHtml('<div id="' +
  22380. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  22381. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  22382. );
  22383. popup.getDom().className += ' ' + this.className;
  22384. }, this));
  22385. this.popup = popup;
  22386. },
  22387. _onPopupShow: function (){
  22388. this.addState('opened');
  22389. },
  22390. _onPopupHide: function (){
  22391. this.removeState('opened');
  22392. },
  22393. getHtmlTpl: function (){
  22394. return '<div id="##" class="edui-box %%">' +
  22395. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  22396. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  22397. '<div class="edui-box edui-icon"></div>' +
  22398. '</div>' +
  22399. '<div class="edui-box edui-splitborder"></div>' +
  22400. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  22401. '</div></div></div>';
  22402. },
  22403. showPopup: function (){
  22404. // 当popup往上弹出的时候,做特殊处理
  22405. var rect = uiUtils.getClientRect(this.getDom());
  22406. rect.top -= this.popup.SHADOW_RADIUS;
  22407. rect.height += this.popup.SHADOW_RADIUS;
  22408. this.popup.showAnchorRect(rect);
  22409. },
  22410. _onArrowClick: function (event, el){
  22411. if (!this.isDisabled()) {
  22412. this.showPopup();
  22413. }
  22414. },
  22415. _onButtonClick: function (){
  22416. if (!this.isDisabled()) {
  22417. this.fireEvent('buttonclick');
  22418. }
  22419. }
  22420. };
  22421. utils.inherits(SplitButton, UIBase);
  22422. utils.extend(SplitButton.prototype, Stateful, true);
  22423. })();
  22424. ///import core
  22425. ///import uicore
  22426. ///import ui/colorpicker.js
  22427. ///import ui/popup.js
  22428. ///import ui/splitbutton.js
  22429. (function (){
  22430. var utils = baidu.editor.utils,
  22431. uiUtils = baidu.editor.ui.uiUtils,
  22432. ColorPicker = baidu.editor.ui.ColorPicker,
  22433. Popup = baidu.editor.ui.Popup,
  22434. SplitButton = baidu.editor.ui.SplitButton,
  22435. ColorButton = baidu.editor.ui.ColorButton = function (options){
  22436. this.initOptions(options);
  22437. this.initColorButton();
  22438. };
  22439. ColorButton.prototype = {
  22440. initColorButton: function (){
  22441. var me = this;
  22442. this.popup = new Popup({
  22443. content: new ColorPicker({
  22444. noColorText: me.editor.getLang("clearColor"),
  22445. editor:me.editor,
  22446. onpickcolor: function (t, color){
  22447. me._onPickColor(color);
  22448. },
  22449. onpicknocolor: function (t, color){
  22450. me._onPickNoColor(color);
  22451. }
  22452. }),
  22453. editor:me.editor
  22454. });
  22455. this.initSplitButton();
  22456. },
  22457. _SplitButton_postRender: SplitButton.prototype.postRender,
  22458. postRender: function (){
  22459. this._SplitButton_postRender();
  22460. this.getDom('button_body').appendChild(
  22461. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  22462. );
  22463. this.getDom().className += ' edui-colorbutton';
  22464. },
  22465. setColor: function (color){
  22466. this.getDom('colorlump').style.backgroundColor = color;
  22467. this.color = color;
  22468. },
  22469. _onPickColor: function (color){
  22470. if (this.fireEvent('pickcolor', color) !== false) {
  22471. this.setColor(color);
  22472. this.popup.hide();
  22473. }
  22474. },
  22475. _onPickNoColor: function (color){
  22476. if (this.fireEvent('picknocolor') !== false) {
  22477. this.popup.hide();
  22478. }
  22479. }
  22480. };
  22481. utils.inherits(ColorButton, SplitButton);
  22482. })();
  22483. ///import core
  22484. ///import uicore
  22485. ///import ui/popup.js
  22486. ///import ui/tablepicker.js
  22487. ///import ui/splitbutton.js
  22488. (function (){
  22489. var utils = baidu.editor.utils,
  22490. Popup = baidu.editor.ui.Popup,
  22491. TablePicker = baidu.editor.ui.TablePicker,
  22492. SplitButton = baidu.editor.ui.SplitButton,
  22493. TableButton = baidu.editor.ui.TableButton = function (options){
  22494. this.initOptions(options);
  22495. this.initTableButton();
  22496. };
  22497. TableButton.prototype = {
  22498. initTableButton: function (){
  22499. var me = this;
  22500. this.popup = new Popup({
  22501. content: new TablePicker({
  22502. editor:me.editor,
  22503. onpicktable: function (t, numCols, numRows){
  22504. me._onPickTable(numCols, numRows);
  22505. }
  22506. }),
  22507. 'editor':me.editor
  22508. });
  22509. this.initSplitButton();
  22510. },
  22511. _onPickTable: function (numCols, numRows){
  22512. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  22513. this.popup.hide();
  22514. }
  22515. }
  22516. };
  22517. utils.inherits(TableButton, SplitButton);
  22518. })();
  22519. ///import core
  22520. ///import uicore
  22521. (function () {
  22522. var utils = baidu.editor.utils,
  22523. UIBase = baidu.editor.ui.UIBase;
  22524. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  22525. this.initOptions(options);
  22526. this.initAutoTypeSetPicker();
  22527. };
  22528. AutoTypeSetPicker.prototype = {
  22529. initAutoTypeSetPicker:function () {
  22530. this.initUIBase();
  22531. },
  22532. getHtmlTpl:function () {
  22533. var me = this.editor,
  22534. opt = me.options.autotypeset,
  22535. lang = me.getLang("autoTypeSet");
  22536. var textAlignInputName = 'textAlignValue' + me.uid,
  22537. imageBlockInputName = 'imageBlockLineValue' + me.uid;
  22538. return '<div id="##" class="edui-autotypesetpicker %%">' +
  22539. '<div class="edui-autotypesetpicker-body">' +
  22540. '<table >' +
  22541. '<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>' +
  22542. '<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>' +
  22543. '<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>' +
  22544. '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  22545. '<td nowrap colspan="2" id="'+ imageBlockInputName +'">' +
  22546. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  22547. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  22548. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  22549. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' +
  22550. '<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>' +
  22551. '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  22552. '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  22553. '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' +
  22554. '</table>' +
  22555. '</div>' +
  22556. '</div>';
  22557. },
  22558. _UIBase_render:UIBase.prototype.render
  22559. };
  22560. utils.inherits(AutoTypeSetPicker, UIBase);
  22561. })();
  22562. ///import core
  22563. ///import uicore
  22564. ///import ui/popup.js
  22565. ///import ui/autotypesetpicker.js
  22566. ///import ui/splitbutton.js
  22567. (function (){
  22568. var utils = baidu.editor.utils,
  22569. Popup = baidu.editor.ui.Popup,
  22570. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  22571. SplitButton = baidu.editor.ui.SplitButton,
  22572. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  22573. this.initOptions(options);
  22574. this.initAutoTypeSetButton();
  22575. };
  22576. function getPara(me){
  22577. var opt = me.editor.options.autotypeset,
  22578. cont = me.getDom(),
  22579. editorId = me.editor.uid,
  22580. inputType = null,
  22581. attrName = null,
  22582. ipts = domUtils.getElementsByTagName(cont,"input");
  22583. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  22584. inputType = ipt.getAttribute("type");
  22585. if(inputType=="checkbox"){
  22586. attrName = ipt.getAttribute("name");
  22587. opt[attrName] && delete opt[attrName];
  22588. if(ipt.checked){
  22589. var attrValue = document.getElementById( attrName+"Value" + editorId );
  22590. if(attrValue){
  22591. if(/input/ig.test(attrValue.tagName)){
  22592. opt[attrName] = attrValue.value;
  22593. }else{
  22594. var iptChilds = attrValue.getElementsByTagName("input");
  22595. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  22596. if(iptchild.checked){
  22597. opt[attrName] = iptchild.value;
  22598. break;
  22599. }
  22600. }
  22601. }
  22602. }else{
  22603. opt[attrName] = true;
  22604. }
  22605. }
  22606. }
  22607. }
  22608. var selects = domUtils.getElementsByTagName(cont,"select");
  22609. for(var i=0,si;si=selects[i++];){
  22610. var attr = si.getAttribute('name');
  22611. opt[attr] = opt[attr] ? si.value : '';
  22612. }
  22613. me.editor.options.autotypeset = opt;
  22614. }
  22615. AutoTypeSetButton.prototype = {
  22616. initAutoTypeSetButton: function (){
  22617. var me = this;
  22618. this.popup = new Popup({
  22619. //传入配置参数
  22620. content: new AutoTypeSetPicker({editor:me.editor}),
  22621. 'editor':me.editor,
  22622. hide : function(){
  22623. if (!this._hidden && this.getDom()) {
  22624. getPara(this);
  22625. this.getDom().style.display = 'none';
  22626. this._hidden = true;
  22627. this.fireEvent('hide');
  22628. }
  22629. }
  22630. });
  22631. var flag = 0;
  22632. this.popup.addListener('postRenderAfter',function(){
  22633. var popupUI = this;
  22634. if(flag)return;
  22635. var cont = this.getDom(),
  22636. btn = cont.getElementsByTagName('button')[0];
  22637. btn.onclick = function(){
  22638. getPara(popupUI);
  22639. me.editor.execCommand('autotypeset');
  22640. popupUI.hide()
  22641. };
  22642. flag = 1;
  22643. });
  22644. this.initSplitButton();
  22645. }
  22646. };
  22647. utils.inherits(AutoTypeSetButton, SplitButton);
  22648. })();
  22649. ///import core
  22650. ///import uicore
  22651. (function () {
  22652. var utils = baidu.editor.utils,
  22653. Popup = baidu.editor.ui.Popup,
  22654. Stateful = baidu.editor.ui.Stateful,
  22655. UIBase = baidu.editor.ui.UIBase;
  22656. /**
  22657. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  22658. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  22659. * @update 2013/4/2 hancong03@baidu.com
  22660. */
  22661. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  22662. this.initOptions(options);
  22663. this.initSelected();
  22664. this.initCellAlignPicker();
  22665. };
  22666. CellAlignPicker.prototype = {
  22667. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  22668. initSelected: function(){
  22669. var status = {
  22670. valign: {
  22671. top: 0,
  22672. middle: 1,
  22673. bottom: 2
  22674. },
  22675. align: {
  22676. left: 0,
  22677. center: 1,
  22678. right: 2
  22679. },
  22680. count: 3
  22681. },
  22682. result = -1;
  22683. if( this.selected ) {
  22684. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  22685. }
  22686. },
  22687. initCellAlignPicker:function () {
  22688. this.initUIBase();
  22689. this.Stateful_init();
  22690. },
  22691. getHtmlTpl:function () {
  22692. var alignType = [ 'left', 'center', 'right' ],
  22693. COUNT = 9,
  22694. tempClassName = null,
  22695. tempIndex = -1,
  22696. tmpl = [];
  22697. for( var i= 0; i<COUNT; i++ ) {
  22698. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  22699. tempIndex = i % 3;
  22700. tempIndex === 0 && tmpl.push('<tr>');
  22701. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  22702. tempIndex === 2 && tmpl.push('</tr>');
  22703. }
  22704. return '<div id="##" class="edui-cellalignpicker %%">' +
  22705. '<div class="edui-cellalignpicker-body">' +
  22706. '<table onclick="$$._onClick(event);">' +
  22707. tmpl.join('') +
  22708. '</table>' +
  22709. '</div>' +
  22710. '</div>';
  22711. },
  22712. getStateDom: function (){
  22713. return this.target;
  22714. },
  22715. _onClick: function (evt){
  22716. var target= evt.target || evt.srcElement;
  22717. if(/icon/.test(target.className)){
  22718. this.items[target.parentNode.getAttribute("index")].onclick();
  22719. Popup.postHide(evt);
  22720. }
  22721. },
  22722. _UIBase_render:UIBase.prototype.render
  22723. };
  22724. utils.inherits(CellAlignPicker, UIBase);
  22725. utils.extend(CellAlignPicker.prototype, Stateful,true);
  22726. })();
  22727. ///import core
  22728. ///import uicore
  22729. (function () {
  22730. var utils = baidu.editor.utils,
  22731. Stateful = baidu.editor.ui.Stateful,
  22732. uiUtils = baidu.editor.ui.uiUtils,
  22733. UIBase = baidu.editor.ui.UIBase;
  22734. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  22735. this.initOptions(options);
  22736. this.initPastePicker();
  22737. };
  22738. PastePicker.prototype = {
  22739. initPastePicker:function () {
  22740. this.initUIBase();
  22741. this.Stateful_init();
  22742. },
  22743. getHtmlTpl:function () {
  22744. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  22745. '<div class="edui-pastecontainer">' +
  22746. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  22747. '<div class="edui-button">' +
  22748. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  22749. '<div class="edui-richtxticon"></div></div>' +
  22750. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  22751. '<div class="edui-tagicon"></div></div>' +
  22752. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  22753. '<div class="edui-plaintxticon"></div></div>' +
  22754. '</div>' +
  22755. '</div>' +
  22756. '</div>'
  22757. },
  22758. getStateDom:function () {
  22759. return this.target;
  22760. },
  22761. format:function (param) {
  22762. this.editor.ui._isTransfer = true;
  22763. this.editor.fireEvent('pasteTransfer', param);
  22764. },
  22765. _onClick:function (cur) {
  22766. var node = domUtils.getNextDomNode(cur),
  22767. screenHt = uiUtils.getViewportRect().height,
  22768. subPop = uiUtils.getClientRect(node);
  22769. if ((subPop.top + subPop.height) > screenHt)
  22770. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  22771. else
  22772. node.style.top = "";
  22773. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  22774. node.style.visibility = "visible";
  22775. domUtils.addClass(cur, "edui-state-opened");
  22776. } else {
  22777. node.style.visibility = "hidden";
  22778. domUtils.removeClasses(cur, "edui-state-opened")
  22779. }
  22780. },
  22781. _UIBase_render:UIBase.prototype.render
  22782. };
  22783. utils.inherits(PastePicker, UIBase);
  22784. utils.extend(PastePicker.prototype, Stateful, true);
  22785. })();
  22786. (function (){
  22787. var utils = baidu.editor.utils,
  22788. uiUtils = baidu.editor.ui.uiUtils,
  22789. UIBase = baidu.editor.ui.UIBase,
  22790. Toolbar = baidu.editor.ui.Toolbar = function (options){
  22791. this.initOptions(options);
  22792. this.initToolbar();
  22793. };
  22794. Toolbar.prototype = {
  22795. items: null,
  22796. initToolbar: function (){
  22797. this.items = this.items || [];
  22798. this.initUIBase();
  22799. },
  22800. add: function (item){
  22801. this.items.push(item);
  22802. },
  22803. getHtmlTpl: function (){
  22804. var buff = [];
  22805. for (var i=0; i<this.items.length; i++) {
  22806. buff[i] = this.items[i].renderHtml();
  22807. }
  22808. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  22809. buff.join('') +
  22810. '</div>'
  22811. },
  22812. postRender: function (){
  22813. var box = this.getDom();
  22814. for (var i=0; i<this.items.length; i++) {
  22815. this.items[i].postRender();
  22816. }
  22817. uiUtils.makeUnselectable(box);
  22818. },
  22819. _onMouseDown: function (){
  22820. return false;
  22821. }
  22822. };
  22823. utils.inherits(Toolbar, UIBase);
  22824. })();
  22825. ///import core
  22826. ///import uicore
  22827. ///import ui\popup.js
  22828. ///import ui\stateful.js
  22829. (function () {
  22830. var utils = baidu.editor.utils,
  22831. domUtils = baidu.editor.dom.domUtils,
  22832. uiUtils = baidu.editor.ui.uiUtils,
  22833. UIBase = baidu.editor.ui.UIBase,
  22834. Popup = baidu.editor.ui.Popup,
  22835. Stateful = baidu.editor.ui.Stateful,
  22836. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  22837. Menu = baidu.editor.ui.Menu = function (options) {
  22838. this.initOptions(options);
  22839. this.initMenu();
  22840. };
  22841. var menuSeparator = {
  22842. renderHtml:function () {
  22843. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  22844. },
  22845. postRender:function () {
  22846. },
  22847. queryAutoHide:function () {
  22848. return true;
  22849. }
  22850. };
  22851. Menu.prototype = {
  22852. items:null,
  22853. uiName:'menu',
  22854. initMenu:function () {
  22855. this.items = this.items || [];
  22856. this.initPopup();
  22857. this.initItems();
  22858. },
  22859. initItems:function () {
  22860. for (var i = 0; i < this.items.length; i++) {
  22861. var item = this.items[i];
  22862. if (item == '-') {
  22863. this.items[i] = this.getSeparator();
  22864. } else if (!(item instanceof MenuItem)) {
  22865. item.editor = this.editor;
  22866. item.theme = this.editor.options.theme;
  22867. this.items[i] = this.createItem(item);
  22868. }
  22869. }
  22870. },
  22871. getSeparator:function () {
  22872. return menuSeparator;
  22873. },
  22874. createItem:function (item) {
  22875. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  22876. item.menu = this;
  22877. return new MenuItem(item);
  22878. },
  22879. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  22880. getContentHtmlTpl:function () {
  22881. if (this.items.length == 0) {
  22882. return this._Popup_getContentHtmlTpl();
  22883. }
  22884. var buff = [];
  22885. for (var i = 0; i < this.items.length; i++) {
  22886. var item = this.items[i];
  22887. buff[i] = item.renderHtml();
  22888. }
  22889. return ('<div class="%%-body">' + buff.join('') + '</div>');
  22890. },
  22891. _Popup_postRender:Popup.prototype.postRender,
  22892. postRender:function () {
  22893. var me = this;
  22894. for (var i = 0; i < this.items.length; i++) {
  22895. var item = this.items[i];
  22896. item.ownerMenu = this;
  22897. item.postRender();
  22898. }
  22899. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  22900. evt = evt || event;
  22901. var rel = evt.relatedTarget || evt.fromElement;
  22902. var el = me.getDom();
  22903. if (!uiUtils.contains(el, rel) && el !== rel) {
  22904. me.fireEvent('over');
  22905. }
  22906. });
  22907. this._Popup_postRender();
  22908. },
  22909. queryAutoHide:function (el) {
  22910. if (el) {
  22911. if (uiUtils.contains(this.getDom(), el)) {
  22912. return false;
  22913. }
  22914. for (var i = 0; i < this.items.length; i++) {
  22915. var item = this.items[i];
  22916. if (item.queryAutoHide(el) === false) {
  22917. return false;
  22918. }
  22919. }
  22920. }
  22921. },
  22922. clearItems:function () {
  22923. for (var i = 0; i < this.items.length; i++) {
  22924. var item = this.items[i];
  22925. clearTimeout(item._showingTimer);
  22926. clearTimeout(item._closingTimer);
  22927. if (item.subMenu) {
  22928. item.subMenu.destroy();
  22929. }
  22930. }
  22931. this.items = [];
  22932. },
  22933. destroy:function () {
  22934. if (this.getDom()) {
  22935. domUtils.remove(this.getDom());
  22936. }
  22937. this.clearItems();
  22938. },
  22939. dispose:function () {
  22940. this.destroy();
  22941. }
  22942. };
  22943. utils.inherits(Menu, Popup);
  22944. /**
  22945. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  22946. * @type {Function}
  22947. */
  22948. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  22949. this.initOptions(options);
  22950. this.initUIBase();
  22951. this.Stateful_init();
  22952. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  22953. if (options.className && options.className.indexOf("aligntd") != -1) {
  22954. var me = this;
  22955. //获取单元格对齐初始状态
  22956. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  22957. this.subMenu = new Popup({
  22958. content:new CellAlignPicker(this.subMenu),
  22959. parentMenu:me,
  22960. editor:me.editor,
  22961. destroy:function () {
  22962. if (this.getDom()) {
  22963. domUtils.remove(this.getDom());
  22964. }
  22965. }
  22966. });
  22967. this.subMenu.addListener("postRenderAfter", function () {
  22968. domUtils.on(this.getDom(), "mouseover", function () {
  22969. me.addState('opened');
  22970. });
  22971. });
  22972. } else {
  22973. this.subMenu = new Menu(this.subMenu);
  22974. }
  22975. }
  22976. };
  22977. MenuItem.prototype = {
  22978. label:'',
  22979. subMenu:null,
  22980. ownerMenu:null,
  22981. uiName:'menuitem',
  22982. alwalysHoverable:true,
  22983. getHtmlTpl:function () {
  22984. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  22985. '<div class="%%-body">' +
  22986. this.renderLabelHtml() +
  22987. '</div>' +
  22988. '</div>';
  22989. },
  22990. postRender:function () {
  22991. var me = this;
  22992. this.addListener('over', function () {
  22993. me.ownerMenu.fireEvent('submenuover', me);
  22994. if (me.subMenu) {
  22995. me.delayShowSubMenu();
  22996. }
  22997. });
  22998. if (this.subMenu) {
  22999. this.getDom().className += ' edui-hassubmenu';
  23000. this.subMenu.render();
  23001. this.addListener('out', function () {
  23002. me.delayHideSubMenu();
  23003. });
  23004. this.subMenu.addListener('over', function () {
  23005. clearTimeout(me._closingTimer);
  23006. me._closingTimer = null;
  23007. me.addState('opened');
  23008. });
  23009. this.ownerMenu.addListener('hide', function () {
  23010. me.hideSubMenu();
  23011. });
  23012. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  23013. if (subMenu !== me) {
  23014. me.delayHideSubMenu();
  23015. }
  23016. });
  23017. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  23018. this.subMenu.queryAutoHide = function (el) {
  23019. if (el && uiUtils.contains(me.getDom(), el)) {
  23020. return false;
  23021. }
  23022. return this._bakQueryAutoHide(el);
  23023. };
  23024. }
  23025. this.getDom().style.tabIndex = '-1';
  23026. uiUtils.makeUnselectable(this.getDom());
  23027. this.Stateful_postRender();
  23028. },
  23029. delayShowSubMenu:function () {
  23030. var me = this;
  23031. if (!me.isDisabled()) {
  23032. me.addState('opened');
  23033. clearTimeout(me._showingTimer);
  23034. clearTimeout(me._closingTimer);
  23035. me._closingTimer = null;
  23036. me._showingTimer = setTimeout(function () {
  23037. me.showSubMenu();
  23038. }, 250);
  23039. }
  23040. },
  23041. delayHideSubMenu:function () {
  23042. var me = this;
  23043. if (!me.isDisabled()) {
  23044. me.removeState('opened');
  23045. clearTimeout(me._showingTimer);
  23046. if (!me._closingTimer) {
  23047. me._closingTimer = setTimeout(function () {
  23048. if (!me.hasState('opened')) {
  23049. me.hideSubMenu();
  23050. }
  23051. me._closingTimer = null;
  23052. }, 400);
  23053. }
  23054. }
  23055. },
  23056. renderLabelHtml:function () {
  23057. return '<div class="edui-arrow"></div>' +
  23058. '<div class="edui-box edui-icon"></div>' +
  23059. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  23060. },
  23061. getStateDom:function () {
  23062. return this.getDom();
  23063. },
  23064. queryAutoHide:function (el) {
  23065. if (this.subMenu && this.hasState('opened')) {
  23066. return this.subMenu.queryAutoHide(el);
  23067. }
  23068. },
  23069. _onClick:function (event, this_) {
  23070. if (this.hasState('disabled')) return;
  23071. if (this.fireEvent('click', event, this_) !== false) {
  23072. if (this.subMenu) {
  23073. this.showSubMenu();
  23074. } else {
  23075. Popup.postHide(event);
  23076. }
  23077. }
  23078. },
  23079. showSubMenu:function () {
  23080. var rect = uiUtils.getClientRect(this.getDom());
  23081. rect.right -= 5;
  23082. rect.left += 2;
  23083. rect.width -= 7;
  23084. rect.top -= 4;
  23085. rect.bottom += 4;
  23086. rect.height += 8;
  23087. this.subMenu.showAnchorRect(rect, true, true);
  23088. },
  23089. hideSubMenu:function () {
  23090. this.subMenu.hide();
  23091. }
  23092. };
  23093. utils.inherits(MenuItem, UIBase);
  23094. utils.extend(MenuItem.prototype, Stateful, true);
  23095. })();
  23096. ///import core
  23097. ///import uicore
  23098. ///import ui/menu.js
  23099. ///import ui/splitbutton.js
  23100. (function (){
  23101. // todo: menu和item提成通用list
  23102. var utils = baidu.editor.utils,
  23103. uiUtils = baidu.editor.ui.uiUtils,
  23104. Menu = baidu.editor.ui.Menu,
  23105. SplitButton = baidu.editor.ui.SplitButton,
  23106. Combox = baidu.editor.ui.Combox = function (options){
  23107. this.initOptions(options);
  23108. this.initCombox();
  23109. };
  23110. Combox.prototype = {
  23111. uiName: 'combox',
  23112. initCombox: function (){
  23113. var me = this;
  23114. this.items = this.items || [];
  23115. for (var i=0; i<this.items.length; i++) {
  23116. var item = this.items[i];
  23117. item.uiName = 'listitem';
  23118. item.index = i;
  23119. item.onclick = function (){
  23120. me.selectByIndex(this.index);
  23121. };
  23122. }
  23123. this.popup = new Menu({
  23124. items: this.items,
  23125. uiName: 'list',
  23126. editor:this.editor,
  23127. captureWheel: true,
  23128. combox: this
  23129. });
  23130. this.initSplitButton();
  23131. },
  23132. _SplitButton_postRender: SplitButton.prototype.postRender,
  23133. postRender: function (){
  23134. this._SplitButton_postRender();
  23135. this.setLabel(this.label || '');
  23136. this.setValue(this.initValue || '');
  23137. },
  23138. showPopup: function (){
  23139. var rect = uiUtils.getClientRect(this.getDom());
  23140. rect.top += 1;
  23141. rect.bottom -= 1;
  23142. rect.height -= 2;
  23143. this.popup.showAnchorRect(rect);
  23144. },
  23145. getValue: function (){
  23146. return this.value;
  23147. },
  23148. setValue: function (value){
  23149. var index = this.indexByValue(value);
  23150. if (index != -1) {
  23151. this.selectedIndex = index;
  23152. this.setLabel(this.items[index].label);
  23153. this.value = this.items[index].value;
  23154. } else {
  23155. this.selectedIndex = -1;
  23156. this.setLabel(this.getLabelForUnknowValue(value));
  23157. this.value = value;
  23158. }
  23159. },
  23160. setLabel: function (label){
  23161. this.getDom('button_body').innerHTML = label;
  23162. this.label = label;
  23163. },
  23164. getLabelForUnknowValue: function (value){
  23165. return value;
  23166. },
  23167. indexByValue: function (value){
  23168. for (var i=0; i<this.items.length; i++) {
  23169. if (value == this.items[i].value) {
  23170. return i;
  23171. }
  23172. }
  23173. return -1;
  23174. },
  23175. getItem: function (index){
  23176. return this.items[index];
  23177. },
  23178. selectByIndex: function (index){
  23179. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  23180. this.selectedIndex = index;
  23181. this.value = this.items[index].value;
  23182. this.setLabel(this.items[index].label);
  23183. }
  23184. }
  23185. };
  23186. utils.inherits(Combox, SplitButton);
  23187. })();
  23188. ///import core
  23189. ///import uicore
  23190. ///import ui/mask.js
  23191. ///import ui/button.js
  23192. (function (){
  23193. var utils = baidu.editor.utils,
  23194. domUtils = baidu.editor.dom.domUtils,
  23195. uiUtils = baidu.editor.ui.uiUtils,
  23196. Mask = baidu.editor.ui.Mask,
  23197. UIBase = baidu.editor.ui.UIBase,
  23198. Button = baidu.editor.ui.Button,
  23199. Dialog = baidu.editor.ui.Dialog = function (options){
  23200. this.initOptions(utils.extend({
  23201. autoReset: true,
  23202. draggable: true,
  23203. onok: function (){},
  23204. oncancel: function (){},
  23205. onclose: function (t, ok){
  23206. return ok ? this.onok() : this.oncancel();
  23207. },
  23208. //是否控制dialog中的scroll事件, 默认为不阻止
  23209. holdScroll: false
  23210. },options));
  23211. this.initDialog();
  23212. };
  23213. var modalMask;
  23214. var dragMask;
  23215. Dialog.prototype = {
  23216. draggable: false,
  23217. uiName: 'dialog',
  23218. initDialog: function (){
  23219. var me = this,
  23220. theme=this.editor.options.theme;
  23221. this.initUIBase();
  23222. this.modalMask = (modalMask || (modalMask = new Mask({
  23223. className: 'edui-dialog-modalmask',
  23224. theme:theme
  23225. })));
  23226. this.dragMask = (dragMask || (dragMask = new Mask({
  23227. className: 'edui-dialog-dragmask',
  23228. theme:theme
  23229. })));
  23230. this.closeButton = new Button({
  23231. className: 'edui-dialog-closebutton',
  23232. title: me.closeDialog,
  23233. theme:theme,
  23234. onclick: function (){
  23235. me.close(false);
  23236. }
  23237. });
  23238. this.fullscreen && this.initResizeEvent();
  23239. if (this.buttons) {
  23240. for (var i=0; i<this.buttons.length; i++) {
  23241. if (!(this.buttons[i] instanceof Button)) {
  23242. this.buttons[i] = new Button(this.buttons[i]);
  23243. }
  23244. }
  23245. }
  23246. },
  23247. initResizeEvent: function () {
  23248. var me = this;
  23249. domUtils.on( window, "resize", function () {
  23250. if ( me._hidden || me._hidden === undefined ) {
  23251. return;
  23252. }
  23253. if ( me.__resizeTimer ) {
  23254. window.clearTimeout( me.__resizeTimer );
  23255. }
  23256. me.__resizeTimer = window.setTimeout( function () {
  23257. me.__resizeTimer = null;
  23258. var dialogWrapNode = me.getDom(),
  23259. contentNode = me.getDom('content'),
  23260. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  23261. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  23262. vpRect = uiUtils.getViewportRect();
  23263. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  23264. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  23265. dialogWrapNode.style.width = vpRect.width + "px";
  23266. dialogWrapNode.style.height = vpRect.height + "px";
  23267. me.fireEvent( "resize" );
  23268. }, 100 );
  23269. } );
  23270. },
  23271. fitSize: function (){
  23272. var popBodyEl = this.getDom('body');
  23273. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  23274. // uiUtils.removeStyle(popBodyEl, 'width');
  23275. // uiUtils.removeStyle(popBodyEl, 'height');
  23276. // }
  23277. var size = this.mesureSize();
  23278. popBodyEl.style.width = size.width + 'px';
  23279. popBodyEl.style.height = size.height + 'px';
  23280. return size;
  23281. },
  23282. safeSetOffset: function (offset){
  23283. var me = this;
  23284. var el = me.getDom();
  23285. var vpRect = uiUtils.getViewportRect();
  23286. var rect = uiUtils.getClientRect(el);
  23287. var left = offset.left;
  23288. if (left + rect.width > vpRect.right) {
  23289. left = vpRect.right - rect.width;
  23290. }
  23291. var top = offset.top;
  23292. if (top + rect.height > vpRect.bottom) {
  23293. top = vpRect.bottom - rect.height;
  23294. }
  23295. el.style.left = Math.max(left, 0) + 'px';
  23296. el.style.top = Math.max(top, 0) + 'px';
  23297. },
  23298. showAtCenter: function (){
  23299. var vpRect = uiUtils.getViewportRect();
  23300. if ( !this.fullscreen ) {
  23301. this.getDom().style.display = '';
  23302. var popSize = this.fitSize();
  23303. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  23304. var left = vpRect.width / 2 - popSize.width / 2;
  23305. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  23306. var popEl = this.getDom();
  23307. this.safeSetOffset({
  23308. left: Math.max(left | 0, 0),
  23309. top: Math.max(top | 0, 0)
  23310. });
  23311. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  23312. popEl.className += ' edui-state-centered';
  23313. }
  23314. } else {
  23315. var dialogWrapNode = this.getDom(),
  23316. contentNode = this.getDom('content');
  23317. dialogWrapNode.style.display = "block";
  23318. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  23319. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  23320. dialogWrapNode.style.left = "-100000px";
  23321. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  23322. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  23323. dialogWrapNode.style.width = vpRect.width + "px";
  23324. dialogWrapNode.style.height = vpRect.height + "px";
  23325. dialogWrapNode.style.left = 0;
  23326. //保存环境的overflow值
  23327. this._originalContext = {
  23328. html: {
  23329. overflowX: document.documentElement.style.overflowX,
  23330. overflowY: document.documentElement.style.overflowY
  23331. },
  23332. body: {
  23333. overflowX: document.body.style.overflowX,
  23334. overflowY: document.body.style.overflowY
  23335. }
  23336. };
  23337. document.documentElement.style.overflowX = 'hidden';
  23338. document.documentElement.style.overflowY = 'hidden';
  23339. document.body.style.overflowX = 'hidden';
  23340. document.body.style.overflowY = 'hidden';
  23341. }
  23342. this._show();
  23343. },
  23344. getContentHtml: function (){
  23345. var contentHtml = '';
  23346. if (typeof this.content == 'string') {
  23347. contentHtml = this.content;
  23348. } else if (this.iframeUrl) {
  23349. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  23350. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  23351. }
  23352. return contentHtml;
  23353. },
  23354. getHtmlTpl: function (){
  23355. var footHtml = '';
  23356. if (this.buttons) {
  23357. var buff = [];
  23358. for (var i=0; i<this.buttons.length; i++) {
  23359. buff[i] = this.buttons[i].renderHtml();
  23360. }
  23361. footHtml = '<div class="%%-foot">' +
  23362. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  23363. '</div>';
  23364. }
  23365. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  23366. '<div class="%%-shadow"></div>' +
  23367. '<div id="##_titlebar" class="%%-titlebar">' +
  23368. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  23369. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  23370. '</div>' +
  23371. this.closeButton.renderHtml() +
  23372. '</div>' +
  23373. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  23374. footHtml +
  23375. '</div></div></div>';
  23376. },
  23377. postRender: function (){
  23378. // todo: 保持居中/记住上次关闭位置选项
  23379. if (!this.modalMask.getDom()) {
  23380. this.modalMask.render();
  23381. this.modalMask.hide();
  23382. }
  23383. if (!this.dragMask.getDom()) {
  23384. this.dragMask.render();
  23385. this.dragMask.hide();
  23386. }
  23387. var me = this;
  23388. this.addListener('show', function (){
  23389. me.modalMask.show(this.getDom().style.zIndex - 2);
  23390. });
  23391. this.addListener('hide', function (){
  23392. me.modalMask.hide();
  23393. });
  23394. if (this.buttons) {
  23395. for (var i=0; i<this.buttons.length; i++) {
  23396. this.buttons[i].postRender();
  23397. }
  23398. }
  23399. domUtils.on(window, 'resize', function (){
  23400. setTimeout(function (){
  23401. if (!me.isHidden()) {
  23402. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  23403. }
  23404. });
  23405. });
  23406. //hold住scroll事件,防止dialog的滚动影响页面
  23407. if( this.holdScroll ) {
  23408. if( !me.iframeUrl ) {
  23409. domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  23410. domUtils.preventDefault(e);
  23411. } );
  23412. } else {
  23413. me.addListener('dialogafterreset', function(){
  23414. window.setTimeout(function(){
  23415. var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  23416. if( browser.ie ) {
  23417. var timer = window.setInterval(function(){
  23418. if( iframeWindow.document && iframeWindow.document.body ) {
  23419. window.clearInterval( timer );
  23420. timer = null;
  23421. domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  23422. domUtils.preventDefault(e);
  23423. } );
  23424. }
  23425. }, 100);
  23426. } else {
  23427. domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  23428. domUtils.preventDefault(e);
  23429. } );
  23430. }
  23431. }, 1);
  23432. });
  23433. }
  23434. }
  23435. this._hide();
  23436. },
  23437. mesureSize: function (){
  23438. var body = this.getDom('body');
  23439. var width = uiUtils.getClientRect(this.getDom('content')).width;
  23440. var dialogBodyStyle = body.style;
  23441. dialogBodyStyle.width = width;
  23442. return uiUtils.getClientRect(body);
  23443. },
  23444. _onTitlebarMouseDown: function (evt, el){
  23445. if (this.draggable) {
  23446. var rect;
  23447. var vpRect = uiUtils.getViewportRect();
  23448. var me = this;
  23449. uiUtils.startDrag(evt, {
  23450. ondragstart: function (){
  23451. rect = uiUtils.getClientRect(me.getDom());
  23452. me.getDom('contmask').style.visibility = 'visible';
  23453. me.dragMask.show(me.getDom().style.zIndex - 1);
  23454. },
  23455. ondragmove: function (x, y){
  23456. var left = rect.left + x;
  23457. var top = rect.top + y;
  23458. me.safeSetOffset({
  23459. left: left,
  23460. top: top
  23461. });
  23462. },
  23463. ondragstop: function (){
  23464. me.getDom('contmask').style.visibility = 'hidden';
  23465. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  23466. me.dragMask.hide();
  23467. }
  23468. });
  23469. }
  23470. },
  23471. reset: function (){
  23472. this.getDom('content').innerHTML = this.getContentHtml();
  23473. this.fireEvent('dialogafterreset');
  23474. },
  23475. _show: function (){
  23476. if (this._hidden) {
  23477. this.getDom().style.display = '';
  23478. //要高过编辑器的zindxe
  23479. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  23480. this._hidden = false;
  23481. this.fireEvent('show');
  23482. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  23483. }
  23484. },
  23485. isHidden: function (){
  23486. return this._hidden;
  23487. },
  23488. _hide: function (){
  23489. if (!this._hidden) {
  23490. var wrapNode = this.getDom();
  23491. wrapNode.style.display = 'none';
  23492. wrapNode.style.zIndex = '';
  23493. wrapNode.style.width = '';
  23494. wrapNode.style.height = '';
  23495. this._hidden = true;
  23496. this.fireEvent('hide');
  23497. }
  23498. },
  23499. open: function (){
  23500. if (this.autoReset) {
  23501. //有可能还没有渲染
  23502. try{
  23503. this.reset();
  23504. }catch(e){
  23505. this.render();
  23506. this.open()
  23507. }
  23508. }
  23509. this.showAtCenter();
  23510. if (this.iframeUrl) {
  23511. try {
  23512. this.getDom('iframe').focus();
  23513. } catch(ex){}
  23514. }
  23515. },
  23516. _onCloseButtonClick: function (evt, el){
  23517. this.close(false);
  23518. },
  23519. close: function (ok){
  23520. if (this.fireEvent('close', ok) !== false) {
  23521. //还原环境
  23522. if ( this.fullscreen ) {
  23523. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  23524. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  23525. document.body.style.overflowX = this._originalContext.body.overflowX;
  23526. document.body.style.overflowY = this._originalContext.body.overflowY;
  23527. delete this._originalContext;
  23528. }
  23529. this._hide();
  23530. }
  23531. }
  23532. };
  23533. utils.inherits(Dialog, UIBase);
  23534. })();
  23535. ///import core
  23536. ///import uicore
  23537. ///import ui/menu.js
  23538. ///import ui/splitbutton.js
  23539. (function (){
  23540. var utils = baidu.editor.utils,
  23541. Menu = baidu.editor.ui.Menu,
  23542. SplitButton = baidu.editor.ui.SplitButton,
  23543. MenuButton = baidu.editor.ui.MenuButton = function (options){
  23544. this.initOptions(options);
  23545. this.initMenuButton();
  23546. };
  23547. MenuButton.prototype = {
  23548. initMenuButton: function (){
  23549. var me = this;
  23550. this.uiName = "menubutton";
  23551. this.popup = new Menu({
  23552. items: me.items,
  23553. className: me.className,
  23554. editor:me.editor
  23555. });
  23556. this.popup.addListener('show', function (){
  23557. var list = this;
  23558. for (var i=0; i<list.items.length; i++) {
  23559. list.items[i].removeState('checked');
  23560. if (list.items[i].value == me._value) {
  23561. list.items[i].addState('checked');
  23562. this.value = me._value;
  23563. }
  23564. }
  23565. });
  23566. this.initSplitButton();
  23567. },
  23568. setValue : function(value){
  23569. this._value = value;
  23570. }
  23571. };
  23572. utils.inherits(MenuButton, SplitButton);
  23573. })();
  23574. //ui跟编辑器的适配層
  23575. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  23576. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  23577. (function () {
  23578. var utils = baidu.editor.utils;
  23579. var editorui = baidu.editor.ui;
  23580. var _Dialog = editorui.Dialog;
  23581. editorui.buttons = {};
  23582. editorui.Dialog = function (options) {
  23583. var dialog = new _Dialog(options);
  23584. dialog.addListener('hide', function () {
  23585. if (dialog.editor) {
  23586. var editor = dialog.editor;
  23587. try {
  23588. if (browser.gecko) {
  23589. var y = editor.window.scrollY,
  23590. x = editor.window.scrollX;
  23591. editor.body.focus();
  23592. editor.window.scrollTo(x, y);
  23593. } else {
  23594. editor.focus();
  23595. }
  23596. } catch (ex) {
  23597. }
  23598. }
  23599. });
  23600. return dialog;
  23601. };
  23602. var iframeUrlMap = {
  23603. 'anchor':'~/dialogs/anchor/anchor.html',
  23604. 'insertimage':'~/dialogs/image/image.html',
  23605. 'link':'~/dialogs/link/link.html',
  23606. 'spechars':'~/dialogs/spechars/spechars.html',
  23607. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  23608. 'map':'~/dialogs/map/map.html',
  23609. 'gmap':'~/dialogs/gmap/gmap.html',
  23610. 'insertvideo':'~/dialogs/video/video.html',
  23611. 'help':'~/dialogs/help/help.html',
  23612. 'preview':'~/dialogs/preview/preview.html',
  23613. 'emotion':'~/dialogs/emotion/emotion.html',
  23614. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  23615. 'attachment':'~/dialogs/attachment/attachment.html',
  23616. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  23617. 'edittip':'~/dialogs/table/edittip.html',
  23618. 'edittable':'~/dialogs/table/edittable.html',
  23619. 'edittd':'~/dialogs/table/edittd.html',
  23620. 'webapp':'~/dialogs/webapp/webapp.html',
  23621. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  23622. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  23623. 'music':'~/dialogs/music/music.html',
  23624. 'template':'~/dialogs/template/template.html',
  23625. 'background':'~/dialogs/background/background.html',
  23626. 'charts': '~/dialogs/charts/charts.html'
  23627. };
  23628. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  23629. var btnCmds = ['undo', 'redo', 'formatmatch',
  23630. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  23631. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  23632. 'blockquote', 'pasteplain', 'pagebreak',
  23633. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  23634. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  23635. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  23636. for (var i = 0, ci; ci = btnCmds[i++];) {
  23637. ci = ci.toLowerCase();
  23638. editorui[ci] = function (cmd) {
  23639. return function (editor) {
  23640. var ui = new editorui.Button({
  23641. className:'edui-for-' + cmd,
  23642. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  23643. onclick:function () {
  23644. editor.execCommand(cmd);
  23645. },
  23646. theme:editor.options.theme,
  23647. showText:false
  23648. });
  23649. editorui.buttons[cmd] = ui;
  23650. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23651. var state = editor.queryCommandState(cmd);
  23652. if (state == -1) {
  23653. ui.setDisabled(true);
  23654. ui.setChecked(false);
  23655. } else {
  23656. if (!uiReady) {
  23657. ui.setDisabled(false);
  23658. ui.setChecked(state);
  23659. }
  23660. }
  23661. });
  23662. return ui;
  23663. };
  23664. }(ci);
  23665. }
  23666. //清除文档
  23667. editorui.cleardoc = function (editor) {
  23668. var ui = new editorui.Button({
  23669. className:'edui-for-cleardoc',
  23670. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  23671. theme:editor.options.theme,
  23672. onclick:function () {
  23673. if (confirm(editor.getLang("confirmClear"))) {
  23674. editor.execCommand('cleardoc');
  23675. }
  23676. }
  23677. });
  23678. editorui.buttons["cleardoc"] = ui;
  23679. editor.addListener('selectionchange', function () {
  23680. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  23681. });
  23682. return ui;
  23683. };
  23684. //排版,图片排版,文字方向
  23685. var typeset = {
  23686. 'justify':['left', 'right', 'center', 'justify'],
  23687. 'imagefloat':['none', 'left', 'center', 'right'],
  23688. 'directionality':['ltr', 'rtl']
  23689. };
  23690. for (var p in typeset) {
  23691. (function (cmd, val) {
  23692. for (var i = 0, ci; ci = val[i++];) {
  23693. (function (cmd2) {
  23694. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  23695. var ui = new editorui.Button({
  23696. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  23697. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  23698. theme:editor.options.theme,
  23699. onclick:function () {
  23700. editor.execCommand(cmd, cmd2);
  23701. }
  23702. });
  23703. editorui.buttons[cmd] = ui;
  23704. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23705. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  23706. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  23707. });
  23708. return ui;
  23709. };
  23710. })(ci)
  23711. }
  23712. })(p, typeset[p])
  23713. }
  23714. //字体颜色和背景颜色
  23715. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  23716. editorui[ci] = function (cmd) {
  23717. return function (editor) {
  23718. var ui = new editorui.ColorButton({
  23719. className:'edui-for-' + cmd,
  23720. color:'default',
  23721. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  23722. editor:editor,
  23723. onpickcolor:function (t, color) {
  23724. editor.execCommand(cmd, color);
  23725. },
  23726. onpicknocolor:function () {
  23727. editor.execCommand(cmd, 'default');
  23728. this.setColor('transparent');
  23729. this.color = 'default';
  23730. },
  23731. onbuttonclick:function () {
  23732. editor.execCommand(cmd, this.color);
  23733. }
  23734. });
  23735. editorui.buttons[cmd] = ui;
  23736. editor.addListener('selectionchange', function () {
  23737. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  23738. });
  23739. return ui;
  23740. };
  23741. }(ci);
  23742. }
  23743. var dialogBtns = {
  23744. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  23745. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  23746. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  23747. };
  23748. for (var p in dialogBtns) {
  23749. (function (type, vals) {
  23750. for (var i = 0, ci; ci = vals[i++];) {
  23751. //todo opera下存在问题
  23752. if (browser.opera && ci === "searchreplace") {
  23753. continue;
  23754. }
  23755. (function (cmd) {
  23756. editorui[cmd] = function (editor, iframeUrl, title) {
  23757. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  23758. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  23759. var dialog;
  23760. //没有iframeUrl不创建dialog
  23761. if (iframeUrl) {
  23762. dialog = new editorui.Dialog(utils.extend({
  23763. iframeUrl:editor.ui.mapUrl(iframeUrl),
  23764. editor:editor,
  23765. className:'edui-for-' + cmd,
  23766. title:title,
  23767. holdScroll: cmd === 'insertimage',
  23768. fullscreen: /charts|preview/.test(cmd),
  23769. closeDialog:editor.getLang("closeDialog")
  23770. }, type == 'ok' ? {
  23771. buttons:[
  23772. {
  23773. className:'edui-okbutton',
  23774. label:editor.getLang("ok"),
  23775. editor:editor,
  23776. onclick:function () {
  23777. dialog.close(true);
  23778. }
  23779. },
  23780. {
  23781. className:'edui-cancelbutton',
  23782. label:editor.getLang("cancel"),
  23783. editor:editor,
  23784. onclick:function () {
  23785. dialog.close(false);
  23786. }
  23787. }
  23788. ]
  23789. } : {}));
  23790. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  23791. }
  23792. var ui = new editorui.Button({
  23793. className:'edui-for-' + cmd,
  23794. title:title,
  23795. onclick:function () {
  23796. if (dialog) {
  23797. switch (cmd) {
  23798. case "wordimage":
  23799. var images = editor.execCommand("wordimage");
  23800. if (images && images.length) {
  23801. dialog.render();
  23802. dialog.open();
  23803. }
  23804. break;
  23805. case "scrawl":
  23806. if (editor.queryCommandState("scrawl") != -1) {
  23807. dialog.render();
  23808. dialog.open();
  23809. }
  23810. break;
  23811. default:
  23812. dialog.render();
  23813. dialog.open();
  23814. }
  23815. }
  23816. },
  23817. theme:editor.options.theme,
  23818. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  23819. });
  23820. editorui.buttons[cmd] = ui;
  23821. editor.addListener('selectionchange', function () {
  23822. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  23823. var unNeedCheckState = {'edittable':1};
  23824. if (cmd in unNeedCheckState)return;
  23825. var state = editor.queryCommandState(cmd);
  23826. if (ui.getDom()) {
  23827. ui.setDisabled(state == -1);
  23828. ui.setChecked(state);
  23829. }
  23830. });
  23831. return ui;
  23832. };
  23833. })(ci.toLowerCase())
  23834. }
  23835. })(p, dialogBtns[p])
  23836. }
  23837. editorui.snapscreen = function (editor, iframeUrl, title) {
  23838. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  23839. var ui = new editorui.Button({
  23840. className:'edui-for-snapscreen',
  23841. title:title,
  23842. onclick:function () {
  23843. editor.execCommand("snapscreen");
  23844. },
  23845. theme:editor.options.theme
  23846. });
  23847. editorui.buttons['snapscreen'] = ui;
  23848. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  23849. if (iframeUrl) {
  23850. var dialog = new editorui.Dialog({
  23851. iframeUrl:editor.ui.mapUrl(iframeUrl),
  23852. editor:editor,
  23853. className:'edui-for-snapscreen',
  23854. title:title,
  23855. buttons:[
  23856. {
  23857. className:'edui-okbutton',
  23858. label:editor.getLang("ok"),
  23859. editor:editor,
  23860. onclick:function () {
  23861. dialog.close(true);
  23862. }
  23863. },
  23864. {
  23865. className:'edui-cancelbutton',
  23866. label:editor.getLang("cancel"),
  23867. editor:editor,
  23868. onclick:function () {
  23869. dialog.close(false);
  23870. }
  23871. }
  23872. ]
  23873. });
  23874. dialog.render();
  23875. editor.ui._dialogs["snapscreenDialog"] = dialog;
  23876. }
  23877. editor.addListener('selectionchange', function () {
  23878. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  23879. });
  23880. return ui;
  23881. };
  23882. editorui.insertcode = function (editor, list, title) {
  23883. list = editor.options['insertcode'] || [];
  23884. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  23885. // if (!list.length) return;
  23886. var items = [];
  23887. utils.each(list,function(key,val){
  23888. items.push({
  23889. label:key,
  23890. value:val,
  23891. theme:editor.options.theme,
  23892. renderLabelHtml:function () {
  23893. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  23894. }
  23895. });
  23896. });
  23897. var ui = new editorui.Combox({
  23898. editor:editor,
  23899. items:items,
  23900. onselect:function (t, index) {
  23901. editor.execCommand('insertcode', this.items[index].value);
  23902. },
  23903. onbuttonclick:function () {
  23904. this.showPopup();
  23905. },
  23906. title:title,
  23907. initValue:title,
  23908. className:'edui-for-insertcode',
  23909. indexByValue:function (value) {
  23910. if (value) {
  23911. for (var i = 0, ci; ci = this.items[i]; i++) {
  23912. if (ci.value.indexOf(value) != -1)
  23913. return i;
  23914. }
  23915. }
  23916. return -1;
  23917. }
  23918. });
  23919. editorui.buttons['insertcode'] = ui;
  23920. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23921. if (!uiReady) {
  23922. var state = editor.queryCommandState('insertcode');
  23923. if (state == -1) {
  23924. ui.setDisabled(true);
  23925. } else {
  23926. ui.setDisabled(false);
  23927. var value = editor.queryCommandValue('insertcode');
  23928. if(!value){
  23929. ui.setValue(title);
  23930. return;
  23931. }
  23932. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  23933. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  23934. ui.setValue(value);
  23935. }
  23936. }
  23937. });
  23938. return ui;
  23939. };
  23940. editorui.fontfamily = function (editor, list, title) {
  23941. list = editor.options['fontfamily'] || [];
  23942. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  23943. if (!list.length) return;
  23944. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  23945. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  23946. (function (key, val) {
  23947. items.push({
  23948. label:key,
  23949. value:val,
  23950. theme:editor.options.theme,
  23951. renderLabelHtml:function () {
  23952. return '<div class="edui-label %%-label" style="font-family:' +
  23953. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  23954. }
  23955. });
  23956. })(ci.label || langLabel, ci.val)
  23957. }
  23958. var ui = new editorui.Combox({
  23959. editor:editor,
  23960. items:items,
  23961. onselect:function (t, index) {
  23962. editor.execCommand('FontFamily', this.items[index].value);
  23963. },
  23964. onbuttonclick:function () {
  23965. this.showPopup();
  23966. },
  23967. title:title,
  23968. initValue:title,
  23969. className:'edui-for-fontfamily',
  23970. indexByValue:function (value) {
  23971. if (value) {
  23972. for (var i = 0, ci; ci = this.items[i]; i++) {
  23973. if (ci.value.indexOf(value) != -1)
  23974. return i;
  23975. }
  23976. }
  23977. return -1;
  23978. }
  23979. });
  23980. editorui.buttons['fontfamily'] = ui;
  23981. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  23982. if (!uiReady) {
  23983. var state = editor.queryCommandState('FontFamily');
  23984. if (state == -1) {
  23985. ui.setDisabled(true);
  23986. } else {
  23987. ui.setDisabled(false);
  23988. var value = editor.queryCommandValue('FontFamily');
  23989. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  23990. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  23991. ui.setValue(value);
  23992. }
  23993. }
  23994. });
  23995. return ui;
  23996. };
  23997. editorui.fontsize = function (editor, list, title) {
  23998. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  23999. list = list || editor.options['fontsize'] || [];
  24000. if (!list.length) return;
  24001. var items = [];
  24002. for (var i = 0; i < list.length; i++) {
  24003. var size = list[i] + 'px';
  24004. items.push({
  24005. label:size,
  24006. value:size,
  24007. theme:editor.options.theme,
  24008. renderLabelHtml:function () {
  24009. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  24010. this.value + '">' + (this.label || '') + '</div>';
  24011. }
  24012. });
  24013. }
  24014. var ui = new editorui.Combox({
  24015. editor:editor,
  24016. items:items,
  24017. title:title,
  24018. initValue:title,
  24019. onselect:function (t, index) {
  24020. editor.execCommand('FontSize', this.items[index].value);
  24021. },
  24022. onbuttonclick:function () {
  24023. this.showPopup();
  24024. },
  24025. className:'edui-for-fontsize'
  24026. });
  24027. editorui.buttons['fontsize'] = ui;
  24028. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  24029. if (!uiReady) {
  24030. var state = editor.queryCommandState('FontSize');
  24031. if (state == -1) {
  24032. ui.setDisabled(true);
  24033. } else {
  24034. ui.setDisabled(false);
  24035. ui.setValue(editor.queryCommandValue('FontSize'));
  24036. }
  24037. }
  24038. });
  24039. return ui;
  24040. };
  24041. editorui.paragraph = function (editor, list, title) {
  24042. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  24043. list = editor.options['paragraph'] || [];
  24044. if (utils.isEmptyObject(list)) return;
  24045. var items = [];
  24046. for (var i in list) {
  24047. items.push({
  24048. value:i,
  24049. label:list[i] || editor.getLang("paragraph")[i],
  24050. theme:editor.options.theme,
  24051. renderLabelHtml:function () {
  24052. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  24053. }
  24054. })
  24055. }
  24056. var ui = new editorui.Combox({
  24057. editor:editor,
  24058. items:items,
  24059. title:title,
  24060. initValue:title,
  24061. className:'edui-for-paragraph',
  24062. onselect:function (t, index) {
  24063. editor.execCommand('Paragraph', this.items[index].value);
  24064. },
  24065. onbuttonclick:function () {
  24066. this.showPopup();
  24067. }
  24068. });
  24069. editorui.buttons['paragraph'] = ui;
  24070. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  24071. if (!uiReady) {
  24072. var state = editor.queryCommandState('Paragraph');
  24073. if (state == -1) {
  24074. ui.setDisabled(true);
  24075. } else {
  24076. ui.setDisabled(false);
  24077. var value = editor.queryCommandValue('Paragraph');
  24078. var index = ui.indexByValue(value);
  24079. if (index != -1) {
  24080. ui.setValue(value);
  24081. } else {
  24082. ui.setValue(ui.initValue);
  24083. }
  24084. }
  24085. }
  24086. });
  24087. return ui;
  24088. };
  24089. //自定义标题
  24090. editorui.customstyle = function (editor) {
  24091. var list = editor.options['customstyle'] || [],
  24092. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  24093. if (!list.length)return;
  24094. var langCs = editor.getLang('customstyle');
  24095. for (var i = 0, items = [], t; t = list[i++];) {
  24096. (function (t) {
  24097. var ck = {};
  24098. ck.label = t.label ? t.label : langCs[t.name];
  24099. ck.style = t.style;
  24100. ck.className = t.className;
  24101. ck.tag = t.tag;
  24102. items.push({
  24103. label:ck.label,
  24104. value:ck,
  24105. theme:editor.options.theme,
  24106. renderLabelHtml:function () {
  24107. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  24108. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  24109. + '</div>';
  24110. }
  24111. });
  24112. })(t);
  24113. }
  24114. var ui = new editorui.Combox({
  24115. editor:editor,
  24116. items:items,
  24117. title:title,
  24118. initValue:title,
  24119. className:'edui-for-customstyle',
  24120. onselect:function (t, index) {
  24121. editor.execCommand('customstyle', this.items[index].value);
  24122. },
  24123. onbuttonclick:function () {
  24124. this.showPopup();
  24125. },
  24126. indexByValue:function (value) {
  24127. for (var i = 0, ti; ti = this.items[i++];) {
  24128. if (ti.label == value) {
  24129. return i - 1
  24130. }
  24131. }
  24132. return -1;
  24133. }
  24134. });
  24135. editorui.buttons['customstyle'] = ui;
  24136. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  24137. if (!uiReady) {
  24138. var state = editor.queryCommandState('customstyle');
  24139. if (state == -1) {
  24140. ui.setDisabled(true);
  24141. } else {
  24142. ui.setDisabled(false);
  24143. var value = editor.queryCommandValue('customstyle');
  24144. var index = ui.indexByValue(value);
  24145. if (index != -1) {
  24146. ui.setValue(value);
  24147. } else {
  24148. ui.setValue(ui.initValue);
  24149. }
  24150. }
  24151. }
  24152. });
  24153. return ui;
  24154. };
  24155. editorui.inserttable = function (editor, iframeUrl, title) {
  24156. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  24157. var ui = new editorui.TableButton({
  24158. editor:editor,
  24159. title:title,
  24160. className:'edui-for-inserttable',
  24161. onpicktable:function (t, numCols, numRows) {
  24162. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  24163. },
  24164. onbuttonclick:function () {
  24165. this.showPopup();
  24166. }
  24167. });
  24168. editorui.buttons['inserttable'] = ui;
  24169. editor.addListener('selectionchange', function () {
  24170. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  24171. });
  24172. return ui;
  24173. };
  24174. editorui.lineheight = function (editor) {
  24175. var val = editor.options.lineheight || [];
  24176. if (!val.length)return;
  24177. for (var i = 0, ci, items = []; ci = val[i++];) {
  24178. items.push({
  24179. //todo:写死了
  24180. label:ci,
  24181. value:ci,
  24182. theme:editor.options.theme,
  24183. onclick:function () {
  24184. editor.execCommand("lineheight", this.value);
  24185. }
  24186. })
  24187. }
  24188. var ui = new editorui.MenuButton({
  24189. editor:editor,
  24190. className:'edui-for-lineheight',
  24191. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  24192. items:items,
  24193. onbuttonclick:function () {
  24194. var value = editor.queryCommandValue('LineHeight') || this.value;
  24195. editor.execCommand("LineHeight", value);
  24196. }
  24197. });
  24198. editorui.buttons['lineheight'] = ui;
  24199. editor.addListener('selectionchange', function () {
  24200. var state = editor.queryCommandState('LineHeight');
  24201. if (state == -1) {
  24202. ui.setDisabled(true);
  24203. } else {
  24204. ui.setDisabled(false);
  24205. var value = editor.queryCommandValue('LineHeight');
  24206. value && ui.setValue((value + '').replace(/cm/, ''));
  24207. ui.setChecked(state)
  24208. }
  24209. });
  24210. return ui;
  24211. };
  24212. var rowspacings = ['top', 'bottom'];
  24213. for (var r = 0, ri; ri = rowspacings[r++];) {
  24214. (function (cmd) {
  24215. editorui['rowspacing' + cmd] = function (editor) {
  24216. var val = editor.options['rowspacing' + cmd] || [];
  24217. if (!val.length) return null;
  24218. for (var i = 0, ci, items = []; ci = val[i++];) {
  24219. items.push({
  24220. label:ci,
  24221. value:ci,
  24222. theme:editor.options.theme,
  24223. onclick:function () {
  24224. editor.execCommand("rowspacing", this.value, cmd);
  24225. }
  24226. })
  24227. }
  24228. var ui = new editorui.MenuButton({
  24229. editor:editor,
  24230. className:'edui-for-rowspacing' + cmd,
  24231. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  24232. items:items,
  24233. onbuttonclick:function () {
  24234. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  24235. editor.execCommand("rowspacing", value, cmd);
  24236. }
  24237. });
  24238. editorui.buttons[cmd] = ui;
  24239. editor.addListener('selectionchange', function () {
  24240. var state = editor.queryCommandState('rowspacing', cmd);
  24241. if (state == -1) {
  24242. ui.setDisabled(true);
  24243. } else {
  24244. ui.setDisabled(false);
  24245. var value = editor.queryCommandValue('rowspacing', cmd);
  24246. value && ui.setValue((value + '').replace(/%/, ''));
  24247. ui.setChecked(state)
  24248. }
  24249. });
  24250. return ui;
  24251. }
  24252. })(ri)
  24253. }
  24254. //有序,无序列表
  24255. var lists = ['insertorderedlist', 'insertunorderedlist'];
  24256. for (var l = 0, cl; cl = lists[l++];) {
  24257. (function (cmd) {
  24258. editorui[cmd] = function (editor) {
  24259. var vals = editor.options[cmd],
  24260. _onMenuClick = function () {
  24261. editor.execCommand(cmd, this.value);
  24262. }, items = [];
  24263. for (var i in vals) {
  24264. items.push({
  24265. label:vals[i] || editor.getLang()[cmd][i] || "",
  24266. value:i,
  24267. theme:editor.options.theme,
  24268. onclick:_onMenuClick
  24269. })
  24270. }
  24271. var ui = new editorui.MenuButton({
  24272. editor:editor,
  24273. className:'edui-for-' + cmd,
  24274. title:editor.getLang("labelMap." + cmd) || '',
  24275. 'items':items,
  24276. onbuttonclick:function () {
  24277. var value = editor.queryCommandValue(cmd) || this.value;
  24278. editor.execCommand(cmd, value);
  24279. }
  24280. });
  24281. editorui.buttons[cmd] = ui;
  24282. editor.addListener('selectionchange', function () {
  24283. var state = editor.queryCommandState(cmd);
  24284. if (state == -1) {
  24285. ui.setDisabled(true);
  24286. } else {
  24287. ui.setDisabled(false);
  24288. var value = editor.queryCommandValue(cmd);
  24289. ui.setValue(value);
  24290. ui.setChecked(state)
  24291. }
  24292. });
  24293. return ui;
  24294. };
  24295. })(cl)
  24296. }
  24297. editorui.fullscreen = function (editor, title) {
  24298. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  24299. var ui = new editorui.Button({
  24300. className:'edui-for-fullscreen',
  24301. title:title,
  24302. theme:editor.options.theme,
  24303. onclick:function () {
  24304. if (editor.ui) {
  24305. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  24306. }
  24307. this.setChecked(editor.ui.isFullScreen());
  24308. }
  24309. });
  24310. editorui.buttons['fullscreen'] = ui;
  24311. editor.addListener('selectionchange', function () {
  24312. var state = editor.queryCommandState('fullscreen');
  24313. ui.setDisabled(state == -1);
  24314. ui.setChecked(editor.ui.isFullScreen());
  24315. });
  24316. return ui;
  24317. };
  24318. // 表情
  24319. editorui["emotion"] = function (editor, iframeUrl) {
  24320. var cmd = "emotion";
  24321. var ui = new editorui.MultiMenuPop({
  24322. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  24323. editor:editor,
  24324. className:'edui-for-' + cmd,
  24325. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  24326. });
  24327. editorui.buttons[cmd] = ui;
  24328. editor.addListener('selectionchange', function () {
  24329. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  24330. });
  24331. return ui;
  24332. };
  24333. editorui.autotypeset = function (editor) {
  24334. var ui = new editorui.AutoTypeSetButton({
  24335. editor:editor,
  24336. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  24337. className:'edui-for-autotypeset',
  24338. onbuttonclick:function () {
  24339. editor.execCommand('autotypeset')
  24340. }
  24341. });
  24342. editorui.buttons['autotypeset'] = ui;
  24343. editor.addListener('selectionchange', function () {
  24344. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  24345. });
  24346. return ui;
  24347. };
  24348. })();
  24349. ///import core
  24350. ///commands 全屏
  24351. ///commandsName FullScreen
  24352. ///commandsTitle 全屏
  24353. (function () {
  24354. var utils = baidu.editor.utils,
  24355. uiUtils = baidu.editor.ui.uiUtils,
  24356. UIBase = baidu.editor.ui.UIBase,
  24357. domUtils = baidu.editor.dom.domUtils;
  24358. var nodeStack = [];
  24359. function EditorUI(options) {
  24360. this.initOptions(options);
  24361. this.initEditorUI();
  24362. }
  24363. EditorUI.prototype = {
  24364. uiName:'editor',
  24365. initEditorUI:function () {
  24366. this.editor.ui = this;
  24367. this._dialogs = {};
  24368. this.initUIBase();
  24369. this._initToolbars();
  24370. var editor = this.editor,
  24371. me = this;
  24372. editor.addListener('ready', function () {
  24373. //提供getDialog方法
  24374. editor.getDialog = function (name) {
  24375. return editor.ui._dialogs[name + "Dialog"];
  24376. };
  24377. domUtils.on(editor.window, 'scroll', function (evt) {
  24378. baidu.editor.ui.Popup.postHide(evt);
  24379. });
  24380. //提供编辑器实时宽高(全屏时宽高不变化)
  24381. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  24382. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  24383. //display bottom-bar label based on config
  24384. if (editor.options.elementPathEnabled) {
  24385. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  24386. }
  24387. if (editor.options.wordCount) {
  24388. function countFn() {
  24389. setCount(editor,me);
  24390. domUtils.un(editor.document, "click", arguments.callee);
  24391. }
  24392. domUtils.on(editor.document, "click", countFn);
  24393. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  24394. }
  24395. editor.ui._scale();
  24396. if (editor.options.scaleEnabled) {
  24397. if (editor.autoHeightEnabled) {
  24398. editor.disableAutoHeight();
  24399. }
  24400. me.enableScale();
  24401. } else {
  24402. me.disableScale();
  24403. }
  24404. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  24405. editor.ui.getDom('elementpath').style.display = "none";
  24406. editor.ui.getDom('wordcount').style.display = "none";
  24407. editor.ui.getDom('scale').style.display = "none";
  24408. }
  24409. if (!editor.selection.isFocus())return;
  24410. editor.fireEvent('selectionchange', false, true);
  24411. });
  24412. editor.addListener('mousedown', function (t, evt) {
  24413. var el = evt.target || evt.srcElement;
  24414. baidu.editor.ui.Popup.postHide(evt, el);
  24415. baidu.editor.ui.ShortCutMenu.postHide(evt);
  24416. });
  24417. editor.addListener("delcells", function () {
  24418. if (UE.ui['edittip']) {
  24419. new UE.ui['edittip'](editor);
  24420. }
  24421. editor.getDialog('edittip').open();
  24422. });
  24423. var pastePop, isPaste = false, timer;
  24424. editor.addListener("afterpaste", function () {
  24425. if(editor.queryCommandState('pasteplain'))
  24426. return;
  24427. if(baidu.editor.ui.PastePicker){
  24428. pastePop = new baidu.editor.ui.Popup({
  24429. content:new baidu.editor.ui.PastePicker({editor:editor}),
  24430. editor:editor,
  24431. className:'edui-wordpastepop'
  24432. });
  24433. pastePop.render();
  24434. }
  24435. isPaste = true;
  24436. });
  24437. editor.addListener("afterinserthtml", function () {
  24438. clearTimeout(timer);
  24439. timer = setTimeout(function () {
  24440. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  24441. if(pastePop.isHidden()){
  24442. var span = domUtils.createElement(editor.document, 'span', {
  24443. 'style':"line-height:0px;",
  24444. 'innerHTML':'\ufeff'
  24445. }),
  24446. range = editor.selection.getRange();
  24447. range.insertNode(span);
  24448. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  24449. pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  24450. domUtils.remove(span);
  24451. }else{
  24452. pastePop.show();
  24453. }
  24454. delete editor.ui._isTransfer;
  24455. isPaste = false;
  24456. }
  24457. }, 200)
  24458. });
  24459. editor.addListener('contextmenu', function (t, evt) {
  24460. baidu.editor.ui.Popup.postHide(evt);
  24461. });
  24462. editor.addListener('keydown', function (t, evt) {
  24463. if (pastePop) pastePop.dispose(evt);
  24464. var keyCode = evt.keyCode || evt.which;
  24465. if(evt.altKey&&keyCode==90){
  24466. UE.ui.buttons['fullscreen'].onclick();
  24467. }
  24468. });
  24469. editor.addListener('wordcount', function (type) {
  24470. setCount(this,me);
  24471. });
  24472. function setCount(editor,ui) {
  24473. editor.setOpt({
  24474. wordCount:true,
  24475. maximumWords:10000,
  24476. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  24477. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  24478. });
  24479. var opt = editor.options,
  24480. max = opt.maximumWords,
  24481. msg = opt.wordCountMsg ,
  24482. errMsg = opt.wordOverFlowMsg,
  24483. countDom = ui.getDom('wordcount');
  24484. if (!opt.wordCount) {
  24485. return;
  24486. }
  24487. var count = editor.getContentLength(true);
  24488. if (count > max) {
  24489. countDom.innerHTML = errMsg;
  24490. editor.fireEvent("wordcountoverflow");
  24491. } else {
  24492. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  24493. }
  24494. }
  24495. editor.addListener('selectionchange', function () {
  24496. if (editor.options.elementPathEnabled) {
  24497. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  24498. }
  24499. if (editor.options.scaleEnabled) {
  24500. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  24501. }
  24502. });
  24503. var popup = new baidu.editor.ui.Popup({
  24504. editor:editor,
  24505. content:'',
  24506. className:'edui-bubble',
  24507. _onEditButtonClick:function () {
  24508. this.hide();
  24509. editor.ui._dialogs.linkDialog.open();
  24510. },
  24511. _onImgEditButtonClick:function (name) {
  24512. this.hide();
  24513. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  24514. },
  24515. _onImgSetFloat:function (value) {
  24516. this.hide();
  24517. editor.execCommand("imagefloat", value);
  24518. },
  24519. _setIframeAlign:function (value) {
  24520. var frame = popup.anchorEl;
  24521. var newFrame = frame.cloneNode(true);
  24522. switch (value) {
  24523. case -2:
  24524. newFrame.setAttribute("align", "");
  24525. break;
  24526. case -1:
  24527. newFrame.setAttribute("align", "left");
  24528. break;
  24529. case 1:
  24530. newFrame.setAttribute("align", "right");
  24531. break;
  24532. }
  24533. frame.parentNode.insertBefore(newFrame, frame);
  24534. domUtils.remove(frame);
  24535. popup.anchorEl = newFrame;
  24536. popup.showAnchor(popup.anchorEl);
  24537. },
  24538. _updateIframe:function () {
  24539. var frame = editor._iframe = popup.anchorEl;
  24540. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  24541. editor.selection.getRange().selectNode(frame).select();
  24542. editor.ui._dialogs.mapDialog.open();
  24543. popup.hide();
  24544. } else {
  24545. editor.ui._dialogs.insertframeDialog.open();
  24546. popup.hide();
  24547. }
  24548. },
  24549. _onRemoveButtonClick:function (cmdName) {
  24550. editor.execCommand(cmdName);
  24551. this.hide();
  24552. },
  24553. queryAutoHide:function (el) {
  24554. if (el && el.ownerDocument == editor.document) {
  24555. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  24556. return el !== popup.anchorEl;
  24557. }
  24558. }
  24559. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  24560. }
  24561. });
  24562. popup.render();
  24563. if (editor.options.imagePopup) {
  24564. editor.addListener('mouseover', function (t, evt) {
  24565. evt = evt || window.event;
  24566. var el = evt.target || evt.srcElement;
  24567. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  24568. var html = popup.formatHtml(
  24569. '<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;' +
  24570. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  24571. if (html) {
  24572. popup.getDom('content').innerHTML = html;
  24573. popup.anchorEl = el;
  24574. popup.showAnchor(popup.anchorEl);
  24575. } else {
  24576. popup.hide();
  24577. }
  24578. }
  24579. });
  24580. editor.addListener('selectionchange', function (t, causeByUi) {
  24581. if (!causeByUi) return;
  24582. var html = '', str = "",
  24583. img = editor.selection.getRange().getClosedNode(),
  24584. dialogs = editor.ui._dialogs;
  24585. if (img && img.tagName == 'IMG') {
  24586. var dialogName = 'insertimageDialog';
  24587. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  24588. dialogName = "insertvideoDialog"
  24589. }
  24590. if (img.className.indexOf("edui-faked-webapp") != -1) {
  24591. dialogName = "webappDialog"
  24592. }
  24593. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  24594. dialogName = "mapDialog"
  24595. }
  24596. if (img.className.indexOf("edui-faked-music") != -1) {
  24597. dialogName = "musicDialog"
  24598. }
  24599. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  24600. dialogName = "gmapDialog"
  24601. }
  24602. if (img.getAttribute("anchorname")) {
  24603. dialogName = "anchorDialog";
  24604. html = popup.formatHtml(
  24605. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  24606. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  24607. }
  24608. if (img.getAttribute("word_img")) {
  24609. //todo 放到dialog去做查询
  24610. editor.word_img = [img.getAttribute("word_img")];
  24611. dialogName = "wordimageDialog"
  24612. }
  24613. if (!dialogs[dialogName]) {
  24614. return;
  24615. }
  24616. str = '<nobr>' + editor.getLang("property") + ': '+
  24617. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  24618. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  24619. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  24620. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  24621. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  24622. !html && (html = popup.formatHtml(str))
  24623. }
  24624. if (editor.ui._dialogs.linkDialog) {
  24625. var link = editor.queryCommandValue('link');
  24626. var url;
  24627. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  24628. var txt = url;
  24629. if (url.length > 30) {
  24630. txt = url.substring(0, 20) + "...";
  24631. }
  24632. if (html) {
  24633. html += '<div style="height:5px;"></div>'
  24634. }
  24635. html += popup.formatHtml(
  24636. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  24637. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  24638. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  24639. popup.showAnchor(link);
  24640. }
  24641. }
  24642. if (html) {
  24643. popup.getDom('content').innerHTML = html;
  24644. popup.anchorEl = img || link;
  24645. popup.showAnchor(popup.anchorEl);
  24646. } else {
  24647. popup.hide();
  24648. }
  24649. });
  24650. }
  24651. },
  24652. _initToolbars:function () {
  24653. var editor = this.editor;
  24654. var toolbars = this.toolbars || [];
  24655. var toolbarUis = [];
  24656. for (var i = 0; i < toolbars.length; i++) {
  24657. var toolbar = toolbars[i];
  24658. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  24659. for (var j = 0; j < toolbar.length; j++) {
  24660. var toolbarItem = toolbar[j];
  24661. var toolbarItemUi = null;
  24662. if (typeof toolbarItem == 'string') {
  24663. toolbarItem = toolbarItem.toLowerCase();
  24664. if (toolbarItem == '|') {
  24665. toolbarItem = 'Separator';
  24666. }
  24667. if(toolbarItem == '||'){
  24668. toolbarItem = 'Breakline';
  24669. }
  24670. if (baidu.editor.ui[toolbarItem]) {
  24671. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  24672. }
  24673. //fullscreen这里单独处理一下,放到首行去
  24674. if (toolbarItem == 'fullscreen') {
  24675. if (toolbarUis && toolbarUis[0]) {
  24676. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  24677. } else {
  24678. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  24679. }
  24680. continue;
  24681. }
  24682. } else {
  24683. toolbarItemUi = toolbarItem;
  24684. }
  24685. if (toolbarItemUi && toolbarItemUi.id) {
  24686. toolbarUi.add(toolbarItemUi);
  24687. }
  24688. }
  24689. toolbarUis[i] = toolbarUi;
  24690. }
  24691. this.toolbars = toolbarUis;
  24692. },
  24693. getHtmlTpl:function () {
  24694. return '<div id="##" class="%%">' +
  24695. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  24696. (this.toolbars.length ?
  24697. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  24698. this.renderToolbarBoxHtml() +
  24699. '</div></div>' : '') +
  24700. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  24701. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  24702. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  24703. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  24704. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  24705. '</div>' +
  24706. '</div>' +
  24707. '<div id="##_iframeholder" class="%%-iframeholder"></div>' +
  24708. //modify wdcount by matao
  24709. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  24710. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  24711. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  24712. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  24713. '</tr></table></div>' +
  24714. '<div id="##_scalelayer"></div>' +
  24715. '</div>';
  24716. },
  24717. showWordImageDialog:function () {
  24718. this._dialogs['wordimageDialog'].open();
  24719. },
  24720. renderToolbarBoxHtml:function () {
  24721. var buff = [];
  24722. for (var i = 0; i < this.toolbars.length; i++) {
  24723. buff.push(this.toolbars[i].renderHtml());
  24724. }
  24725. return buff.join('');
  24726. },
  24727. setFullScreen:function (fullscreen) {
  24728. var editor = this.editor,
  24729. container = editor.container.parentNode.parentNode;
  24730. if (this._fullscreen != fullscreen) {
  24731. this._fullscreen = fullscreen;
  24732. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  24733. if (baidu.editor.browser.gecko) {
  24734. var bk = editor.selection.getRange().createBookmark();
  24735. }
  24736. if (fullscreen) {
  24737. while (container.tagName != "BODY") {
  24738. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  24739. nodeStack.push(position);
  24740. container.style.position = "static";
  24741. container = container.parentNode;
  24742. }
  24743. this._bakHtmlOverflow = document.documentElement.style.overflow;
  24744. this._bakBodyOverflow = document.body.style.overflow;
  24745. this._bakAutoHeight = this.editor.autoHeightEnabled;
  24746. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  24747. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  24748. if (this._bakAutoHeight) {
  24749. //当全屏时不能执行自动长高
  24750. editor.autoHeightEnabled = false;
  24751. this.editor.disableAutoHeight();
  24752. }
  24753. document.documentElement.style.overflow = 'hidden';
  24754. //修复,滚动条不收起的问题
  24755. window.scrollTo(0,window.scrollY);
  24756. this._bakCssText = this.getDom().style.cssText;
  24757. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  24758. editor.iframe.parentNode.style.width = '';
  24759. this._updateFullScreen();
  24760. } else {
  24761. while (container.tagName != "BODY") {
  24762. container.style.position = nodeStack.shift();
  24763. container = container.parentNode;
  24764. }
  24765. this.getDom().style.cssText = this._bakCssText;
  24766. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  24767. if (this._bakAutoHeight) {
  24768. editor.autoHeightEnabled = true;
  24769. this.editor.enableAutoHeight();
  24770. }
  24771. document.documentElement.style.overflow = this._bakHtmlOverflow;
  24772. document.body.style.overflow = this._bakBodyOverflow;
  24773. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  24774. window.scrollTo(0, this._bakScrollTop);
  24775. }
  24776. if (browser.gecko && editor.body.contentEditable === 'true') {
  24777. var input = document.createElement('input');
  24778. document.body.appendChild(input);
  24779. editor.body.contentEditable = false;
  24780. setTimeout(function () {
  24781. input.focus();
  24782. setTimeout(function () {
  24783. editor.body.contentEditable = true;
  24784. editor.fireEvent('fullscreenchanged', fullscreen);
  24785. editor.selection.getRange().moveToBookmark(bk).select(true);
  24786. baidu.editor.dom.domUtils.remove(input);
  24787. fullscreen && window.scroll(0, 0);
  24788. }, 0)
  24789. }, 0)
  24790. }
  24791. if(editor.body.contentEditable === 'true'){
  24792. this.editor.fireEvent('fullscreenchanged', fullscreen);
  24793. this.triggerLayout();
  24794. }
  24795. }
  24796. },
  24797. _updateFullScreen:function () {
  24798. if (this._fullscreen) {
  24799. var vpRect = uiUtils.getViewportRect();
  24800. 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);
  24801. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  24802. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0));
  24803. //不手动调一下,会导致全屏失效
  24804. if(browser.gecko){
  24805. try{
  24806. window.onresize();
  24807. }catch(e){
  24808. }
  24809. }
  24810. }
  24811. },
  24812. _updateElementPath:function () {
  24813. var bottom = this.getDom('elementpath'), list;
  24814. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  24815. var buff = [];
  24816. for (var i = 0, ci; ci = list[i]; i++) {
  24817. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  24818. }
  24819. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  24820. } else {
  24821. bottom.style.display = 'none'
  24822. }
  24823. },
  24824. disableElementPath:function () {
  24825. var bottom = this.getDom('elementpath');
  24826. bottom.innerHTML = '';
  24827. bottom.style.display = 'none';
  24828. this.elementPathEnabled = false;
  24829. },
  24830. enableElementPath:function () {
  24831. var bottom = this.getDom('elementpath');
  24832. bottom.style.display = '';
  24833. this.elementPathEnabled = true;
  24834. this._updateElementPath();
  24835. },
  24836. _scale:function () {
  24837. var doc = document,
  24838. editor = this.editor,
  24839. editorHolder = editor.container,
  24840. editorDocument = editor.document,
  24841. toolbarBox = this.getDom("toolbarbox"),
  24842. bottombar = this.getDom("bottombar"),
  24843. scale = this.getDom("scale"),
  24844. scalelayer = this.getDom("scalelayer");
  24845. var isMouseMove = false,
  24846. position = null,
  24847. minEditorHeight = 0,
  24848. minEditorWidth = editor.options.minFrameWidth,
  24849. pageX = 0,
  24850. pageY = 0,
  24851. scaleWidth = 0,
  24852. scaleHeight = 0;
  24853. function down() {
  24854. position = domUtils.getXY(editorHolder);
  24855. if (!minEditorHeight) {
  24856. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  24857. }
  24858. 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:"
  24859. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  24860. domUtils.on(doc, "mousemove", move);
  24861. domUtils.on(editorDocument, "mouseup", up);
  24862. domUtils.on(doc, "mouseup", up);
  24863. }
  24864. var me = this;
  24865. //by xuheng 全屏时关掉缩放
  24866. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  24867. if (fullScreen) {
  24868. me.disableScale();
  24869. } else {
  24870. if (me.editor.options.scaleEnabled) {
  24871. me.enableScale();
  24872. var tmpNode = me.editor.document.createElement('span');
  24873. me.editor.body.appendChild(tmpNode);
  24874. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  24875. domUtils.remove(tmpNode)
  24876. }
  24877. }
  24878. });
  24879. function move(event) {
  24880. clearSelection();
  24881. var e = event || window.event;
  24882. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  24883. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  24884. scaleWidth = pageX - position.x;
  24885. scaleHeight = pageY - position.y;
  24886. if (scaleWidth >= minEditorWidth) {
  24887. isMouseMove = true;
  24888. scalelayer.style.width = scaleWidth + 'px';
  24889. }
  24890. if (scaleHeight >= minEditorHeight) {
  24891. isMouseMove = true;
  24892. scalelayer.style.height = scaleHeight + "px";
  24893. }
  24894. }
  24895. function up() {
  24896. if (isMouseMove) {
  24897. isMouseMove = false;
  24898. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  24899. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  24900. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2);
  24901. }
  24902. if (scalelayer) {
  24903. scalelayer.style.display = "none";
  24904. }
  24905. clearSelection();
  24906. domUtils.un(doc, "mousemove", move);
  24907. domUtils.un(editorDocument, "mouseup", up);
  24908. domUtils.un(doc, "mouseup", up);
  24909. }
  24910. function clearSelection() {
  24911. if (browser.ie)
  24912. doc.selection.clear();
  24913. else
  24914. window.getSelection().removeAllRanges();
  24915. }
  24916. this.enableScale = function () {
  24917. //trace:2868
  24918. if (editor.queryCommandState("source") == 1) return;
  24919. scale.style.display = "";
  24920. this.scaleEnabled = true;
  24921. domUtils.on(scale, "mousedown", down);
  24922. };
  24923. this.disableScale = function () {
  24924. scale.style.display = "none";
  24925. this.scaleEnabled = false;
  24926. domUtils.un(scale, "mousedown", down);
  24927. };
  24928. },
  24929. isFullScreen:function () {
  24930. return this._fullscreen;
  24931. },
  24932. postRender:function () {
  24933. UIBase.prototype.postRender.call(this);
  24934. for (var i = 0; i < this.toolbars.length; i++) {
  24935. this.toolbars[i].postRender();
  24936. }
  24937. var me = this;
  24938. var timerId,
  24939. domUtils = baidu.editor.dom.domUtils,
  24940. updateFullScreenTime = function () {
  24941. clearTimeout(timerId);
  24942. timerId = setTimeout(function () {
  24943. me._updateFullScreen();
  24944. });
  24945. };
  24946. domUtils.on(window, 'resize', updateFullScreenTime);
  24947. me.addListener('destroy', function () {
  24948. domUtils.un(window, 'resize', updateFullScreenTime);
  24949. clearTimeout(timerId);
  24950. })
  24951. },
  24952. showToolbarMsg:function (msg, flag) {
  24953. this.getDom('toolbarmsg_label').innerHTML = msg;
  24954. this.getDom('toolbarmsg').style.display = '';
  24955. //
  24956. if (!flag) {
  24957. var w = this.getDom('upload_dialog');
  24958. w.style.display = 'none';
  24959. }
  24960. },
  24961. hideToolbarMsg:function () {
  24962. this.getDom('toolbarmsg').style.display = 'none';
  24963. },
  24964. mapUrl:function (url) {
  24965. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  24966. },
  24967. triggerLayout:function () {
  24968. var dom = this.getDom();
  24969. if (dom.style.zoom == '1') {
  24970. dom.style.zoom = '100%';
  24971. } else {
  24972. dom.style.zoom = '1';
  24973. }
  24974. }
  24975. };
  24976. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  24977. var instances = {};
  24978. UE.ui.Editor = function (options) {
  24979. var editor = new UE.Editor(options);
  24980. editor.options.editor = editor;
  24981. utils.loadFile(document, {
  24982. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  24983. tag:"link",
  24984. type:"text/css",
  24985. rel:"stylesheet"
  24986. });
  24987. var oldRender = editor.render;
  24988. editor.render = function (holder) {
  24989. if (holder.constructor === String) {
  24990. editor.key = holder;
  24991. instances[holder] = editor;
  24992. }
  24993. utils.domReady(function () {
  24994. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  24995. function renderUI() {
  24996. editor.setOpt({
  24997. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  24998. });
  24999. new EditorUI(editor.options);
  25000. if (holder) {
  25001. if (holder.constructor === String) {
  25002. holder = document.getElementById(holder);
  25003. }
  25004. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  25005. if (holder && /script|textarea/ig.test(holder.tagName)) {
  25006. var newDiv = document.createElement('div');
  25007. holder.parentNode.insertBefore(newDiv, holder);
  25008. var cont = holder.value || holder.innerHTML;
  25009. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  25010. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  25011. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  25012. .replace(/>[\n\r\t]+</g, '><');
  25013. holder.className && (newDiv.className = holder.className);
  25014. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  25015. if (/textarea/i.test(holder.tagName)) {
  25016. editor.textarea = holder;
  25017. editor.textarea.style.display = 'none';
  25018. } else {
  25019. holder.parentNode.removeChild(holder);
  25020. holder.id && (newDiv.id = holder.id);
  25021. }
  25022. holder = newDiv;
  25023. holder.innerHTML = '';
  25024. }
  25025. }
  25026. domUtils.addClass(holder, "edui-" + editor.options.theme);
  25027. editor.ui.render(holder);
  25028. var opt = editor.options;
  25029. //给实例添加一个编辑器的容器引用
  25030. editor.container = editor.ui.getDom();
  25031. var parents = domUtils.findParents(holder,true);
  25032. var displays = [];
  25033. for(var i = 0 ,ci;ci=parents[i];i++){
  25034. displays[i] = ci.style.display;
  25035. ci.style.display = 'block'
  25036. }
  25037. if (opt.initialFrameWidth) {
  25038. opt.minFrameWidth = opt.initialFrameWidth;
  25039. } else {
  25040. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  25041. }
  25042. if (opt.initialFrameHeight) {
  25043. opt.minFrameHeight = opt.initialFrameHeight;
  25044. } else {
  25045. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  25046. }
  25047. for(var i = 0 ,ci;ci=parents[i];i++){
  25048. ci.style.display = displays[i]
  25049. }
  25050. //编辑器最外容器设置了高度,会导致,编辑器不占位
  25051. //todo 先去掉,没有找到原因
  25052. if(holder.style.height){
  25053. holder.style.height = ''
  25054. }
  25055. //update-begin--Author:yugwu Date:20170626 for:[TASK #2135]【浏览器兼容问题】IE8下样式乱了-------------------- --
  25056. editor.container.style.width = opt.initialFrameWidth + (!/^\+?[1-9][0-9]*$/.test(opt.initialFrameWidth) ? '' : 'px');
  25057. //update-end--Author:yugwu Date:20170626 for:[TASK #2135]【浏览器兼容问题】IE8下样式乱了-------------------- --
  25058. editor.container.style.zIndex = opt.zIndex;
  25059. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  25060. editor.fireEvent("afteruiready");
  25061. }
  25062. })
  25063. };
  25064. return editor;
  25065. };
  25066. /**
  25067. * @file
  25068. * @name UE
  25069. * @short UE
  25070. * @desc UEditor的顶部命名空间
  25071. */
  25072. /**
  25073. * @name getEditor
  25074. * @since 1.2.4+
  25075. * @grammar UE.getEditor(id,[opt]) => Editor实例
  25076. * @desc 提供一个全局的方法得到编辑器实例
  25077. *
  25078. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  25079. * * ''opt'' 编辑器的可选参数
  25080. * @example
  25081. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  25082. * this.setContent('hello')
  25083. * }});
  25084. * UE.getEditor('containerId'); //返回刚创建的实例
  25085. *
  25086. */
  25087. UE.getEditor = function (id, opt) {
  25088. var editor = instances[id];
  25089. if (!editor) {
  25090. editor = instances[id] = new UE.ui.Editor(opt);
  25091. editor.render(id);
  25092. }
  25093. return editor;
  25094. };
  25095. UE.delEditor = function (id) {
  25096. var editor;
  25097. if (editor = instances[id]) {
  25098. editor.key && editor.destroy();
  25099. delete instances[id]
  25100. }
  25101. }
  25102. })();
  25103. ///import core
  25104. ///import uicore
  25105. ///commands 表情
  25106. (function(){
  25107. var utils = baidu.editor.utils,
  25108. Popup = baidu.editor.ui.Popup,
  25109. SplitButton = baidu.editor.ui.SplitButton,
  25110. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  25111. this.initOptions(options);
  25112. this.initMultiMenu();
  25113. };
  25114. MultiMenuPop.prototype = {
  25115. initMultiMenu: function (){
  25116. var me = this;
  25117. this.popup = new Popup({
  25118. content: '',
  25119. editor : me.editor,
  25120. iframe_rendered: false,
  25121. onshow: function (){
  25122. if (!this.iframe_rendered) {
  25123. this.iframe_rendered = true;
  25124. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  25125. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25126. }
  25127. }
  25128. // canSideUp:false,
  25129. // canSideLeft:false
  25130. });
  25131. this.onbuttonclick = function(){
  25132. this.showPopup();
  25133. };
  25134. this.initSplitButton();
  25135. }
  25136. };
  25137. utils.inherits(MultiMenuPop, SplitButton);
  25138. })();
  25139. (function () {
  25140. var UI = baidu.editor.ui,
  25141. UIBase = UI.UIBase,
  25142. uiUtils = UI.uiUtils,
  25143. utils = baidu.editor.utils,
  25144. domUtils = baidu.editor.dom.domUtils;
  25145. var allMenus = [],//存储所有快捷菜单
  25146. timeID,
  25147. isSubMenuShow = false;//是否有子pop显示
  25148. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25149. this.initOptions (options);
  25150. this.initShortCutMenu ();
  25151. };
  25152. ShortCutMenu.postHide = hideAllMenu;
  25153. ShortCutMenu.prototype = {
  25154. isHidden : true ,
  25155. SPACE : 5 ,
  25156. initShortCutMenu : function () {
  25157. this.items = this.items || [];
  25158. this.initUIBase ();
  25159. this.initItems ();
  25160. this.initEvent ();
  25161. allMenus.push (this);
  25162. } ,
  25163. initEvent : function () {
  25164. var me = this,
  25165. doc = me.editor.document;
  25166. domUtils.on (doc , "mousemove" , function (e) {
  25167. if (me.isHidden === false) {
  25168. //有pop显示就不隐藏快捷菜单
  25169. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  25170. var flag = true,
  25171. el = me.getDom (),
  25172. wt = el.offsetWidth,
  25173. ht = el.offsetHeight,
  25174. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25175. distanceY = ht / 2,//距离中心Y标准
  25176. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  25177. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  25178. clearTimeout (timeID);
  25179. timeID = setTimeout (function () {
  25180. if (y > 0 && y < distanceY) {
  25181. me.setOpacity (el , "1");
  25182. } else if (y > distanceY && y < distanceY + 70) {
  25183. me.setOpacity (el , "0.5");
  25184. flag = false;
  25185. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25186. me.hide ();
  25187. }
  25188. if (flag && x > 0 && x < distanceX) {
  25189. me.setOpacity (el , "1")
  25190. } else if (x > distanceX && x < distanceX + 70) {
  25191. me.setOpacity (el , "0.5")
  25192. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25193. me.hide ();
  25194. }
  25195. });
  25196. }
  25197. });
  25198. //ie\ff下 mouseout不准
  25199. if (browser.chrome) {
  25200. domUtils.on (doc , "mouseout" , function (e) {
  25201. var relatedTgt = e.relatedTarget || e.toElement;
  25202. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25203. me.hide ();
  25204. }
  25205. });
  25206. }
  25207. me.editor.addListener ("afterhidepop" , function () {
  25208. if (!me.isHidden) {
  25209. isSubMenuShow = true;
  25210. }
  25211. });
  25212. } ,
  25213. initItems : function () {
  25214. if (utils.isArray (this.items)) {
  25215. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25216. var item = this.items[i].toLowerCase ();
  25217. if (UI[item]) {
  25218. this.items[i] = new UI[item] (this.editor);
  25219. this.items[i].className += " edui-shortcutsubmenu ";
  25220. }
  25221. }
  25222. }
  25223. } ,
  25224. setOpacity : function (el , value) {
  25225. if (browser.ie && browser.version < 9) {
  25226. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25227. } else {
  25228. el.style.opacity = value;
  25229. }
  25230. } ,
  25231. getSubMenuMark : function () {
  25232. isSubMenuShow = false;
  25233. var layerEle = uiUtils.getFixedLayer ();
  25234. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25235. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25236. });
  25237. for (var i = 0, node ; node = list[i++] ;) {
  25238. if (node.style.display != "none") {
  25239. isSubMenuShow = true;
  25240. }
  25241. }
  25242. return isSubMenuShow;
  25243. } ,
  25244. show : function (e , hasContextmenu) {
  25245. var me = this,
  25246. offset = {},
  25247. el = this.getDom (),
  25248. fixedlayer = uiUtils.getFixedLayer ();
  25249. function setPos (offset) {
  25250. if (offset.left < 0) {
  25251. offset.left = 0;
  25252. }
  25253. if (offset.top < 0) {
  25254. offset.top = 0;
  25255. }
  25256. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25257. }
  25258. function setPosByCxtMenu (menu) {
  25259. if (!menu.tagName) {
  25260. menu = menu.getDom ();
  25261. }
  25262. offset.left = parseInt (menu.style.left);
  25263. offset.top = parseInt (menu.style.top);
  25264. offset.top -= el.offsetHeight + 15;
  25265. setPos (offset);
  25266. }
  25267. me.eventType = e.type;
  25268. el.style.cssText = "display:block;left:-9999px";
  25269. if (e.type == "contextmenu" && hasContextmenu) {
  25270. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25271. if (menu) {
  25272. setPosByCxtMenu (menu)
  25273. } else {
  25274. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25275. setPosByCxtMenu (menu);
  25276. });
  25277. }
  25278. } else {
  25279. offset = uiUtils.getViewportOffsetByEvent (e);
  25280. offset.top -= el.offsetHeight + me.SPACE;
  25281. offset.left += me.SPACE + 20;
  25282. setPos (offset);
  25283. me.setOpacity (el , 0.2);
  25284. }
  25285. me.isHidden = false;
  25286. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25287. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25288. if (me.editor) {
  25289. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25290. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25291. }
  25292. } ,
  25293. hide : function () {
  25294. if (this.getDom ()) {
  25295. this.getDom ().style.display = "none";
  25296. }
  25297. this.isHidden = true;
  25298. } ,
  25299. postRender : function () {
  25300. if (utils.isArray (this.items)) {
  25301. for (var i = 0, item ; item = this.items[i++] ;) {
  25302. item.postRender ();
  25303. }
  25304. }
  25305. } ,
  25306. getHtmlTpl : function () {
  25307. var buff;
  25308. if (utils.isArray (this.items)) {
  25309. buff = [];
  25310. for (var i = 0 ; i < this.items.length ; i++) {
  25311. buff[i] = this.items[i].renderHtml ();
  25312. }
  25313. buff = buff.join ("");
  25314. } else {
  25315. buff = this.items;
  25316. }
  25317. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25318. buff +
  25319. '</div>';
  25320. }
  25321. };
  25322. utils.inherits (ShortCutMenu , UIBase);
  25323. function hideAllMenu (e) {
  25324. var tgt = e.target || e.srcElement,
  25325. cur = domUtils.findParent (tgt , function (node) {
  25326. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25327. } , true);
  25328. if (!cur) {
  25329. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25330. menu.hide ()
  25331. }
  25332. }
  25333. }
  25334. domUtils.on (document , 'mousedown' , function (e) {
  25335. hideAllMenu (e);
  25336. });
  25337. domUtils.on (window , 'scroll' , function (e) {
  25338. hideAllMenu (e);
  25339. });
  25340. }) ();
  25341. (function (){
  25342. var utils = baidu.editor.utils,
  25343. UIBase = baidu.editor.ui.UIBase,
  25344. Breakline = baidu.editor.ui.Breakline = function (options){
  25345. this.initOptions(options);
  25346. this.initSeparator();
  25347. };
  25348. Breakline.prototype = {
  25349. uiName: 'Breakline',
  25350. initSeparator: function (){
  25351. this.initUIBase();
  25352. },
  25353. getHtmlTpl: function (){
  25354. return '<br/>';
  25355. }
  25356. };
  25357. utils.inherits(Breakline, UIBase);
  25358. })();
  25359. })()