ueditor.all.min.js 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572
  1. /*!
  2. * UEditor
  3. * version: ueditor
  4. * build: Tue Jan 09 2024 10:10:58 GMT+0800 (中国标准时间)
  5. */
  6. (function(){
  7. // editor.js
  8. UEDITOR_CONFIG = window.UEDITOR_CONFIG || {};
  9. var baidu = window.baidu || {};
  10. window.baidu = baidu;
  11. window.UE = baidu.editor = window.UE || {};
  12. UE.plugins = {};
  13. UE.commands = {};
  14. UE.instants = {};
  15. UE.I18N = {};
  16. UE._customizeUI = {};
  17. UE.version = "1.4.3";
  18. var dom = UE.dom = {};
  19. // core/browser.js
  20. /**
  21. * 浏览器判断模块
  22. * @file
  23. * @module UE.browser
  24. * @since 1.2.6.1
  25. */
  26. /**
  27. * 提供浏览器检测的模块
  28. * @unfile
  29. * @module UE.browser
  30. */
  31. var browser = UE.browser = function(){
  32. var agent = navigator.userAgent.toLowerCase(),
  33. opera = window.opera,
  34. browser = {
  35. /**
  36. * @property {boolean} ie 检测当前浏览器是否为IE
  37. * @example
  38. * ```javascript
  39. * if ( UE.browser.ie ) {
  40. * console.log( '当前浏览器是IE' );
  41. * }
  42. * ```
  43. */
  44. ie : /(msie\s|trident.*rv:)([\w.]+)/.test(agent),
  45. /**
  46. * @property {boolean} opera 检测当前浏览器是否为Opera
  47. * @example
  48. * ```javascript
  49. * if ( UE.browser.opera ) {
  50. * console.log( '当前浏览器是Opera' );
  51. * }
  52. * ```
  53. */
  54. opera : ( !!opera && opera.version ),
  55. /**
  56. * @property {boolean} webkit 检测当前浏览器是否是webkit内核的浏览器
  57. * @example
  58. * ```javascript
  59. * if ( UE.browser.webkit ) {
  60. * console.log( '当前浏览器是webkit内核浏览器' );
  61. * }
  62. * ```
  63. */
  64. webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ),
  65. /**
  66. * @property {boolean} mac 检测当前浏览器是否是运行在mac平台下
  67. * @example
  68. * ```javascript
  69. * if ( UE.browser.mac ) {
  70. * console.log( '当前浏览器运行在mac平台下' );
  71. * }
  72. * ```
  73. */
  74. mac : ( agent.indexOf( 'macintosh' ) > -1 ),
  75. /**
  76. * @property {boolean} quirks 检测当前浏览器是否处于“怪异模式”下
  77. * @example
  78. * ```javascript
  79. * if ( UE.browser.quirks ) {
  80. * console.log( '当前浏览器运行处于“怪异模式”' );
  81. * }
  82. * ```
  83. */
  84. quirks : ( document.compatMode == 'BackCompat' )
  85. };
  86. /**
  87. * @property {boolean} gecko 检测当前浏览器内核是否是gecko内核
  88. * @example
  89. * ```javascript
  90. * if ( UE.browser.gecko ) {
  91. * console.log( '当前浏览器内核是gecko内核' );
  92. * }
  93. * ```
  94. */
  95. browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera && !browser.ie);
  96. var version = 0;
  97. // Internet Explorer 6.0+
  98. if ( browser.ie ){
  99. var v1 = agent.match(/(?:msie\s([\w.]+))/);
  100. var v2 = agent.match(/(?:trident.*rv:([\w.]+))/);
  101. if(v1 && v2 && v1[1] && v2[1]){
  102. version = Math.max(v1[1]*1,v2[1]*1);
  103. }else if(v1 && v1[1]){
  104. version = v1[1]*1;
  105. }else if(v2 && v2[1]){
  106. version = v2[1]*1;
  107. }else{
  108. version = 0;
  109. }
  110. browser.ie11Compat = document.documentMode == 11;
  111. /**
  112. * @property { boolean } ie9Compat 检测浏览器模式是否为 IE9 兼容模式
  113. * @warning 如果浏览器不是IE, 则该值为undefined
  114. * @example
  115. * ```javascript
  116. * if ( UE.browser.ie9Compat ) {
  117. * console.log( '当前浏览器运行在IE9兼容模式下' );
  118. * }
  119. * ```
  120. */
  121. browser.ie9Compat = document.documentMode == 9;
  122. /**
  123. * @property { boolean } ie8 检测浏览器是否是IE8浏览器
  124. * @warning 如果浏览器不是IE, 则该值为undefined
  125. * @example
  126. * ```javascript
  127. * if ( UE.browser.ie8 ) {
  128. * console.log( '当前浏览器是IE8浏览器' );
  129. * }
  130. * ```
  131. */
  132. browser.ie8 = !!document.documentMode;
  133. /**
  134. * @property { boolean } ie8Compat 检测浏览器模式是否为 IE8 兼容模式
  135. * @warning 如果浏览器不是IE, 则该值为undefined
  136. * @example
  137. * ```javascript
  138. * if ( UE.browser.ie8Compat ) {
  139. * console.log( '当前浏览器运行在IE8兼容模式下' );
  140. * }
  141. * ```
  142. */
  143. browser.ie8Compat = document.documentMode == 8;
  144. /**
  145. * @property { boolean } ie7Compat 检测浏览器模式是否为 IE7 兼容模式
  146. * @warning 如果浏览器不是IE, 则该值为undefined
  147. * @example
  148. * ```javascript
  149. * if ( UE.browser.ie7Compat ) {
  150. * console.log( '当前浏览器运行在IE7兼容模式下' );
  151. * }
  152. * ```
  153. */
  154. browser.ie7Compat = ( ( version == 7 && !document.documentMode )
  155. || document.documentMode == 7 );
  156. /**
  157. * @property { boolean } ie6Compat 检测浏览器模式是否为 IE6 模式 或者怪异模式
  158. * @warning 如果浏览器不是IE, 则该值为undefined
  159. * @example
  160. * ```javascript
  161. * if ( UE.browser.ie6Compat ) {
  162. * console.log( '当前浏览器运行在IE6模式或者怪异模式下' );
  163. * }
  164. * ```
  165. */
  166. browser.ie6Compat = ( version < 7 || browser.quirks );
  167. browser.ie9above = version > 8;
  168. browser.ie9below = version < 9;
  169. browser.ie11above = version > 10;
  170. browser.ie11below = version < 11;
  171. }
  172. // Gecko.
  173. if ( browser.gecko ){
  174. var geckoRelease = agent.match( /rv:([\d\.]+)/ );
  175. if ( geckoRelease )
  176. {
  177. geckoRelease = geckoRelease[1].split( '.' );
  178. version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1;
  179. }
  180. }
  181. /**
  182. * @property { Number } chrome 检测当前浏览器是否为Chrome, 如果是,则返回Chrome的大版本号
  183. * @warning 如果浏览器不是chrome, 则该值为undefined
  184. * @example
  185. * ```javascript
  186. * if ( UE.browser.chrome ) {
  187. * console.log( '当前浏览器是Chrome' );
  188. * }
  189. * ```
  190. */
  191. if (/chrome\/(\d+\.\d)/i.test(agent)) {
  192. browser.chrome = + RegExp['\x241'];
  193. }
  194. /**
  195. * @property { Number } safari 检测当前浏览器是否为Safari, 如果是,则返回Safari的大版本号
  196. * @warning 如果浏览器不是safari, 则该值为undefined
  197. * @example
  198. * ```javascript
  199. * if ( UE.browser.safari ) {
  200. * console.log( '当前浏览器是Safari' );
  201. * }
  202. * ```
  203. */
  204. if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){
  205. browser.safari = + (RegExp['\x241'] || RegExp['\x242']);
  206. }
  207. // Opera 9.50+
  208. if ( browser.opera )
  209. version = parseFloat( opera.version() );
  210. // WebKit 522+ (Safari 3+)
  211. if ( browser.webkit )
  212. version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] );
  213. /**
  214. * @property { Number } version 检测当前浏览器版本号
  215. * @remind
  216. * <ul>
  217. * <li>IE系列返回值为5,6,7,8,9,10等</li>
  218. * <li>gecko系列会返回10900,158900等</li>
  219. * <li>webkit系列会返回其build号 (如 522等)</li>
  220. * </ul>
  221. * @example
  222. * ```javascript
  223. * console.log( '当前浏览器版本号是: ' + UE.browser.version );
  224. * ```
  225. */
  226. browser.version = version;
  227. /**
  228. * @property { boolean } isCompatible 检测当前浏览器是否能够与UEditor良好兼容
  229. * @example
  230. * ```javascript
  231. * if ( UE.browser.isCompatible ) {
  232. * console.log( '浏览器与UEditor能够良好兼容' );
  233. * }
  234. * ```
  235. */
  236. browser.isCompatible =
  237. !browser.mobile && (
  238. ( browser.ie && version >= 6 ) ||
  239. ( browser.gecko && version >= 10801 ) ||
  240. ( browser.opera && version >= 9.5 ) ||
  241. ( browser.air && version >= 1 ) ||
  242. ( browser.webkit && version >= 522 ) ||
  243. false );
  244. return browser;
  245. }();
  246. //快捷方式
  247. var ie = browser.ie,
  248. webkit = browser.webkit,
  249. gecko = browser.gecko,
  250. opera = browser.opera;
  251. // core/utils.js
  252. /**
  253. * 工具函数包
  254. * @file
  255. * @module UE.utils
  256. * @since 1.2.6.1
  257. */
  258. /**
  259. * UEditor封装使用的静态工具函数
  260. * @module UE.utils
  261. * @unfile
  262. */
  263. var utils = UE.utils = {
  264. /**
  265. * 用给定的迭代器遍历对象
  266. * @method each
  267. * @param { Object } obj 需要遍历的对象
  268. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  269. * @example
  270. * ```javascript
  271. * var demoObj = {
  272. * key1: 1,
  273. * key2: 2
  274. * };
  275. *
  276. * //output: key1: 1, key2: 2
  277. * UE.utils.each( demoObj, funciton ( value, key ) {
  278. *
  279. * console.log( key + ":" + value );
  280. *
  281. * } );
  282. * ```
  283. */
  284. /**
  285. * 用给定的迭代器遍历数组或类数组对象
  286. * @method each
  287. * @param { Array } array 需要遍历的数组或者类数组
  288. * @param { Function } iterator 迭代器, 该方法接受两个参数, 第一个参数是当前所处理的value, 第二个参数是当前遍历对象的key
  289. * @example
  290. * ```javascript
  291. * var divs = document.getElmentByTagNames( "div" );
  292. *
  293. * //output: 0: DIV, 1: DIV ...
  294. * UE.utils.each( divs, funciton ( value, key ) {
  295. *
  296. * console.log( key + ":" + value.tagName );
  297. *
  298. * } );
  299. * ```
  300. */
  301. each : function(obj, iterator, context) {
  302. if (obj == null) return;
  303. if (obj.length === +obj.length) {
  304. for (var i = 0, l = obj.length; i < l; i++) {
  305. if(iterator.call(context, obj[i], i, obj) === false)
  306. return false;
  307. }
  308. } else {
  309. for (var key in obj) {
  310. if (obj.hasOwnProperty(key)) {
  311. if(iterator.call(context, obj[key], key, obj) === false)
  312. return false;
  313. }
  314. }
  315. }
  316. },
  317. /**
  318. * 以给定对象作为原型创建一个新对象
  319. * @method makeInstance
  320. * @param { Object } protoObject 该对象将作为新创建对象的原型
  321. * @return { Object } 新的对象, 该对象的原型是给定的protoObject对象
  322. * @example
  323. * ```javascript
  324. *
  325. * var protoObject = { sayHello: function () { console.log('Hello UEditor!'); } };
  326. *
  327. * var newObject = UE.utils.makeInstance( protoObject );
  328. * //output: Hello UEditor!
  329. * newObject.sayHello();
  330. * ```
  331. */
  332. makeInstance:function (obj) {
  333. var noop = new Function();
  334. noop.prototype = obj;
  335. obj = new noop;
  336. noop.prototype = null;
  337. return obj;
  338. },
  339. /**
  340. * 将source对象中的属性扩展到target对象上
  341. * @method extend
  342. * @remind 该方法将强制把source对象上的属性复制到target对象上
  343. * @see UE.utils.extend(Object,Object,Boolean)
  344. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  345. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  346. * @return { Object } 返回target对象
  347. * @example
  348. * ```javascript
  349. *
  350. * var target = { name: 'target', sex: 1 },
  351. * source = { name: 'source', age: 17 };
  352. *
  353. * UE.utils.extend( target, source );
  354. *
  355. * //output: { name: 'source', sex: 1, age: 17 }
  356. * console.log( target );
  357. *
  358. * ```
  359. */
  360. /**
  361. * 将source对象中的属性扩展到target对象上, 根据指定的isKeepTarget值决定是否保留目标对象中与
  362. * 源对象属性名相同的属性值。
  363. * @method extend
  364. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  365. * @param { Object } source 源对象, 该对象的属性会被附加到target对象上
  366. * @param { Boolean } isKeepTarget 是否保留目标对象中与源对象中属性名相同的属性
  367. * @return { Object } 返回target对象
  368. * @example
  369. * ```javascript
  370. *
  371. * var target = { name: 'target', sex: 1 },
  372. * source = { name: 'source', age: 17 };
  373. *
  374. * UE.utils.extend( target, source, true );
  375. *
  376. * //output: { name: 'target', sex: 1, age: 17 }
  377. * console.log( target );
  378. *
  379. * ```
  380. */
  381. extend:function (t, s, b) {
  382. if (s) {
  383. for (var k in s) {
  384. if (!b || !t.hasOwnProperty(k)) {
  385. t[k] = s[k];
  386. }
  387. }
  388. }
  389. return t;
  390. },
  391. /**
  392. * 将给定的多个对象的属性复制到目标对象target上
  393. * @method extend2
  394. * @remind 该方法将强制把源对象上的属性复制到target对象上
  395. * @remind 该方法支持两个及以上的参数, 从第二个参数开始, 其属性都会被复制到第一个参数上。 如果遇到同名的属性,
  396. * 将会覆盖掉之前的值。
  397. * @param { Object } target 目标对象, 新的属性将附加到该对象上
  398. * @param { Object... } source 源对象, 支持多个对象, 该对象的属性会被附加到target对象上
  399. * @return { Object } 返回target对象
  400. * @example
  401. * ```javascript
  402. *
  403. * var target = {},
  404. * source1 = { name: 'source', age: 17 },
  405. * source2 = { title: 'dev' };
  406. *
  407. * UE.utils.extend2( target, source1, source2 );
  408. *
  409. * //output: { name: 'source', age: 17, title: 'dev' }
  410. * console.log( target );
  411. *
  412. * ```
  413. */
  414. extend2:function (t) {
  415. var a = arguments;
  416. for (var i = 1; i < a.length; i++) {
  417. var x = a[i];
  418. for (var k in x) {
  419. if (!t.hasOwnProperty(k)) {
  420. t[k] = x[k];
  421. }
  422. }
  423. }
  424. return t;
  425. },
  426. /**
  427. * 模拟继承机制, 使得subClass继承自superClass
  428. * @method inherits
  429. * @param { Object } subClass 子类对象
  430. * @param { Object } superClass 超类对象
  431. * @warning 该方法只能让subClass继承超类的原型, subClass对象自身的属性和方法不会被继承
  432. * @return { Object } 继承superClass后的子类对象
  433. * @example
  434. * ```javascript
  435. * function SuperClass(){
  436. * this.name = "小李";
  437. * }
  438. *
  439. * SuperClass.prototype = {
  440. * hello:function(str){
  441. * console.log(this.name + str);
  442. * }
  443. * }
  444. *
  445. * function SubClass(){
  446. * this.name = "小张";
  447. * }
  448. *
  449. * UE.utils.inherits(SubClass,SuperClass);
  450. *
  451. * var sub = new SubClass();
  452. * //output: '小张早上好!
  453. * sub.hello("早上好!");
  454. * ```
  455. */
  456. inherits:function (subClass, superClass) {
  457. var oldP = subClass.prototype,
  458. newP = utils.makeInstance(superClass.prototype);
  459. utils.extend(newP, oldP, true);
  460. subClass.prototype = newP;
  461. return (newP.constructor = subClass);
  462. },
  463. /**
  464. * 用指定的context对象作为函数fn的上下文
  465. * @method bind
  466. * @param { Function } fn 需要绑定上下文的函数对象
  467. * @param { Object } content 函数fn新的上下文对象
  468. * @return { Function } 一个新的函数, 该函数作为原始函数fn的代理, 将完成fn的上下文调换工作。
  469. * @example
  470. * ```javascript
  471. *
  472. * var name = 'window',
  473. * newTest = null;
  474. *
  475. * function test () {
  476. * console.log( this.name );
  477. * }
  478. *
  479. * newTest = UE.utils.bind( test, { name: 'object' } );
  480. *
  481. * //output: object
  482. * newTest();
  483. *
  484. * //output: window
  485. * test();
  486. *
  487. * ```
  488. */
  489. bind:function (fn, context) {
  490. return function () {
  491. return fn.apply(context, arguments);
  492. };
  493. },
  494. /**
  495. * 创建延迟指定时间后执行的函数fn
  496. * @method defer
  497. * @param { Function } fn 需要延迟执行的函数对象
  498. * @param { int } delay 延迟的时间, 单位是毫秒
  499. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  500. * 而不能保证刚好到达延迟时间时执行。
  501. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  502. * @example
  503. * ```javascript
  504. * var start = 0;
  505. *
  506. * function test(){
  507. * console.log( new Date() - start );
  508. * }
  509. *
  510. * var testDefer = UE.utils.defer( test, 1000 );
  511. * //
  512. * start = new Date();
  513. * //output: (大约在1000毫秒之后输出) 1000
  514. * testDefer();
  515. * ```
  516. */
  517. /**
  518. * 创建延迟指定时间后执行的函数fn, 如果在延迟时间内再次执行该方法, 将会根据指定的exclusion的值,
  519. * 决定是否取消前一次函数的执行, 如果exclusion的值为true, 则取消执行,反之,将继续执行前一个方法。
  520. * @method defer
  521. * @param { Function } fn 需要延迟执行的函数对象
  522. * @param { int } delay 延迟的时间, 单位是毫秒
  523. * @param { Boolean } exclusion 如果在延迟时间内再次执行该函数,该值将决定是否取消执行前一次函数的执行,
  524. * 值为true表示取消执行, 反之则将在执行前一次函数之后才执行本次函数调用。
  525. * @warning 该方法的时间控制是不精确的,仅仅只能保证函数的执行是在给定的时间之后,
  526. * 而不能保证刚好到达延迟时间时执行。
  527. * @return { Function } 目标函数fn的代理函数, 只有执行该函数才能起到延时效果
  528. * @example
  529. * ```javascript
  530. *
  531. * function test(){
  532. * console.log(1);
  533. * }
  534. *
  535. * var testDefer = UE.utils.defer( test, 1000, true );
  536. *
  537. * //output: (两次调用仅有一次输出) 1
  538. * testDefer();
  539. * testDefer();
  540. * ```
  541. */
  542. defer:function (fn, delay, exclusion) {
  543. var timerID;
  544. return function () {
  545. if (exclusion) {
  546. clearTimeout(timerID);
  547. }
  548. timerID = setTimeout(fn, delay);
  549. };
  550. },
  551. /**
  552. * 获取元素item在数组array中首次出现的位置, 如果未找到item, 则返回-1
  553. * @method indexOf
  554. * @remind 该方法的匹配过程使用的是恒等“===”
  555. * @param { Array } array 需要查找的数组对象
  556. * @param { * } item 需要在目标数组中查找的值
  557. * @return { int } 返回item在目标数组array中首次出现的位置, 如果在数组中未找到item, 则返回-1
  558. * @example
  559. * ```javascript
  560. * var item = 1,
  561. * arr = [ 3, 4, 6, 8, 1, 1, 2 ];
  562. *
  563. * //output: 4
  564. * console.log( UE.utils.indexOf( arr, item ) );
  565. * ```
  566. */
  567. /**
  568. * 获取元素item数组array中首次出现的位置, 如果未找到item, 则返回-1。通过start的值可以指定搜索的起始位置。
  569. * @method indexOf
  570. * @remind 该方法的匹配过程使用的是恒等“===”
  571. * @param { Array } array 需要查找的数组对象
  572. * @param { * } item 需要在目标数组中查找的值
  573. * @param { int } start 搜索的起始位置
  574. * @return { int } 返回item在目标数组array中的start位置之后首次出现的位置, 如果在数组中未找到item, 则返回-1
  575. * @example
  576. * ```javascript
  577. * var item = 1,
  578. * arr = [ 3, 4, 6, 8, 1, 2, 8, 3, 2, 1, 1, 4 ];
  579. *
  580. * //output: 9
  581. * console.log( UE.utils.indexOf( arr, item, 5 ) );
  582. * ```
  583. */
  584. indexOf:function (array, item, start) {
  585. var index = -1;
  586. start = this.isNumber(start) ? start : 0;
  587. this.each(array, function (v, i) {
  588. if (i >= start && v === item) {
  589. index = i;
  590. return false;
  591. }
  592. });
  593. return index;
  594. },
  595. /**
  596. * 移除数组array中所有的元素item
  597. * @method removeItem
  598. * @param { Array } array 要移除元素的目标数组
  599. * @param { * } item 将要被移除的元素
  600. * @remind 该方法的匹配过程使用的是恒等“===”
  601. * @example
  602. * ```javascript
  603. * var arr = [ 4, 5, 7, 1, 3, 4, 6 ];
  604. *
  605. * UE.utils.removeItem( arr, 4 );
  606. * //output: [ 5, 7, 1, 3, 6 ]
  607. * console.log( arr );
  608. *
  609. * ```
  610. */
  611. removeItem:function (array, item) {
  612. for (var i = 0, l = array.length; i < l; i++) {
  613. if (array[i] === item) {
  614. array.splice(i, 1);
  615. i--;
  616. }
  617. }
  618. },
  619. /**
  620. * 删除字符串str的首尾空格
  621. * @method trim
  622. * @param { String } str 需要删除首尾空格的字符串
  623. * @return { String } 删除了首尾的空格后的字符串
  624. * @example
  625. * ```javascript
  626. *
  627. * var str = " UEdtior ";
  628. *
  629. * //output: 9
  630. * console.log( str.length );
  631. *
  632. * //output: 7
  633. * console.log( UE.utils.trim( " UEdtior " ).length );
  634. *
  635. * //output: 9
  636. * console.log( str.length );
  637. *
  638. * ```
  639. */
  640. trim:function (str) {
  641. return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, '');
  642. },
  643. /**
  644. * 将字符串str以','分隔成数组后,将该数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  645. * @method listToMap
  646. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  647. * @param { String } str 该字符串将被以','分割为数组, 然后进行转化
  648. * @return { Object } 转化之后的hash对象
  649. * @example
  650. * ```javascript
  651. *
  652. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  653. * console.log( UE.utils.listToMap( 'UEdtior,Hello' ) );
  654. *
  655. * ```
  656. */
  657. /**
  658. * 将字符串数组转换成哈希对象, 其生成的hash对象的key为数组中的元素, value为1
  659. * @method listToMap
  660. * @warning 该方法在生成的hash对象中,会为每一个key同时生成一个另一个全大写的key。
  661. * @param { Array } arr 字符串数组
  662. * @return { Object } 转化之后的hash对象
  663. * @example
  664. * ```javascript
  665. *
  666. * //output: Object {UEdtior: 1, UEDTIOR: 1, Hello: 1, HELLO: 1}
  667. * console.log( UE.utils.listToMap( [ 'UEdtior', 'Hello' ] ) );
  668. *
  669. * ```
  670. */
  671. listToMap:function (list) {
  672. if (!list)return {};
  673. list = utils.isArray(list) ? list : list.split(',');
  674. for (var i = 0, ci, obj = {}; ci = list[i++];) {
  675. obj[ci.toUpperCase()] = obj[ci] = 1;
  676. }
  677. return obj;
  678. },
  679. /**
  680. * 将str中的html符号转义,将转义“',&,<,",>”五个字符
  681. * @method unhtml
  682. * @param { String } str 需要转义的字符串
  683. * @return { String } 转义后的字符串
  684. * @example
  685. * ```javascript
  686. * var html = '<body>&</body>';
  687. *
  688. * //output: &lt;body&gt;&amp;&lt;/body&gt;
  689. * console.log( UE.utils.unhtml( html ) );
  690. *
  691. * ```
  692. */
  693. unhtml:function (str, reg) {
  694. return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp|#\d+);)?/g, function (a, b) {
  695. if (b) {
  696. return a;
  697. } else {
  698. return {
  699. '<':'&lt;',
  700. '&':'&amp;',
  701. '"':'&quot;',
  702. '>':'&gt;',
  703. "'":'&#39;'
  704. }[a]
  705. }
  706. }) : '';
  707. },
  708. /**
  709. * 将url中的html字符转义, 仅转义 ', ", <, > 四个字符
  710. * @param { String } str 需要转义的字符串
  711. * @param { RegExp } reg 自定义的正则
  712. * @return { String } 转义后的字符串
  713. */
  714. unhtmlForUrl:function (str, reg) {
  715. return str ? str.replace(reg || /[<">']/g, function (a) {
  716. return {
  717. '<':'&lt;',
  718. '&':'&amp;',
  719. '"':'&quot;',
  720. '>':'&gt;',
  721. "'":'&#39;'
  722. }[a]
  723. }) : '';
  724. },
  725. /**
  726. * 将str中的转义字符还原成html字符
  727. * @see UE.utils.unhtml(String);
  728. * @method html
  729. * @param { String } str 需要逆转义的字符串
  730. * @return { String } 逆转义后的字符串
  731. * @example
  732. * ```javascript
  733. *
  734. * var str = '&lt;body&gt;&amp;&lt;/body&gt;';
  735. *
  736. * //output: <body>&</body>
  737. * console.log( UE.utils.html( str ) );
  738. *
  739. * ```
  740. */
  741. html:function (str) {
  742. return str ? str.replace(/&((g|l|quo)t|amp|#39|nbsp);/g, function (m) {
  743. return {
  744. '&lt;':'<',
  745. '&amp;':'&',
  746. '&quot;':'"',
  747. '&gt;':'>',
  748. '&#39;':"'",
  749. '&nbsp;':' '
  750. }[m]
  751. }) : '';
  752. },
  753. /**
  754. * 将css样式转换为驼峰的形式
  755. * @method cssStyleToDomStyle
  756. * @param { String } cssName 需要转换的css样式名
  757. * @return { String } 转换成驼峰形式后的css样式名
  758. * @example
  759. * ```javascript
  760. *
  761. * var str = 'border-top';
  762. *
  763. * //output: borderTop
  764. * console.log( UE.utils.cssStyleToDomStyle( str ) );
  765. *
  766. * ```
  767. */
  768. cssStyleToDomStyle:function () {
  769. var test = document.createElement('div').style,
  770. cache = {
  771. 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float'
  772. };
  773. return function (cssName) {
  774. return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) {
  775. return match.charAt(1).toUpperCase();
  776. }));
  777. };
  778. }(),
  779. /**
  780. * 动态加载文件到doc中
  781. * @method loadFile
  782. * @param { DomDocument } document 需要加载资源文件的文档对象
  783. * @param { Object } options 加载资源文件的属性集合, 取值请参考代码示例
  784. * @example
  785. * ```javascript
  786. *
  787. * UE.utils.loadFile( document, {
  788. * src:"test.js",
  789. * tag:"script",
  790. * type:"text/javascript",
  791. * defer:"defer"
  792. * } );
  793. *
  794. * ```
  795. */
  796. /**
  797. * 动态加载文件到doc中,加载成功后执行的回调函数fn
  798. * @method loadFile
  799. * @param { DomDocument } document 需要加载资源文件的文档对象
  800. * @param { Object } options 加载资源文件的属性集合, 该集合支持的值是script标签和style标签支持的所有属性。
  801. * @param { Function } fn 资源文件加载成功之后执行的回调
  802. * @warning 对于在同一个文档中多次加载同一URL的文件, 该方法会在第一次加载之后缓存该请求,
  803. * 在此之后的所有同一URL的请求, 将会直接触发回调。
  804. * @example
  805. * ```javascript
  806. *
  807. * UE.utils.loadFile( document, {
  808. * src:"test.js",
  809. * tag:"script",
  810. * type:"text/javascript",
  811. * defer:"defer"
  812. * }, function () {
  813. * console.log('加载成功');
  814. * } );
  815. *
  816. * ```
  817. */
  818. loadFile:function () {
  819. var tmpList = [];
  820. function getItem(doc, obj) {
  821. try {
  822. for (var i = 0, ci; ci = tmpList[i++];) {
  823. if (ci.doc === doc && ci.url == (obj.src || obj.href)) {
  824. return ci;
  825. }
  826. }
  827. } catch (e) {
  828. return null;
  829. }
  830. }
  831. return function (doc, obj, fn) {
  832. var item = getItem(doc, obj);
  833. if (item) {
  834. if (item.ready) {
  835. fn && fn();
  836. } else {
  837. item.funs.push(fn)
  838. }
  839. return;
  840. }
  841. tmpList.push({
  842. doc:doc,
  843. url:obj.src || obj.href,
  844. funs:[fn]
  845. });
  846. if (!doc.body) {
  847. var html = [];
  848. for (var p in obj) {
  849. if (p == 'tag')continue;
  850. html.push(p + '="' + obj[p] + '"')
  851. }
  852. doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>');
  853. return;
  854. }
  855. if (obj.id && doc.getElementById(obj.id)) {
  856. return;
  857. }
  858. var element = doc.createElement(obj.tag);
  859. delete obj.tag;
  860. for (var p in obj) {
  861. element.setAttribute(p, obj[p]);
  862. }
  863. element.onload = element.onreadystatechange = function () {
  864. if (!this.readyState || /loaded|complete/.test(this.readyState)) {
  865. item = getItem(doc, obj);
  866. if (item.funs.length > 0) {
  867. item.ready = 1;
  868. for (var fi; fi = item.funs.pop();) {
  869. fi();
  870. }
  871. }
  872. element.onload = element.onreadystatechange = null;
  873. }
  874. };
  875. element.onerror = function () {
  876. throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ')
  877. };
  878. doc.getElementsByTagName("head")[0].appendChild(element);
  879. }
  880. }(),
  881. /**
  882. * 判断obj对象是否为空
  883. * @method isEmptyObject
  884. * @param { * } obj 需要判断的对象
  885. * @remind 如果判断的对象是NULL, 将直接返回true, 如果是数组且为空, 返回true, 如果是字符串, 且字符串为空,
  886. * 返回true, 如果是普通对象, 且该对象没有任何实例属性, 返回true
  887. * @return { Boolean } 对象是否为空
  888. * @example
  889. * ```javascript
  890. *
  891. * //output: true
  892. * console.log( UE.utils.isEmptyObject( {} ) );
  893. *
  894. * //output: true
  895. * console.log( UE.utils.isEmptyObject( [] ) );
  896. *
  897. * //output: true
  898. * console.log( UE.utils.isEmptyObject( "" ) );
  899. *
  900. * //output: false
  901. * console.log( UE.utils.isEmptyObject( { key: 1 } ) );
  902. *
  903. * //output: false
  904. * console.log( UE.utils.isEmptyObject( [1] ) );
  905. *
  906. * //output: false
  907. * console.log( UE.utils.isEmptyObject( "1" ) );
  908. *
  909. * ```
  910. */
  911. isEmptyObject:function (obj) {
  912. if (obj == null) return true;
  913. if (this.isArray(obj) || this.isString(obj)) return obj.length === 0;
  914. for (var key in obj) if (obj.hasOwnProperty(key)) return false;
  915. return true;
  916. },
  917. /**
  918. * 把rgb格式的颜色值转换成16进制格式
  919. * @method fixColor
  920. * @param { String } rgb格式的颜色值
  921. * @param { String }
  922. * @example
  923. * rgb(255,255,255) => "#ffffff"
  924. */
  925. fixColor:function (name, value) {
  926. if (/color/i.test(name) && /rgba?/.test(value)) {
  927. var array = value.split(",");
  928. if (array.length > 3)
  929. return "";
  930. value = "#";
  931. for (var i = 0, color; color = array[i++];) {
  932. color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16);
  933. value += color.length == 1 ? "0" + color : color;
  934. }
  935. value = value.toUpperCase();
  936. }
  937. return value;
  938. },
  939. /**
  940. * 只针对border,padding,margin做了处理,因为性能问题
  941. * @public
  942. * @function
  943. * @param {String} val style字符串
  944. */
  945. optCss:function (val) {
  946. var padding, margin, border;
  947. val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) {
  948. if (val.split(' ').length == 1) {
  949. switch (key) {
  950. case 'padding':
  951. !padding && (padding = {});
  952. padding[name] = val;
  953. return '';
  954. case 'margin':
  955. !margin && (margin = {});
  956. margin[name] = val;
  957. return '';
  958. case 'border':
  959. return val == 'initial' ? '' : str;
  960. }
  961. }
  962. return str;
  963. });
  964. function opt(obj, name) {
  965. if (!obj) {
  966. return '';
  967. }
  968. var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = '';
  969. if (!t || !l || !b || !r) {
  970. for (var p in obj) {
  971. val += ';' + name + '-' + p + ':' + obj[p] + ';';
  972. }
  973. } else {
  974. val += ';' + name + ':' +
  975. (t == b && b == l && l == r ? t :
  976. t == b && l == r ? (t + ' ' + l) :
  977. l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';'
  978. }
  979. return val;
  980. }
  981. val += opt(padding, 'padding') + opt(margin, 'margin');
  982. return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';')
  983. .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) {
  984. return b ? b + ";;" : ';'
  985. });
  986. },
  987. /**
  988. * 克隆对象
  989. * @method clone
  990. * @param { Object } source 源对象
  991. * @return { Object } source的一个副本
  992. */
  993. /**
  994. * 深度克隆对象,将source的属性克隆到target对象, 会覆盖target重名的属性。
  995. * @method clone
  996. * @param { Object } source 源对象
  997. * @param { Object } target 目标对象
  998. * @return { Object } 附加了source对象所有属性的target对象
  999. */
  1000. clone:function (source, target) {
  1001. var tmp;
  1002. target = target || {};
  1003. for (var i in source) {
  1004. if (source.hasOwnProperty(i)) {
  1005. tmp = source[i];
  1006. if (typeof tmp == 'object') {
  1007. target[i] = utils.isArray(tmp) ? [] : {};
  1008. utils.clone(source[i], target[i])
  1009. } else {
  1010. target[i] = tmp;
  1011. }
  1012. }
  1013. }
  1014. return target;
  1015. },
  1016. /**
  1017. * 把cm/pt为单位的值转换为px为单位的值
  1018. * @method transUnitToPx
  1019. * @param { String } 待转换的带单位的字符串
  1020. * @return { String } 转换为px为计量单位的值的字符串
  1021. * @example
  1022. * ```javascript
  1023. *
  1024. * //output: 500px
  1025. * console.log( UE.utils.transUnitToPx( '20cm' ) );
  1026. *
  1027. * //output: 27px
  1028. * console.log( UE.utils.transUnitToPx( '20pt' ) );
  1029. *
  1030. * ```
  1031. */
  1032. transUnitToPx:function (val) {
  1033. if (!/(pt|cm)/.test(val)) {
  1034. return val
  1035. }
  1036. var unit;
  1037. val.replace(/([\d.]+)(\w+)/, function (str, v, u) {
  1038. val = v;
  1039. unit = u;
  1040. });
  1041. switch (unit) {
  1042. case 'cm':
  1043. val = parseFloat(val) * 25;
  1044. break;
  1045. case 'pt':
  1046. val = Math.round(parseFloat(val) * 96 / 72);
  1047. }
  1048. return val + (val ? 'px' : '');
  1049. },
  1050. /**
  1051. * 在dom树ready之后执行给定的回调函数
  1052. * @method domReady
  1053. * @remind 如果在执行该方法的时候, dom树已经ready, 那么回调函数将立刻执行
  1054. * @param { Function } fn dom树ready之后的回调函数
  1055. * @example
  1056. * ```javascript
  1057. *
  1058. * UE.utils.domReady( function () {
  1059. *
  1060. * console.log('123');
  1061. *
  1062. * } );
  1063. *
  1064. * ```
  1065. */
  1066. domReady:function () {
  1067. var fnArr = [];
  1068. function doReady(doc) {
  1069. //确保onready只执行一次
  1070. doc.isReady = true;
  1071. for (var ci; ci = fnArr.pop(); ci()) {
  1072. }
  1073. }
  1074. return function (onready, win) {
  1075. win = win || window;
  1076. var doc = win.document;
  1077. onready && fnArr.push(onready);
  1078. if (doc.readyState === "complete") {
  1079. doReady(doc);
  1080. } else {
  1081. doc.isReady && doReady(doc);
  1082. if (browser.ie && browser.version != 11) {
  1083. (function () {
  1084. if (doc.isReady) return;
  1085. try {
  1086. doc.documentElement.doScroll("left");
  1087. } catch (error) {
  1088. setTimeout(arguments.callee, 0);
  1089. return;
  1090. }
  1091. doReady(doc);
  1092. })();
  1093. win.attachEvent('onload', function () {
  1094. doReady(doc)
  1095. });
  1096. } else {
  1097. doc.addEventListener("DOMContentLoaded", function () {
  1098. doc.removeEventListener("DOMContentLoaded", arguments.callee, false);
  1099. doReady(doc);
  1100. }, false);
  1101. win.addEventListener('load', function () {
  1102. doReady(doc)
  1103. }, false);
  1104. }
  1105. }
  1106. }
  1107. }(),
  1108. /**
  1109. * 动态添加css样式
  1110. * @method cssRule
  1111. * @param { String } 节点名称
  1112. * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上'])
  1113. * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色
  1114. * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc}
  1115. * @grammar UE.utils.cssRule('body',document) => 返回指定key的样式,并且指定是哪个document
  1116. * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色
  1117. */
  1118. cssRule:browser.ie && browser.version != 11 ? function (key, style, doc) {
  1119. var indexList, index;
  1120. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1121. //获取样式
  1122. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1123. indexList = doc.indexList || (doc.indexList = {});
  1124. index = indexList[key];
  1125. if(index !== undefined){
  1126. return doc.styleSheets[index].cssText
  1127. }
  1128. return undefined;
  1129. }
  1130. doc = doc || document;
  1131. indexList = doc.indexList || (doc.indexList = {});
  1132. index = indexList[key];
  1133. //清除样式
  1134. if(style === ''){
  1135. if(index!== undefined){
  1136. doc.styleSheets[index].cssText = '';
  1137. delete indexList[key];
  1138. return true
  1139. }
  1140. return false;
  1141. }
  1142. //添加样式
  1143. if(index!== undefined){
  1144. sheetStyle = doc.styleSheets[index];
  1145. }else{
  1146. sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length);
  1147. indexList[key] = index;
  1148. }
  1149. sheetStyle.cssText = style;
  1150. }: function (key, style, doc) {
  1151. var head, node;
  1152. if(style === undefined || style && style.nodeType && style.nodeType == 9){
  1153. //获取样式
  1154. doc = style && style.nodeType && style.nodeType == 9 ? style : (doc || document);
  1155. node = doc.getElementById(key);
  1156. return node ? node.innerHTML : undefined;
  1157. }
  1158. doc = doc || document;
  1159. node = doc.getElementById(key);
  1160. //清除样式
  1161. if(style === ''){
  1162. if(node){
  1163. node.parentNode.removeChild(node);
  1164. return true
  1165. }
  1166. return false;
  1167. }
  1168. //添加样式
  1169. if(node){
  1170. node.innerHTML = style;
  1171. }else{
  1172. node = doc.createElement('style');
  1173. node.id = key;
  1174. node.innerHTML = style;
  1175. doc.getElementsByTagName('head')[0].appendChild(node);
  1176. }
  1177. },
  1178. sort:function(array,compareFn){
  1179. compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);};
  1180. for(var i= 0,len = array.length; i<len; i++){
  1181. for(var j = i,length = array.length; j<length; j++){
  1182. if(compareFn(array[i], array[j]) > 0){
  1183. var t = array[i];
  1184. array[i] = array[j];
  1185. array[j] = t;
  1186. }
  1187. }
  1188. }
  1189. return array;
  1190. },
  1191. serializeParam:function (json) {
  1192. var strArr = [];
  1193. for (var i in json) {
  1194. //忽略默认的几个参数
  1195. if(i=="method" || i=="timeout" || i=="async") continue;
  1196. //传递过来的对象和函数不在提交之列
  1197. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  1198. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  1199. } else if (utils.isArray(json[i])) {
  1200. //支持传数组内容
  1201. for(var j = 0; j < json[i].length; j++) {
  1202. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  1203. }
  1204. }
  1205. }
  1206. return strArr.join("&");
  1207. },
  1208. formatUrl:function (url) {
  1209. var u = url.replace(/&&/g, '&');
  1210. u = u.replace(/\?&/g, '?');
  1211. u = u.replace(/&$/g, '');
  1212. u = u.replace(/&#/g, '#');
  1213. u = u.replace(/&+/g, '&');
  1214. return u;
  1215. },
  1216. isCrossDomainUrl:function (url) {
  1217. var a = document.createElement('a');
  1218. a.href = url;
  1219. if (browser.ie) {
  1220. a.href = a.href;
  1221. }
  1222. return !(a.protocol == location.protocol && a.hostname == location.hostname &&
  1223. (a.port == location.port || (a.port == '80' && location.port == '') || (a.port == '' && location.port == '80')));
  1224. },
  1225. clearEmptyAttrs : function(obj){
  1226. for(var p in obj){
  1227. if(obj[p] === ''){
  1228. delete obj[p]
  1229. }
  1230. }
  1231. return obj;
  1232. },
  1233. str2json : function(s){
  1234. if (!utils.isString(s)) return null;
  1235. if (window.JSON) {
  1236. return JSON.parse(s);
  1237. } else {
  1238. return (new Function("return " + utils.trim(s || '')))();
  1239. }
  1240. },
  1241. json2str : (function(){
  1242. if (window.JSON) {
  1243. return JSON.stringify;
  1244. } else {
  1245. var escapeMap = {
  1246. "\b": '\\b',
  1247. "\t": '\\t',
  1248. "\n": '\\n',
  1249. "\f": '\\f',
  1250. "\r": '\\r',
  1251. '"' : '\\"',
  1252. "\\": '\\\\'
  1253. };
  1254. function encodeString(source) {
  1255. if (/["\\\x00-\x1f]/.test(source)) {
  1256. source = source.replace(
  1257. /["\\\x00-\x1f]/g,
  1258. function (match) {
  1259. var c = escapeMap[match];
  1260. if (c) {
  1261. return c;
  1262. }
  1263. c = match.charCodeAt();
  1264. return "\\u00"
  1265. + Math.floor(c / 16).toString(16)
  1266. + (c % 16).toString(16);
  1267. });
  1268. }
  1269. return '"' + source + '"';
  1270. }
  1271. function encodeArray(source) {
  1272. var result = ["["],
  1273. l = source.length,
  1274. preComma, i, item;
  1275. for (i = 0; i < l; i++) {
  1276. item = source[i];
  1277. switch (typeof item) {
  1278. case "undefined":
  1279. case "function":
  1280. case "unknown":
  1281. break;
  1282. default:
  1283. if(preComma) {
  1284. result.push(',');
  1285. }
  1286. result.push(utils.json2str(item));
  1287. preComma = 1;
  1288. }
  1289. }
  1290. result.push("]");
  1291. return result.join("");
  1292. }
  1293. function pad(source) {
  1294. return source < 10 ? '0' + source : source;
  1295. }
  1296. function encodeDate(source){
  1297. return '"' + source.getFullYear() + "-"
  1298. + pad(source.getMonth() + 1) + "-"
  1299. + pad(source.getDate()) + "T"
  1300. + pad(source.getHours()) + ":"
  1301. + pad(source.getMinutes()) + ":"
  1302. + pad(source.getSeconds()) + '"';
  1303. }
  1304. return function (value) {
  1305. switch (typeof value) {
  1306. case 'undefined':
  1307. return 'undefined';
  1308. case 'number':
  1309. return isFinite(value) ? String(value) : "null";
  1310. case 'string':
  1311. return encodeString(value);
  1312. case 'boolean':
  1313. return String(value);
  1314. default:
  1315. if (value === null) {
  1316. return 'null';
  1317. } else if (utils.isArray(value)) {
  1318. return encodeArray(value);
  1319. } else if (utils.isDate(value)) {
  1320. return encodeDate(value);
  1321. } else {
  1322. var result = ['{'],
  1323. encode = utils.json2str,
  1324. preComma,
  1325. item;
  1326. for (var key in value) {
  1327. if (Object.prototype.hasOwnProperty.call(value, key)) {
  1328. item = value[key];
  1329. switch (typeof item) {
  1330. case 'undefined':
  1331. case 'unknown':
  1332. case 'function':
  1333. break;
  1334. default:
  1335. if (preComma) {
  1336. result.push(',');
  1337. }
  1338. preComma = 1;
  1339. result.push(encode(key) + ':' + encode(item));
  1340. }
  1341. }
  1342. }
  1343. result.push('}');
  1344. return result.join('');
  1345. }
  1346. }
  1347. };
  1348. }
  1349. })()
  1350. };
  1351. /**
  1352. * 判断给定的对象是否是字符串
  1353. * @method isString
  1354. * @param { * } object 需要判断的对象
  1355. * @return { Boolean } 给定的对象是否是字符串
  1356. */
  1357. /**
  1358. * 判断给定的对象是否是数组
  1359. * @method isArray
  1360. * @param { * } object 需要判断的对象
  1361. * @return { Boolean } 给定的对象是否是数组
  1362. */
  1363. /**
  1364. * 判断给定的对象是否是一个Function
  1365. * @method isFunction
  1366. * @param { * } object 需要判断的对象
  1367. * @return { Boolean } 给定的对象是否是Function
  1368. */
  1369. /**
  1370. * 判断给定的对象是否是Number
  1371. * @method isNumber
  1372. * @param { * } object 需要判断的对象
  1373. * @return { Boolean } 给定的对象是否是Number
  1374. */
  1375. /**
  1376. * 判断给定的对象是否是一个正则表达式
  1377. * @method isRegExp
  1378. * @param { * } object 需要判断的对象
  1379. * @return { Boolean } 给定的对象是否是正则表达式
  1380. */
  1381. /**
  1382. * 判断给定的对象是否是一个普通对象
  1383. * @method isObject
  1384. * @param { * } object 需要判断的对象
  1385. * @return { Boolean } 给定的对象是否是普通对象
  1386. */
  1387. utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object', 'Date'], function (v) {
  1388. UE.utils['is' + v] = function (obj) {
  1389. return Object.prototype.toString.apply(obj) == '[object ' + v + ']';
  1390. }
  1391. });
  1392. // core/EventBase.js
  1393. /**
  1394. * UE采用的事件基类
  1395. * @file
  1396. * @module UE
  1397. * @class EventBase
  1398. * @since 1.2.6.1
  1399. */
  1400. /**
  1401. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  1402. * @unfile
  1403. * @module UE
  1404. */
  1405. /**
  1406. * UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。
  1407. * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。
  1408. * @unfile
  1409. * @module UE
  1410. * @class EventBase
  1411. */
  1412. /**
  1413. * 通过此构造器,子类可以继承EventBase获取事件监听的方法
  1414. * @constructor
  1415. * @example
  1416. * ```javascript
  1417. * UE.EventBase.call(editor);
  1418. * ```
  1419. */
  1420. var EventBase = UE.EventBase = function () {};
  1421. EventBase.prototype = {
  1422. /**
  1423. * 注册事件监听器
  1424. * @method addListener
  1425. * @param { String } types 监听的事件名称,同时监听多个事件使用空格分隔
  1426. * @param { Function } fn 监听的事件被触发时,会执行该回调函数
  1427. * @waining 事件被触发时,监听的函数假如返回的值恒等于true,回调函数的队列中后面的函数将不执行
  1428. * @example
  1429. * ```javascript
  1430. * editor.addListener('selectionchange',function(){
  1431. * console.log("选区已经变化!");
  1432. * })
  1433. * editor.addListener('beforegetcontent aftergetcontent',function(type){
  1434. * if(type == 'beforegetcontent'){
  1435. * //do something
  1436. * }else{
  1437. * //do something
  1438. * }
  1439. * console.log(this.getContent) // this是注册的事件的编辑器实例
  1440. * })
  1441. * ```
  1442. * @see UE.EventBase:fireEvent(String)
  1443. */
  1444. addListener:function (types, listener) {
  1445. types = utils.trim(types).split(/\s+/);
  1446. for (var i = 0, ti; ti = types[i++];) {
  1447. getListener(this, ti, true).push(listener);
  1448. }
  1449. },
  1450. on : function(types, listener){
  1451. return this.addListener(types,listener);
  1452. },
  1453. off : function(types, listener){
  1454. return this.removeListener(types, listener)
  1455. },
  1456. trigger:function(){
  1457. return this.fireEvent.apply(this,arguments);
  1458. },
  1459. /**
  1460. * 移除事件监听器
  1461. * @method removeListener
  1462. * @param { String } types 移除的事件名称,同时移除多个事件使用空格分隔
  1463. * @param { Function } fn 移除监听事件的函数引用
  1464. * @example
  1465. * ```javascript
  1466. * //changeCallback为方法体
  1467. * editor.removeListener("selectionchange",changeCallback);
  1468. * ```
  1469. */
  1470. removeListener:function (types, listener) {
  1471. types = utils.trim(types).split(/\s+/);
  1472. for (var i = 0, ti; ti = types[i++];) {
  1473. utils.removeItem(getListener(this, ti) || [], listener);
  1474. }
  1475. },
  1476. /**
  1477. * 触发事件
  1478. * @method fireEvent
  1479. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1480. * @remind 该方法会触发addListener
  1481. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1482. * @example
  1483. * ```javascript
  1484. * editor.fireEvent("selectionchange");
  1485. * ```
  1486. */
  1487. /**
  1488. * 触发事件
  1489. * @method fireEvent
  1490. * @param { String } types 触发的事件名称,同时触发多个事件使用空格分隔
  1491. * @param { *... } options 可选参数,可以传入一个或多个参数,会传给事件触发的回调函数
  1492. * @return { * } 返回触发事件的队列中,最后执行的回调函数的返回值
  1493. * @example
  1494. * ```javascript
  1495. *
  1496. * editor.addListener( "selectionchange", function ( type, arg1, arg2 ) {
  1497. *
  1498. * console.log( arg1 + " " + arg2 );
  1499. *
  1500. * } );
  1501. *
  1502. * //触发selectionchange事件, 会执行上面的事件监听器
  1503. * //output: Hello World
  1504. * editor.fireEvent("selectionchange", "Hello", "World");
  1505. * ```
  1506. */
  1507. fireEvent:function () {
  1508. var types = arguments[0];
  1509. types = utils.trim(types).split(' ');
  1510. for (var i = 0, ti; ti = types[i++];) {
  1511. var listeners = getListener(this, ti),
  1512. r, t, k;
  1513. if (listeners) {
  1514. k = listeners.length;
  1515. while (k--) {
  1516. if(!listeners[k])continue;
  1517. t = listeners[k].apply(this, arguments);
  1518. if(t === true){
  1519. return t;
  1520. }
  1521. if (t !== undefined) {
  1522. r = t;
  1523. }
  1524. }
  1525. }
  1526. if (t = this['on' + ti.toLowerCase()]) {
  1527. r = t.apply(this, arguments);
  1528. }
  1529. }
  1530. return r;
  1531. }
  1532. };
  1533. /**
  1534. * 获得对象所拥有监听类型的所有监听器
  1535. * @unfile
  1536. * @module UE
  1537. * @since 1.2.6.1
  1538. * @method getListener
  1539. * @public
  1540. * @param { Object } obj 查询监听器的对象
  1541. * @param { String } type 事件类型
  1542. * @param { Boolean } force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组
  1543. * @return { Array } 监听器数组
  1544. */
  1545. function getListener(obj, type, force) {
  1546. var allListeners;
  1547. type = type.toLowerCase();
  1548. return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) )
  1549. && ( allListeners[type] || force && ( allListeners[type] = [] ) ) );
  1550. }
  1551. // core/dtd.js
  1552. ///import editor.js
  1553. ///import core/dom/dom.js
  1554. ///import core/utils.js
  1555. /**
  1556. * dtd html语义化的体现类
  1557. * @constructor
  1558. * @namespace dtd
  1559. */
  1560. var dtd = dom.dtd = (function() {
  1561. function _( s ) {
  1562. for (var k in s) {
  1563. s[k.toUpperCase()] = s[k];
  1564. }
  1565. return s;
  1566. }
  1567. var X = utils.extend2;
  1568. var A = _({isindex:1,fieldset:1}),
  1569. B = _({input:1,button:1,select:1,textarea:1,label:1}),
  1570. C = X( _({a:1}), B ),
  1571. D = X( {iframe:1}, C ),
  1572. 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}),
  1573. F = _({ins:1,del:1,script:1,style:1}),
  1574. 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 ),
  1575. 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 ),
  1576. I = X( _({p:1}), H ),
  1577. J = X( _({iframe:1}), H, B ),
  1578. 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}),
  1579. L = X( _({a:0}), J ),//a不能被切开,所以把他
  1580. M = _({tr:1}),
  1581. N = _({'#':1}),
  1582. O = X( _({param:1}), K ),
  1583. P = X( _({form:1}), A, D, E, I ),
  1584. Q = _({li:1,ol:1,ul:1}),
  1585. R = _({style:1,script:1}),
  1586. S = _({base:1,link:1,meta:1,title:1}),
  1587. T = X( S, R ),
  1588. U = _({head:1,body:1}),
  1589. V = _({html:1});
  1590. 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}),
  1591. 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});
  1592. return _({
  1593. // $ 表示自定的属性
  1594. // body外的元素列表.
  1595. $nonBodyContent: X( V, U, S ),
  1596. //块结构元素列表
  1597. $block : block,
  1598. //内联元素列表
  1599. $inline : L,
  1600. $inlineWithA : X(_({a:1}),L),
  1601. $body : X( _({script:1,style:1}), block ),
  1602. $cdata : _({script:1,style:1}),
  1603. //自闭和元素
  1604. $empty : empty,
  1605. //不是自闭合,但不能让range选中里边
  1606. $nonChild : _({iframe:1,textarea:1}),
  1607. //列表元素列表
  1608. $listItem : _({dd:1,dt:1,li:1}),
  1609. //列表根元素列表
  1610. $list: _({ul:1,ol:1,dl:1}),
  1611. //不能认为是空的元素
  1612. $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}),
  1613. //如果没有子节点就可以删除的元素列表,像span,a
  1614. $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}),
  1615. $removeEmptyBlock : _({'p':1,'div':1}),
  1616. //在table元素里的元素列表
  1617. $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}),
  1618. //不转换的标签
  1619. $notTransContent : _({pre:1,script:1,style:1,textarea:1}),
  1620. html: U,
  1621. head: T,
  1622. style: N,
  1623. script: N,
  1624. body: P,
  1625. base: {},
  1626. link: {},
  1627. meta: {},
  1628. title: N,
  1629. col : {},
  1630. tr : _({td:1,th:1}),
  1631. img : {},
  1632. embed: {},
  1633. colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}),
  1634. noscript : P,
  1635. td : P,
  1636. br : {},
  1637. th : P,
  1638. center : P,
  1639. kbd : L,
  1640. button : X( I, E ),
  1641. basefont : {},
  1642. h5 : L,
  1643. h4 : L,
  1644. samp : L,
  1645. h6 : L,
  1646. ol : Q,
  1647. h1 : L,
  1648. h3 : L,
  1649. option : N,
  1650. h2 : L,
  1651. form : X( A, D, E, I ),
  1652. select : _({optgroup:1,option:1}),
  1653. font : L,
  1654. ins : L,
  1655. menu : Q,
  1656. abbr : L,
  1657. label : L,
  1658. table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}),
  1659. code : L,
  1660. tfoot : M,
  1661. cite : L,
  1662. li : P,
  1663. input : {},
  1664. iframe : P,
  1665. strong : L,
  1666. textarea : N,
  1667. noframes : P,
  1668. big : L,
  1669. small : L,
  1670. //trace:
  1671. span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}),
  1672. hr : L,
  1673. dt : L,
  1674. sub : L,
  1675. optgroup : _({option:1}),
  1676. param : {},
  1677. bdo : L,
  1678. 'var' : L,
  1679. div : P,
  1680. object : O,
  1681. sup : L,
  1682. dd : P,
  1683. strike : L,
  1684. area : {},
  1685. dir : Q,
  1686. map : X( _({area:1,form:1,p:1}), A, F, E ),
  1687. applet : O,
  1688. dl : _({dt:1,dd:1}),
  1689. del : L,
  1690. isindex : {},
  1691. fieldset : X( _({legend:1}), K ),
  1692. thead : M,
  1693. ul : Q,
  1694. acronym : L,
  1695. b : L,
  1696. a : X( _({a:1}), J ),
  1697. blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P),
  1698. caption : L,
  1699. i : L,
  1700. u : L,
  1701. tbody : M,
  1702. s : L,
  1703. address : X( D, I ),
  1704. tt : L,
  1705. legend : L,
  1706. q : L,
  1707. pre : X( G, C ),
  1708. p : X(_({'a':1}),L),
  1709. em :L,
  1710. dfn : L
  1711. });
  1712. })();
  1713. // core/domUtils.js
  1714. /**
  1715. * Dom操作工具包
  1716. * @file
  1717. * @module UE.dom.domUtils
  1718. * @since 1.2.6.1
  1719. */
  1720. /**
  1721. * Dom操作工具包
  1722. * @unfile
  1723. * @module UE.dom.domUtils
  1724. */
  1725. function getDomNode(node, start, ltr, startFromChild, fn, guard) {
  1726. var tmpNode = startFromChild && node[start],
  1727. parent;
  1728. !tmpNode && (tmpNode = node[ltr]);
  1729. while (!tmpNode && (parent = (parent || node).parentNode)) {
  1730. if (parent.tagName == 'BODY' || guard && !guard(parent)) {
  1731. return null;
  1732. }
  1733. tmpNode = parent[ltr];
  1734. }
  1735. if (tmpNode && fn && !fn(tmpNode)) {
  1736. return getDomNode(tmpNode, start, ltr, false, fn);
  1737. }
  1738. return tmpNode;
  1739. }
  1740. var attrFix = ie && browser.version < 9 ? {
  1741. tabindex:"tabIndex",
  1742. readonly:"readOnly",
  1743. "for":"htmlFor",
  1744. "class":"className",
  1745. maxlength:"maxLength",
  1746. cellspacing:"cellSpacing",
  1747. cellpadding:"cellPadding",
  1748. rowspan:"rowSpan",
  1749. colspan:"colSpan",
  1750. usemap:"useMap",
  1751. frameborder:"frameBorder"
  1752. } : {
  1753. tabindex:"tabIndex",
  1754. readonly:"readOnly"
  1755. },
  1756. styleBlock = utils.listToMap([
  1757. '-webkit-box', '-moz-box', 'block' ,
  1758. 'list-item' , 'table' , 'table-row-group' ,
  1759. 'table-header-group', 'table-footer-group' ,
  1760. 'table-row' , 'table-column-group' , 'table-column' ,
  1761. 'table-cell' , 'table-caption'
  1762. ]);
  1763. var domUtils = dom.domUtils = {
  1764. //节点常量
  1765. NODE_ELEMENT:1,
  1766. NODE_DOCUMENT:9,
  1767. NODE_TEXT:3,
  1768. NODE_COMMENT:8,
  1769. NODE_DOCUMENT_FRAGMENT:11,
  1770. //位置关系
  1771. POSITION_IDENTICAL:0,
  1772. POSITION_DISCONNECTED:1,
  1773. POSITION_FOLLOWING:2,
  1774. POSITION_PRECEDING:4,
  1775. POSITION_IS_CONTAINED:8,
  1776. POSITION_CONTAINS:16,
  1777. //ie6使用其他的会有一段空白出现
  1778. fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B',
  1779. //-------------------------Node部分--------------------------------
  1780. keys:{
  1781. /*Backspace*/ 8:1, /*Delete*/ 46:1,
  1782. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  1783. 37:1, 38:1, 39:1, 40:1,
  1784. 13:1 /*enter*/
  1785. },
  1786. /**
  1787. * 获取节点A相对于节点B的位置关系
  1788. * @method getPosition
  1789. * @param { Node } nodeA 需要查询位置关系的节点A
  1790. * @param { Node } nodeB 需要查询位置关系的节点B
  1791. * @return { Number } 节点A与节点B的关系
  1792. * @example
  1793. * ```javascript
  1794. * //output: 20
  1795. * var position = UE.dom.domUtils.getPosition( document.documentElement, document.body );
  1796. *
  1797. * switch ( position ) {
  1798. *
  1799. * //0
  1800. * case UE.dom.domUtils.POSITION_IDENTICAL:
  1801. * console.log('元素相同');
  1802. * break;
  1803. * //1
  1804. * case UE.dom.domUtils.POSITION_DISCONNECTED:
  1805. * console.log('两个节点在不同的文档中');
  1806. * break;
  1807. * //2
  1808. * case UE.dom.domUtils.POSITION_FOLLOWING:
  1809. * console.log('节点A在节点B之后');
  1810. * break;
  1811. * //4
  1812. * case UE.dom.domUtils.POSITION_PRECEDING;
  1813. * console.log('节点A在节点B之前');
  1814. * break;
  1815. * //8
  1816. * case UE.dom.domUtils.POSITION_IS_CONTAINED:
  1817. * console.log('节点A被节点B包含');
  1818. * break;
  1819. * case 10:
  1820. * console.log('节点A被节点B包含且节点A在节点B之后');
  1821. * break;
  1822. * //16
  1823. * case UE.dom.domUtils.POSITION_CONTAINS:
  1824. * console.log('节点A包含节点B');
  1825. * break;
  1826. * case 20:
  1827. * console.log('节点A包含节点B且节点A在节点B之前');
  1828. * break;
  1829. *
  1830. * }
  1831. * ```
  1832. */
  1833. getPosition:function (nodeA, nodeB) {
  1834. // 如果两个节点是同一个节点
  1835. if (nodeA === nodeB) {
  1836. // domUtils.POSITION_IDENTICAL
  1837. return 0;
  1838. }
  1839. var node,
  1840. parentsA = [nodeA],
  1841. parentsB = [nodeB];
  1842. node = nodeA;
  1843. while (node = node.parentNode) {
  1844. // 如果nodeB是nodeA的祖先节点
  1845. if (node === nodeB) {
  1846. // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING
  1847. return 10;
  1848. }
  1849. parentsA.push(node);
  1850. }
  1851. node = nodeB;
  1852. while (node = node.parentNode) {
  1853. // 如果nodeA是nodeB的祖先节点
  1854. if (node === nodeA) {
  1855. // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING
  1856. return 20;
  1857. }
  1858. parentsB.push(node);
  1859. }
  1860. parentsA.reverse();
  1861. parentsB.reverse();
  1862. if (parentsA[0] !== parentsB[0]) {
  1863. // domUtils.POSITION_DISCONNECTED
  1864. return 1;
  1865. }
  1866. var i = -1;
  1867. while (i++, parentsA[i] === parentsB[i]) {
  1868. }
  1869. nodeA = parentsA[i];
  1870. nodeB = parentsB[i];
  1871. while (nodeA = nodeA.nextSibling) {
  1872. if (nodeA === nodeB) {
  1873. // domUtils.POSITION_PRECEDING
  1874. return 4
  1875. }
  1876. }
  1877. // domUtils.POSITION_FOLLOWING
  1878. return 2;
  1879. },
  1880. /**
  1881. * 检测节点node在父节点中的索引位置
  1882. * @method getNodeIndex
  1883. * @param { Node } node 需要检测的节点对象
  1884. * @return { Number } 该节点在父节点中的位置
  1885. * @see UE.dom.domUtils.getNodeIndex(Node,Boolean)
  1886. */
  1887. /**
  1888. * 检测节点node在父节点中的索引位置, 根据给定的mergeTextNode参数决定是否要合并多个连续的文本节点为一个节点
  1889. * @method getNodeIndex
  1890. * @param { Node } node 需要检测的节点对象
  1891. * @param { Boolean } mergeTextNode 是否合并多个连续的文本节点为一个节点
  1892. * @return { Number } 该节点在父节点中的位置
  1893. * @example
  1894. * ```javascript
  1895. *
  1896. * var node = document.createElement("div");
  1897. *
  1898. * node.appendChild( document.createTextNode( "hello" ) );
  1899. * node.appendChild( document.createTextNode( "world" ) );
  1900. * node.appendChild( node = document.createElement( "div" ) );
  1901. *
  1902. * //output: 2
  1903. * console.log( UE.dom.domUtils.getNodeIndex( node ) );
  1904. *
  1905. * //output: 1
  1906. * console.log( UE.dom.domUtils.getNodeIndex( node, true ) );
  1907. *
  1908. * ```
  1909. */
  1910. getNodeIndex:function (node, ignoreTextNode) {
  1911. var preNode = node,
  1912. i = 0;
  1913. while (preNode = preNode.previousSibling) {
  1914. if (ignoreTextNode && preNode.nodeType == 3) {
  1915. if(preNode.nodeType != preNode.nextSibling.nodeType ){
  1916. i++;
  1917. }
  1918. continue;
  1919. }
  1920. i++;
  1921. }
  1922. return i;
  1923. },
  1924. /**
  1925. * 检测节点node是否在给定的document对象上
  1926. * @method inDoc
  1927. * @param { Node } node 需要检测的节点对象
  1928. * @param { DomDocument } doc 需要检测的document对象
  1929. * @return { Boolean } 该节点node是否在给定的document的dom树上
  1930. * @example
  1931. * ```javascript
  1932. *
  1933. * var node = document.createElement("div");
  1934. *
  1935. * //output: false
  1936. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1937. *
  1938. * document.body.appendChild( node );
  1939. *
  1940. * //output: true
  1941. * console.log( UE.do.domUtils.inDoc( node, document ) );
  1942. *
  1943. * ```
  1944. */
  1945. inDoc:function (node, doc) {
  1946. return domUtils.getPosition(node, doc) == 10;
  1947. },
  1948. /**
  1949. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1950. * 查找的起点是给定node节点的父节点。
  1951. * @method findParent
  1952. * @param { Node } node 需要查找的节点
  1953. * @param { Function } filterFn 自定义的过滤方法。
  1954. * @warning 查找的终点是到body节点为止
  1955. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1956. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1957. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1958. * @example
  1959. * ```javascript
  1960. * var filterNode = UE.dom.domUtils.findParent( document.body.firstChild, function ( node ) {
  1961. *
  1962. * //由于查找的终点是body节点, 所以永远也不会匹配当前过滤器的条件, 即这里永远会返回false
  1963. * return node.tagName === "HTML";
  1964. *
  1965. * } );
  1966. *
  1967. * //output: true
  1968. * console.log( filterNode === null );
  1969. * ```
  1970. */
  1971. /**
  1972. * 根据给定的过滤规则filterFn, 查找符合该过滤规则的node节点的第一个祖先节点,
  1973. * 如果includeSelf的值为true,则查找的起点是给定的节点node, 否则, 起点是node的父节点
  1974. * @method findParent
  1975. * @param { Node } node 需要查找的节点
  1976. * @param { Function } filterFn 自定义的过滤方法。
  1977. * @param { Boolean } includeSelf 查找过程是否包含自身
  1978. * @warning 查找的终点是到body节点为止
  1979. * @remind 自定义的过滤方法filterFn接受一个Node对象作为参数, 该对象代表当前执行检测的祖先节点。 如果该
  1980. * 节点满足过滤条件, 则要求返回true, 这时将直接返回该节点作为findParent()的结果, 否则, 请返回false。
  1981. * @remind 如果includeSelf为true, 则过滤器第一次执行时的参数会是节点本身。
  1982. * 反之, 过滤器第一次执行时的参数将是该节点的父节点。
  1983. * @return { Node | Null } 如果找到符合过滤条件的节点, 就返回该节点, 否则返回NULL
  1984. * @example
  1985. * ```html
  1986. * <body>
  1987. *
  1988. * <div id="test">
  1989. * </div>
  1990. *
  1991. * <script type="text/javascript">
  1992. *
  1993. * //output: DIV, BODY
  1994. * var filterNode = UE.dom.domUtils.findParent( document.getElementById( "test" ), function ( node ) {
  1995. *
  1996. * console.log( node.tagName );
  1997. * return false;
  1998. *
  1999. * }, true );
  2000. *
  2001. * </script>
  2002. * </body>
  2003. * ```
  2004. */
  2005. findParent:function (node, filterFn, includeSelf) {
  2006. if (node && !domUtils.isBody(node)) {
  2007. node = includeSelf ? node : node.parentNode;
  2008. while (node) {
  2009. if (!filterFn || filterFn(node) || domUtils.isBody(node)) {
  2010. return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node;
  2011. }
  2012. node = node.parentNode;
  2013. }
  2014. }
  2015. return null;
  2016. },
  2017. /**
  2018. * 查找node的节点名为tagName的第一个祖先节点, 查找的起点是node节点的父节点。
  2019. * @method findParentByTagName
  2020. * @param { Node } node 需要查找的节点对象
  2021. * @param { Array } tagNames 需要查找的父节点的名称数组
  2022. * @warning 查找的终点是到body节点为止
  2023. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2024. * @example
  2025. * ```javascript
  2026. * var node = UE.dom.domUtils.findParentByTagName( document.getElementsByTagName("div")[0], [ "BODY" ] );
  2027. * //output: BODY
  2028. * console.log( node.tagName );
  2029. * ```
  2030. */
  2031. /**
  2032. * 查找node的节点名为tagName的祖先节点, 如果includeSelf的值为true,则查找的起点是给定的节点node,
  2033. * 否则, 起点是node的父节点。
  2034. * @method findParentByTagName
  2035. * @param { Node } node 需要查找的节点对象
  2036. * @param { Array } tagNames 需要查找的父节点的名称数组
  2037. * @param { Boolean } includeSelf 查找过程是否包含node节点自身
  2038. * @warning 查找的终点是到body节点为止
  2039. * @return { Node | NULL } 如果找到符合条件的节点, 则返回该节点, 否则返回NULL
  2040. * @example
  2041. * ```javascript
  2042. * var queryTarget = document.getElementsByTagName("div")[0];
  2043. * var node = UE.dom.domUtils.findParentByTagName( queryTarget, [ "DIV" ], true );
  2044. * //output: true
  2045. * console.log( queryTarget === node );
  2046. * ```
  2047. */
  2048. findParentByTagName:function (node, tagNames, includeSelf, excludeFn) {
  2049. tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]);
  2050. return domUtils.findParent(node, function (node) {
  2051. return tagNames[node.tagName] && !(excludeFn && excludeFn(node));
  2052. }, includeSelf);
  2053. },
  2054. /**
  2055. * 查找节点node的祖先节点集合, 查找的起点是给定节点的父节点,结果集中不包含给定的节点。
  2056. * @method findParents
  2057. * @param { Node } node 需要查找的节点对象
  2058. * @return { Array } 给定节点的祖先节点数组
  2059. * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身
  2060. * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身
  2061. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取
  2062. * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个
  2063. */
  2064. /**
  2065. * 查找节点node的祖先节点集合, 如果includeSelf的值为true,
  2066. * 则返回的结果集中允许出现当前给定的节点, 否则, 该节点不会出现在其结果集中。
  2067. * @method findParents
  2068. * @param { Node } node 需要查找的节点对象
  2069. * @param { Boolean } includeSelf 查找的结果中是否允许包含当前查找的节点对象
  2070. * @return { Array } 给定节点的祖先节点数组
  2071. */
  2072. findParents:function (node, includeSelf, filterFn, closerFirst) {
  2073. var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : [];
  2074. while (node = domUtils.findParent(node, filterFn)) {
  2075. parents.push(node);
  2076. }
  2077. return closerFirst ? parents : parents.reverse();
  2078. },
  2079. /**
  2080. * 在节点node后面插入新节点newNode
  2081. * @method insertAfter
  2082. * @param { Node } node 目标节点
  2083. * @param { Node } newNode 新插入的节点, 该节点将置于目标节点之后
  2084. * @return { Node } 新插入的节点
  2085. */
  2086. insertAfter:function (node, newNode) {
  2087. return node.nextSibling ? node.parentNode.insertBefore(newNode, node.nextSibling):
  2088. node.parentNode.appendChild(newNode);
  2089. },
  2090. /**
  2091. * 删除节点node及其下属的所有节点
  2092. * @method remove
  2093. * @param { Node } node 需要删除的节点对象
  2094. * @return { Node } 返回刚删除的节点对象
  2095. * @example
  2096. * ```html
  2097. * <div id="test">
  2098. * <div id="child">你好</div>
  2099. * </div>
  2100. * <script>
  2101. * UE.dom.domUtils.remove( document.body, false );
  2102. * //output: false
  2103. * console.log( document.getElementById( "child" ) !== null );
  2104. * </script>
  2105. * ```
  2106. */
  2107. /**
  2108. * 删除节点node,并根据keepChildren的值决定是否保留子节点
  2109. * @method remove
  2110. * @param { Node } node 需要删除的节点对象
  2111. * @param { Boolean } keepChildren 是否需要保留子节点
  2112. * @return { Node } 返回刚删除的节点对象
  2113. * @example
  2114. * ```html
  2115. * <div id="test">
  2116. * <div id="child">你好</div>
  2117. * </div>
  2118. * <script>
  2119. * UE.dom.domUtils.remove( document.body, true );
  2120. * //output: true
  2121. * console.log( document.getElementById( "child" ) !== null );
  2122. * </script>
  2123. * ```
  2124. */
  2125. remove:function (node, keepChildren) {
  2126. var parent = node.parentNode,
  2127. child;
  2128. if (parent) {
  2129. if (keepChildren && node.hasChildNodes()) {
  2130. while (child = node.firstChild) {
  2131. parent.insertBefore(child, node);
  2132. }
  2133. }
  2134. parent.removeChild(node);
  2135. }
  2136. return node;
  2137. },
  2138. /**
  2139. * 取得node节点的下一个兄弟节点, 如果该节点其后没有兄弟节点, 则递归查找其父节点之后的第一个兄弟节点,
  2140. * 直到找到满足条件的节点或者递归到BODY节点之后才会结束。
  2141. * @method getNextDomNode
  2142. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2143. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2144. * @example
  2145. * ```html
  2146. * <body>
  2147. * <div id="test">
  2148. * <span></span>
  2149. * </div>
  2150. * <i>xxx</i>
  2151. * </body>
  2152. * <script>
  2153. *
  2154. * //output: i节点
  2155. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2156. *
  2157. * </script>
  2158. * ```
  2159. * @example
  2160. * ```html
  2161. * <body>
  2162. * <div>
  2163. * <span></span>
  2164. * <i id="test">xxx</i>
  2165. * </div>
  2166. * <b>xxx</b>
  2167. * </body>
  2168. * <script>
  2169. *
  2170. * //由于id为test的i节点之后没有兄弟节点, 则查找其父节点(div)后面的兄弟节点
  2171. * //output: b节点
  2172. * console.log( UE.dom.domUtils.getNextDomNode( document.getElementById( "test" ) ) );
  2173. *
  2174. * </script>
  2175. * ```
  2176. */
  2177. /**
  2178. * 取得node节点的下一个兄弟节点, 如果startFromChild的值为ture,则先获取其子节点,
  2179. * 如果有子节点则直接返回第一个子节点;如果没有子节点或者startFromChild的值为false,
  2180. * 则执行<a href="#UE.dom.domUtils.getNextDomNode(Node)">getNextDomNode(Node node)</a>的查找过程。
  2181. * @method getNextDomNode
  2182. * @param { Node } node 需要获取其后的兄弟节点的节点对象
  2183. * @param { Boolean } startFromChild 查找过程是否从其子节点开始
  2184. * @return { Node | NULL } 如果找满足条件的节点, 则返回该节点, 否则返回NULL
  2185. * @see UE.dom.domUtils.getNextDomNode(Node)
  2186. */
  2187. getNextDomNode:function (node, startFromChild, filterFn, guard) {
  2188. return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard);
  2189. },
  2190. getPreDomNode:function (node, startFromChild, filterFn, guard) {
  2191. return getDomNode(node, 'lastChild', 'previousSibling', startFromChild, filterFn, guard);
  2192. },
  2193. /**
  2194. * 检测节点node是否属是UEditor定义的bookmark节点
  2195. * @method isBookmarkNode
  2196. * @private
  2197. * @param { Node } node 需要检测的节点对象
  2198. * @return { Boolean } 是否是bookmark节点
  2199. * @example
  2200. * ```html
  2201. * <span id="_baidu_bookmark_1"></span>
  2202. * <script>
  2203. * var bookmarkNode = document.getElementById("_baidu_bookmark_1");
  2204. * //output: true
  2205. * console.log( UE.dom.domUtils.isBookmarkNode( bookmarkNode ) );
  2206. * </script>
  2207. * ```
  2208. */
  2209. isBookmarkNode:function (node) {
  2210. return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id);
  2211. },
  2212. /**
  2213. * 获取节点node所属的window对象
  2214. * @method getWindow
  2215. * @param { Node } node 节点对象
  2216. * @return { Window } 当前节点所属的window对象
  2217. * @example
  2218. * ```javascript
  2219. * //output: true
  2220. * console.log( UE.dom.domUtils.getWindow( document.body ) === window );
  2221. * ```
  2222. */
  2223. getWindow:function (node) {
  2224. var doc = node.ownerDocument || node;
  2225. return doc.defaultView || doc.parentWindow;
  2226. },
  2227. /**
  2228. * 获取离nodeA与nodeB最近的公共的祖先节点
  2229. * @method getCommonAncestor
  2230. * @param { Node } nodeA 第一个节点
  2231. * @param { Node } nodeB 第二个节点
  2232. * @remind 如果给定的两个节点是同一个节点, 将直接返回该节点。
  2233. * @return { Node | NULL } 如果未找到公共节点, 返回NULL, 否则返回最近的公共祖先节点。
  2234. * @example
  2235. * ```javascript
  2236. * var commonAncestor = UE.dom.domUtils.getCommonAncestor( document.body, document.body.firstChild );
  2237. * //output: true
  2238. * console.log( commonAncestor.tagName.toLowerCase() === 'body' );
  2239. * ```
  2240. */
  2241. getCommonAncestor:function (nodeA, nodeB) {
  2242. if (nodeA === nodeB)
  2243. return nodeA;
  2244. var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1;
  2245. while (parent = parent.parentNode) {
  2246. if (parent === nodeB) {
  2247. return parent;
  2248. }
  2249. parentsA.push(parent);
  2250. }
  2251. parent = nodeB;
  2252. while (parent = parent.parentNode) {
  2253. if (parent === nodeA)
  2254. return parent;
  2255. parentsB.push(parent);
  2256. }
  2257. parentsA.reverse();
  2258. parentsB.reverse();
  2259. while (i++, parentsA[i] === parentsB[i]) {
  2260. }
  2261. return i == 0 ? null : parentsA[i - 1];
  2262. },
  2263. /**
  2264. * 清除node节点左右连续为空的兄弟inline节点
  2265. * @method clearEmptySibling
  2266. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2267. * 则这些兄弟节点将被删除
  2268. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点
  2269. * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点
  2270. * @example
  2271. * ```html
  2272. * <body>
  2273. * <div></div>
  2274. * <span id="test"></span>
  2275. * <i></i>
  2276. * <b></b>
  2277. * <em>xxx</em>
  2278. * <span></span>
  2279. * </body>
  2280. * <script>
  2281. *
  2282. * UE.dom.domUtils.clearEmptySibling( document.getElementById( "test" ) );
  2283. *
  2284. * //output: <div></div><span id="test"></span><em>xxx</em><span></span>
  2285. * console.log( document.body.innerHTML );
  2286. *
  2287. * </script>
  2288. * ```
  2289. */
  2290. /**
  2291. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2292. * 则忽略对右边兄弟节点的操作。
  2293. * @method clearEmptySibling
  2294. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2295. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2296. * 则这些兄弟节点将被删除
  2297. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2298. */
  2299. /**
  2300. * 清除node节点左右连续为空的兄弟inline节点, 如果ignoreNext的值为true,
  2301. * 则忽略对右边兄弟节点的操作, 如果ignorePre的值为true,则忽略对左边兄弟节点的操作。
  2302. * @method clearEmptySibling
  2303. * @param { Node } node 执行的节点对象, 如果该节点的左右连续的兄弟节点是空的inline节点,
  2304. * @param { Boolean } ignoreNext 是否忽略忽略对右边的兄弟节点的操作
  2305. * @param { Boolean } ignorePre 是否忽略忽略对左边的兄弟节点的操作
  2306. * 则这些兄弟节点将被删除
  2307. * @see UE.dom.domUtils.clearEmptySibling(Node)
  2308. */
  2309. clearEmptySibling:function (node, ignoreNext, ignorePre) {
  2310. function clear(next, dir) {
  2311. var tmpNode;
  2312. while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next)
  2313. //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了
  2314. || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) {
  2315. tmpNode = next[dir];
  2316. domUtils.remove(next);
  2317. next = tmpNode;
  2318. }
  2319. }
  2320. !ignoreNext && clear(node.nextSibling, 'nextSibling');
  2321. !ignorePre && clear(node.previousSibling, 'previousSibling');
  2322. },
  2323. /**
  2324. * 将一个文本节点textNode拆分成两个文本节点,offset指定拆分位置
  2325. * @method split
  2326. * @param { Node } textNode 需要拆分的文本节点对象
  2327. * @param { int } offset 需要拆分的位置, 位置计算从0开始
  2328. * @return { Node } 拆分后形成的新节点
  2329. * @example
  2330. * ```html
  2331. * <div id="test">abcdef</div>
  2332. * <script>
  2333. * var newNode = UE.dom.domUtils.split( document.getElementById( "test" ).firstChild, 3 );
  2334. * //output: def
  2335. * console.log( newNode.nodeValue );
  2336. * </script>
  2337. * ```
  2338. */
  2339. split:function (node, offset) {
  2340. var doc = node.ownerDocument;
  2341. if (browser.ie && offset == node.nodeValue.length) {
  2342. var next = doc.createTextNode('');
  2343. return domUtils.insertAfter(node, next);
  2344. }
  2345. var retval = node.splitText(offset);
  2346. //ie8下splitText不会跟新childNodes,我们手动触发他的更新
  2347. if (browser.ie8) {
  2348. var tmpNode = doc.createTextNode('');
  2349. domUtils.insertAfter(retval, tmpNode);
  2350. domUtils.remove(tmpNode);
  2351. }
  2352. return retval;
  2353. },
  2354. /**
  2355. * 检测文本节点textNode是否为空节点(包括空格、换行、占位符等字符)
  2356. * @method isWhitespace
  2357. * @param { Node } node 需要检测的节点对象
  2358. * @return { Boolean } 检测的节点是否为空
  2359. * @example
  2360. * ```html
  2361. * <div id="test">
  2362. *
  2363. * </div>
  2364. * <script>
  2365. * //output: true
  2366. * console.log( UE.dom.domUtils.isWhitespace( document.getElementById("test").firstChild ) );
  2367. * </script>
  2368. * ```
  2369. */
  2370. isWhitespace:function (node) {
  2371. return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue);
  2372. },
  2373. /**
  2374. * 获取元素element相对于viewport的位置坐标
  2375. * @method getXY
  2376. * @param { Node } element 需要计算位置的节点对象
  2377. * @return { Object } 返回形如{x:left,y:top}的一个key-value映射对象, 其中键x代表水平偏移距离,
  2378. * y代表垂直偏移距离。
  2379. *
  2380. * @example
  2381. * ```javascript
  2382. * var location = UE.dom.domUtils.getXY( document.getElementById("test") );
  2383. * //output: test的坐标为: 12, 24
  2384. * console.log( 'test的坐标为: ', location.x, ',', location.y );
  2385. * ```
  2386. */
  2387. getXY:function (element) {
  2388. var x = 0, y = 0;
  2389. while (element.offsetParent) {
  2390. y += element.offsetTop;
  2391. x += element.offsetLeft;
  2392. element = element.offsetParent;
  2393. }
  2394. return { 'x':x, 'y':y};
  2395. },
  2396. /**
  2397. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2398. * @method on
  2399. * @param { Node } element 需要绑定事件的节点对象
  2400. * @param { String } type 绑定的事件类型
  2401. * @param { Function } handler 事件处理器
  2402. * @example
  2403. * ```javascript
  2404. * UE.dom.domUtils.on(document.body,"click",function(e){
  2405. * //e为事件对象,this为被点击元素对戏那个
  2406. * });
  2407. * ```
  2408. */
  2409. /**
  2410. * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数
  2411. * @method on
  2412. * @param { Node } element 需要绑定事件的节点对象
  2413. * @param { Array } type 绑定的事件类型数组
  2414. * @param { Function } handler 事件处理器
  2415. * @example
  2416. * ```javascript
  2417. * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){
  2418. * //evt为事件对象,this为被点击元素对象
  2419. * });
  2420. * ```
  2421. */
  2422. on:function (element, type, handler) {
  2423. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2424. k = types.length;
  2425. if (k) while (k--) {
  2426. type = types[k];
  2427. if (element.addEventListener) {
  2428. element.addEventListener(type, handler, false);
  2429. } else {
  2430. if (!handler._d) {
  2431. handler._d = {
  2432. els : []
  2433. };
  2434. }
  2435. var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element);
  2436. if (!handler._d[key] || index == -1) {
  2437. if(index == -1){
  2438. handler._d.els.push(element);
  2439. }
  2440. if(!handler._d[key]){
  2441. handler._d[key] = function (evt) {
  2442. return handler.call(evt.srcElement, evt || window.event);
  2443. };
  2444. }
  2445. element.attachEvent('on' + type, handler._d[key]);
  2446. }
  2447. }
  2448. }
  2449. element = null;
  2450. },
  2451. /**
  2452. * 解除DOM事件绑定
  2453. * @method un
  2454. * @param { Node } element 需要解除事件绑定的节点对象
  2455. * @param { String } type 需要接触绑定的事件类型
  2456. * @param { Function } handler 对应的事件处理器
  2457. * @example
  2458. * ```javascript
  2459. * UE.dom.domUtils.un(document.body,"click",function(evt){
  2460. * //evt为事件对象,this为被点击元素对象
  2461. * });
  2462. * ```
  2463. */
  2464. /**
  2465. * 解除DOM事件绑定
  2466. * @method un
  2467. * @param { Node } element 需要解除事件绑定的节点对象
  2468. * @param { Array } type 需要接触绑定的事件类型数组
  2469. * @param { Function } handler 对应的事件处理器
  2470. * @example
  2471. * ```javascript
  2472. * UE.dom.domUtils.un(document.body, ["click","mousedown"],function(evt){
  2473. * //evt为事件对象,this为被点击元素对象
  2474. * });
  2475. * ```
  2476. */
  2477. un:function (element, type, handler) {
  2478. var types = utils.isArray(type) ? type : utils.trim(type).split(/\s+/),
  2479. k = types.length;
  2480. if (k) while (k--) {
  2481. type = types[k];
  2482. if (element.removeEventListener) {
  2483. element.removeEventListener(type, handler, false);
  2484. } else {
  2485. var key = type + handler.toString();
  2486. try{
  2487. element.detachEvent('on' + type, handler._d ? handler._d[key] : handler);
  2488. }catch(e){}
  2489. if (handler._d && handler._d[key]) {
  2490. var index = utils.indexOf(handler._d.els,element);
  2491. if(index!=-1){
  2492. handler._d.els.splice(index,1);
  2493. }
  2494. handler._d.els.length == 0 && delete handler._d[key];
  2495. }
  2496. }
  2497. }
  2498. },
  2499. /**
  2500. * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值
  2501. * @method isSameElement
  2502. * @param { Node } nodeA 需要比较的节点
  2503. * @param { Node } nodeB 需要比较的节点
  2504. * @return { Boolean } 两个节点是否具有相同的标签名、属性名以及属性值
  2505. * @example
  2506. * ```html
  2507. * <span style="font-size:12px">ssss</span>
  2508. * <span style="font-size:12px">bbbbb</span>
  2509. * <span style="font-size:13px">ssss</span>
  2510. * <span style="font-size:14px">bbbbb</span>
  2511. *
  2512. * <script>
  2513. *
  2514. * var nodes = document.getElementsByTagName( "span" );
  2515. *
  2516. * //output: true
  2517. * console.log( UE.dom.domUtils.isSameElement( nodes[0], nodes[1] ) );
  2518. *
  2519. * //output: false
  2520. * console.log( UE.dom.domUtils.isSameElement( nodes[2], nodes[3] ) );
  2521. *
  2522. * </script>
  2523. * ```
  2524. */
  2525. isSameElement:function (nodeA, nodeB) {
  2526. if (nodeA.tagName != nodeB.tagName) {
  2527. return false;
  2528. }
  2529. var thisAttrs = nodeA.attributes,
  2530. otherAttrs = nodeB.attributes;
  2531. if (!ie && thisAttrs.length != otherAttrs.length) {
  2532. return false;
  2533. }
  2534. var attrA, attrB, al = 0, bl = 0;
  2535. for (var i = 0; attrA = thisAttrs[i++];) {
  2536. if (attrA.nodeName == 'style') {
  2537. if (attrA.specified) {
  2538. al++;
  2539. }
  2540. if (domUtils.isSameStyle(nodeA, nodeB)) {
  2541. continue;
  2542. } else {
  2543. return false;
  2544. }
  2545. }
  2546. if (ie) {
  2547. if (attrA.specified) {
  2548. al++;
  2549. attrB = otherAttrs.getNamedItem(attrA.nodeName);
  2550. } else {
  2551. continue;
  2552. }
  2553. } else {
  2554. attrB = nodeB.attributes[attrA.nodeName];
  2555. }
  2556. if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) {
  2557. return false;
  2558. }
  2559. }
  2560. // 有可能attrB的属性包含了attrA的属性之外还有自己的属性
  2561. if (ie) {
  2562. for (i = 0; attrB = otherAttrs[i++];) {
  2563. if (attrB.specified) {
  2564. bl++;
  2565. }
  2566. }
  2567. if (al != bl) {
  2568. return false;
  2569. }
  2570. }
  2571. return true;
  2572. },
  2573. /**
  2574. * 判断节点nodeA与节点nodeB的元素的style属性是否一致
  2575. * @method isSameStyle
  2576. * @param { Node } nodeA 需要比较的节点
  2577. * @param { Node } nodeB 需要比较的节点
  2578. * @return { Boolean } 两个节点是否具有相同的style属性值
  2579. * @example
  2580. * ```html
  2581. * <span style="font-size:12px">ssss</span>
  2582. * <span style="font-size:12px">bbbbb</span>
  2583. * <span style="font-size:13px">ssss</span>
  2584. * <span style="font-size:14px">bbbbb</span>
  2585. *
  2586. * <script>
  2587. *
  2588. * var nodes = document.getElementsByTagName( "span" );
  2589. *
  2590. * //output: true
  2591. * console.log( UE.dom.domUtils.isSameStyle( nodes[0], nodes[1] ) );
  2592. *
  2593. * //output: false
  2594. * console.log( UE.dom.domUtils.isSameStyle( nodes[2], nodes[3] ) );
  2595. *
  2596. * </script>
  2597. * ```
  2598. */
  2599. isSameStyle:function (nodeA, nodeB) {
  2600. var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'),
  2601. styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':');
  2602. if (browser.opera) {
  2603. styleA = nodeA.style;
  2604. styleB = nodeB.style;
  2605. if (styleA.length != styleB.length)
  2606. return false;
  2607. for (var p in styleA) {
  2608. if (/^(\d+|csstext)$/i.test(p)) {
  2609. continue;
  2610. }
  2611. if (styleA[p] != styleB[p]) {
  2612. return false;
  2613. }
  2614. }
  2615. return true;
  2616. }
  2617. if (!styleA || !styleB) {
  2618. return styleA == styleB;
  2619. }
  2620. styleA = styleA.split(';');
  2621. styleB = styleB.split(';');
  2622. if (styleA.length != styleB.length) {
  2623. return false;
  2624. }
  2625. for (var i = 0, ci; ci = styleA[i++];) {
  2626. if (utils.indexOf(styleB, ci) == -1) {
  2627. return false;
  2628. }
  2629. }
  2630. return true;
  2631. },
  2632. /**
  2633. * 检查节点node是否为block元素
  2634. * @method isBlockElm
  2635. * @param { Node } node 需要检测的节点对象
  2636. * @return { Boolean } 是否是block元素节点
  2637. * @warning 该方法的判断规则如下: 如果该元素原本是block元素, 则不论该元素当前的css样式是什么都会返回true;
  2638. * 否则,检测该元素的css样式, 如果该元素当前是block元素, 则返回true。 其余情况下都返回false。
  2639. * @example
  2640. * ```html
  2641. * <span id="test1" style="display: block"></span>
  2642. * <span id="test2"></span>
  2643. * <div id="test3" style="display: inline"></div>
  2644. *
  2645. * <script>
  2646. *
  2647. * //output: true
  2648. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test1") ) );
  2649. *
  2650. * //output: false
  2651. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test2") ) );
  2652. *
  2653. * //output: true
  2654. * console.log( UE.dom.domUtils.isBlockElm( document.getElementById("test3") ) );
  2655. *
  2656. * </script>
  2657. * ```
  2658. */
  2659. isBlockElm:function (node) {
  2660. return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName];
  2661. },
  2662. /**
  2663. * 检测node节点是否为body节点
  2664. * @method isBody
  2665. * @param { Element } node 需要检测的dom元素
  2666. * @return { Boolean } 给定的元素是否是body元素
  2667. * @example
  2668. * ```javascript
  2669. * //output: true
  2670. * console.log( UE.dom.domUtils.isBody( document.body ) );
  2671. * ```
  2672. */
  2673. isBody:function (node) {
  2674. return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body';
  2675. },
  2676. /**
  2677. * 以node节点为分界,将该节点的指定祖先节点parent拆分成两个独立的节点,
  2678. * 拆分形成的两个节点之间是node节点
  2679. * @method breakParent
  2680. * @param { Node } node 作为分界的节点对象
  2681. * @param { Node } parent 该节点必须是node节点的祖先节点, 且是block节点。
  2682. * @return { Node } 给定的node分界节点
  2683. * @example
  2684. * ```javascript
  2685. *
  2686. * var node = document.createElement("span"),
  2687. * wrapNode = document.createElement( "div" ),
  2688. * parent = document.createElement("p");
  2689. *
  2690. * parent.appendChild( node );
  2691. * wrapNode.appendChild( parent );
  2692. *
  2693. * //拆分前
  2694. * //output: <p><span></span></p>
  2695. * console.log( wrapNode.innerHTML );
  2696. *
  2697. *
  2698. * UE.dom.domUtils.breakParent( node, parent );
  2699. * //拆分后
  2700. * //output: <p></p><span></span><p></p>
  2701. * console.log( wrapNode.innerHTML );
  2702. *
  2703. * ```
  2704. */
  2705. breakParent:function (node, parent) {
  2706. var tmpNode,
  2707. parentClone = node,
  2708. clone = node,
  2709. leftNodes,
  2710. rightNodes;
  2711. do {
  2712. parentClone = parentClone.parentNode;
  2713. if (leftNodes) {
  2714. tmpNode = parentClone.cloneNode(false);
  2715. tmpNode.appendChild(leftNodes);
  2716. leftNodes = tmpNode;
  2717. tmpNode = parentClone.cloneNode(false);
  2718. tmpNode.appendChild(rightNodes);
  2719. rightNodes = tmpNode;
  2720. } else {
  2721. leftNodes = parentClone.cloneNode(false);
  2722. rightNodes = leftNodes.cloneNode(false);
  2723. }
  2724. while (tmpNode = clone.previousSibling) {
  2725. leftNodes.insertBefore(tmpNode, leftNodes.firstChild);
  2726. }
  2727. while (tmpNode = clone.nextSibling) {
  2728. rightNodes.appendChild(tmpNode);
  2729. }
  2730. clone = parentClone;
  2731. } while (parent !== parentClone);
  2732. tmpNode = parent.parentNode;
  2733. tmpNode.insertBefore(leftNodes, parent);
  2734. tmpNode.insertBefore(rightNodes, parent);
  2735. tmpNode.insertBefore(node, rightNodes);
  2736. domUtils.remove(parent);
  2737. return node;
  2738. },
  2739. /**
  2740. * 检查节点node是否是空inline节点
  2741. * @method isEmptyInlineElement
  2742. * @param { Node } node 需要检测的节点对象
  2743. * @return { Number } 如果给定的节点是空的inline节点, 则返回1, 否则返回0。
  2744. * @example
  2745. * ```html
  2746. * <b><i></i></b> => 1
  2747. * <b><i></i><u></u></b> => 1
  2748. * <b></b> => 1
  2749. * <b>xx<i></i></b> => 0
  2750. * ```
  2751. */
  2752. isEmptyInlineElement:function (node) {
  2753. if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) {
  2754. return 0;
  2755. }
  2756. node = node.firstChild;
  2757. while (node) {
  2758. //如果是创建的bookmark就跳过
  2759. if (domUtils.isBookmarkNode(node)) {
  2760. return 0;
  2761. }
  2762. if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) ||
  2763. node.nodeType == 3 && !domUtils.isWhitespace(node)
  2764. ) {
  2765. return 0;
  2766. }
  2767. node = node.nextSibling;
  2768. }
  2769. return 1;
  2770. },
  2771. /**
  2772. * 删除node节点下首尾两端的空白文本子节点
  2773. * @method trimWhiteTextNode
  2774. * @param { Element } node 需要执行删除操作的元素对象
  2775. * @example
  2776. * ```javascript
  2777. * var node = document.createElement("div");
  2778. *
  2779. * node.appendChild( document.createTextNode( "" ) );
  2780. *
  2781. * node.appendChild( document.createElement("div") );
  2782. *
  2783. * node.appendChild( document.createTextNode( "" ) );
  2784. *
  2785. * //3
  2786. * console.log( node.childNodes.length );
  2787. *
  2788. * UE.dom.domUtils.trimWhiteTextNode( node );
  2789. *
  2790. * //1
  2791. * console.log( node.childNodes.length );
  2792. * ```
  2793. */
  2794. trimWhiteTextNode:function (node) {
  2795. function remove(dir) {
  2796. var child;
  2797. while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) {
  2798. node.removeChild(child);
  2799. }
  2800. }
  2801. remove('firstChild');
  2802. remove('lastChild');
  2803. },
  2804. /**
  2805. * 合并node节点下相同的子节点
  2806. * @name mergeChild
  2807. * @desc
  2808. * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签
  2809. * @example
  2810. * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p>
  2811. * ==> UE.dom.domUtils.mergeChild(node,'span')
  2812. * <p><span style="font-size:12px;">xxaaxx</span></p>
  2813. */
  2814. mergeChild:function (node, tagName, attrs) {
  2815. var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase());
  2816. for (var i = 0, ci; ci = list[i++];) {
  2817. if (!ci.parentNode || domUtils.isBookmarkNode(ci)) {
  2818. continue;
  2819. }
  2820. //span单独处理
  2821. if (ci.tagName.toLowerCase() == 'span') {
  2822. if (node === ci.parentNode) {
  2823. domUtils.trimWhiteTextNode(node);
  2824. if (node.childNodes.length == 1) {
  2825. node.style.cssText = ci.style.cssText + ";" + node.style.cssText;
  2826. domUtils.remove(ci, true);
  2827. continue;
  2828. }
  2829. }
  2830. ci.style.cssText = node.style.cssText + ';' + ci.style.cssText;
  2831. if (attrs) {
  2832. var style = attrs.style;
  2833. if (style) {
  2834. style = style.split(';');
  2835. for (var j = 0, s; s = style[j++];) {
  2836. ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1];
  2837. }
  2838. }
  2839. }
  2840. if (domUtils.isSameStyle(ci, node)) {
  2841. domUtils.remove(ci, true);
  2842. }
  2843. continue;
  2844. }
  2845. if (domUtils.isSameElement(node, ci)) {
  2846. domUtils.remove(ci, true);
  2847. }
  2848. }
  2849. },
  2850. /**
  2851. * 原生方法getElementsByTagName的封装
  2852. * @method getElementsByTagName
  2853. * @param { Node } node 目标节点对象
  2854. * @param { String } tagName 需要查找的节点的tagName, 多个tagName以空格分割
  2855. * @return { Array } 符合条件的节点集合
  2856. */
  2857. getElementsByTagName:function (node, name,filter) {
  2858. if(filter && utils.isString(filter)){
  2859. var className = filter;
  2860. filter = function(node){return domUtils.hasClass(node,className)}
  2861. }
  2862. name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' ');
  2863. var arr = [];
  2864. for(var n = 0,ni;ni=name[n++];){
  2865. var list = node.getElementsByTagName(ni);
  2866. for (var i = 0, ci; ci = list[i++];) {
  2867. if(!filter || filter(ci))
  2868. arr.push(ci);
  2869. }
  2870. }
  2871. return arr;
  2872. },
  2873. /**
  2874. * 将节点node提取到父节点上
  2875. * @method mergeToParent
  2876. * @param { Element } node 需要提取的元素对象
  2877. * @example
  2878. * ```html
  2879. * <div id="parent">
  2880. * <div id="sub">
  2881. * <span id="child"></span>
  2882. * </div>
  2883. * </div>
  2884. *
  2885. * <script>
  2886. *
  2887. * var child = document.getElementById( "child" );
  2888. *
  2889. * //output: sub
  2890. * console.log( child.parentNode.id );
  2891. *
  2892. * UE.dom.domUtils.mergeToParent( child );
  2893. *
  2894. * //output: parent
  2895. * console.log( child.parentNode.id );
  2896. *
  2897. * </script>
  2898. * ```
  2899. */
  2900. mergeToParent:function (node) {
  2901. var parent = node.parentNode;
  2902. while (parent && dtd.$removeEmpty[parent.tagName]) {
  2903. if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理
  2904. domUtils.trimWhiteTextNode(parent);
  2905. //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span>
  2906. if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node)
  2907. || (parent.tagName == 'A' && node.tagName == 'SPAN')) {
  2908. if (parent.childNodes.length > 1 || parent !== node.parentNode) {
  2909. node.style.cssText = parent.style.cssText + ";" + node.style.cssText;
  2910. parent = parent.parentNode;
  2911. continue;
  2912. } else {
  2913. parent.style.cssText += ";" + node.style.cssText;
  2914. //trace:952 a标签要保持下划线
  2915. if (parent.tagName == 'A') {
  2916. parent.style.textDecoration = 'underline';
  2917. }
  2918. }
  2919. }
  2920. if (parent.tagName != 'A') {
  2921. parent === node.parentNode && domUtils.remove(node, true);
  2922. break;
  2923. }
  2924. }
  2925. parent = parent.parentNode;
  2926. }
  2927. },
  2928. /**
  2929. * 合并节点node的左右兄弟节点
  2930. * @method mergeSibling
  2931. * @param { Element } node 需要合并的目标节点
  2932. * @example
  2933. * ```html
  2934. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2935. *
  2936. * <script>
  2937. * var demoNode = document.getElementById("test");
  2938. * UE.dom.domUtils.mergeSibling( demoNode );
  2939. * //output: xxxxoooxxxx
  2940. * console.log( demoNode.innerHTML );
  2941. * </script>
  2942. * ```
  2943. */
  2944. /**
  2945. * 合并节点node的左右兄弟节点, 可以根据给定的条件选择是否忽略合并左节点。
  2946. * @method mergeSibling
  2947. * @param { Element } node 需要合并的目标节点
  2948. * @param { Boolean } ignorePre 是否忽略合并左节点
  2949. * @example
  2950. * ```html
  2951. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2952. *
  2953. * <script>
  2954. * var demoNode = document.getElementById("test");
  2955. * UE.dom.domUtils.mergeSibling( demoNode, true );
  2956. * //output: oooxxxx
  2957. * console.log( demoNode.innerHTML );
  2958. * </script>
  2959. * ```
  2960. */
  2961. /**
  2962. * 合并节点node的左右兄弟节点,可以根据给定的条件选择是否忽略合并左右节点。
  2963. * @method mergeSibling
  2964. * @param { Element } node 需要合并的目标节点
  2965. * @param { Boolean } ignorePre 是否忽略合并左节点
  2966. * @param { Boolean } ignoreNext 是否忽略合并右节点
  2967. * @remind 如果同时忽略左右节点, 则该操作什么也不会做
  2968. * @example
  2969. * ```html
  2970. * <b>xxxx</b><b id="test">ooo</b><b>xxxx</b>
  2971. *
  2972. * <script>
  2973. * var demoNode = document.getElementById("test");
  2974. * UE.dom.domUtils.mergeSibling( demoNode, false, true );
  2975. * //output: xxxxooo
  2976. * console.log( demoNode.innerHTML );
  2977. * </script>
  2978. * ```
  2979. */
  2980. mergeSibling:function (node, ignorePre, ignoreNext) {
  2981. function merge(rtl, start, node) {
  2982. var next;
  2983. if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) {
  2984. while (next.firstChild) {
  2985. if (start == 'firstChild') {
  2986. node.insertBefore(next.lastChild, node.firstChild);
  2987. } else {
  2988. node.appendChild(next.firstChild);
  2989. }
  2990. }
  2991. domUtils.remove(next);
  2992. }
  2993. }
  2994. !ignorePre && merge('previousSibling', 'firstChild', node);
  2995. !ignoreNext && merge('nextSibling', 'lastChild', node);
  2996. },
  2997. /**
  2998. * 设置节点node及其子节点不会被选中
  2999. * @method unSelectable
  3000. * @param { Element } node 需要执行操作的dom元素
  3001. * @remind 执行该操作后的节点, 将不能被鼠标选中
  3002. * @example
  3003. * ```javascript
  3004. * UE.dom.domUtils.unSelectable( document.body );
  3005. * ```
  3006. */
  3007. unSelectable:ie && browser.ie9below || browser.opera ? function (node) {
  3008. //for ie9
  3009. node.onselectstart = function () {
  3010. return false;
  3011. };
  3012. node.onclick = node.onkeyup = node.onkeydown = function () {
  3013. return false;
  3014. };
  3015. node.unselectable = 'on';
  3016. node.setAttribute("unselectable", "on");
  3017. for (var i = 0, ci; ci = node.all[i++];) {
  3018. switch (ci.tagName.toLowerCase()) {
  3019. case 'iframe' :
  3020. case 'textarea' :
  3021. case 'input' :
  3022. case 'select' :
  3023. break;
  3024. default :
  3025. ci.unselectable = 'on';
  3026. node.setAttribute("unselectable", "on");
  3027. }
  3028. }
  3029. } : function (node) {
  3030. node.style.MozUserSelect =
  3031. node.style.webkitUserSelect =
  3032. node.style.msUserSelect =
  3033. node.style.KhtmlUserSelect = 'none';
  3034. },
  3035. /**
  3036. * 删除节点node上的指定属性名称的属性
  3037. * @method removeAttributes
  3038. * @param { Node } node 需要删除属性的节点对象
  3039. * @param { String } attrNames 可以是空格隔开的多个属性名称,该操作将会依次删除相应的属性
  3040. * @example
  3041. * ```html
  3042. * <div id="wrap">
  3043. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3044. * </div>
  3045. *
  3046. * <script>
  3047. *
  3048. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), "id name" );
  3049. *
  3050. * //output: <span style="font-size:14px;">xxxxx</span>
  3051. * console.log( document.getElementById("wrap").innerHTML );
  3052. *
  3053. * </script>
  3054. * ```
  3055. */
  3056. /**
  3057. * 删除节点node上的指定属性名称的属性
  3058. * @method removeAttributes
  3059. * @param { Node } node 需要删除属性的节点对象
  3060. * @param { Array } attrNames 需要删除的属性名数组
  3061. * @example
  3062. * ```html
  3063. * <div id="wrap">
  3064. * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span>
  3065. * </div>
  3066. *
  3067. * <script>
  3068. *
  3069. * UE.dom.domUtils.removeAttributes( document.getElementById( "test" ), ["id", "name"] );
  3070. *
  3071. * //output: <span style="font-size:14px;">xxxxx</span>
  3072. * console.log( document.getElementById("wrap").innerHTML );
  3073. *
  3074. * </script>
  3075. * ```
  3076. */
  3077. removeAttributes:function (node, attrNames) {
  3078. attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' ');
  3079. for (var i = 0, ci; ci = attrNames[i++];) {
  3080. ci = attrFix[ci] || ci;
  3081. switch (ci) {
  3082. case 'className':
  3083. node[ci] = '';
  3084. break;
  3085. case 'style':
  3086. node.style.cssText = '';
  3087. var val = node.getAttributeNode('style');
  3088. !browser.ie && val && node.removeAttributeNode(val);
  3089. }
  3090. node.removeAttribute(ci);
  3091. }
  3092. },
  3093. /**
  3094. * 在doc下创建一个标签名为tag,属性为attrs的元素
  3095. * @method createElement
  3096. * @param { DomDocument } doc 新创建的元素属于该document节点创建
  3097. * @param { String } tagName 需要创建的元素的标签名
  3098. * @param { Object } attrs 新创建的元素的属性key-value集合
  3099. * @return { Element } 新创建的元素对象
  3100. * @example
  3101. * ```javascript
  3102. * var ele = UE.dom.domUtils.createElement( document, 'div', {
  3103. * id: 'test'
  3104. * } );
  3105. *
  3106. * //output: DIV
  3107. * console.log( ele.tagName );
  3108. *
  3109. * //output: test
  3110. * console.log( ele.id );
  3111. *
  3112. * ```
  3113. */
  3114. createElement:function (doc, tag, attrs) {
  3115. return domUtils.setAttributes(doc.createElement(tag), attrs)
  3116. },
  3117. /**
  3118. * 为节点node添加属性attrs,attrs为属性键值对
  3119. * @method setAttributes
  3120. * @param { Element } node 需要设置属性的元素对象
  3121. * @param { Object } attrs 需要设置的属性名-值对
  3122. * @return { Element } 设置属性的元素对象
  3123. * @example
  3124. * ```html
  3125. * <span id="test"></span>
  3126. *
  3127. * <script>
  3128. *
  3129. * var testNode = UE.dom.domUtils.setAttributes( document.getElementById( "test" ), {
  3130. * id: 'demo'
  3131. * } );
  3132. *
  3133. * //output: demo
  3134. * console.log( testNode.id );
  3135. *
  3136. * </script>
  3137. *
  3138. */
  3139. setAttributes:function (node, attrs) {
  3140. for (var attr in attrs) {
  3141. if(attrs.hasOwnProperty(attr)){
  3142. var value = attrs[attr];
  3143. switch (attr) {
  3144. case 'class':
  3145. //ie下要这样赋值,setAttribute不起作用
  3146. node.className = value;
  3147. break;
  3148. case 'style' :
  3149. node.style.cssText = node.style.cssText + ";" + value;
  3150. break;
  3151. case 'innerHTML':
  3152. node[attr] = value;
  3153. break;
  3154. case 'value':
  3155. node.value = value;
  3156. break;
  3157. default:
  3158. node.setAttribute(attrFix[attr] || attr, value);
  3159. }
  3160. }
  3161. }
  3162. return node;
  3163. },
  3164. /**
  3165. * 获取元素element经过计算后的样式值
  3166. * @method getComputedStyle
  3167. * @param { Element } element 需要获取样式的元素对象
  3168. * @param { String } styleName 需要获取的样式名
  3169. * @return { String } 获取到的样式值
  3170. * @example
  3171. * ```html
  3172. * <style type="text/css">
  3173. * #test {
  3174. * font-size: 15px;
  3175. * }
  3176. * </style>
  3177. *
  3178. * <span id="test"></span>
  3179. *
  3180. * <script>
  3181. * //output: 15px
  3182. * console.log( UE.dom.domUtils.getComputedStyle( document.getElementById( "test" ), 'font-size' ) );
  3183. * </script>
  3184. * ```
  3185. */
  3186. getComputedStyle:function (element, styleName) {
  3187. //一下的属性单独处理
  3188. var pros = 'width height top left';
  3189. if(pros.indexOf(styleName) > -1){
  3190. return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px';
  3191. }
  3192. //忽略文本节点
  3193. if (element.nodeType == 3) {
  3194. element = element.parentNode;
  3195. }
  3196. //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改.
  3197. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize &&
  3198. !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) {
  3199. var span = element.ownerDocument.createElement('span');
  3200. span.style.cssText = 'padding:0;border:0;font-family:simsun;';
  3201. span.innerHTML = '.';
  3202. element.appendChild(span);
  3203. var result = span.offsetHeight;
  3204. element.removeChild(span);
  3205. span = null;
  3206. return result + 'px';
  3207. }
  3208. try {
  3209. var value = domUtils.getStyle(element, styleName) ||
  3210. (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) :
  3211. ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]);
  3212. } catch (e) {
  3213. return "";
  3214. }
  3215. return utils.transUnitToPx(utils.fixColor(styleName, value));
  3216. },
  3217. /**
  3218. * 删除元素element指定的className
  3219. * @method removeClasses
  3220. * @param { Element } ele 需要删除class的元素节点
  3221. * @param { String } classNames 需要删除的className, 多个className之间以空格分开
  3222. * @example
  3223. * ```html
  3224. * <span id="test" class="test1 test2 test3">xxx</span>
  3225. *
  3226. * <script>
  3227. *
  3228. * var testNode = document.getElementById( "test" );
  3229. * UE.dom.domUtils.removeClasses( testNode, "test1 test2" );
  3230. *
  3231. * //output: test3
  3232. * console.log( testNode.className );
  3233. *
  3234. * </script>
  3235. * ```
  3236. */
  3237. /**
  3238. * 删除元素element指定的className
  3239. * @method removeClasses
  3240. * @param { Element } ele 需要删除class的元素节点
  3241. * @param { Array } classNames 需要删除的className数组
  3242. * @example
  3243. * ```html
  3244. * <span id="test" class="test1 test2 test3">xxx</span>
  3245. *
  3246. * <script>
  3247. *
  3248. * var testNode = document.getElementById( "test" );
  3249. * UE.dom.domUtils.removeClasses( testNode, ["test1", "test2"] );
  3250. *
  3251. * //output: test3
  3252. * console.log( testNode.className );
  3253. *
  3254. * </script>
  3255. * ```
  3256. */
  3257. removeClasses:function (elm, classNames) {
  3258. classNames = utils.isArray(classNames) ? classNames :
  3259. utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3260. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3261. cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'')
  3262. }
  3263. cls = utils.trim(cls).replace(/[ ]{2,}/g,' ');
  3264. if(cls){
  3265. elm.className = cls;
  3266. }else{
  3267. domUtils.removeAttributes(elm,['class']);
  3268. }
  3269. },
  3270. /**
  3271. * 给元素element添加className
  3272. * @method addClass
  3273. * @param { Node } ele 需要增加className的元素
  3274. * @param { String } classNames 需要添加的className, 多个className之间以空格分割
  3275. * @remind 相同的类名不会被重复添加
  3276. * @example
  3277. * ```html
  3278. * <span id="test" class="cls1 cls2"></span>
  3279. *
  3280. * <script>
  3281. * var testNode = document.getElementById("test");
  3282. *
  3283. * UE.dom.domUtils.addClass( testNode, "cls2 cls3 cls4" );
  3284. *
  3285. * //output: cl1 cls2 cls3 cls4
  3286. * console.log( testNode.className );
  3287. *
  3288. * <script>
  3289. * ```
  3290. */
  3291. /**
  3292. * 给元素element添加className
  3293. * @method addClass
  3294. * @param { Node } ele 需要增加className的元素
  3295. * @param { Array } classNames 需要添加的className的数组
  3296. * @remind 相同的类名不会被重复添加
  3297. * @example
  3298. * ```html
  3299. * <span id="test" class="cls1 cls2"></span>
  3300. *
  3301. * <script>
  3302. * var testNode = document.getElementById("test");
  3303. *
  3304. * UE.dom.domUtils.addClass( testNode, ["cls2", "cls3", "cls4"] );
  3305. *
  3306. * //output: cl1 cls2 cls3 cls4
  3307. * console.log( testNode.className );
  3308. *
  3309. * <script>
  3310. * ```
  3311. */
  3312. addClass:function (elm, classNames) {
  3313. if(!elm)return;
  3314. classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' ');
  3315. for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){
  3316. if(!new RegExp('\\b' + ci + '\\b').test(cls)){
  3317. cls += ' ' + ci;
  3318. }
  3319. }
  3320. elm.className = utils.trim(cls);
  3321. },
  3322. /**
  3323. * 判断元素element是否包含给定的样式类名className
  3324. * @method hasClass
  3325. * @param { Node } ele 需要检测的元素
  3326. * @param { String } classNames 需要检测的className, 多个className之间用空格分割
  3327. * @return { Boolean } 元素是否包含所有给定的className
  3328. * @example
  3329. * ```html
  3330. * <span id="test1" class="cls1 cls2"></span>
  3331. *
  3332. * <script>
  3333. * var test1 = document.getElementById("test1");
  3334. *
  3335. * //output: false
  3336. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1 cls3" ) );
  3337. *
  3338. * //output: true
  3339. * console.log( UE.dom.domUtils.hasClass( test1, "cls2 cls1" ) );
  3340. * </script>
  3341. * ```
  3342. */
  3343. /**
  3344. * 判断元素element是否包含给定的样式类名className
  3345. * @method hasClass
  3346. * @param { Node } ele 需要检测的元素
  3347. * @param { Array } classNames 需要检测的className数组
  3348. * @return { Boolean } 元素是否包含所有给定的className
  3349. * @example
  3350. * ```html
  3351. * <span id="test1" class="cls1 cls2"></span>
  3352. *
  3353. * <script>
  3354. * var test1 = document.getElementById("test1");
  3355. *
  3356. * //output: false
  3357. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1", "cls3" ] ) );
  3358. *
  3359. * //output: true
  3360. * console.log( UE.dom.domUtils.hasClass( test1, [ "cls2", "cls1" ]) );
  3361. * </script>
  3362. * ```
  3363. */
  3364. hasClass:function (element, className) {
  3365. if(utils.isRegExp(className)){
  3366. return className.test(element.className)
  3367. }
  3368. className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' ');
  3369. for(var i = 0,ci,cls = element.className;ci=className[i++];){
  3370. if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){
  3371. return false;
  3372. }
  3373. }
  3374. return i - 1 == className.length;
  3375. },
  3376. /**
  3377. * 阻止事件默认行为
  3378. * @method preventDefault
  3379. * @param { Event } evt 需要阻止默认行为的事件对象
  3380. * @example
  3381. * ```javascript
  3382. * UE.dom.domUtils.preventDefault( evt );
  3383. * ```
  3384. */
  3385. preventDefault:function (evt) {
  3386. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  3387. },
  3388. /**
  3389. * 删除元素element指定的样式
  3390. * @method removeStyle
  3391. * @param { Element } element 需要删除样式的元素
  3392. * @param { String } styleName 需要删除的样式名
  3393. * @example
  3394. * ```html
  3395. * <span id="test" style="color: red; background: blue;"></span>
  3396. *
  3397. * <script>
  3398. *
  3399. * var testNode = document.getElementById("test");
  3400. *
  3401. * UE.dom.domUtils.removeStyle( testNode, 'color' );
  3402. *
  3403. * //output: background: blue;
  3404. * console.log( testNode.style.cssText );
  3405. *
  3406. * </script>
  3407. * ```
  3408. */
  3409. removeStyle:function (element, name) {
  3410. if(browser.ie ){
  3411. //针对color先单独处理一下
  3412. if(name == 'color'){
  3413. name = '(^|;)' + name;
  3414. }
  3415. element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'')
  3416. }else{
  3417. if (element.style.removeProperty) {
  3418. element.style.removeProperty (name);
  3419. }else {
  3420. element.style.removeAttribute (utils.cssStyleToDomStyle(name));
  3421. }
  3422. }
  3423. if (!element.style.cssText) {
  3424. domUtils.removeAttributes(element, ['style']);
  3425. }
  3426. },
  3427. /**
  3428. * 获取元素element的style属性的指定值
  3429. * @method getStyle
  3430. * @param { Element } element 需要获取属性值的元素
  3431. * @param { String } styleName 需要获取的style的名称
  3432. * @warning 该方法仅获取元素style属性中所标明的值
  3433. * @return { String } 该元素包含指定的style属性值
  3434. * @example
  3435. * ```html
  3436. * <div id="test" style="color: red;"></div>
  3437. *
  3438. * <script>
  3439. *
  3440. * var testNode = document.getElementById( "test" );
  3441. *
  3442. * //output: red
  3443. * console.log( UE.dom.domUtils.getStyle( testNode, "color" ) );
  3444. *
  3445. * //output: ""
  3446. * console.log( UE.dom.domUtils.getStyle( testNode, "background" ) );
  3447. *
  3448. * </script>
  3449. * ```
  3450. */
  3451. getStyle:function (element, name) {
  3452. var value = element.style[ utils.cssStyleToDomStyle(name) ];
  3453. return utils.fixColor(name, value);
  3454. },
  3455. /**
  3456. * 为元素element设置样式属性值
  3457. * @method setStyle
  3458. * @param { Element } element 需要设置样式的元素
  3459. * @param { String } styleName 样式名
  3460. * @param { String } styleValue 样式值
  3461. * @example
  3462. * ```html
  3463. * <div id="test"></div>
  3464. *
  3465. * <script>
  3466. *
  3467. * var testNode = document.getElementById( "test" );
  3468. *
  3469. * //output: ""
  3470. * console.log( testNode.style.color );
  3471. *
  3472. * UE.dom.domUtils.setStyle( testNode, 'color', 'red' );
  3473. * //output: "red"
  3474. * console.log( testNode.style.color );
  3475. *
  3476. * </script>
  3477. * ```
  3478. */
  3479. setStyle:function (element, name, value) {
  3480. element.style[utils.cssStyleToDomStyle(name)] = value;
  3481. if(!utils.trim(element.style.cssText)){
  3482. this.removeAttributes(element,'style')
  3483. }
  3484. },
  3485. /**
  3486. * 为元素element设置多个样式属性值
  3487. * @method setStyles
  3488. * @param { Element } element 需要设置样式的元素
  3489. * @param { Object } styles 样式名值对
  3490. * @example
  3491. * ```html
  3492. * <div id="test"></div>
  3493. *
  3494. * <script>
  3495. *
  3496. * var testNode = document.getElementById( "test" );
  3497. *
  3498. * //output: ""
  3499. * console.log( testNode.style.color );
  3500. *
  3501. * UE.dom.domUtils.setStyles( testNode, {
  3502. * 'color': 'red'
  3503. * } );
  3504. * //output: "red"
  3505. * console.log( testNode.style.color );
  3506. *
  3507. * </script>
  3508. * ```
  3509. */
  3510. setStyles:function (element, styles) {
  3511. for (var name in styles) {
  3512. if (styles.hasOwnProperty(name)) {
  3513. domUtils.setStyle(element, name, styles[name]);
  3514. }
  3515. }
  3516. },
  3517. /**
  3518. * 删除_moz_dirty属性
  3519. * @private
  3520. * @method removeDirtyAttr
  3521. */
  3522. removeDirtyAttr:function (node) {
  3523. for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) {
  3524. ci.removeAttribute('_moz_dirty');
  3525. }
  3526. node.removeAttribute('_moz_dirty');
  3527. },
  3528. /**
  3529. * 获取子节点的数量
  3530. * @method getChildCount
  3531. * @param { Element } node 需要检测的元素
  3532. * @return { Number } 给定的node元素的子节点数量
  3533. * @example
  3534. * ```html
  3535. * <div id="test">
  3536. * <span></span>
  3537. * </div>
  3538. *
  3539. * <script>
  3540. *
  3541. * //output: 3
  3542. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test") ) );
  3543. *
  3544. * </script>
  3545. * ```
  3546. */
  3547. /**
  3548. * 根据给定的过滤规则, 获取符合条件的子节点的数量
  3549. * @method getChildCount
  3550. * @param { Element } node 需要检测的元素
  3551. * @param { Function } fn 过滤器, 要求对符合条件的子节点返回true, 反之则要求返回false
  3552. * @return { Number } 符合过滤条件的node元素的子节点数量
  3553. * @example
  3554. * ```html
  3555. * <div id="test">
  3556. * <span></span>
  3557. * </div>
  3558. *
  3559. * <script>
  3560. *
  3561. * //output: 1
  3562. * console.log( UE.dom.domUtils.getChildCount( document.getElementById("test"), function ( node ) {
  3563. *
  3564. * return node.nodeType === 1;
  3565. *
  3566. * } ) );
  3567. *
  3568. * </script>
  3569. * ```
  3570. */
  3571. getChildCount:function (node, fn) {
  3572. var count = 0, first = node.firstChild;
  3573. fn = fn || function () {
  3574. return 1;
  3575. };
  3576. while (first) {
  3577. if (fn(first)) {
  3578. count++;
  3579. }
  3580. first = first.nextSibling;
  3581. }
  3582. return count;
  3583. },
  3584. /**
  3585. * 判断给定节点是否为空节点
  3586. * @method isEmptyNode
  3587. * @param { Node } node 需要检测的节点对象
  3588. * @return { Boolean } 节点是否为空
  3589. * @example
  3590. * ```javascript
  3591. * UE.dom.domUtils.isEmptyNode( document.body );
  3592. * ```
  3593. */
  3594. isEmptyNode:function (node) {
  3595. return !node.firstChild || domUtils.getChildCount(node, function (node) {
  3596. return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node)
  3597. }) == 0
  3598. },
  3599. clearSelectedArr:function (nodes) {
  3600. var node;
  3601. while (node = nodes.pop()) {
  3602. domUtils.removeAttributes(node, ['class']);
  3603. }
  3604. },
  3605. /**
  3606. * 将显示区域滚动到指定节点的位置
  3607. * @method scrollToView
  3608. * @param {Node} node 节点
  3609. * @param {window} win window对象
  3610. * @param {Number} offsetTop 距离上方的偏移量
  3611. */
  3612. scrollToView:function (node, win, offsetTop) {
  3613. var getViewPaneSize = function () {
  3614. var doc = win.document,
  3615. mode = doc.compatMode == 'CSS1Compat';
  3616. return {
  3617. width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0,
  3618. height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0
  3619. };
  3620. },
  3621. getScrollPosition = function (win) {
  3622. if ('pageXOffset' in win) {
  3623. return {
  3624. x:win.pageXOffset || 0,
  3625. y:win.pageYOffset || 0
  3626. };
  3627. }
  3628. else {
  3629. var doc = win.document;
  3630. return {
  3631. x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0,
  3632. y:doc.documentElement.scrollTop || doc.body.scrollTop || 0
  3633. };
  3634. }
  3635. };
  3636. var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop;
  3637. offset += (node.offsetHeight || 0);
  3638. var elementPosition = domUtils.getXY(node);
  3639. offset += elementPosition.y;
  3640. var currentScroll = getScrollPosition(win).y;
  3641. // offset += 50;
  3642. if (offset > currentScroll || offset < currentScroll - winHeight) {
  3643. win.scrollTo(0, offset + (offset < 0 ? -20 : 20));
  3644. }
  3645. },
  3646. /**
  3647. * 判断给定节点是否为br
  3648. * @method isBr
  3649. * @param { Node } node 需要判断的节点对象
  3650. * @return { Boolean } 给定的节点是否是br节点
  3651. */
  3652. isBr:function (node) {
  3653. return node.nodeType == 1 && node.tagName == 'BR';
  3654. },
  3655. /**
  3656. * 判断给定的节点是否是一个“填充”节点
  3657. * @private
  3658. * @method isFillChar
  3659. * @param { Node } node 需要判断的节点
  3660. * @param { Boolean } isInStart 是否从节点内容的开始位置匹配
  3661. * @returns { Boolean } 节点是否是填充节点
  3662. */
  3663. isFillChar:function (node,isInStart) {
  3664. if(node.nodeType != 3)
  3665. return false;
  3666. var text = node.nodeValue;
  3667. if(isInStart){
  3668. return new RegExp('^' + domUtils.fillChar).test(text)
  3669. }
  3670. return !text.replace(new RegExp(domUtils.fillChar,'g'), '').length
  3671. },
  3672. isStartInblock:function (range) {
  3673. var tmpRange = range.cloneRange(),
  3674. flag = 0,
  3675. start = tmpRange.startContainer,
  3676. tmp;
  3677. if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){
  3678. start = start.childNodes[tmpRange.startOffset];
  3679. var pre = start.previousSibling;
  3680. while(pre && domUtils.isFillChar(pre)){
  3681. start = pre;
  3682. pre = pre.previousSibling;
  3683. }
  3684. }
  3685. if(this.isFillChar(start,true) && tmpRange.startOffset == 1){
  3686. tmpRange.setStartBefore(start);
  3687. start = tmpRange.startContainer;
  3688. }
  3689. while (start && domUtils.isFillChar(start)) {
  3690. tmp = start;
  3691. start = start.previousSibling
  3692. }
  3693. if (tmp) {
  3694. tmpRange.setStartBefore(tmp);
  3695. start = tmpRange.startContainer;
  3696. }
  3697. if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) {
  3698. tmpRange.setStart(start, 0).collapse(true);
  3699. }
  3700. while (!tmpRange.startOffset) {
  3701. start = tmpRange.startContainer;
  3702. if (domUtils.isBlockElm(start) || domUtils.isBody(start)) {
  3703. flag = 1;
  3704. break;
  3705. }
  3706. var pre = tmpRange.startContainer.previousSibling,
  3707. tmpNode;
  3708. if (!pre) {
  3709. tmpRange.setStartBefore(tmpRange.startContainer);
  3710. } else {
  3711. while (pre && domUtils.isFillChar(pre)) {
  3712. tmpNode = pre;
  3713. pre = pre.previousSibling;
  3714. }
  3715. if (tmpNode) {
  3716. tmpRange.setStartBefore(tmpNode);
  3717. } else {
  3718. tmpRange.setStartBefore(tmpRange.startContainer);
  3719. }
  3720. }
  3721. }
  3722. return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0;
  3723. },
  3724. /**
  3725. * 判断给定的元素是否是一个空元素
  3726. * @method isEmptyBlock
  3727. * @param { Element } node 需要判断的元素
  3728. * @return { Boolean } 是否是空元素
  3729. * @example
  3730. * ```html
  3731. * <div id="test"></div>
  3732. *
  3733. * <script>
  3734. * //output: true
  3735. * console.log( UE.dom.domUtils.isEmptyBlock( document.getElementById("test") ) );
  3736. * </script>
  3737. * ```
  3738. */
  3739. /**
  3740. * 根据指定的判断规则判断给定的元素是否是一个空元素
  3741. * @method isEmptyBlock
  3742. * @param { Element } node 需要判断的元素
  3743. * @param { RegExp } reg 对内容执行判断的正则表达式对象
  3744. * @return { Boolean } 是否是空元素
  3745. */
  3746. isEmptyBlock:function (node,reg) {
  3747. if(node.nodeType != 1)
  3748. return 0;
  3749. reg = reg || new RegExp('[ \xa0\t\r\n' + domUtils.fillChar + ']', 'g');
  3750. if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) {
  3751. return 0;
  3752. }
  3753. for (var n in dtd.$isNotEmpty) {
  3754. if (node.getElementsByTagName(n).length) {
  3755. return 0;
  3756. }
  3757. }
  3758. return 1;
  3759. },
  3760. /**
  3761. * 移动元素使得该元素的位置移动指定的偏移量的距离
  3762. * @method setViewportOffset
  3763. * @param { Element } element 需要设置偏移量的元素
  3764. * @param { Object } offset 偏移量, 形如{ left: 100, top: 50 }的一个键值对, 表示该元素将在
  3765. * 现有的位置上向水平方向偏移offset.left的距离, 在竖直方向上偏移
  3766. * offset.top的距离
  3767. * @example
  3768. * ```html
  3769. * <div id="test" style="top: 100px; left: 50px; position: absolute;"></div>
  3770. *
  3771. * <script>
  3772. *
  3773. * var testNode = document.getElementById("test");
  3774. *
  3775. * UE.dom.domUtils.setViewportOffset( testNode, {
  3776. * left: 200,
  3777. * top: 50
  3778. * } );
  3779. *
  3780. * //output: top: 300px; left: 100px; position: absolute;
  3781. * console.log( testNode.style.cssText );
  3782. *
  3783. * </script>
  3784. * ```
  3785. */
  3786. setViewportOffset:function (element, offset) {
  3787. var left = parseInt(element.style.left) | 0;
  3788. var top = parseInt(element.style.top) | 0;
  3789. var rect = element.getBoundingClientRect();
  3790. var offsetLeft = offset.left - rect.left;
  3791. var offsetTop = offset.top - rect.top;
  3792. if (offsetLeft) {
  3793. element.style.left = left + offsetLeft + 'px';
  3794. }
  3795. if (offsetTop) {
  3796. element.style.top = top + offsetTop + 'px';
  3797. }
  3798. },
  3799. /**
  3800. * 用“填充字符”填充节点
  3801. * @method fillNode
  3802. * @private
  3803. * @param { DomDocument } doc 填充的节点所在的docment对象
  3804. * @param { Node } node 需要填充的节点对象
  3805. * @example
  3806. * ```html
  3807. * <div id="test"></div>
  3808. *
  3809. * <script>
  3810. * var testNode = document.getElementById("test");
  3811. *
  3812. * //output: 0
  3813. * console.log( testNode.childNodes.length );
  3814. *
  3815. * UE.dom.domUtils.fillNode( document, testNode );
  3816. *
  3817. * //output: 1
  3818. * console.log( testNode.childNodes.length );
  3819. *
  3820. * </script>
  3821. * ```
  3822. */
  3823. fillNode:function (doc, node) {
  3824. var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br');
  3825. node.innerHTML = '';
  3826. node.appendChild(tmpNode);
  3827. },
  3828. /**
  3829. * 把节点src的所有子节点追加到另一个节点tag上去
  3830. * @method moveChild
  3831. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3832. * @param { Node } tag 目标节点, 从源节点移除的子节点将被追加到该节点下
  3833. * @example
  3834. * ```html
  3835. * <div id="test1">
  3836. * <span></span>
  3837. * </div>
  3838. * <div id="test2">
  3839. * <div></div>
  3840. * </div>
  3841. *
  3842. * <script>
  3843. *
  3844. * var test1 = document.getElementById("test1"),
  3845. * test2 = document.getElementById("test2");
  3846. *
  3847. * UE.dom.domUtils.moveChild( test1, test2 );
  3848. *
  3849. * //output: ""(空字符串)
  3850. * console.log( test1.innerHTML );
  3851. *
  3852. * //output: "<div></div><span></span>"
  3853. * console.log( test2.innerHTML );
  3854. *
  3855. * </script>
  3856. * ```
  3857. */
  3858. /**
  3859. * 把节点src的所有子节点移动到另一个节点tag上去, 可以通过dir参数控制附加的行为是“追加”还是“插入顶部”
  3860. * @method moveChild
  3861. * @param { Node } src 源节点, 该节点下的所有子节点将被移除
  3862. * @param { Node } tag 目标节点, 从源节点移除的子节点将被附加到该节点下
  3863. * @param { Boolean } dir 附加方式, 如果为true, 则附加进去的节点将被放到目标节点的顶部, 反之,则放到末尾
  3864. * @example
  3865. * ```html
  3866. * <div id="test1">
  3867. * <span></span>
  3868. * </div>
  3869. * <div id="test2">
  3870. * <div></div>
  3871. * </div>
  3872. *
  3873. * <script>
  3874. *
  3875. * var test1 = document.getElementById("test1"),
  3876. * test2 = document.getElementById("test2");
  3877. *
  3878. * UE.dom.domUtils.moveChild( test1, test2, true );
  3879. *
  3880. * //output: ""(空字符串)
  3881. * console.log( test1.innerHTML );
  3882. *
  3883. * //output: "<span></span><div></div>"
  3884. * console.log( test2.innerHTML );
  3885. *
  3886. * </script>
  3887. * ```
  3888. */
  3889. moveChild:function (src, tag, dir) {
  3890. while (src.firstChild) {
  3891. if (dir && tag.firstChild) {
  3892. tag.insertBefore(src.lastChild, tag.firstChild);
  3893. } else {
  3894. tag.appendChild(src.firstChild);
  3895. }
  3896. }
  3897. },
  3898. /**
  3899. * 判断节点的标签上是否不存在任何属性
  3900. * @method hasNoAttributes
  3901. * @private
  3902. * @param { Node } node 需要检测的节点对象
  3903. * @return { Boolean } 节点是否不包含任何属性
  3904. * @example
  3905. * ```html
  3906. * <div id="test"><span>xxxx</span></div>
  3907. *
  3908. * <script>
  3909. *
  3910. * //output: false
  3911. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test") ) );
  3912. *
  3913. * //output: true
  3914. * console.log( UE.dom.domUtils.hasNoAttributes( document.getElementById("test").firstChild ) );
  3915. *
  3916. * </script>
  3917. * ```
  3918. */
  3919. hasNoAttributes:function (node) {
  3920. return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0;
  3921. },
  3922. /**
  3923. * 检测节点是否是UEditor所使用的辅助节点
  3924. * @method isCustomeNode
  3925. * @private
  3926. * @param { Node } node 需要检测的节点
  3927. * @remind 辅助节点是指编辑器要完成工作临时添加的节点, 在输出的时候将会从编辑器内移除, 不会影响最终的结果。
  3928. * @return { Boolean } 给定的节点是否是一个辅助节点
  3929. */
  3930. isCustomeNode:function (node) {
  3931. return node.nodeType == 1 && node.getAttribute('_ue_custom_node_');
  3932. },
  3933. /**
  3934. * 检测节点的标签是否是给定的标签
  3935. * @method isTagNode
  3936. * @param { Node } node 需要检测的节点对象
  3937. * @param { String } tagName 标签
  3938. * @return { Boolean } 节点的标签是否是给定的标签
  3939. * @example
  3940. * ```html
  3941. * <div id="test"></div>
  3942. *
  3943. * <script>
  3944. *
  3945. * //output: true
  3946. * console.log( UE.dom.domUtils.isTagNode( document.getElementById("test"), "div" ) );
  3947. *
  3948. * </script>
  3949. * ```
  3950. */
  3951. isTagNode:function (node, tagNames) {
  3952. return node.nodeType == 1 && new RegExp('\\b' + node.tagName + '\\b','i').test(tagNames)
  3953. },
  3954. /**
  3955. * 给定一个节点数组,在通过指定的过滤器过滤后, 获取其中满足过滤条件的第一个节点
  3956. * @method filterNodeList
  3957. * @param { Array } nodeList 需要过滤的节点数组
  3958. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3959. * @return { Node | NULL } 如果找到符合过滤条件的节点, 则返回该节点, 否则返回NULL
  3960. * @example
  3961. * ```javascript
  3962. * var divNodes = document.getElementsByTagName("div");
  3963. * divNodes = [].slice.call( divNodes, 0 );
  3964. *
  3965. * //output: null
  3966. * console.log( UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  3967. * return node.tagName.toLowerCase() !== 'div';
  3968. * } ) );
  3969. * ```
  3970. */
  3971. /**
  3972. * 给定一个节点数组nodeList和一组标签名tagNames, 获取其中能够匹配标签名的节点集合中的第一个节点
  3973. * @method filterNodeList
  3974. * @param { Array } nodeList 需要过滤的节点数组
  3975. * @param { String } tagNames 需要匹配的标签名, 多个标签名之间用空格分割
  3976. * @return { Node | NULL } 如果找到标签名匹配的节点, 则返回该节点, 否则返回NULL
  3977. * @example
  3978. * ```javascript
  3979. * var divNodes = document.getElementsByTagName("div");
  3980. * divNodes = [].slice.call( divNodes, 0 );
  3981. *
  3982. * //output: null
  3983. * console.log( UE.dom.domUtils.filterNodeList( divNodes, 'a span' ) );
  3984. * ```
  3985. */
  3986. /**
  3987. * 给定一个节点数组,在通过指定的过滤器过滤后, 如果参数forAll为true, 则会返回所有满足过滤
  3988. * 条件的节点集合, 否则, 返回满足条件的节点集合中的第一个节点
  3989. * @method filterNodeList
  3990. * @param { Array } nodeList 需要过滤的节点数组
  3991. * @param { Function } fn 过滤器, 对符合条件的节点, 执行结果返回true, 反之则返回false
  3992. * @param { Boolean } forAll 是否返回整个节点数组, 如果该参数为false, 则返回节点集合中的第一个节点
  3993. * @return { Array | Node | NULL } 如果找到符合过滤条件的节点, 则根据参数forAll的值决定返回满足
  3994. * 过滤条件的节点数组或第一个节点, 否则返回NULL
  3995. * @example
  3996. * ```javascript
  3997. * var divNodes = document.getElementsByTagName("div");
  3998. * divNodes = [].slice.call( divNodes, 0 );
  3999. *
  4000. * //output: 3(假定有3个div)
  4001. * console.log( divNodes.length );
  4002. *
  4003. * var nodes = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4004. * return node.tagName.toLowerCase() === 'div';
  4005. * }, true );
  4006. *
  4007. * //output: 3
  4008. * console.log( nodes.length );
  4009. *
  4010. * var node = UE.dom.domUtils.filterNodeList( divNodes, function ( node ) {
  4011. * return node.tagName.toLowerCase() === 'div';
  4012. * }, false );
  4013. *
  4014. * //output: div
  4015. * console.log( node.nodeName );
  4016. * ```
  4017. */
  4018. filterNodeList : function(nodelist,filter,forAll){
  4019. var results = [];
  4020. if(!utils .isFunction(filter)){
  4021. var str = filter;
  4022. filter = function(n){
  4023. return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1
  4024. };
  4025. }
  4026. utils.each(nodelist,function(n){
  4027. filter(n) && results.push(n)
  4028. });
  4029. return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results
  4030. },
  4031. /**
  4032. * 查询给定的range选区是否在给定的node节点内,且在该节点的最末尾
  4033. * @method isInNodeEndBoundary
  4034. * @param { UE.dom.Range } rng 需要判断的range对象, 该对象的startContainer不能为NULL
  4035. * @param node 需要检测的节点对象
  4036. * @return { Number } 如果给定的选取range对象是在node内部的最末端, 则返回1, 否则返回0
  4037. */
  4038. isInNodeEndBoundary : function (rng,node){
  4039. var start = rng.startContainer;
  4040. if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){
  4041. return 0;
  4042. }
  4043. if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){
  4044. return 0;
  4045. }
  4046. while(start !== node){
  4047. if(start.nextSibling){
  4048. return 0
  4049. };
  4050. start = start.parentNode;
  4051. }
  4052. return 1;
  4053. },
  4054. isBoundaryNode : function (node,dir){
  4055. var tmp;
  4056. while(!domUtils.isBody(node)){
  4057. tmp = node;
  4058. node = node.parentNode;
  4059. if(tmp !== node[dir]){
  4060. return false;
  4061. }
  4062. }
  4063. return true;
  4064. },
  4065. fillHtml : browser.ie11below ? '&nbsp;' : '<br/>'
  4066. };
  4067. var fillCharReg = new RegExp(domUtils.fillChar, 'g');
  4068. // core/Range.js
  4069. /**
  4070. * Range封装
  4071. * @file
  4072. * @module UE.dom
  4073. * @class Range
  4074. * @since 1.2.6.1
  4075. */
  4076. /**
  4077. * dom操作封装
  4078. * @unfile
  4079. * @module UE.dom
  4080. */
  4081. /**
  4082. * Range实现类,本类是UEditor底层核心类,封装不同浏览器之间的Range操作。
  4083. * @unfile
  4084. * @module UE.dom
  4085. * @class Range
  4086. */
  4087. (function () {
  4088. var guid = 0,
  4089. fillChar = domUtils.fillChar,
  4090. fillData;
  4091. /**
  4092. * 更新range的collapse状态
  4093. * @param {Range} range range对象
  4094. */
  4095. function updateCollapse(range) {
  4096. range.collapsed =
  4097. range.startContainer && range.endContainer &&
  4098. range.startContainer === range.endContainer &&
  4099. range.startOffset == range.endOffset;
  4100. }
  4101. function selectOneNode(rng){
  4102. return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1
  4103. }
  4104. function setEndPoint(toStart, node, offset, range) {
  4105. //如果node是自闭合标签要处理
  4106. if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) {
  4107. offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1);
  4108. node = node.parentNode;
  4109. }
  4110. if (toStart) {
  4111. range.startContainer = node;
  4112. range.startOffset = offset;
  4113. if (!range.endContainer) {
  4114. range.collapse(true);
  4115. }
  4116. } else {
  4117. range.endContainer = node;
  4118. range.endOffset = offset;
  4119. if (!range.startContainer) {
  4120. range.collapse(false);
  4121. }
  4122. }
  4123. updateCollapse(range);
  4124. return range;
  4125. }
  4126. function execContentsAction(range, action) {
  4127. //调整边界
  4128. //range.includeBookmark();
  4129. var start = range.startContainer,
  4130. end = range.endContainer,
  4131. startOffset = range.startOffset,
  4132. endOffset = range.endOffset,
  4133. doc = range.document,
  4134. frag = doc.createDocumentFragment(),
  4135. tmpStart, tmpEnd;
  4136. if (start.nodeType == 1) {
  4137. start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode('')));
  4138. }
  4139. if (end.nodeType == 1) {
  4140. end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode('')));
  4141. }
  4142. if (start === end && start.nodeType == 3) {
  4143. frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset)));
  4144. //is not clone
  4145. if (action) {
  4146. start.deleteData(startOffset, endOffset - startOffset);
  4147. range.collapse(true);
  4148. }
  4149. return frag;
  4150. }
  4151. var current, currentLevel, clone = frag,
  4152. startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true);
  4153. for (var i = 0; startParents[i] == endParents[i];) {
  4154. i++;
  4155. }
  4156. for (var j = i, si; si = startParents[j]; j++) {
  4157. current = si.nextSibling;
  4158. if (si == start) {
  4159. if (!tmpStart) {
  4160. if (range.startContainer.nodeType == 3) {
  4161. clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset)));
  4162. //is not clone
  4163. if (action) {
  4164. start.deleteData(startOffset, start.nodeValue.length - startOffset);
  4165. }
  4166. } else {
  4167. clone.appendChild(!action ? start.cloneNode(true) : start);
  4168. }
  4169. }
  4170. } else {
  4171. currentLevel = si.cloneNode(false);
  4172. clone.appendChild(currentLevel);
  4173. }
  4174. while (current) {
  4175. if (current === end || current === endParents[j]) {
  4176. break;
  4177. }
  4178. si = current.nextSibling;
  4179. clone.appendChild(!action ? current.cloneNode(true) : current);
  4180. current = si;
  4181. }
  4182. clone = currentLevel;
  4183. }
  4184. clone = frag;
  4185. if (!startParents[i]) {
  4186. clone.appendChild(startParents[i - 1].cloneNode(false));
  4187. clone = clone.firstChild;
  4188. }
  4189. for (var j = i, ei; ei = endParents[j]; j++) {
  4190. current = ei.previousSibling;
  4191. if (ei == end) {
  4192. if (!tmpEnd && range.endContainer.nodeType == 3) {
  4193. clone.appendChild(doc.createTextNode(end.substringData(0, endOffset)));
  4194. //is not clone
  4195. if (action) {
  4196. end.deleteData(0, endOffset);
  4197. }
  4198. }
  4199. } else {
  4200. currentLevel = ei.cloneNode(false);
  4201. clone.appendChild(currentLevel);
  4202. }
  4203. //如果两端同级,右边第一次已经被开始做了
  4204. if (j != i || !startParents[i]) {
  4205. while (current) {
  4206. if (current === start) {
  4207. break;
  4208. }
  4209. ei = current.previousSibling;
  4210. clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild);
  4211. current = ei;
  4212. }
  4213. }
  4214. clone = currentLevel;
  4215. }
  4216. if (action) {
  4217. range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true);
  4218. }
  4219. tmpStart && domUtils.remove(tmpStart);
  4220. tmpEnd && domUtils.remove(tmpEnd);
  4221. return frag;
  4222. }
  4223. /**
  4224. * 创建一个跟document绑定的空的Range实例
  4225. * @constructor
  4226. * @param { Document } document 新建的选区所属的文档对象
  4227. */
  4228. /**
  4229. * @property { Node } startContainer 当前Range的开始边界的容器节点, 可以是一个元素节点或者是文本节点
  4230. */
  4231. /**
  4232. * @property { Node } startOffset 当前Range的开始边界容器节点的偏移量, 如果是元素节点,
  4233. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4234. */
  4235. /**
  4236. * @property { Node } endContainer 当前Range的结束边界的容器节点, 可以是一个元素节点或者是文本节点
  4237. */
  4238. /**
  4239. * @property { Node } endOffset 当前Range的结束边界容器节点的偏移量, 如果是元素节点,
  4240. * 该值就是childNodes中的第几个节点, 如果是文本节点就是文本内容的第几个字符
  4241. */
  4242. /**
  4243. * @property { Boolean } collapsed 当前Range是否闭合
  4244. * @default true
  4245. * @remind Range是闭合的时候, startContainer === endContainer && startOffset === endOffset
  4246. */
  4247. /**
  4248. * @property { Document } document 当前Range所属的Document对象
  4249. * @remind 不同range的的document属性可以是不同的
  4250. */
  4251. var Range = dom.Range = function (document) {
  4252. var me = this;
  4253. me.startContainer =
  4254. me.startOffset =
  4255. me.endContainer =
  4256. me.endOffset = null;
  4257. me.document = document;
  4258. me.collapsed = true;
  4259. };
  4260. /**
  4261. * 删除fillData
  4262. * @param doc
  4263. * @param excludeNode
  4264. */
  4265. function removeFillData(doc, excludeNode) {
  4266. try {
  4267. if (fillData && domUtils.inDoc(fillData, doc)) {
  4268. if (!fillData.nodeValue.replace(fillCharReg, '').length) {
  4269. var tmpNode = fillData.parentNode;
  4270. domUtils.remove(fillData);
  4271. while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) &&
  4272. //safari的contains有bug
  4273. (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode))
  4274. ) {
  4275. fillData = tmpNode.parentNode;
  4276. domUtils.remove(tmpNode);
  4277. tmpNode = fillData;
  4278. }
  4279. } else {
  4280. fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, '');
  4281. }
  4282. }
  4283. } catch (e) {
  4284. }
  4285. }
  4286. /**
  4287. * @param node
  4288. * @param dir
  4289. */
  4290. function mergeSibling(node, dir) {
  4291. var tmpNode;
  4292. node = node[dir];
  4293. while (node && domUtils.isFillChar(node)) {
  4294. tmpNode = node[dir];
  4295. domUtils.remove(node);
  4296. node = tmpNode;
  4297. }
  4298. }
  4299. Range.prototype = {
  4300. /**
  4301. * 克隆选区的内容到一个DocumentFragment里
  4302. * @method cloneContents
  4303. * @return { DocumentFragment | NULL } 如果选区是闭合的将返回null, 否则, 返回包含所clone内容的DocumentFragment元素
  4304. * @example
  4305. * ```html
  4306. * <body>
  4307. * <!-- 中括号表示选区 -->
  4308. * <b>x<i>x[x</i>xx]x</b>
  4309. *
  4310. * <script>
  4311. * //range是已选中的选区
  4312. * var fragment = range.cloneContents(),
  4313. * node = document.createElement("div");
  4314. *
  4315. * node.appendChild( fragment );
  4316. *
  4317. * //output: <i>x</i>xx
  4318. * console.log( node.innerHTML );
  4319. *
  4320. * </script>
  4321. * </body>
  4322. * ```
  4323. */
  4324. cloneContents:function () {
  4325. return this.collapsed ? null : execContentsAction(this, 0);
  4326. },
  4327. /**
  4328. * 删除当前选区范围中的所有内容
  4329. * @method deleteContents
  4330. * @remind 执行完该操作后, 当前Range对象变成了闭合状态
  4331. * @return { UE.dom.Range } 当前操作的Range对象
  4332. * @example
  4333. * ```html
  4334. * <body>
  4335. * <!-- 中括号表示选区 -->
  4336. * <b>x<i>x[x</i>xx]x</b>
  4337. *
  4338. * <script>
  4339. * //range是已选中的选区
  4340. * range.deleteContents();
  4341. *
  4342. * //竖线表示闭合后的选区位置
  4343. * //output: <b>x<i>x</i>|x</b>
  4344. * console.log( document.body.innerHTML );
  4345. *
  4346. * //此时, range的各项属性为
  4347. * //output: B
  4348. * console.log( range.startContainer.tagName );
  4349. * //output: 2
  4350. * console.log( range.startOffset );
  4351. * //output: B
  4352. * console.log( range.endContainer.tagName );
  4353. * //output: 2
  4354. * console.log( range.endOffset );
  4355. * //output: true
  4356. * console.log( range.collapsed );
  4357. *
  4358. * </script>
  4359. * </body>
  4360. * ```
  4361. */
  4362. deleteContents:function () {
  4363. var txt;
  4364. if (!this.collapsed) {
  4365. execContentsAction(this, 1);
  4366. }
  4367. if (browser.webkit) {
  4368. txt = this.startContainer;
  4369. if (txt.nodeType == 3 && !txt.nodeValue.length) {
  4370. this.setStartBefore(txt).collapse(true);
  4371. domUtils.remove(txt);
  4372. }
  4373. }
  4374. return this;
  4375. },
  4376. /**
  4377. * 将当前选区的内容提取到一个DocumentFragment里
  4378. * @method extractContents
  4379. * @remind 执行该操作后, 选区将变成闭合状态
  4380. * @warning 执行该操作后, 原来选区所选中的内容将从dom树上剥离出来
  4381. * @return { DocumentFragment } 返回包含所提取内容的DocumentFragment对象
  4382. * @example
  4383. * ```html
  4384. * <body>
  4385. * <!-- 中括号表示选区 -->
  4386. * <b>x<i>x[x</i>xx]x</b>
  4387. *
  4388. * <script>
  4389. * //range是已选中的选区
  4390. * var fragment = range.extractContents(),
  4391. * node = document.createElement( "div" );
  4392. *
  4393. * node.appendChild( fragment );
  4394. *
  4395. * //竖线表示闭合后的选区位置
  4396. *
  4397. * //output: <b>x<i>x</i>|x</b>
  4398. * console.log( document.body.innerHTML );
  4399. * //output: <i>x</i>xx
  4400. * console.log( node.innerHTML );
  4401. *
  4402. * //此时, range的各项属性为
  4403. * //output: B
  4404. * console.log( range.startContainer.tagName );
  4405. * //output: 2
  4406. * console.log( range.startOffset );
  4407. * //output: B
  4408. * console.log( range.endContainer.tagName );
  4409. * //output: 2
  4410. * console.log( range.endOffset );
  4411. * //output: true
  4412. * console.log( range.collapsed );
  4413. *
  4414. * </script>
  4415. * </body>
  4416. */
  4417. extractContents:function () {
  4418. return this.collapsed ? null : execContentsAction(this, 2);
  4419. },
  4420. /**
  4421. * 设置Range的开始容器节点和偏移量
  4422. * @method setStart
  4423. * @remind 如果给定的节点是元素节点,那么offset指的是其子元素中索引为offset的元素,
  4424. * 如果是文本节点,那么offset指的是其文本内容的第offset个字符
  4425. * @remind 如果提供的容器节点是一个不能包含子元素的节点, 则该选区的开始容器将被设置
  4426. * 为该节点的父节点, 此时, 其距离开始容器的偏移量也变成了该节点在其父节点
  4427. * 中的索引
  4428. * @param { Node } node 将被设为当前选区开始边界容器的节点对象
  4429. * @param { int } offset 选区的开始位置偏移量
  4430. * @return { UE.dom.Range } 当前range对象
  4431. * @example
  4432. * ```html
  4433. * <!-- 选区 -->
  4434. * <b>xxx<i>x<span>xx</span>xx<em>xx</em>xxx</i>[xxx]</b>
  4435. *
  4436. * <script>
  4437. *
  4438. * //执行操作
  4439. * range.setStart( document.getElementsByTagName("i")[0], 1 );
  4440. *
  4441. * //此时, 选区变成了
  4442. * //<b>xxx<i>x[<span>xx</span>xx<em>xx</em>xxx</i>xxx]</b>
  4443. *
  4444. * </script>
  4445. * ```
  4446. * @example
  4447. * ```html
  4448. * <!-- 选区 -->
  4449. * <b>xxx<img>[xx]x</b>
  4450. *
  4451. * <script>
  4452. *
  4453. * //执行操作
  4454. * range.setStart( document.getElementsByTagName("img")[0], 3 );
  4455. *
  4456. * //此时, 选区变成了
  4457. * //<b>xxx[<img>xx]x</b>
  4458. *
  4459. * </script>
  4460. * ```
  4461. */
  4462. setStart:function (node, offset) {
  4463. return setEndPoint(true, node, offset, this);
  4464. },
  4465. /**
  4466. * 设置Range的结束容器和偏移量
  4467. * @method setEnd
  4468. * @param { Node } node 作为当前选区结束边界容器的节点对象
  4469. * @param { int } offset 结束边界的偏移量
  4470. * @see UE.dom.Range:setStart(Node,int)
  4471. * @return { UE.dom.Range } 当前range对象
  4472. */
  4473. setEnd:function (node, offset) {
  4474. return setEndPoint(false, node, offset, this);
  4475. },
  4476. /**
  4477. * 将Range开始位置设置到node节点之后
  4478. * @method setStartAfter
  4479. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引+1
  4480. * @param { Node } node 选区的开始边界将紧接着该节点之后
  4481. * @return { UE.dom.Range } 当前range对象
  4482. * @example
  4483. * ```html
  4484. * <!-- 选区示例 -->
  4485. * <b>xx<i>xxx</i><span>xx[x</span>xxx]</b>
  4486. *
  4487. * <script>
  4488. *
  4489. * //执行操作
  4490. * range.setStartAfter( document.getElementsByTagName("i")[0] );
  4491. *
  4492. * //结果选区
  4493. * //<b>xx<i>xxx</i>[<span>xxx</span>xxx]</b>
  4494. *
  4495. * </script>
  4496. * ```
  4497. */
  4498. setStartAfter:function (node) {
  4499. return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4500. },
  4501. /**
  4502. * 将Range开始位置设置到node节点之前
  4503. * @method setStartBefore
  4504. * @remind 该操作将会把给定节点的父节点作为range的开始容器, 且偏移量是该节点在其父节点中的位置索引
  4505. * @param { Node } node 新的选区开始位置在该节点之前
  4506. * @see UE.dom.Range:setStartAfter(Node)
  4507. * @return { UE.dom.Range } 当前range对象
  4508. */
  4509. setStartBefore:function (node) {
  4510. return this.setStart(node.parentNode, domUtils.getNodeIndex(node));
  4511. },
  4512. /**
  4513. * 将Range结束位置设置到node节点之后
  4514. * @method setEndAfter
  4515. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引+1
  4516. * @param { Node } node 目标节点
  4517. * @see UE.dom.Range:setStartAfter(Node)
  4518. * @return { UE.dom.Range } 当前range对象
  4519. * @example
  4520. * ```html
  4521. * <!-- 选区示例 -->
  4522. * <b>[xx<i>xxx</i><span>xx]x</span>xxx</b>
  4523. *
  4524. * <script>
  4525. *
  4526. * //执行操作
  4527. * range.setStartAfter( document.getElementsByTagName("span")[0] );
  4528. *
  4529. * //结果选区
  4530. * //<b>[xx<i>xxx</i><span>xxx</span>]xxx</b>
  4531. *
  4532. * </script>
  4533. * ```
  4534. */
  4535. setEndAfter:function (node) {
  4536. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1);
  4537. },
  4538. /**
  4539. * 将Range结束位置设置到node节点之前
  4540. * @method setEndBefore
  4541. * @remind 该操作将会把给定节点的父节点作为range的结束容器, 且偏移量是该节点在其父节点中的位置索引
  4542. * @param { Node } node 目标节点
  4543. * @see UE.dom.Range:setEndAfter(Node)
  4544. * @return { UE.dom.Range } 当前range对象
  4545. */
  4546. setEndBefore:function (node) {
  4547. return this.setEnd(node.parentNode, domUtils.getNodeIndex(node));
  4548. },
  4549. /**
  4550. * 设置Range的开始位置到node节点内的第一个子节点之前
  4551. * @method setStartAtFirst
  4552. * @remind 选区的开始容器将变成给定的节点, 且偏移量为0
  4553. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4554. * @param { Node } node 目标节点
  4555. * @see UE.dom.Range:setStartBefore(Node)
  4556. * @return { UE.dom.Range } 当前range对象
  4557. * @example
  4558. * ```html
  4559. * <!-- 选区示例 -->
  4560. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4561. *
  4562. * <script>
  4563. *
  4564. * //执行操作
  4565. * range.setStartAtFirst( document.getElementsByTagName("i")[0] );
  4566. *
  4567. * //结果选区
  4568. * //<b>xx<i>[xxx</i><span>xx]x</span>xxx</b>
  4569. *
  4570. * </script>
  4571. * ```
  4572. */
  4573. setStartAtFirst:function (node) {
  4574. return this.setStart(node, 0);
  4575. },
  4576. /**
  4577. * 设置Range的开始位置到node节点内的最后一个节点之后
  4578. * @method setStartAtLast
  4579. * @remind 选区的开始容器将变成给定的节点, 且偏移量为该节点的子节点数
  4580. * @remind 如果给定的节点是元素节点, 则该节点必须是允许包含子节点的元素。
  4581. * @param { Node } node 目标节点
  4582. * @see UE.dom.Range:setStartAtFirst(Node)
  4583. * @return { UE.dom.Range } 当前range对象
  4584. */
  4585. setStartAtLast:function (node) {
  4586. return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4587. },
  4588. /**
  4589. * 设置Range的结束位置到node节点内的第一个节点之前
  4590. * @method setEndAtFirst
  4591. * @param { Node } node 目标节点
  4592. * @remind 选区的结束容器将变成给定的节点, 且偏移量为0
  4593. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4594. * @see UE.dom.Range:setStartAtFirst(Node)
  4595. * @return { UE.dom.Range } 当前range对象
  4596. */
  4597. setEndAtFirst:function (node) {
  4598. return this.setEnd(node, 0);
  4599. },
  4600. /**
  4601. * 设置Range的结束位置到node节点内的最后一个节点之后
  4602. * @method setEndAtLast
  4603. * @param { Node } node 目标节点
  4604. * @remind 选区的结束容器将变成给定的节点, 且偏移量为该节点的子节点数量
  4605. * @remind node必须是一个元素节点, 且必须是允许包含子节点的元素。
  4606. * @see UE.dom.Range:setStartAtFirst(Node)
  4607. * @return { UE.dom.Range } 当前range对象
  4608. */
  4609. setEndAtLast:function (node) {
  4610. return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length);
  4611. },
  4612. /**
  4613. * 选中给定节点
  4614. * @method selectNode
  4615. * @remind 此时, 选区的开始容器和结束容器都是该节点的父节点, 其startOffset是该节点在父节点中的位置索引,
  4616. * 而endOffset为startOffset+1
  4617. * @param { Node } node 需要选中的节点
  4618. * @return { UE.dom.Range } 当前range对象,此时的range仅包含当前给定的节点对象
  4619. * @example
  4620. * ```html
  4621. * <!-- 选区示例 -->
  4622. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4623. *
  4624. * <script>
  4625. *
  4626. * //执行操作
  4627. * range.selectNode( document.getElementsByTagName("i")[0] );
  4628. *
  4629. * //结果选区
  4630. * //<b>xx[<i>xxx</i>]<span>xxx</span>xxx</b>
  4631. *
  4632. * </script>
  4633. * ```
  4634. */
  4635. selectNode:function (node) {
  4636. return this.setStartBefore(node).setEndAfter(node);
  4637. },
  4638. /**
  4639. * 选中给定节点内部的所有节点
  4640. * @method selectNodeContents
  4641. * @remind 此时, 选区的开始容器和结束容器都是该节点, 其startOffset为0,
  4642. * 而endOffset是该节点的子节点数。
  4643. * @param { Node } node 目标节点, 当前range将包含该节点内的所有节点
  4644. * @return { UE.dom.Range } 当前range对象, 此时range仅包含给定节点的所有子节点
  4645. * @example
  4646. * ```html
  4647. * <!-- 选区示例 -->
  4648. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4649. *
  4650. * <script>
  4651. *
  4652. * //执行操作
  4653. * range.selectNode( document.getElementsByTagName("b")[0] );
  4654. *
  4655. * //结果选区
  4656. * //<b>[xx<i>xxx</i><span>xxx</span>xxx]</b>
  4657. *
  4658. * </script>
  4659. * ```
  4660. */
  4661. selectNodeContents:function (node) {
  4662. return this.setStart(node, 0).setEndAtLast(node);
  4663. },
  4664. /**
  4665. * clone当前Range对象
  4666. * @method cloneRange
  4667. * @remind 返回的range是一个全新的range对象, 其内部所有属性与当前被clone的range相同。
  4668. * @return { UE.dom.Range } 当前range对象的一个副本
  4669. */
  4670. cloneRange:function () {
  4671. var me = this;
  4672. return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset);
  4673. },
  4674. /**
  4675. * 向当前选区的结束处闭合选区
  4676. * @method collapse
  4677. * @return { UE.dom.Range } 当前range对象
  4678. * @example
  4679. * ```html
  4680. * <!-- 选区示例 -->
  4681. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4682. *
  4683. * <script>
  4684. *
  4685. * //执行操作
  4686. * range.collapse();
  4687. *
  4688. * //结果选区
  4689. * //“|”表示选区已闭合
  4690. * //<b>xx<i>xxx</i><span>xx|x</span>xxx</b>
  4691. *
  4692. * </script>
  4693. * ```
  4694. */
  4695. /**
  4696. * 闭合当前选区,根据给定的toStart参数项决定是向当前选区开始处闭合还是向结束处闭合,
  4697. * 如果toStart的值为true,则向开始位置闭合, 反之,向结束位置闭合。
  4698. * @method collapse
  4699. * @param { Boolean } toStart 是否向选区开始处闭合
  4700. * @return { UE.dom.Range } 当前range对象,此时range对象处于闭合状态
  4701. * @see UE.dom.Range:collapse()
  4702. * @example
  4703. * ```html
  4704. * <!-- 选区示例 -->
  4705. * <b>xx<i>xxx</i><span>[xx]x</span>xxx</b>
  4706. *
  4707. * <script>
  4708. *
  4709. * //执行操作
  4710. * range.collapse( true );
  4711. *
  4712. * //结果选区
  4713. * //“|”表示选区已闭合
  4714. * //<b>xx<i>xxx</i><span>|xxx</span>xxx</b>
  4715. *
  4716. * </script>
  4717. * ```
  4718. */
  4719. collapse:function (toStart) {
  4720. var me = this;
  4721. if (toStart) {
  4722. me.endContainer = me.startContainer;
  4723. me.endOffset = me.startOffset;
  4724. } else {
  4725. me.startContainer = me.endContainer;
  4726. me.startOffset = me.endOffset;
  4727. }
  4728. me.collapsed = true;
  4729. return me;
  4730. },
  4731. /**
  4732. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置
  4733. * @method shrinkBoundary
  4734. * @return { UE.dom.Range } 当前range对象
  4735. * @example
  4736. * ```html
  4737. * <span>xx<b>xx[</b>xxxxx]</span> => <span>xx<b>xx</b>[xxxxx]</span>
  4738. * ```
  4739. *
  4740. * @example
  4741. * ```html
  4742. * <!-- 选区示例 -->
  4743. * <b>x[xx</b><i>]xxx</i>
  4744. *
  4745. * <script>
  4746. *
  4747. * //执行收缩
  4748. * range.shrinkBoundary();
  4749. *
  4750. * //结果选区
  4751. * //<b>x[xx]</b><i>xxx</i>
  4752. * </script>
  4753. * ```
  4754. *
  4755. * @example
  4756. * ```html
  4757. * [<b><i>xxxx</i>xxxxxxx</b>] => <b><i>[xxxx</i>xxxxxxx]</b>
  4758. * ```
  4759. */
  4760. /**
  4761. * 调整range的开始位置和结束位置,使其"收缩"到最小的位置,
  4762. * 如果ignoreEnd的值为true,则忽略对结束位置的调整
  4763. * @method shrinkBoundary
  4764. * @param { Boolean } ignoreEnd 是否忽略对结束位置的调整
  4765. * @return { UE.dom.Range } 当前range对象
  4766. * @see UE.dom.domUtils.Range:shrinkBoundary()
  4767. */
  4768. shrinkBoundary:function (ignoreEnd) {
  4769. var me = this, child,
  4770. collapsed = me.collapsed;
  4771. function check(node){
  4772. return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName]
  4773. }
  4774. while (me.startContainer.nodeType == 1 //是element
  4775. && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element
  4776. && check(child)) {
  4777. me.setStart(child, 0);
  4778. }
  4779. if (collapsed) {
  4780. return me.collapse(true);
  4781. }
  4782. if (!ignoreEnd) {
  4783. while (me.endContainer.nodeType == 1//是element
  4784. && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错
  4785. && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element
  4786. && check(child)) {
  4787. me.setEnd(child, child.childNodes.length);
  4788. }
  4789. }
  4790. return me;
  4791. },
  4792. /**
  4793. * 获取离当前选区内包含的所有节点最近的公共祖先节点,
  4794. * @method getCommonAncestor
  4795. * @remind 返回的公共祖先节点一定不是range自身的容器节点, 但有可能是一个文本节点
  4796. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4797. * @example
  4798. * ```html
  4799. * //选区示例
  4800. * <span>xxx<b>x[x<em>xx]x</em>xxx</b>xx</span>
  4801. * <script>
  4802. *
  4803. * var node = range.getCommonAncestor();
  4804. *
  4805. * //公共祖先节点是: b节点
  4806. * //输出: B
  4807. * console.log(node.tagName);
  4808. *
  4809. * </script>
  4810. * ```
  4811. */
  4812. /**
  4813. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4814. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4815. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点
  4816. * @method getCommonAncestor
  4817. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4818. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4819. * @see UE.dom.Range:getCommonAncestor()
  4820. * @example
  4821. * ```html
  4822. * <body>
  4823. *
  4824. * <!-- 选区示例 -->
  4825. * <b>xxx<i>xxxx<span>xx[x</span>xx]x</i>xxxxxxx</b>
  4826. *
  4827. * <script>
  4828. *
  4829. * var node = range.getCommonAncestor( false );
  4830. *
  4831. * //这里的公共祖先节点是B而不是I, 是因为参数限制了获取到的节点不能是容器节点
  4832. * //output: B
  4833. * console.log( node.tagName );
  4834. *
  4835. * </script>
  4836. *
  4837. * </body>
  4838. * ```
  4839. */
  4840. /**
  4841. * 获取当前选区所包含的所有节点的公共祖先节点, 可以根据给定的参数 includeSelf 决定获取到
  4842. * 的公共祖先节点是否可以是当前选区的startContainer或endContainer节点, 如果 includeSelf
  4843. * 的取值为true, 则返回的节点可以是自身的容器节点, 否则, 则不能是容器节点; 同时可以根据
  4844. * ignoreTextNode 参数的取值决定是否忽略类型为文本节点的祖先节点。
  4845. * @method getCommonAncestor
  4846. * @param { Boolean } includeSelf 是否允许获取到的公共祖先节点是当前range对象的容器节点
  4847. * @param { Boolean } ignoreTextNode 获取祖先节点的过程中是否忽略类型为文本节点的祖先节点
  4848. * @return { Node } 当前range对象内所有节点的公共祖先节点
  4849. * @see UE.dom.Range:getCommonAncestor()
  4850. * @see UE.dom.Range:getCommonAncestor(Boolean)
  4851. * @example
  4852. * ```html
  4853. * <body>
  4854. *
  4855. * <!-- 选区示例 -->
  4856. * <b>xxx<i>xxxx<span>x[x]x</span>xxx</i>xxxxxxx</b>
  4857. *
  4858. * <script>
  4859. *
  4860. * var node = range.getCommonAncestor( true, false );
  4861. *
  4862. * //output: SPAN
  4863. * console.log( node.tagName );
  4864. *
  4865. * </script>
  4866. *
  4867. * </body>
  4868. * ```
  4869. */
  4870. getCommonAncestor:function (includeSelf, ignoreTextNode) {
  4871. var me = this,
  4872. start = me.startContainer,
  4873. end = me.endContainer;
  4874. if (start === end) {
  4875. if (includeSelf && selectOneNode(this)) {
  4876. start = start.childNodes[me.startOffset];
  4877. if(start.nodeType == 1)
  4878. return start;
  4879. }
  4880. //只有在上来就相等的情况下才会出现是文本的情况
  4881. return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start;
  4882. }
  4883. return domUtils.getCommonAncestor(start, end);
  4884. },
  4885. /**
  4886. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上
  4887. * @method trimBoundary
  4888. * @remind 该操作有可能会引起文本节点被切开
  4889. * @return { UE.dom.Range } 当前range对象
  4890. * @example
  4891. * ```html
  4892. *
  4893. * //选区示例
  4894. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4895. *
  4896. * <script>
  4897. * //未调整前, 选区的开始容器和结束都是文本节点
  4898. * //执行调整
  4899. * range.trimBoundary();
  4900. *
  4901. * //调整之后, 容器节点变成了i节点
  4902. * //<b>xxx[<i>xxxxx</i>]xxx</b>
  4903. * </script>
  4904. * ```
  4905. */
  4906. /**
  4907. * 调整当前Range的开始和结束边界容器,如果是容器节点是文本节点,就调整到包含该文本节点的父节点上,
  4908. * 可以根据 ignoreEnd 参数的值决定是否调整对结束边界的调整
  4909. * @method trimBoundary
  4910. * @param { Boolean } ignoreEnd 是否忽略对结束边界的调整
  4911. * @return { UE.dom.Range } 当前range对象
  4912. * @example
  4913. * ```html
  4914. *
  4915. * //选区示例
  4916. * <b>xxx<i>[xxxxx]</i>xxx</b>
  4917. *
  4918. * <script>
  4919. * //未调整前, 选区的开始容器和结束都是文本节点
  4920. * //执行调整
  4921. * range.trimBoundary( true );
  4922. *
  4923. * //调整之后, 开始容器节点变成了i节点
  4924. * //但是, 结束容器没有发生变化
  4925. * //<b>xxx[<i>xxxxx]</i>xxx</b>
  4926. * </script>
  4927. * ```
  4928. */
  4929. trimBoundary:function (ignoreEnd) {
  4930. this.txtToElmBoundary();
  4931. var start = this.startContainer,
  4932. offset = this.startOffset,
  4933. collapsed = this.collapsed,
  4934. end = this.endContainer;
  4935. if (start.nodeType == 3) {
  4936. if (offset == 0) {
  4937. this.setStartBefore(start);
  4938. } else {
  4939. if (offset >= start.nodeValue.length) {
  4940. this.setStartAfter(start);
  4941. } else {
  4942. var textNode = domUtils.split(start, offset);
  4943. //跟新结束边界
  4944. if (start === end) {
  4945. this.setEnd(textNode, this.endOffset - offset);
  4946. } else if (start.parentNode === end) {
  4947. this.endOffset += 1;
  4948. }
  4949. this.setStartBefore(textNode);
  4950. }
  4951. }
  4952. if (collapsed) {
  4953. return this.collapse(true);
  4954. }
  4955. }
  4956. if (!ignoreEnd) {
  4957. offset = this.endOffset;
  4958. end = this.endContainer;
  4959. if (end.nodeType == 3) {
  4960. if (offset == 0) {
  4961. this.setEndBefore(end);
  4962. } else {
  4963. offset < end.nodeValue.length && domUtils.split(end, offset);
  4964. this.setEndAfter(end);
  4965. }
  4966. }
  4967. }
  4968. return this;
  4969. },
  4970. /**
  4971. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则什么也不做
  4972. * @method txtToElmBoundary
  4973. * @remind 该操作不会修改dom节点
  4974. * @return { UE.dom.Range } 当前range对象
  4975. */
  4976. /**
  4977. * 如果选区在文本的边界上,就扩展选区到文本的父节点上, 如果当前选区是闭合的, 则根据参数项
  4978. * ignoreCollapsed 的值决定是否执行该调整
  4979. * @method txtToElmBoundary
  4980. * @param { Boolean } ignoreCollapsed 是否忽略选区的闭合状态, 如果该参数取值为true, 则
  4981. * 不论选区是否闭合, 都会执行该操作, 反之, 则不会对闭合的选区执行该操作
  4982. * @return { UE.dom.Range } 当前range对象
  4983. */
  4984. txtToElmBoundary:function (ignoreCollapsed) {
  4985. function adjust(r, c) {
  4986. var container = r[c + 'Container'],
  4987. offset = r[c + 'Offset'];
  4988. if (container.nodeType == 3) {
  4989. if (!offset) {
  4990. r['set' + c.replace(/(\w)/, function (a) {
  4991. return a.toUpperCase();
  4992. }) + 'Before'](container);
  4993. } else if (offset >= container.nodeValue.length) {
  4994. r['set' + c.replace(/(\w)/, function (a) {
  4995. return a.toUpperCase();
  4996. }) + 'After' ](container);
  4997. }
  4998. }
  4999. }
  5000. if (ignoreCollapsed || !this.collapsed) {
  5001. adjust(this, 'start');
  5002. adjust(this, 'end');
  5003. }
  5004. return this;
  5005. },
  5006. /**
  5007. * 在当前选区的开始位置前插入节点,新插入的节点会被该range包含
  5008. * @method insertNode
  5009. * @param { Node } node 需要插入的节点
  5010. * @remind 插入的节点可以是一个DocumentFragment依次插入多个节点
  5011. * @return { UE.dom.Range } 当前range对象
  5012. */
  5013. insertNode:function (node) {
  5014. var first = node, length = 1;
  5015. if (node.nodeType == 11) {
  5016. first = node.firstChild;
  5017. length = node.childNodes.length;
  5018. }
  5019. this.trimBoundary(true);
  5020. var start = this.startContainer,
  5021. offset = this.startOffset;
  5022. var nextNode = start.childNodes[ offset ];
  5023. if (nextNode) {
  5024. start.insertBefore(node, nextNode);
  5025. } else {
  5026. start.appendChild(node);
  5027. }
  5028. if (first.parentNode === this.endContainer) {
  5029. this.endOffset = this.endOffset + length;
  5030. }
  5031. return this.setStartBefore(first);
  5032. },
  5033. /**
  5034. * 闭合选区到当前选区的开始位置, 并且定位光标到闭合后的位置
  5035. * @method setCursor
  5036. * @return { UE.dom.Range } 当前range对象
  5037. * @see UE.dom.Range:collapse()
  5038. */
  5039. /**
  5040. * 闭合选区,可以根据参数toEnd的值控制选区是向前闭合还是向后闭合, 并且定位光标到闭合后的位置。
  5041. * @method setCursor
  5042. * @param { Boolean } toEnd 是否向后闭合, 如果为true, 则闭合选区时, 将向结束容器方向闭合,
  5043. * 反之,则向开始容器方向闭合
  5044. * @return { UE.dom.Range } 当前range对象
  5045. * @see UE.dom.Range:collapse(Boolean)
  5046. */
  5047. setCursor:function (toEnd, noFillData) {
  5048. return this.collapse(!toEnd).select(noFillData);
  5049. },
  5050. /**
  5051. * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置
  5052. * @method createBookmark
  5053. * @param { Boolean } serialize 控制返回的标记位置是对当前位置的引用还是ID,如果该值为true,则
  5054. * 返回标记位置的ID, 反之则返回标记位置节点的引用
  5055. * @return { Object } 返回一个书签记录键值对, 其包含的key有: start => 开始标记的ID或者引用,
  5056. * end => 结束标记的ID或引用, id => 当前标记的类型, 如果为true,则表示
  5057. * 返回的记录的类型为ID, 反之则为引用
  5058. */
  5059. createBookmark:function (serialize, same) {
  5060. var endNode,
  5061. startNode = this.document.createElement('span');
  5062. startNode.style.cssText = 'display:none;line-height:0px;';
  5063. startNode.appendChild(this.document.createTextNode('\u200D'));
  5064. startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++);
  5065. if (!this.collapsed) {
  5066. endNode = startNode.cloneNode(true);
  5067. endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++);
  5068. }
  5069. this.insertNode(startNode);
  5070. if (endNode) {
  5071. this.collapse().insertNode(endNode).setEndBefore(endNode);
  5072. }
  5073. this.setStartAfter(startNode);
  5074. return {
  5075. start:serialize ? startNode.id : startNode,
  5076. end:endNode ? serialize ? endNode.id : endNode : null,
  5077. id:serialize
  5078. }
  5079. },
  5080. /**
  5081. * 调整当前range的边界到书签位置,并删除该书签对象所标记的位置内的节点
  5082. * @method moveToBookmark
  5083. * @param { BookMark } bookmark createBookmark所创建的标签对象
  5084. * @return { UE.dom.Range } 当前range对象
  5085. * @see UE.dom.Range:createBookmark(Boolean)
  5086. */
  5087. moveToBookmark:function (bookmark) {
  5088. var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start,
  5089. end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end;
  5090. this.setStartBefore(start);
  5091. domUtils.remove(start);
  5092. if (end) {
  5093. this.setEndBefore(end);
  5094. domUtils.remove(end);
  5095. } else {
  5096. this.collapse(true);
  5097. }
  5098. return this;
  5099. },
  5100. /**
  5101. * 调整range的边界,使其"放大"到最近的父节点
  5102. * @method enlarge
  5103. * @remind 会引起选区的变化
  5104. * @return { UE.dom.Range } 当前range对象
  5105. */
  5106. /**
  5107. * 调整range的边界,使其"放大"到最近的父节点,根据参数 toBlock 的取值, 可以
  5108. * 要求扩大之后的父节点是block节点
  5109. * @method enlarge
  5110. * @param { Boolean } toBlock 是否要求扩大之后的父节点必须是block节点
  5111. * @return { UE.dom.Range } 当前range对象
  5112. */
  5113. enlarge:function (toBlock, stopFn) {
  5114. var isBody = domUtils.isBody,
  5115. pre, node, tmp = this.document.createTextNode('');
  5116. if (toBlock) {
  5117. node = this.startContainer;
  5118. if (node.nodeType == 1) {
  5119. if (node.childNodes[this.startOffset]) {
  5120. pre = node = node.childNodes[this.startOffset]
  5121. } else {
  5122. node.appendChild(tmp);
  5123. pre = node = tmp;
  5124. }
  5125. } else {
  5126. pre = node;
  5127. }
  5128. while (1) {
  5129. if (domUtils.isBlockElm(node)) {
  5130. node = pre;
  5131. while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) {
  5132. node = pre;
  5133. }
  5134. this.setStartBefore(node);
  5135. break;
  5136. }
  5137. pre = node;
  5138. node = node.parentNode;
  5139. }
  5140. node = this.endContainer;
  5141. if (node.nodeType == 1) {
  5142. if (pre = node.childNodes[this.endOffset]) {
  5143. node.insertBefore(tmp, pre);
  5144. } else {
  5145. node.appendChild(tmp);
  5146. }
  5147. pre = node = tmp;
  5148. } else {
  5149. pre = node;
  5150. }
  5151. while (1) {
  5152. if (domUtils.isBlockElm(node)) {
  5153. node = pre;
  5154. while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) {
  5155. node = pre;
  5156. }
  5157. this.setEndAfter(node);
  5158. break;
  5159. }
  5160. pre = node;
  5161. node = node.parentNode;
  5162. }
  5163. if (tmp.parentNode === this.endContainer) {
  5164. this.endOffset--;
  5165. }
  5166. domUtils.remove(tmp);
  5167. }
  5168. // 扩展边界到最大
  5169. if (!this.collapsed) {
  5170. while (this.startOffset == 0) {
  5171. if (stopFn && stopFn(this.startContainer)) {
  5172. break;
  5173. }
  5174. if (isBody(this.startContainer)) {
  5175. break;
  5176. }
  5177. this.setStartBefore(this.startContainer);
  5178. }
  5179. while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) {
  5180. if (stopFn && stopFn(this.endContainer)) {
  5181. break;
  5182. }
  5183. if (isBody(this.endContainer)) {
  5184. break;
  5185. }
  5186. this.setEndAfter(this.endContainer);
  5187. }
  5188. }
  5189. return this;
  5190. },
  5191. enlargeToBlockElm:function(ignoreEnd){
  5192. while(!domUtils.isBlockElm(this.startContainer)){
  5193. this.setStartBefore(this.startContainer);
  5194. }
  5195. if(!ignoreEnd){
  5196. while(!domUtils.isBlockElm(this.endContainer)){
  5197. this.setEndAfter(this.endContainer);
  5198. }
  5199. }
  5200. return this;
  5201. },
  5202. /**
  5203. * 调整Range的边界,使其"缩小"到最合适的位置
  5204. * @method adjustmentBoundary
  5205. * @return { UE.dom.Range } 当前range对象
  5206. * @see UE.dom.Range:shrinkBoundary()
  5207. */
  5208. adjustmentBoundary:function () {
  5209. if (!this.collapsed) {
  5210. while (!domUtils.isBody(this.startContainer) &&
  5211. this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length &&
  5212. this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5213. ) {
  5214. this.setStartAfter(this.startContainer);
  5215. }
  5216. while (!domUtils.isBody(this.endContainer) && !this.endOffset &&
  5217. this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  5218. ) {
  5219. this.setEndBefore(this.endContainer);
  5220. }
  5221. }
  5222. return this;
  5223. },
  5224. /**
  5225. * 给range选区中的内容添加给定的inline标签
  5226. * @method applyInlineStyle
  5227. * @param { String } tagName 需要添加的标签名
  5228. * @example
  5229. * ```html
  5230. * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p>
  5231. * ```
  5232. */
  5233. /**
  5234. * 给range选区中的内容添加给定的inline标签, 并且为标签附加上一些初始化属性。
  5235. * @method applyInlineStyle
  5236. * @param { String } tagName 需要添加的标签名
  5237. * @param { Object } attrs 跟随新添加的标签的属性
  5238. * @return { UE.dom.Range } 当前选区
  5239. * @example
  5240. * ```html
  5241. * <p>xxxx[xxxx]x</p>
  5242. *
  5243. * ==>
  5244. *
  5245. * <!-- 执行操作 -->
  5246. * range.applyInlineStyle("strong",{"style":"font-size:12px"})
  5247. *
  5248. * ==>
  5249. *
  5250. * <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p>
  5251. * ```
  5252. */
  5253. applyInlineStyle:function (tagName, attrs, list) {
  5254. if (this.collapsed)return this;
  5255. this.trimBoundary().enlarge(false,
  5256. function (node) {
  5257. return node.nodeType == 1 && domUtils.isBlockElm(node)
  5258. }).adjustmentBoundary();
  5259. var bookmark = this.createBookmark(),
  5260. end = bookmark.end,
  5261. filterFn = function (node) {
  5262. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  5263. },
  5264. current = domUtils.getNextDomNode(bookmark.start, false, filterFn),
  5265. node,
  5266. pre,
  5267. range = this.cloneRange();
  5268. while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5269. if (current.nodeType == 3 || dtd[tagName][current.tagName]) {
  5270. range.setStartBefore(current);
  5271. node = current;
  5272. while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) {
  5273. pre = node;
  5274. node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) {
  5275. return dtd[tagName][parent.tagName];
  5276. });
  5277. }
  5278. var frag = range.setEndAfter(pre).extractContents(), elm;
  5279. if (list && list.length > 0) {
  5280. var level, top;
  5281. top = level = list[0].cloneNode(false);
  5282. for (var i = 1, ci; ci = list[i++];) {
  5283. level.appendChild(ci.cloneNode(false));
  5284. level = level.firstChild;
  5285. }
  5286. elm = level;
  5287. } else {
  5288. elm = range.document.createElement(tagName);
  5289. }
  5290. if (attrs) {
  5291. domUtils.setAttributes(elm, attrs);
  5292. }
  5293. elm.appendChild(frag);
  5294. range.insertNode(list ? top : elm);
  5295. //处理下滑线在a上的情况
  5296. var aNode;
  5297. if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) {
  5298. domUtils.setAttributes(aNode, attrs);
  5299. domUtils.remove(elm, true);
  5300. elm = aNode;
  5301. } else {
  5302. domUtils.mergeSibling(elm);
  5303. domUtils.clearEmptySibling(elm);
  5304. }
  5305. //去除子节点相同的
  5306. domUtils.mergeChild(elm, attrs);
  5307. current = domUtils.getNextDomNode(elm, false, filterFn);
  5308. domUtils.mergeToParent(elm);
  5309. if (node === end) {
  5310. break;
  5311. }
  5312. } else {
  5313. current = domUtils.getNextDomNode(current, true, filterFn);
  5314. }
  5315. }
  5316. return this.moveToBookmark(bookmark);
  5317. },
  5318. /**
  5319. * 移除当前选区内指定的inline标签,但保留其中的内容
  5320. * @method removeInlineStyle
  5321. * @param { String } tagName 需要移除的标签名
  5322. * @return { UE.dom.Range } 当前的range对象
  5323. * @example
  5324. * ```html
  5325. * xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span>
  5326. * ```
  5327. */
  5328. /**
  5329. * 移除当前选区内指定的一组inline标签,但保留其中的内容
  5330. * @method removeInlineStyle
  5331. * @param { Array } tagNameArr 需要移除的标签名的数组
  5332. * @return { UE.dom.Range } 当前的range对象
  5333. * @see UE.dom.Range:removeInlineStyle(String)
  5334. */
  5335. removeInlineStyle:function (tagNames) {
  5336. if (this.collapsed)return this;
  5337. tagNames = utils.isArray(tagNames) ? tagNames : [tagNames];
  5338. this.shrinkBoundary().adjustmentBoundary();
  5339. var start = this.startContainer, end = this.endContainer;
  5340. while (1) {
  5341. if (start.nodeType == 1) {
  5342. if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) {
  5343. break;
  5344. }
  5345. if (start.tagName.toLowerCase() == 'body') {
  5346. start = null;
  5347. break;
  5348. }
  5349. }
  5350. start = start.parentNode;
  5351. }
  5352. while (1) {
  5353. if (end.nodeType == 1) {
  5354. if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) {
  5355. break;
  5356. }
  5357. if (end.tagName.toLowerCase() == 'body') {
  5358. end = null;
  5359. break;
  5360. }
  5361. }
  5362. end = end.parentNode;
  5363. }
  5364. var bookmark = this.createBookmark(),
  5365. frag,
  5366. tmpRange;
  5367. if (start) {
  5368. tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start);
  5369. frag = tmpRange.extractContents();
  5370. tmpRange.insertNode(frag);
  5371. domUtils.clearEmptySibling(start, true);
  5372. start.parentNode.insertBefore(bookmark.start, start);
  5373. }
  5374. if (end) {
  5375. tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end);
  5376. frag = tmpRange.extractContents();
  5377. tmpRange.insertNode(frag);
  5378. domUtils.clearEmptySibling(end, false, true);
  5379. end.parentNode.insertBefore(bookmark.end, end.nextSibling);
  5380. }
  5381. var current = domUtils.getNextDomNode(bookmark.start, false, function (node) {
  5382. return node.nodeType == 1;
  5383. }), next;
  5384. while (current && current !== bookmark.end) {
  5385. next = domUtils.getNextDomNode(current, true, function (node) {
  5386. return node.nodeType == 1;
  5387. });
  5388. if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) {
  5389. domUtils.remove(current, true);
  5390. }
  5391. current = next;
  5392. }
  5393. return this.moveToBookmark(bookmark);
  5394. },
  5395. /**
  5396. * 获取当前选中的自闭合的节点
  5397. * @method getClosedNode
  5398. * @return { Node | NULL } 如果当前选中的是自闭合节点, 则返回该节点, 否则返回NULL
  5399. */
  5400. getClosedNode:function () {
  5401. var node;
  5402. if (!this.collapsed) {
  5403. var range = this.cloneRange().adjustmentBoundary().shrinkBoundary();
  5404. if (selectOneNode(range)) {
  5405. var child = range.startContainer.childNodes[range.startOffset];
  5406. if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) {
  5407. node = child;
  5408. }
  5409. }
  5410. }
  5411. return node;
  5412. },
  5413. /**
  5414. * 在页面上高亮range所表示的选区
  5415. * @method select
  5416. * @return { UE.dom.Range } 返回当前Range对象
  5417. */
  5418. //这里不区分ie9以上,trace:3824
  5419. select:browser.ie ? function (noFillData, textRange) {
  5420. var nativeRange;
  5421. if (!this.collapsed)
  5422. this.shrinkBoundary();
  5423. var node = this.getClosedNode();
  5424. if (node && !textRange) {
  5425. try {
  5426. nativeRange = this.document.body.createControlRange();
  5427. nativeRange.addElement(node);
  5428. nativeRange.select();
  5429. } catch (e) {}
  5430. return this;
  5431. }
  5432. var bookmark = this.createBookmark(),
  5433. start = bookmark.start,
  5434. end;
  5435. nativeRange = this.document.body.createTextRange();
  5436. nativeRange.moveToElementText(start);
  5437. nativeRange.moveStart('character', 1);
  5438. if (!this.collapsed) {
  5439. var nativeRangeEnd = this.document.body.createTextRange();
  5440. end = bookmark.end;
  5441. nativeRangeEnd.moveToElementText(end);
  5442. nativeRange.setEndPoint('EndToEnd', nativeRangeEnd);
  5443. } else {
  5444. if (!noFillData && this.startContainer.nodeType != 3) {
  5445. //使用<span>|x<span>固定住光标
  5446. var tmpText = this.document.createTextNode(fillChar),
  5447. tmp = this.document.createElement('span');
  5448. tmp.appendChild(this.document.createTextNode(fillChar));
  5449. start.parentNode.insertBefore(tmp, start);
  5450. start.parentNode.insertBefore(tmpText, start);
  5451. //当点b,i,u时,不能清除i上边的b
  5452. removeFillData(this.document, tmpText);
  5453. fillData = tmpText;
  5454. mergeSibling(tmp, 'previousSibling');
  5455. mergeSibling(start, 'nextSibling');
  5456. nativeRange.moveStart('character', -1);
  5457. nativeRange.collapse(true);
  5458. }
  5459. }
  5460. this.moveToBookmark(bookmark);
  5461. tmp && domUtils.remove(tmp);
  5462. //IE在隐藏状态下不支持range操作,catch一下
  5463. try {
  5464. nativeRange.select();
  5465. } catch (e) {
  5466. }
  5467. return this;
  5468. } : function (notInsertFillData) {
  5469. function checkOffset(rng){
  5470. function check(node,offset,dir){
  5471. if(node.nodeType == 3 && node.nodeValue.length < offset){
  5472. rng[dir + 'Offset'] = node.nodeValue.length
  5473. }
  5474. }
  5475. check(rng.startContainer,rng.startOffset,'start');
  5476. check(rng.endContainer,rng.endOffset,'end');
  5477. }
  5478. var win = domUtils.getWindow(this.document),
  5479. sel = win.getSelection(),
  5480. txtNode;
  5481. //FF下关闭自动长高时滚动条在关闭dialog时会跳
  5482. //ff下如果不body.focus将不能定位闭合光标到编辑器内
  5483. browser.gecko ? this.document.body.focus() : win.focus();
  5484. if (sel) {
  5485. sel.removeAllRanges();
  5486. // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断
  5487. // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR'
  5488. if (this.collapsed && !notInsertFillData) {
  5489. // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点
  5490. // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) {
  5491. // var tmp = this.document.createTextNode('');
  5492. // this.insertNode(tmp).setStart(tmp, 0).collapse(true);
  5493. // }
  5494. //
  5495. //处理光标落在文本节点的情况
  5496. //处理以下的情况
  5497. //<b>|xxxx</b>
  5498. //<b>xxxx</b>|xxxx
  5499. //xxxx<b>|</b>
  5500. var start = this.startContainer,child = start;
  5501. if(start.nodeType == 1){
  5502. child = start.childNodes[this.startOffset];
  5503. }
  5504. if( !(start.nodeType == 3 && this.startOffset) &&
  5505. (child ?
  5506. (!child.previousSibling || child.previousSibling.nodeType != 3)
  5507. :
  5508. (!start.lastChild || start.lastChild.nodeType != 3)
  5509. )
  5510. ){
  5511. txtNode = this.document.createTextNode(fillChar);
  5512. //跟着前边走
  5513. this.insertNode(txtNode);
  5514. removeFillData(this.document, txtNode);
  5515. mergeSibling(txtNode, 'previousSibling');
  5516. mergeSibling(txtNode, 'nextSibling');
  5517. fillData = txtNode;
  5518. this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true);
  5519. }
  5520. }
  5521. var nativeRange = this.document.createRange();
  5522. if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){
  5523. var child = this.startContainer.childNodes[this.startOffset];
  5524. if(!child){
  5525. //往前靠拢
  5526. child = this.startContainer.lastChild;
  5527. if( child && domUtils.isBr(child)){
  5528. this.setStartBefore(child).collapse(true);
  5529. }
  5530. }else{
  5531. //向后靠拢
  5532. while(child && domUtils.isBlockElm(child)){
  5533. if(child.nodeType == 1 && child.childNodes[0]){
  5534. child = child.childNodes[0]
  5535. }else{
  5536. break;
  5537. }
  5538. }
  5539. child && this.setStartBefore(child).collapse(true)
  5540. }
  5541. }
  5542. //是createAddress最后一位算的不准,现在这里进行微调
  5543. checkOffset(this);
  5544. nativeRange.setStart(this.startContainer, this.startOffset);
  5545. nativeRange.setEnd(this.endContainer, this.endOffset);
  5546. sel.addRange(nativeRange);
  5547. }
  5548. return this;
  5549. },
  5550. /**
  5551. * 滚动到当前range开始的位置
  5552. * @method scrollToView
  5553. * @param { Window } win 当前range对象所属的window对象
  5554. * @return { UE.dom.Range } 当前Range对象
  5555. */
  5556. /**
  5557. * 滚动到距离当前range开始位置 offset 的位置处
  5558. * @method scrollToView
  5559. * @param { Window } win 当前range对象所属的window对象
  5560. * @param { Number } offset 距离range开始位置处的偏移量, 如果为正数, 则向下偏移, 反之, 则向上偏移
  5561. * @return { UE.dom.Range } 当前Range对象
  5562. */
  5563. scrollToView:function (win, offset) {
  5564. win = win ? window : domUtils.getWindow(this.document);
  5565. var me = this,
  5566. span = me.document.createElement('span');
  5567. //trace:717
  5568. span.innerHTML = '&nbsp;';
  5569. me.cloneRange().insertNode(span);
  5570. domUtils.scrollToView(span, win, offset);
  5571. domUtils.remove(span);
  5572. return me;
  5573. },
  5574. /**
  5575. * 判断当前选区内容是否占位符
  5576. * @private
  5577. * @method inFillChar
  5578. * @return { Boolean } 如果是占位符返回true,否则返回false
  5579. */
  5580. inFillChar : function(){
  5581. var start = this.startContainer;
  5582. if(this.collapsed && start.nodeType == 3
  5583. && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length
  5584. ){
  5585. return true;
  5586. }
  5587. return false;
  5588. },
  5589. /**
  5590. * 保存
  5591. * @method createAddress
  5592. * @private
  5593. * @return { Boolean } 返回开始和结束的位置
  5594. * @example
  5595. * ```html
  5596. * <body>
  5597. * <p>
  5598. * aaaa
  5599. * <em>
  5600. * <!-- 选区开始 -->
  5601. * bbbb
  5602. * <!-- 选区结束 -->
  5603. * </em>
  5604. * </p>
  5605. *
  5606. * <script>
  5607. * //output: {startAddress:[0,1,0,0],endAddress:[0,1,0,4]}
  5608. * console.log( range.createAddress() );
  5609. * </script>
  5610. * </body>
  5611. * ```
  5612. */
  5613. createAddress : function(ignoreEnd,ignoreTxt){
  5614. var addr = {},me = this;
  5615. function getAddress(isStart){
  5616. var node = isStart ? me.startContainer : me.endContainer;
  5617. var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}),
  5618. addrs = [];
  5619. for(var i = 0,ci;ci = parents[i++];){
  5620. addrs.push(domUtils.getNodeIndex(ci,ignoreTxt));
  5621. }
  5622. var firstIndex = 0;
  5623. if(ignoreTxt){
  5624. if(node.nodeType == 3){
  5625. var tmpNode = node.previousSibling;
  5626. while(tmpNode && tmpNode.nodeType == 3){
  5627. firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length;
  5628. tmpNode = tmpNode.previousSibling;
  5629. }
  5630. firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 )
  5631. }else{
  5632. node = node.childNodes[ isStart ? me.startOffset : me.endOffset];
  5633. if(node){
  5634. firstIndex = domUtils.getNodeIndex(node,ignoreTxt);
  5635. }else{
  5636. node = isStart ? me.startContainer : me.endContainer;
  5637. var first = node.firstChild;
  5638. while(first){
  5639. if(domUtils.isFillChar(first)){
  5640. first = first.nextSibling;
  5641. continue;
  5642. }
  5643. firstIndex++;
  5644. if(first.nodeType == 3){
  5645. while( first && first.nodeType == 3){
  5646. first = first.nextSibling;
  5647. }
  5648. }else{
  5649. first = first.nextSibling;
  5650. }
  5651. }
  5652. }
  5653. }
  5654. }else{
  5655. firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset
  5656. }
  5657. if(firstIndex < 0){
  5658. firstIndex = 0;
  5659. }
  5660. addrs.push(firstIndex);
  5661. return addrs;
  5662. }
  5663. addr.startAddress = getAddress(true);
  5664. if(!ignoreEnd){
  5665. addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress();
  5666. }
  5667. return addr;
  5668. },
  5669. /**
  5670. * 保存
  5671. * @method createAddress
  5672. * @private
  5673. * @return { Boolean } 返回开始和结束的位置
  5674. * @example
  5675. * ```html
  5676. * <body>
  5677. * <p>
  5678. * aaaa
  5679. * <em>
  5680. * <!-- 选区开始 -->
  5681. * bbbb
  5682. * <!-- 选区结束 -->
  5683. * </em>
  5684. * </p>
  5685. *
  5686. * <script>
  5687. * var range = editor.selection.getRange();
  5688. * range.moveToAddress({startAddress:[0,1,0,0],endAddress:[0,1,0,4]});
  5689. * range.select();
  5690. * //output: 'bbbb'
  5691. * console.log(editor.selection.getText());
  5692. * </script>
  5693. * </body>
  5694. * ```
  5695. */
  5696. moveToAddress : function(addr,ignoreEnd){
  5697. var me = this;
  5698. function getNode(address,isStart){
  5699. var tmpNode = me.document.body,
  5700. parentNode,offset;
  5701. for(var i= 0,ci,l=address.length;i<l;i++){
  5702. ci = address[i];
  5703. parentNode = tmpNode;
  5704. tmpNode = tmpNode.childNodes[ci];
  5705. if(!tmpNode){
  5706. offset = ci;
  5707. break;
  5708. }
  5709. }
  5710. if(isStart){
  5711. if(tmpNode){
  5712. me.setStartBefore(tmpNode)
  5713. }else{
  5714. me.setStart(parentNode,offset)
  5715. }
  5716. }else{
  5717. if(tmpNode){
  5718. me.setEndBefore(tmpNode)
  5719. }else{
  5720. me.setEnd(parentNode,offset)
  5721. }
  5722. }
  5723. }
  5724. getNode(addr.startAddress,true);
  5725. !ignoreEnd && addr.endAddress && getNode(addr.endAddress);
  5726. return me;
  5727. },
  5728. /**
  5729. * 判断给定的Range对象是否和当前Range对象表示的是同一个选区
  5730. * @method equals
  5731. * @param { UE.dom.Range } 需要判断的Range对象
  5732. * @return { Boolean } 如果给定的Range对象与当前Range对象表示的是同一个选区, 则返回true, 否则返回false
  5733. */
  5734. equals : function(rng){
  5735. for(var p in this){
  5736. if(this.hasOwnProperty(p)){
  5737. if(this[p] !== rng[p])
  5738. return false
  5739. }
  5740. }
  5741. return true;
  5742. },
  5743. /**
  5744. * 遍历range内的节点。每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5745. * 作为其参数。
  5746. * @method traversal
  5747. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5748. * @return { UE.dom.Range } 当前range对象
  5749. * @example
  5750. * ```html
  5751. *
  5752. * <body>
  5753. *
  5754. * <!-- 选区开始 -->
  5755. * <span></span>
  5756. * <a></a>
  5757. * <!-- 选区结束 -->
  5758. * </body>
  5759. *
  5760. * <script>
  5761. *
  5762. * //output: <span></span><a></a>
  5763. * console.log( range.cloneContents() );
  5764. *
  5765. * range.traversal( function ( node ) {
  5766. *
  5767. * if ( node.nodeType === 1 ) {
  5768. * node.className = "test";
  5769. * }
  5770. *
  5771. * } );
  5772. *
  5773. * //output: <span class="test"></span><a class="test"></a>
  5774. * console.log( range.cloneContents() );
  5775. *
  5776. * </script>
  5777. * ```
  5778. */
  5779. /**
  5780. * 遍历range内的节点。
  5781. * 每当遍历一个节点时, 都会执行参数项 doFn 指定的函数, 该函数的接受当前遍历的节点
  5782. * 作为其参数。
  5783. * 可以通过参数项 filterFn 来指定一个过滤器, 只有符合该过滤器过滤规则的节点才会触
  5784. * 发doFn函数的执行
  5785. * @method traversal
  5786. * @param { Function } doFn 对每个遍历的节点要执行的方法, 该方法接受当前遍历的节点作为其参数
  5787. * @param { Function } filterFn 过滤器, 该函数接受当前遍历的节点作为参数, 如果该节点满足过滤
  5788. * 规则, 请返回true, 该节点会触发doFn, 否则, 请返回false, 则该节点不
  5789. * 会触发doFn。
  5790. * @return { UE.dom.Range } 当前range对象
  5791. * @see UE.dom.Range:traversal(Function)
  5792. * @example
  5793. * ```html
  5794. *
  5795. * <body>
  5796. *
  5797. * <!-- 选区开始 -->
  5798. * <span></span>
  5799. * <a></a>
  5800. * <!-- 选区结束 -->
  5801. * </body>
  5802. *
  5803. * <script>
  5804. *
  5805. * //output: <span></span><a></a>
  5806. * console.log( range.cloneContents() );
  5807. *
  5808. * range.traversal( function ( node ) {
  5809. *
  5810. * node.className = "test";
  5811. *
  5812. * }, function ( node ) {
  5813. * return node.nodeType === 1;
  5814. * } );
  5815. *
  5816. * //output: <span class="test"></span><a class="test"></a>
  5817. * console.log( range.cloneContents() );
  5818. *
  5819. * </script>
  5820. * ```
  5821. */
  5822. traversal:function(doFn,filterFn){
  5823. if (this.collapsed)
  5824. return this;
  5825. var bookmark = this.createBookmark(),
  5826. end = bookmark.end,
  5827. current = domUtils.getNextDomNode(bookmark.start, false, filterFn);
  5828. while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) {
  5829. var tmpNode = domUtils.getNextDomNode(current,false,filterFn);
  5830. doFn(current);
  5831. current = tmpNode;
  5832. }
  5833. return this.moveToBookmark(bookmark);
  5834. }
  5835. };
  5836. })();
  5837. // core/Selection.js
  5838. /**
  5839. * 选集
  5840. * @file
  5841. * @module UE.dom
  5842. * @class Selection
  5843. * @since 1.2.6.1
  5844. */
  5845. /**
  5846. * 选区集合
  5847. * @unfile
  5848. * @module UE.dom
  5849. * @class Selection
  5850. */
  5851. (function () {
  5852. function getBoundaryInformation( range, start ) {
  5853. var getIndex = domUtils.getNodeIndex;
  5854. range = range.duplicate();
  5855. range.collapse( start );
  5856. var parent = range.parentElement();
  5857. //如果节点里没有子节点,直接退出
  5858. if ( !parent.hasChildNodes() ) {
  5859. return {container:parent, offset:0};
  5860. }
  5861. var siblings = parent.children,
  5862. child,
  5863. testRange = range.duplicate(),
  5864. startIndex = 0, endIndex = siblings.length - 1, index = -1,
  5865. distance;
  5866. while ( startIndex <= endIndex ) {
  5867. index = Math.floor( (startIndex + endIndex) / 2 );
  5868. child = siblings[index];
  5869. testRange.moveToElementText( child );
  5870. var position = testRange.compareEndPoints( 'StartToStart', range );
  5871. if ( position > 0 ) {
  5872. endIndex = index - 1;
  5873. } else if ( position < 0 ) {
  5874. startIndex = index + 1;
  5875. } else {
  5876. //trace:1043
  5877. return {container:parent, offset:getIndex( child )};
  5878. }
  5879. }
  5880. if ( index == -1 ) {
  5881. testRange.moveToElementText( parent );
  5882. testRange.setEndPoint( 'StartToStart', range );
  5883. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5884. siblings = parent.childNodes;
  5885. if ( !distance ) {
  5886. child = siblings[siblings.length - 1];
  5887. return {container:child, offset:child.nodeValue.length};
  5888. }
  5889. var i = siblings.length;
  5890. while ( distance > 0 ){
  5891. distance -= siblings[ --i ].nodeValue.length;
  5892. }
  5893. return {container:siblings[i], offset:-distance};
  5894. }
  5895. testRange.collapse( position > 0 );
  5896. testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range );
  5897. distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length;
  5898. if ( !distance ) {
  5899. return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ?
  5900. {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} :
  5901. {container:child, offset:position > 0 ? 0 : child.childNodes.length}
  5902. }
  5903. while ( distance > 0 ) {
  5904. try {
  5905. var pre = child;
  5906. child = child[position > 0 ? 'previousSibling' : 'nextSibling'];
  5907. distance -= child.nodeValue.length;
  5908. } catch ( e ) {
  5909. return {container:parent, offset:getIndex( pre )};
  5910. }
  5911. }
  5912. return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance}
  5913. }
  5914. /**
  5915. * 将ieRange转换为Range对象
  5916. * @param {Range} ieRange ieRange对象
  5917. * @param {Range} range Range对象
  5918. * @return {Range} range 返回转换后的Range对象
  5919. */
  5920. function transformIERangeToRange( ieRange, range ) {
  5921. if ( ieRange.item ) {
  5922. range.selectNode( ieRange.item( 0 ) );
  5923. } else {
  5924. var bi = getBoundaryInformation( ieRange, true );
  5925. range.setStart( bi.container, bi.offset );
  5926. if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) {
  5927. bi = getBoundaryInformation( ieRange, false );
  5928. range.setEnd( bi.container, bi.offset );
  5929. }
  5930. }
  5931. return range;
  5932. }
  5933. /**
  5934. * 获得ieRange
  5935. * @param {Selection} sel Selection对象
  5936. * @return {ieRange} 得到ieRange
  5937. */
  5938. function _getIERange( sel ) {
  5939. var ieRange;
  5940. //ie下有可能报错
  5941. try {
  5942. ieRange = sel.getNative().createRange();
  5943. } catch ( e ) {
  5944. return null;
  5945. }
  5946. var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement();
  5947. if ( ( el.ownerDocument || el ) === sel.document ) {
  5948. return ieRange;
  5949. }
  5950. return null;
  5951. }
  5952. var Selection = dom.Selection = function ( doc ) {
  5953. var me = this, iframe;
  5954. me.document = doc;
  5955. if ( browser.ie9below ) {
  5956. iframe = domUtils.getWindow( doc ).frameElement;
  5957. domUtils.on( iframe, 'beforedeactivate', function () {
  5958. me._bakIERange = me.getIERange();
  5959. } );
  5960. domUtils.on( iframe, 'activate', function () {
  5961. try {
  5962. if ( !_getIERange( me ) && me._bakIERange ) {
  5963. me._bakIERange.select();
  5964. }
  5965. } catch ( ex ) {
  5966. }
  5967. me._bakIERange = null;
  5968. } );
  5969. }
  5970. iframe = doc = null;
  5971. };
  5972. Selection.prototype = {
  5973. rangeInBody : function(rng,txtRange){
  5974. var node = browser.ie9below || txtRange ? rng.item ? rng.item() : rng.parentElement() : rng.startContainer;
  5975. return node === this.document.body || domUtils.inDoc(node,this.document);
  5976. },
  5977. /**
  5978. * 获取原生seleciton对象
  5979. * @method getNative
  5980. * @return { Object } 获得selection对象
  5981. * @example
  5982. * ```javascript
  5983. * editor.selection.getNative();
  5984. * ```
  5985. */
  5986. getNative:function () {
  5987. var doc = this.document;
  5988. try {
  5989. return !doc ? null : browser.ie9below ? doc.selection : domUtils.getWindow( doc ).getSelection();
  5990. } catch ( e ) {
  5991. return null;
  5992. }
  5993. },
  5994. /**
  5995. * 获得ieRange
  5996. * @method getIERange
  5997. * @return { Object } 返回ie原生的Range
  5998. * @example
  5999. * ```javascript
  6000. * editor.selection.getIERange();
  6001. * ```
  6002. */
  6003. getIERange:function () {
  6004. var ieRange = _getIERange( this );
  6005. if ( !ieRange ) {
  6006. if ( this._bakIERange ) {
  6007. return this._bakIERange;
  6008. }
  6009. }
  6010. return ieRange;
  6011. },
  6012. /**
  6013. * 缓存当前选区的range和选区的开始节点
  6014. * @method cache
  6015. */
  6016. cache:function () {
  6017. this.clear();
  6018. this._cachedRange = this.getRange();
  6019. this._cachedStartElement = this.getStart();
  6020. this._cachedStartElementPath = this.getStartElementPath();
  6021. },
  6022. /**
  6023. * 获取选区开始位置的父节点到body
  6024. * @method getStartElementPath
  6025. * @return { Array } 返回父节点集合
  6026. * @example
  6027. * ```javascript
  6028. * editor.selection.getStartElementPath();
  6029. * ```
  6030. */
  6031. getStartElementPath:function () {
  6032. if ( this._cachedStartElementPath ) {
  6033. return this._cachedStartElementPath;
  6034. }
  6035. var start = this.getStart();
  6036. if ( start ) {
  6037. return domUtils.findParents( start, true, null, true )
  6038. }
  6039. return [];
  6040. },
  6041. /**
  6042. * 清空缓存
  6043. * @method clear
  6044. */
  6045. clear:function () {
  6046. this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null;
  6047. },
  6048. /**
  6049. * 编辑器是否得到了选区
  6050. * @method isFocus
  6051. */
  6052. isFocus:function () {
  6053. try {
  6054. if(browser.ie9below){
  6055. var nativeRange = _getIERange(this);
  6056. return !!(nativeRange && this.rangeInBody(nativeRange));
  6057. }else{
  6058. return !!this.getNative().rangeCount;
  6059. }
  6060. } catch ( e ) {
  6061. return false;
  6062. }
  6063. },
  6064. /**
  6065. * 获取选区对应的Range
  6066. * @method getRange
  6067. * @return { Object } 得到Range对象
  6068. * @example
  6069. * ```javascript
  6070. * editor.selection.getRange();
  6071. * ```
  6072. */
  6073. getRange:function () {
  6074. var me = this;
  6075. function optimze( range ) {
  6076. var child = me.document.body.firstChild,
  6077. collapsed = range.collapsed;
  6078. while ( child && child.firstChild ) {
  6079. range.setStart( child, 0 );
  6080. child = child.firstChild;
  6081. }
  6082. if ( !range.startContainer ) {
  6083. range.setStart( me.document.body, 0 )
  6084. }
  6085. if ( collapsed ) {
  6086. range.collapse( true );
  6087. }
  6088. }
  6089. if ( me._cachedRange != null ) {
  6090. return this._cachedRange;
  6091. }
  6092. var range = new baidu.editor.dom.Range( me.document );
  6093. if ( browser.ie9below ) {
  6094. var nativeRange = me.getIERange();
  6095. if ( nativeRange ) {
  6096. //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置
  6097. try{
  6098. transformIERangeToRange( nativeRange, range );
  6099. }catch(e){
  6100. optimze( range );
  6101. }
  6102. } else {
  6103. optimze( range );
  6104. }
  6105. } else {
  6106. var sel = me.getNative();
  6107. if ( sel && sel.rangeCount ) {
  6108. var firstRange = sel.getRangeAt( 0 );
  6109. var lastRange = sel.getRangeAt( sel.rangeCount - 1 );
  6110. range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset );
  6111. if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) {
  6112. optimze( range );
  6113. }
  6114. } else {
  6115. //trace:1734 有可能已经不在dom树上了,标识的节点
  6116. if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){
  6117. return this._bakRange;
  6118. }
  6119. optimze( range );
  6120. }
  6121. }
  6122. return this._bakRange = range;
  6123. },
  6124. /**
  6125. * 获取开始元素,用于状态反射
  6126. * @method getStart
  6127. * @return { Element } 获得开始元素
  6128. * @example
  6129. * ```javascript
  6130. * editor.selection.getStart();
  6131. * ```
  6132. */
  6133. getStart:function () {
  6134. if ( this._cachedStartElement ) {
  6135. return this._cachedStartElement;
  6136. }
  6137. var range = browser.ie9below ? this.getIERange() : this.getRange(),
  6138. tmpRange,
  6139. start, tmp, parent;
  6140. if ( browser.ie9below ) {
  6141. if ( !range ) {
  6142. //todo 给第一个值可能会有问题
  6143. return this.document.body.firstChild;
  6144. }
  6145. //control元素
  6146. if ( range.item ){
  6147. return range.item( 0 );
  6148. }
  6149. tmpRange = range.duplicate();
  6150. //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx
  6151. tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 );
  6152. tmpRange.collapse( 1 );
  6153. start = tmpRange.parentElement();
  6154. parent = tmp = range.parentElement();
  6155. while ( tmp = tmp.parentNode ) {
  6156. if ( tmp == start ) {
  6157. start = parent;
  6158. break;
  6159. }
  6160. }
  6161. } else {
  6162. range.shrinkBoundary();
  6163. start = range.startContainer;
  6164. if ( start.nodeType == 1 && start.hasChildNodes() ){
  6165. start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )];
  6166. }
  6167. if ( start.nodeType == 3 ){
  6168. return start.parentNode;
  6169. }
  6170. }
  6171. return start;
  6172. },
  6173. /**
  6174. * 得到选区中的文本
  6175. * @method getText
  6176. * @return { String } 选区中包含的文本
  6177. * @example
  6178. * ```javascript
  6179. * editor.selection.getText();
  6180. * ```
  6181. */
  6182. getText:function () {
  6183. var nativeSel, nativeRange;
  6184. if ( this.isFocus() && (nativeSel = this.getNative()) ) {
  6185. nativeRange = browser.ie9below ? nativeSel.createRange() : nativeSel.getRangeAt( 0 );
  6186. return browser.ie9below ? nativeRange.text : nativeRange.toString();
  6187. }
  6188. return '';
  6189. },
  6190. /**
  6191. * 清除选区
  6192. * @method clearRange
  6193. * @example
  6194. * ```javascript
  6195. * editor.selection.clearRange();
  6196. * ```
  6197. */
  6198. clearRange : function(){
  6199. this.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  6200. }
  6201. };
  6202. })();
  6203. // core/Editor.js
  6204. /**
  6205. * 编辑器主类,包含编辑器提供的大部分公用接口
  6206. * @file
  6207. * @module UE
  6208. * @class Editor
  6209. * @since 1.2.6.1
  6210. */
  6211. /**
  6212. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  6213. * @unfile
  6214. * @module UE
  6215. */
  6216. /**
  6217. * UEditor的核心类,为用户提供与编辑器交互的接口。
  6218. * @unfile
  6219. * @module UE
  6220. * @class Editor
  6221. */
  6222. (function () {
  6223. var uid = 0, _selectionChangeTimer;
  6224. /**
  6225. * 获取编辑器的html内容,赋值到编辑器所在表单的textarea文本域里面
  6226. * @private
  6227. * @method setValue
  6228. * @param { UE.Editor } editor 编辑器事例
  6229. */
  6230. function setValue(form, editor) {
  6231. var textarea;
  6232. if (editor.textarea) {
  6233. if (utils.isString(editor.textarea)) {
  6234. for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) {
  6235. if (ti.id == 'ueditor_textarea_' + editor.options.textarea) {
  6236. textarea = ti;
  6237. break;
  6238. }
  6239. }
  6240. } else {
  6241. textarea = editor.textarea;
  6242. }
  6243. }
  6244. if (!textarea) {
  6245. form.appendChild(textarea = domUtils.createElement(document, 'textarea', {
  6246. 'name': editor.options.textarea,
  6247. 'id': 'ueditor_textarea_' + editor.options.textarea,
  6248. 'style': "display:none"
  6249. }));
  6250. //不要产生多个textarea
  6251. editor.textarea = textarea;
  6252. }
  6253. !textarea.getAttribute('name') && textarea.setAttribute('name', editor.options.textarea );
  6254. textarea.value = editor.hasContents() ?
  6255. (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) :
  6256. ''
  6257. }
  6258. function loadPlugins(me){
  6259. //初始化插件
  6260. for (var pi in UE.plugins) {
  6261. UE.plugins[pi].call(me);
  6262. }
  6263. }
  6264. function checkCurLang(I18N){
  6265. for(var lang in I18N){
  6266. return lang
  6267. }
  6268. }
  6269. function langReadied(me){
  6270. me.langIsReady = true;
  6271. me.fireEvent("langReady");
  6272. }
  6273. /**
  6274. * 编辑器准备就绪后会触发该事件
  6275. * @module UE
  6276. * @class Editor
  6277. * @event ready
  6278. * @remind render方法执行完成之后,会触发该事件
  6279. * @remind
  6280. * @example
  6281. * ```javascript
  6282. * editor.addListener( 'ready', function( editor ) {
  6283. * editor.execCommand( 'focus' ); //编辑器家在完成后,让编辑器拿到焦点
  6284. * } );
  6285. * ```
  6286. */
  6287. /**
  6288. * 执行destroy方法,会触发该事件
  6289. * @module UE
  6290. * @class Editor
  6291. * @event destroy
  6292. * @see UE.Editor:destroy()
  6293. */
  6294. /**
  6295. * 执行reset方法,会触发该事件
  6296. * @module UE
  6297. * @class Editor
  6298. * @event reset
  6299. * @see UE.Editor:reset()
  6300. */
  6301. /**
  6302. * 执行focus方法,会触发该事件
  6303. * @module UE
  6304. * @class Editor
  6305. * @event focus
  6306. * @see UE.Editor:focus(Boolean)
  6307. */
  6308. /**
  6309. * 语言加载完成会触发该事件
  6310. * @module UE
  6311. * @class Editor
  6312. * @event langReady
  6313. */
  6314. /**
  6315. * 运行命令之后会触发该命令
  6316. * @module UE
  6317. * @class Editor
  6318. * @event beforeExecCommand
  6319. */
  6320. /**
  6321. * 运行命令之后会触发该命令
  6322. * @module UE
  6323. * @class Editor
  6324. * @event afterExecCommand
  6325. */
  6326. /**
  6327. * 运行命令之前会触发该命令
  6328. * @module UE
  6329. * @class Editor
  6330. * @event firstBeforeExecCommand
  6331. */
  6332. /**
  6333. * 在getContent方法执行之前会触发该事件
  6334. * @module UE
  6335. * @class Editor
  6336. * @event beforeGetContent
  6337. * @see UE.Editor:getContent()
  6338. */
  6339. /**
  6340. * 在getContent方法执行之后会触发该事件
  6341. * @module UE
  6342. * @class Editor
  6343. * @event afterGetContent
  6344. * @see UE.Editor:getContent()
  6345. */
  6346. /**
  6347. * 在getAllHtml方法执行时会触发该事件
  6348. * @module UE
  6349. * @class Editor
  6350. * @event getAllHtml
  6351. * @see UE.Editor:getAllHtml()
  6352. */
  6353. /**
  6354. * 在setContent方法执行之前会触发该事件
  6355. * @module UE
  6356. * @class Editor
  6357. * @event beforeSetContent
  6358. * @see UE.Editor:setContent(String)
  6359. */
  6360. /**
  6361. * 在setContent方法执行之后会触发该事件
  6362. * @module UE
  6363. * @class Editor
  6364. * @event afterSetContent
  6365. * @see UE.Editor:setContent(String)
  6366. */
  6367. /**
  6368. * 每当编辑器内部选区发生改变时,将触发该事件
  6369. * @event selectionchange
  6370. * @warning 该事件的触发非常频繁,不建议在该事件的处理过程中做重量级的处理
  6371. * @example
  6372. * ```javascript
  6373. * editor.addListener( 'selectionchange', function( editor ) {
  6374. * console.log('选区发生改变');
  6375. * }
  6376. */
  6377. /**
  6378. * 在所有selectionchange的监听函数执行之前,会触发该事件
  6379. * @module UE
  6380. * @class Editor
  6381. * @event beforeSelectionChange
  6382. * @see UE.Editor:selectionchange
  6383. */
  6384. /**
  6385. * 在所有selectionchange的监听函数执行完之后,会触发该事件
  6386. * @module UE
  6387. * @class Editor
  6388. * @event afterSelectionChange
  6389. * @see UE.Editor:selectionchange
  6390. */
  6391. /**
  6392. * 编辑器内容发生改变时会触发该事件
  6393. * @module UE
  6394. * @class Editor
  6395. * @event contentChange
  6396. */
  6397. /**
  6398. * 以默认参数构建一个编辑器实例
  6399. * @constructor
  6400. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6401. * @example
  6402. * ```javascript
  6403. * var editor = new UE.Editor();
  6404. * editor.execCommand('blod');
  6405. * ```
  6406. * @see UE.Config
  6407. */
  6408. /**
  6409. * 以给定的参数集合创建一个编辑器实例,对于未指定的参数,将应用默认参数。
  6410. * @constructor
  6411. * @remind 通过 改构造方法实例化的编辑器,不带ui层.需要render到一个容器,编辑器实例才能正常渲染到页面
  6412. * @param { Object } setting 创建编辑器的参数
  6413. * @example
  6414. * ```javascript
  6415. * var editor = new UE.Editor();
  6416. * editor.execCommand('blod');
  6417. * ```
  6418. * @see UE.Config
  6419. */
  6420. var Editor = UE.Editor = function (options) {
  6421. var me = this;
  6422. me.uid = uid++;
  6423. EventBase.call(me);
  6424. me.commands = {};
  6425. me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true);
  6426. me.shortcutkeys = {};
  6427. me.inputRules = [];
  6428. me.outputRules = [];
  6429. //设置默认的常用属性
  6430. me.setOpt(Editor.defaultOptions(me));
  6431. /* 尝试异步加载后台配置 */
  6432. me.loadServerConfig();
  6433. if(!utils.isEmptyObject(UE.I18N)){
  6434. //修改默认的语言类型
  6435. me.options.lang = checkCurLang(UE.I18N);
  6436. UE.plugin.load(me);
  6437. langReadied(me);
  6438. }else{
  6439. utils.loadFile(document, {
  6440. src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js",
  6441. tag: "script",
  6442. type: "text/javascript",
  6443. defer: "defer"
  6444. }, function () {
  6445. UE.plugin.load(me);
  6446. langReadied(me);
  6447. });
  6448. }
  6449. UE.instants['ueditorInstant' + me.uid] = me;
  6450. };
  6451. Editor.prototype = {
  6452. registerCommand : function(name,obj){
  6453. this.commands[name] = obj;
  6454. },
  6455. /**
  6456. * 编辑器对外提供的监听ready事件的接口, 通过调用该方法,达到的效果与监听ready事件是一致的
  6457. * @method ready
  6458. * @param { Function } fn 编辑器ready之后所执行的回调, 如果在注册事件之前编辑器已经ready,将会
  6459. * 立即触发该回调。
  6460. * @remind 需要等待编辑器加载完成后才能执行的代码,可以使用该方法传入
  6461. * @example
  6462. * ```javascript
  6463. * editor.ready( function( editor ) {
  6464. * editor.setContent('初始化完毕');
  6465. * } );
  6466. * ```
  6467. * @see UE.Editor.event:ready
  6468. */
  6469. ready: function (fn) {
  6470. var me = this;
  6471. if (fn) {
  6472. me.isReady ? fn.apply(me) : me.addListener('ready', fn);
  6473. }
  6474. },
  6475. /**
  6476. * 该方法是提供给插件里面使用,设置配置项默认值
  6477. * @method setOpt
  6478. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6479. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6480. * @param { String } key 编辑器的可接受的选项名称
  6481. * @param { * } val 该选项可接受的值
  6482. * @example
  6483. * ```javascript
  6484. * editor.setOpt( 'initContent', '欢迎使用编辑器' );
  6485. * ```
  6486. */
  6487. /**
  6488. * 该方法是提供给插件里面使用,以{key:value}集合的方式设置插件内用到的配置项默认值
  6489. * @method setOpt
  6490. * @warning 三处设置配置项的优先级: 实例化时传入参数 > setOpt()设置 > config文件里设置
  6491. * @warning 该方法仅供编辑器插件内部和编辑器初始化时调用,其他地方不能调用。
  6492. * @param { Object } options 将要设置的选项的键值对对象
  6493. * @example
  6494. * ```javascript
  6495. * editor.setOpt( {
  6496. * 'initContent': '欢迎使用编辑器'
  6497. * } );
  6498. * ```
  6499. */
  6500. setOpt: function (key, val) {
  6501. var obj = {};
  6502. if (utils.isString(key)) {
  6503. obj[key] = val
  6504. } else {
  6505. obj = key;
  6506. }
  6507. utils.extend(this.options, obj, true);
  6508. },
  6509. getOpt:function(key){
  6510. return this.options[key]
  6511. },
  6512. /**
  6513. * 销毁编辑器实例,使用textarea代替
  6514. * @method destroy
  6515. * @example
  6516. * ```javascript
  6517. * editor.destroy();
  6518. * ```
  6519. */
  6520. destroy: function () {
  6521. var me = this;
  6522. me.fireEvent('destroy');
  6523. var container = me.container.parentNode;
  6524. var textarea = me.textarea;
  6525. if (!textarea) {
  6526. textarea = document.createElement('textarea');
  6527. container.parentNode.insertBefore(textarea, container);
  6528. } else {
  6529. textarea.style.display = ''
  6530. }
  6531. textarea.style.width = me.iframe.offsetWidth + 'px';
  6532. textarea.style.height = me.iframe.offsetHeight + 'px';
  6533. textarea.value = me.getContent();
  6534. textarea.id = me.key;
  6535. container.innerHTML = '';
  6536. domUtils.remove(container);
  6537. var key = me.key;
  6538. //trace:2004
  6539. for (var p in me) {
  6540. if (me.hasOwnProperty(p)) {
  6541. delete this[p];
  6542. }
  6543. }
  6544. UE.delEditor(key);
  6545. },
  6546. /**
  6547. * 渲染编辑器的DOM到指定容器
  6548. * @method render
  6549. * @param { String } containerId 指定一个容器ID
  6550. * @remind 执行该方法,会触发ready事件
  6551. * @warning 必须且只能调用一次
  6552. */
  6553. /**
  6554. * 渲染编辑器的DOM到指定容器
  6555. * @method render
  6556. * @param { Element } containerDom 直接指定容器对象
  6557. * @remind 执行该方法,会触发ready事件
  6558. * @warning 必须且只能调用一次
  6559. */
  6560. render: function (container) {
  6561. var me = this,
  6562. options = me.options,
  6563. getStyleValue=function(attr){
  6564. return parseInt(domUtils.getComputedStyle(container,attr));
  6565. };
  6566. if (utils.isString(container)) {
  6567. container = document.getElementById(container);
  6568. }
  6569. if (container) {
  6570. if(options.initialFrameWidth){
  6571. options.minFrameWidth = options.initialFrameWidth
  6572. }else{
  6573. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6574. }
  6575. if(options.initialFrameHeight){
  6576. options.minFrameHeight = options.initialFrameHeight
  6577. }else{
  6578. options.initialFrameHeight = options.minFrameHeight = container.offsetHeight;
  6579. }
  6580. container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth-
  6581. getStyleValue("padding-left")- getStyleValue("padding-right") +'px';
  6582. container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight -
  6583. getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px';
  6584. container.style.zIndex = options.zIndex;
  6585. var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') +
  6586. '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' +
  6587. '<style type=\'text/css\'>' +
  6588. //设置四周的留边
  6589. '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' +
  6590. //设置默认字体和字号
  6591. //font-family不能呢随便改,在safari下fillchar会有解析问题
  6592. 'body{margin:8px;font-family:sans-serif;font-size:16px;}' +
  6593. //设置段落间距
  6594. 'p{margin:5px 0;}</style>' +
  6595. ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) +
  6596. (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') +
  6597. '</head><body class=\'view\' ></body>' +
  6598. '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' +
  6599. 'setTimeout(function(){editor = window.parent.UE.instants[\'ueditorInstant' + me.uid + '\'];editor._setup(document);},0);' +
  6600. 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>';
  6601. container.appendChild(domUtils.createElement(document, 'iframe', {
  6602. id: 'ueditor_' + me.uid,
  6603. width: "100%",
  6604. height: "100%",
  6605. frameborder: "0",
  6606. //先注释掉了,加的原因忘记了,但开启会直接导致全屏模式下内容多时不会出现滚动条
  6607. // scrolling :'no',
  6608. src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') +
  6609. 'document.write("' + html + '");document.close();}())'
  6610. }));
  6611. container.style.overflow = 'hidden';
  6612. //解决如果是给定的百分比,会导致高度算不对的问题
  6613. setTimeout(function(){
  6614. if( /%$/.test(options.initialFrameWidth)){
  6615. options.minFrameWidth = options.initialFrameWidth = container.offsetWidth;
  6616. //如果这里给定宽度,会导致ie在拖动窗口大小时,编辑区域不随着变化
  6617. // container.style.width = options.initialFrameWidth + 'px';
  6618. }
  6619. if(/%$/.test(options.initialFrameHeight)){
  6620. options.minFrameHeight = options.initialFrameHeight = container.offsetHeight;
  6621. container.style.height = options.initialFrameHeight + 'px';
  6622. }
  6623. })
  6624. }
  6625. },
  6626. /**
  6627. * 编辑器初始化
  6628. * @method _setup
  6629. * @private
  6630. * @param { Element } doc 编辑器Iframe中的文档对象
  6631. */
  6632. _setup: function (doc) {
  6633. var me = this,
  6634. options = me.options;
  6635. if (ie) {
  6636. doc.body.disabled = true;
  6637. doc.body.contentEditable = true;
  6638. doc.body.disabled = false;
  6639. } else {
  6640. doc.body.contentEditable = true;
  6641. }
  6642. doc.body.spellcheck = false;
  6643. me.document = doc;
  6644. me.window = doc.defaultView || doc.parentWindow;
  6645. me.iframe = me.window.frameElement;
  6646. me.body = doc.body;
  6647. me.selection = new dom.Selection(doc);
  6648. //gecko初始化就能得到range,无法判断isFocus了
  6649. var geckoSel;
  6650. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  6651. geckoSel.removeAllRanges();
  6652. }
  6653. this._initEvents();
  6654. //为form提交提供一个隐藏的textarea
  6655. for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) {
  6656. if (form.tagName == 'FORM') {
  6657. me.form = form;
  6658. if(me.options.autoSyncData){
  6659. domUtils.on(me.window,'blur',function(){
  6660. setValue(form,me);
  6661. });
  6662. }else{
  6663. domUtils.on(form, 'submit', function () {
  6664. setValue(this, me);
  6665. });
  6666. }
  6667. break;
  6668. }
  6669. }
  6670. if (options.initialContent) {
  6671. if (options.autoClearinitialContent) {
  6672. var oldExecCommand = me.execCommand;
  6673. me.execCommand = function () {
  6674. me.fireEvent('firstBeforeExecCommand');
  6675. return oldExecCommand.apply(me, arguments);
  6676. };
  6677. this._setDefaultContent(options.initialContent);
  6678. } else
  6679. this.setContent(options.initialContent, false, true);
  6680. }
  6681. //编辑器不能为空内容
  6682. if (domUtils.isEmptyNode(me.body)) {
  6683. me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>';
  6684. }
  6685. //如果要求focus, 就把光标定位到内容开始
  6686. if (options.focus) {
  6687. setTimeout(function () {
  6688. me.focus(me.options.focusInEnd);
  6689. //如果自动清除开着,就不需要做selectionchange;
  6690. !me.options.autoClearinitialContent && me._selectionChange();
  6691. }, 0);
  6692. }
  6693. if (!me.container) {
  6694. me.container = this.iframe.parentNode;
  6695. }
  6696. if (options.fullscreen && me.ui) {
  6697. me.ui.setFullScreen(true);
  6698. }
  6699. try {
  6700. me.document.execCommand('2D-position', false, false);
  6701. } catch (e) {
  6702. }
  6703. try {
  6704. me.document.execCommand('enableInlineTableEditing', false, false);
  6705. } catch (e) {
  6706. }
  6707. try {
  6708. me.document.execCommand('enableObjectResizing', false, false);
  6709. } catch (e) {
  6710. }
  6711. //挂接快捷键
  6712. me._bindshortcutKeys();
  6713. me.isReady = 1;
  6714. me.fireEvent('ready');
  6715. options.onready && options.onready.call(me);
  6716. if (!browser.ie9below) {
  6717. domUtils.on(me.window, ['blur', 'focus'], function (e) {
  6718. //chrome下会出现alt+tab切换时,导致选区位置不对
  6719. if (e.type == 'blur') {
  6720. me._bakRange = me.selection.getRange();
  6721. try {
  6722. me._bakNativeRange = me.selection.getNative().getRangeAt(0);
  6723. me.selection.getNative().removeAllRanges();
  6724. } catch (e) {
  6725. me._bakNativeRange = null;
  6726. }
  6727. } else {
  6728. try {
  6729. me._bakRange && me._bakRange.select();
  6730. } catch (e) {
  6731. }
  6732. }
  6733. });
  6734. }
  6735. //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点
  6736. if (browser.gecko && browser.version <= 10902) {
  6737. //修复ff3.6初始化进来,不能点击获得焦点
  6738. me.body.contentEditable = false;
  6739. setTimeout(function () {
  6740. me.body.contentEditable = true;
  6741. }, 100);
  6742. setInterval(function () {
  6743. me.body.style.height = me.iframe.offsetHeight - 20 + 'px'
  6744. }, 100)
  6745. }
  6746. !options.isShow && me.setHide();
  6747. options.readonly && me.setDisabled();
  6748. },
  6749. /**
  6750. * 同步数据到编辑器所在的form
  6751. * 从编辑器的容器节点向上查找form元素,若找到,就同步编辑内容到找到的form里,为提交数据做准备,主要用于是手动提交的情况
  6752. * 后台取得数据的键值,使用你容器上的name属性,如果没有就使用参数里的textarea项
  6753. * @method sync
  6754. * @example
  6755. * ```javascript
  6756. * editor.sync();
  6757. * form.sumbit(); //form变量已经指向了form元素
  6758. * ```
  6759. */
  6760. /**
  6761. * 根据传入的formId,在页面上查找要同步数据的表单,若找到,就同步编辑内容到找到的form里,为提交数据做准备
  6762. * 后台取得数据的键值,该键值默认使用给定的编辑器容器的name属性,如果没有name属性则使用参数项里给定的“textarea”项
  6763. * @method sync
  6764. * @param { String } formID 指定一个要同步数据的form的id,编辑器的数据会同步到你指定form下
  6765. */
  6766. sync: function (formId) {
  6767. var me = this,
  6768. form = formId ? document.getElementById(formId) :
  6769. domUtils.findParent(me.iframe.parentNode, function (node) {
  6770. return node.tagName == 'FORM'
  6771. }, true);
  6772. form && setValue(form, me);
  6773. },
  6774. /**
  6775. * 设置编辑器高度
  6776. * @method setHeight
  6777. * @remind 当配置项autoHeightEnabled为真时,该方法无效
  6778. * @param { Number } number 设置的高度值,纯数值,不带单位
  6779. * @example
  6780. * ```javascript
  6781. * editor.setHeight(number);
  6782. * ```
  6783. */
  6784. setHeight: function (height,notSetHeight) {
  6785. if (height !== parseInt(this.iframe.parentNode.style.height)) {
  6786. this.iframe.parentNode.style.height = height + 'px';
  6787. }
  6788. !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height);
  6789. this.body.style.height = height + 'px';
  6790. !notSetHeight && this.trigger('setHeight')
  6791. },
  6792. /**
  6793. * 为编辑器的编辑命令提供快捷键
  6794. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6795. * @method addshortcutkey
  6796. * @param { Object } keyset 命令名和快捷键键值对对象,多个按钮的快捷键用“+”分隔
  6797. * @example
  6798. * ```javascript
  6799. * editor.addshortcutkey({
  6800. * "Bold" : "ctrl+66",//^B
  6801. * "Italic" : "ctrl+73", //^I
  6802. * });
  6803. * ```
  6804. */
  6805. /**
  6806. * 这个接口是为插件扩展提供的接口,主要是为新添加的插件,如果需要添加快捷键,所提供的接口
  6807. * @method addshortcutkey
  6808. * @param { String } cmd 触发快捷键时,响应的命令
  6809. * @param { String } keys 快捷键的字符串,多个按钮用“+”分隔
  6810. * @example
  6811. * ```javascript
  6812. * editor.addshortcutkey("Underline", "ctrl+85"); //^U
  6813. * ```
  6814. */
  6815. addshortcutkey: function (cmd, keys) {
  6816. var obj = {};
  6817. if (keys) {
  6818. obj[cmd] = keys
  6819. } else {
  6820. obj = cmd;
  6821. }
  6822. utils.extend(this.shortcutkeys, obj)
  6823. },
  6824. /**
  6825. * 对编辑器设置keydown事件监听,绑定快捷键和命令,当快捷键组合触发成功,会响应对应的命令
  6826. * @method _bindshortcutKeys
  6827. * @private
  6828. */
  6829. _bindshortcutKeys: function () {
  6830. var me = this, shortcutkeys = this.shortcutkeys;
  6831. me.addListener('keydown', function (type, e) {
  6832. var keyCode = e.keyCode || e.which;
  6833. for (var i in shortcutkeys) {
  6834. var tmp = shortcutkeys[i].split(',');
  6835. for (var t = 0, ti; ti = tmp[t++];) {
  6836. ti = ti.split(':');
  6837. var key = ti[0], param = ti[1];
  6838. if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) {
  6839. if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0)
  6840. && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1)
  6841. && keyCode == RegExp.$3
  6842. ) ||
  6843. keyCode == RegExp.$1
  6844. ) {
  6845. if (me.queryCommandState(i,param) != -1)
  6846. me.execCommand(i, param);
  6847. domUtils.preventDefault(e);
  6848. }
  6849. }
  6850. }
  6851. }
  6852. });
  6853. },
  6854. /**
  6855. * 获取编辑器的内容
  6856. * @method getContent
  6857. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6858. * @return { String } 编辑器的内容字符串, 如果编辑器的内容为空,或者是空的标签内容(如:”&lt;p&gt;&lt;br/&gt;&lt;/p&gt;“), 则返回空字符串
  6859. * @example
  6860. * ```javascript
  6861. * //编辑器html内容:<p>1<strong>2<em>34</em>5</strong>6</p>
  6862. * var content = editor.getContent(); //返回值:<p>1<strong>2<em>34</em>5</strong>6</p>
  6863. * ```
  6864. */
  6865. /**
  6866. * 获取编辑器的内容。 可以通过参数定义编辑器内置的判空规则
  6867. * @method getContent
  6868. * @param { Function } fn 自定的判空规则, 要求该方法返回一个boolean类型的值,
  6869. * 代表当前编辑器的内容是否空,
  6870. * 如果返回true, 则该方法将直接返回空字符串;如果返回false,则编辑器将返回
  6871. * 经过内置过滤规则处理后的内容。
  6872. * @remind 该方法在处理包含有初始化内容的时候能起到很好的作用。
  6873. * @warning 该方法获取到的是经过编辑器内置的过滤规则进行过滤后得到的内容
  6874. * @return { String } 编辑器的内容字符串
  6875. * @example
  6876. * ```javascript
  6877. * // editor 是一个编辑器的实例
  6878. * var content = editor.getContent( function ( editor ) {
  6879. * return editor.body.innerHTML === '欢迎使用UEditor'; //返回空字符串
  6880. * } );
  6881. * ```
  6882. */
  6883. getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) {
  6884. var me = this;
  6885. if (cmd && utils.isFunction(cmd)) {
  6886. fn = cmd;
  6887. cmd = '';
  6888. }
  6889. if (fn ? !fn() : !this.hasContents()) {
  6890. return '';
  6891. }
  6892. me.fireEvent('beforegetcontent');
  6893. var root = UE.htmlparser(me.body.innerHTML,ignoreBlank);
  6894. me.filterOutputRule(root);
  6895. me.fireEvent('aftergetcontent', cmd,root);
  6896. return root.toHtml(formatter);
  6897. },
  6898. /**
  6899. * 取得完整的html代码,可以直接显示成完整的html文档
  6900. * @method getAllHtml
  6901. * @return { String } 编辑器的内容html文档字符串
  6902. * @eaxmple
  6903. * ```javascript
  6904. * editor.getAllHtml(); //返回格式大致是: <html><head>...</head><body>...</body></html>
  6905. * ```
  6906. */
  6907. getAllHtml: function () {
  6908. var me = this,
  6909. headHtml = [],
  6910. html = '';
  6911. me.fireEvent('getAllHtml', headHtml);
  6912. if (browser.ie && browser.version > 8) {
  6913. var headHtmlForIE9 = '';
  6914. utils.each(me.document.styleSheets, function (si) {
  6915. headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>');
  6916. });
  6917. utils.each(me.document.getElementsByTagName('script'), function (si) {
  6918. headHtmlForIE9 += si.outerHTML;
  6919. });
  6920. }
  6921. return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '')
  6922. + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>'
  6923. + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>';
  6924. },
  6925. /**
  6926. * 得到编辑器的纯文本内容,但会保留段落格式
  6927. * @method getPlainTxt
  6928. * @return { String } 编辑器带段落格式的纯文本内容字符串
  6929. * @example
  6930. * ```javascript
  6931. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6932. * console.log(editor.getPlainTxt()); //输出:"1\n2\n
  6933. * ```
  6934. */
  6935. getPlainTxt: function () {
  6936. var reg = new RegExp(domUtils.fillChar, 'g'),
  6937. html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理
  6938. html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n')
  6939. .replace(/<br\/?>/gi, '\n')
  6940. .replace(/<[^>/]+>/g, '')
  6941. .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) {
  6942. return dtd.$block[c] ? '\n' : b ? b : '';
  6943. });
  6944. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6945. return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' ');
  6946. },
  6947. /**
  6948. * 获取编辑器中的纯文本内容,没有段落格式
  6949. * @method getContentTxt
  6950. * @return { String } 编辑器不带段落格式的纯文本内容字符串
  6951. * @example
  6952. * ```javascript
  6953. * //编辑器html内容:<p><strong>1</strong></p><p><strong>2</strong></p>
  6954. * console.log(editor.getPlainTxt()); //输出:"12
  6955. * ```
  6956. */
  6957. getContentTxt: function () {
  6958. var reg = new RegExp(domUtils.fillChar, 'g');
  6959. //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0
  6960. return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' ');
  6961. },
  6962. /**
  6963. * 设置编辑器的内容,可修改编辑器当前的html内容
  6964. * @method setContent
  6965. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6966. * @warning 该方法会触发selectionchange事件
  6967. * @param { String } html 要插入的html内容
  6968. * @example
  6969. * ```javascript
  6970. * editor.getContent('<p>test</p>');
  6971. * ```
  6972. */
  6973. /**
  6974. * 设置编辑器的内容,可修改编辑器当前的html内容
  6975. * @method setContent
  6976. * @warning 通过该方法插入的内容,是经过编辑器内置的过滤规则进行过滤后得到的内容
  6977. * @warning 该方法会触发selectionchange事件
  6978. * @param { String } html 要插入的html内容
  6979. * @param { Boolean } isAppendTo 若传入true,不清空原来的内容,在最后插入内容,否则,清空内容再插入
  6980. * @example
  6981. * ```javascript
  6982. * //假设设置前的编辑器内容是 <p>old text</p>
  6983. * editor.setContent('<p>new text</p>', true); //插入的结果是<p>old text</p><p>new text</p>
  6984. * ```
  6985. */
  6986. setContent: function (html, isAppendTo, notFireSelectionchange) {
  6987. var me = this;
  6988. me.fireEvent('beforesetcontent', html);
  6989. var root = UE.htmlparser(html);
  6990. me.filterInputRule(root);
  6991. html = root.toHtml();
  6992. me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html;
  6993. function isCdataDiv(node){
  6994. return node.tagName == 'DIV' && node.getAttribute('cdata_tag');
  6995. }
  6996. //给文本或者inline节点套p标签
  6997. if (me.options.enterTag == 'p') {
  6998. var child = this.body.firstChild, tmpNode;
  6999. if (!child || child.nodeType == 1 &&
  7000. (dtd.$cdata[child.tagName] || isCdataDiv(child) ||
  7001. domUtils.isCustomeNode(child)
  7002. )
  7003. && child === this.body.lastChild) {
  7004. this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML;
  7005. } else {
  7006. var p = me.document.createElement('p');
  7007. while (child) {
  7008. while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) {
  7009. tmpNode = child.nextSibling;
  7010. p.appendChild(child);
  7011. child = tmpNode;
  7012. }
  7013. if (p.firstChild) {
  7014. if (!child) {
  7015. me.body.appendChild(p);
  7016. break;
  7017. } else {
  7018. child.parentNode.insertBefore(p, child);
  7019. p = me.document.createElement('p');
  7020. }
  7021. }
  7022. child = child.nextSibling;
  7023. }
  7024. }
  7025. }
  7026. me.fireEvent('aftersetcontent');
  7027. me.fireEvent('contentchange');
  7028. !notFireSelectionchange && me._selectionChange();
  7029. //清除保存的选区
  7030. me._bakRange = me._bakIERange = me._bakNativeRange = null;
  7031. //trace:1742 setContent后gecko能得到焦点问题
  7032. var geckoSel;
  7033. if (browser.gecko && (geckoSel = this.selection.getNative())) {
  7034. geckoSel.removeAllRanges();
  7035. }
  7036. if(me.options.autoSyncData){
  7037. me.form && setValue(me.form,me);
  7038. }
  7039. },
  7040. /**
  7041. * 让编辑器获得焦点,默认focus到编辑器头部
  7042. * @method focus
  7043. * @example
  7044. * ```javascript
  7045. * editor.focus()
  7046. * ```
  7047. */
  7048. /**
  7049. * 让编辑器获得焦点,toEnd确定focus位置
  7050. * @method focus
  7051. * @param { Boolean } toEnd 默认focus到编辑器头部,toEnd为true时focus到内容尾部
  7052. * @example
  7053. * ```javascript
  7054. * editor.focus(true)
  7055. * ```
  7056. */
  7057. focus: function (toEnd) {
  7058. try {
  7059. var me = this,
  7060. rng = me.selection.getRange();
  7061. if (toEnd) {
  7062. var node = me.body.lastChild;
  7063. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7064. if(domUtils.isEmptyBlock(node)){
  7065. rng.setStartAtFirst(node)
  7066. }else{
  7067. rng.setStartAtLast(node)
  7068. }
  7069. rng.collapse(true);
  7070. }
  7071. rng.setCursor(true);
  7072. } else {
  7073. if(!rng.collapsed && domUtils.isBody(rng.startContainer) && rng.startOffset == 0){
  7074. var node = me.body.firstChild;
  7075. if(node && node.nodeType == 1 && !dtd.$empty[node.tagName]){
  7076. rng.setStartAtFirst(node).collapse(true);
  7077. }
  7078. }
  7079. rng.select(true);
  7080. }
  7081. this.fireEvent('focus selectionchange');
  7082. } catch (e) {
  7083. }
  7084. },
  7085. isFocus:function(){
  7086. return this.selection.isFocus();
  7087. },
  7088. blur:function(){
  7089. var sel = this.selection.getNative();
  7090. if(sel.empty && browser.ie){
  7091. var nativeRng = document.body.createTextRange();
  7092. nativeRng.moveToElementText(document.body);
  7093. nativeRng.collapse(true);
  7094. nativeRng.select();
  7095. sel.empty()
  7096. }else{
  7097. sel.removeAllRanges()
  7098. }
  7099. //this.fireEvent('blur selectionchange');
  7100. },
  7101. /**
  7102. * 初始化UE事件及部分事件代理
  7103. * @method _initEvents
  7104. * @private
  7105. */
  7106. _initEvents: function () {
  7107. var me = this,
  7108. doc = me.document,
  7109. win = me.window;
  7110. me._proxyDomEvent = utils.bind(me._proxyDomEvent, me);
  7111. domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent);
  7112. domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent);
  7113. domUtils.on(me.body,'drop',function(e){
  7114. //阻止ff下默认的弹出新页面打开图片
  7115. if(browser.gecko && e.stopPropagation) { e.stopPropagation(); }
  7116. me.fireEvent('contentchange')
  7117. });
  7118. domUtils.on(doc, ['mouseup', 'keydown'], function (evt) {
  7119. //特殊键不触发selectionchange
  7120. if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) {
  7121. return;
  7122. }
  7123. if (evt.button == 2)return;
  7124. me._selectionChange(250, evt);
  7125. });
  7126. },
  7127. /**
  7128. * 触发事件代理
  7129. * @method _proxyDomEvent
  7130. * @private
  7131. * @return { * } fireEvent的返回值
  7132. * @see UE.EventBase:fireEvent(String)
  7133. */
  7134. _proxyDomEvent: function (evt) {
  7135. if(this.fireEvent('before' + evt.type.replace(/^on/, '').toLowerCase()) === false){
  7136. return false;
  7137. }
  7138. if(this.fireEvent(evt.type.replace(/^on/, ''), evt) === false){
  7139. return false;
  7140. }
  7141. return this.fireEvent('after' + evt.type.replace(/^on/, '').toLowerCase())
  7142. },
  7143. /**
  7144. * 变化选区
  7145. * @method _selectionChange
  7146. * @private
  7147. */
  7148. _selectionChange: function (delay, evt) {
  7149. var me = this;
  7150. //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1)
  7151. // if ( !me.selection.isFocus() ){
  7152. // return;
  7153. // }
  7154. var hackForMouseUp = false;
  7155. var mouseX, mouseY;
  7156. if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') {
  7157. var range = this.selection.getRange();
  7158. if (!range.collapsed) {
  7159. hackForMouseUp = true;
  7160. mouseX = evt.clientX;
  7161. mouseY = evt.clientY;
  7162. }
  7163. }
  7164. clearTimeout(_selectionChangeTimer);
  7165. _selectionChangeTimer = setTimeout(function () {
  7166. if (!me.selection || !me.selection.getNative()) {
  7167. return;
  7168. }
  7169. //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值.
  7170. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响
  7171. var ieRange;
  7172. if (hackForMouseUp && me.selection.getNative().type == 'None') {
  7173. ieRange = me.document.body.createTextRange();
  7174. try {
  7175. ieRange.moveToPoint(mouseX, mouseY);
  7176. } catch (ex) {
  7177. ieRange = null;
  7178. }
  7179. }
  7180. var bakGetIERange;
  7181. if (ieRange) {
  7182. bakGetIERange = me.selection.getIERange;
  7183. me.selection.getIERange = function () {
  7184. return ieRange;
  7185. };
  7186. }
  7187. me.selection.cache();
  7188. if (bakGetIERange) {
  7189. me.selection.getIERange = bakGetIERange;
  7190. }
  7191. if (me.selection._cachedRange && me.selection._cachedStartElement) {
  7192. me.fireEvent('beforeselectionchange');
  7193. // 第二个参数causeByUi为true代表由用户交互造成的selectionchange.
  7194. me.fireEvent('selectionchange', !!evt);
  7195. me.fireEvent('afterselectionchange');
  7196. me.selection.clear();
  7197. }
  7198. }, delay || 50);
  7199. },
  7200. /**
  7201. * 执行编辑命令
  7202. * @method _callCmdFn
  7203. * @private
  7204. * @param { String } fnName 函数名称
  7205. * @param { * } args 传给命令函数的参数
  7206. * @return { * } 返回命令函数运行的返回值
  7207. */
  7208. _callCmdFn: function (fnName, args) {
  7209. var cmdName = args[0].toLowerCase(),
  7210. cmd, cmdFn;
  7211. cmd = this.commands[cmdName] || UE.commands[cmdName];
  7212. cmdFn = cmd && cmd[fnName];
  7213. //没有querycommandstate或者没有command的都默认返回0
  7214. if ((!cmd || !cmdFn) && fnName == 'queryCommandState') {
  7215. return 0;
  7216. } else if (cmdFn) {
  7217. return cmdFn.apply(this, args);
  7218. }
  7219. },
  7220. /**
  7221. * 执行编辑命令cmdName,完成富文本编辑效果
  7222. * @method execCommand
  7223. * @param { String } cmdName 需要执行的命令
  7224. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7225. * @return { * } 返回命令函数运行的返回值
  7226. * @example
  7227. * ```javascript
  7228. * editor.execCommand(cmdName);
  7229. * ```
  7230. */
  7231. execCommand: function (cmdName) {
  7232. cmdName = cmdName.toLowerCase();
  7233. var me = this,
  7234. result,
  7235. cmd = me.commands[cmdName] || UE.commands[cmdName];
  7236. if (!cmd || !cmd.execCommand) {
  7237. return null;
  7238. }
  7239. if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) {
  7240. me.__hasEnterExecCommand = true;
  7241. if (me.queryCommandState.apply(me,arguments) != -1) {
  7242. me.fireEvent('saveScene');
  7243. me.fireEvent.apply(me, ['beforeexeccommand', cmdName].concat(arguments));
  7244. result = this._callCmdFn('execCommand', arguments);
  7245. //保存场景时,做了内容对比,再看是否进行contentchange触发,这里多触发了一次,去掉
  7246. // (!cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange');
  7247. me.fireEvent.apply(me, ['afterexeccommand', cmdName].concat(arguments));
  7248. me.fireEvent('saveScene');
  7249. }
  7250. me.__hasEnterExecCommand = false;
  7251. } else {
  7252. result = this._callCmdFn('execCommand', arguments);
  7253. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me.fireEvent('contentchange')
  7254. }
  7255. (!me.__hasEnterExecCommand && !cmd.ignoreContentChange && !me._ignoreContentChange) && me._selectionChange();
  7256. return result;
  7257. },
  7258. /**
  7259. * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态
  7260. * @method queryCommandState
  7261. * @param { String } cmdName 需要查询的命令名称
  7262. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7263. * @return { Number } number 返回放前命令的状态,返回值三种情况:(-1|0|1)
  7264. * @example
  7265. * ```javascript
  7266. * editor.queryCommandState(cmdName) => (-1|0|1)
  7267. * ```
  7268. * @see COMMAND.LIST
  7269. */
  7270. queryCommandState: function (cmdName) {
  7271. return this._callCmdFn('queryCommandState', arguments);
  7272. },
  7273. /**
  7274. * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值
  7275. * @method queryCommandValue
  7276. * @param { String } cmdName 需要查询的命令名称
  7277. * @remind 具体命令的使用请参考<a href="#COMMAND.LIST">命令列表</a>
  7278. * @remind 只有部分插件有此方法
  7279. * @return { * } 返回每个命令特定的当前状态值
  7280. * @grammar editor.queryCommandValue(cmdName) => {*}
  7281. * @see COMMAND.LIST
  7282. */
  7283. queryCommandValue: function (cmdName) {
  7284. return this._callCmdFn('queryCommandValue', arguments);
  7285. },
  7286. /**
  7287. * 检查编辑区域中是否有内容
  7288. * @method hasContents
  7289. * @remind 默认有文本内容,或者有以下节点都不认为是空
  7290. * table,ul,ol,dl,iframe,area,base,col,hr,img,embed,input,link,meta,param
  7291. * @return { Boolean } 检查有内容返回true,否则返回false
  7292. * @example
  7293. * ```javascript
  7294. * editor.hasContents()
  7295. * ```
  7296. */
  7297. /**
  7298. * 检查编辑区域中是否有内容,若包含参数tags中的节点类型,直接返回true
  7299. * @method hasContents
  7300. * @param { Array } tags 传入数组判断时用到的节点类型
  7301. * @return { Boolean } 若文档中包含tags数组里对应的tag,返回true,否则返回false
  7302. * @example
  7303. * ```javascript
  7304. * editor.hasContents(['span']);
  7305. * ```
  7306. */
  7307. hasContents: function (tags) {
  7308. if (tags) {
  7309. for (var i = 0, ci; ci = tags[i++];) {
  7310. if (this.document.getElementsByTagName(ci).length > 0) {
  7311. return true;
  7312. }
  7313. }
  7314. }
  7315. if (!domUtils.isEmptyBlock(this.body)) {
  7316. return true
  7317. }
  7318. //随时添加,定义的特殊标签如果存在,不能认为是空
  7319. tags = ['div'];
  7320. for (i = 0; ci = tags[i++];) {
  7321. var nodes = domUtils.getElementsByTagName(this.document, ci);
  7322. for (var n = 0, cn; cn = nodes[n++];) {
  7323. if (domUtils.isCustomeNode(cn)) {
  7324. return true;
  7325. }
  7326. }
  7327. }
  7328. return false;
  7329. },
  7330. /**
  7331. * 重置编辑器,可用来做多个tab使用同一个编辑器实例
  7332. * @method reset
  7333. * @remind 此方法会清空编辑器内容,清空回退列表,会触发reset事件
  7334. * @example
  7335. * ```javascript
  7336. * editor.reset()
  7337. * ```
  7338. */
  7339. reset: function () {
  7340. this.fireEvent('reset');
  7341. },
  7342. /**
  7343. * 设置当前编辑区域可以编辑
  7344. * @method setEnabled
  7345. * @example
  7346. * ```javascript
  7347. * editor.setEnabled()
  7348. * ```
  7349. */
  7350. setEnabled: function () {
  7351. var me = this, range;
  7352. if (me.body.contentEditable == 'false') {
  7353. me.body.contentEditable = true;
  7354. range = me.selection.getRange();
  7355. //有可能内容丢失了
  7356. try {
  7357. range.moveToBookmark(me.lastBk);
  7358. delete me.lastBk
  7359. } catch (e) {
  7360. range.setStartAtFirst(me.body).collapse(true)
  7361. }
  7362. range.select(true);
  7363. if (me.bkqueryCommandState) {
  7364. me.queryCommandState = me.bkqueryCommandState;
  7365. delete me.bkqueryCommandState;
  7366. }
  7367. if (me.bkqueryCommandValue) {
  7368. me.queryCommandValue = me.bkqueryCommandValue;
  7369. delete me.bkqueryCommandValue;
  7370. }
  7371. me.fireEvent('selectionchange');
  7372. }
  7373. },
  7374. enable: function () {
  7375. return this.setEnabled();
  7376. },
  7377. /** 设置当前编辑区域不可编辑
  7378. * @method setDisabled
  7379. */
  7380. /** 设置当前编辑区域不可编辑,except中的命令除外
  7381. * @method setDisabled
  7382. * @param { String } except 例外命令的字符串
  7383. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7384. * @example
  7385. * ```javascript
  7386. * editor.setDisabled('bold'); //禁用工具栏中除加粗之外的所有功能
  7387. * ```
  7388. */
  7389. /** 设置当前编辑区域不可编辑,except中的命令除外
  7390. * @method setDisabled
  7391. * @param { Array } except 例外命令的字符串数组,数组中的命令仍然可以执行
  7392. * @remind 即使设置了disable,此处配置的例外命令仍然可以执行
  7393. * @example
  7394. * ```javascript
  7395. * editor.setDisabled(['bold','insertimage']); //禁用工具栏中除加粗和插入图片之外的所有功能
  7396. * ```
  7397. */
  7398. setDisabled: function (except) {
  7399. var me = this;
  7400. except = except ? utils.isArray(except) ? except : [except] : [];
  7401. if (me.body.contentEditable == 'true') {
  7402. if (!me.lastBk) {
  7403. me.lastBk = me.selection.getRange().createBookmark(true);
  7404. }
  7405. me.body.contentEditable = false;
  7406. me.bkqueryCommandState = me.queryCommandState;
  7407. me.bkqueryCommandValue = me.queryCommandValue;
  7408. me.queryCommandState = function (type) {
  7409. if (utils.indexOf(except, type) != -1) {
  7410. return me.bkqueryCommandState.apply(me, arguments);
  7411. }
  7412. return -1;
  7413. };
  7414. me.queryCommandValue = function (type) {
  7415. if (utils.indexOf(except, type) != -1) {
  7416. return me.bkqueryCommandValue.apply(me, arguments);
  7417. }
  7418. return null;
  7419. };
  7420. me.fireEvent('selectionchange');
  7421. }
  7422. },
  7423. disable: function (except) {
  7424. return this.setDisabled(except);
  7425. },
  7426. /**
  7427. * 设置默认内容
  7428. * @method _setDefaultContent
  7429. * @private
  7430. * @param { String } cont 要存入的内容
  7431. */
  7432. _setDefaultContent: function () {
  7433. function clear() {
  7434. var me = this;
  7435. if (me.document.getElementById('initContent')) {
  7436. me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>';
  7437. me.removeListener('firstBeforeExecCommand focus', clear);
  7438. setTimeout(function () {
  7439. me.focus();
  7440. me._selectionChange();
  7441. }, 0)
  7442. }
  7443. }
  7444. return function (cont) {
  7445. var me = this;
  7446. me.body.innerHTML = '<p id="initContent">' + cont + '</p>';
  7447. me.addListener('firstBeforeExecCommand focus', clear);
  7448. }
  7449. }(),
  7450. /**
  7451. * 显示编辑器
  7452. * @method setShow
  7453. * @example
  7454. * ```javascript
  7455. * editor.setShow()
  7456. * ```
  7457. */
  7458. setShow: function () {
  7459. var me = this, range = me.selection.getRange();
  7460. if (me.container.style.display == 'none') {
  7461. //有可能内容丢失了
  7462. try {
  7463. range.moveToBookmark(me.lastBk);
  7464. delete me.lastBk
  7465. } catch (e) {
  7466. range.setStartAtFirst(me.body).collapse(true)
  7467. }
  7468. //ie下focus实效,所以做了个延迟
  7469. setTimeout(function () {
  7470. range.select(true);
  7471. }, 100);
  7472. me.container.style.display = '';
  7473. }
  7474. },
  7475. show: function () {
  7476. return this.setShow();
  7477. },
  7478. /**
  7479. * 隐藏编辑器
  7480. * @method setHide
  7481. * @example
  7482. * ```javascript
  7483. * editor.setHide()
  7484. * ```
  7485. */
  7486. setHide: function () {
  7487. var me = this;
  7488. if (!me.lastBk) {
  7489. me.lastBk = me.selection.getRange().createBookmark(true);
  7490. }
  7491. me.container.style.display = 'none'
  7492. },
  7493. hide: function () {
  7494. return this.setHide();
  7495. },
  7496. /**
  7497. * 根据指定的路径,获取对应的语言资源
  7498. * @method getLang
  7499. * @param { String } path 路径根据的是lang目录下的语言文件的路径结构
  7500. * @return { Object | String } 根据路径返回语言资源的Json格式对象或者语言字符串
  7501. * @example
  7502. * ```javascript
  7503. * editor.getLang('contextMenu.delete'); //如果当前是中文,那返回是的是'删除'
  7504. * ```
  7505. */
  7506. getLang: function (path) {
  7507. var lang = UE.I18N[this.options.lang];
  7508. if (!lang) {
  7509. throw Error("not import language file");
  7510. }
  7511. path = (path || "").split(".");
  7512. for (var i = 0, ci; ci = path[i++];) {
  7513. lang = lang[ci];
  7514. if (!lang)break;
  7515. }
  7516. return lang;
  7517. },
  7518. /**
  7519. * 计算编辑器html内容字符串的长度
  7520. * @method getContentLength
  7521. * @return { Number } 返回计算的长度
  7522. * @example
  7523. * ```javascript
  7524. * //编辑器html内容<p><strong>132</strong></p>
  7525. * editor.getContentLength() //返回27
  7526. * ```
  7527. */
  7528. /**
  7529. * 计算编辑器当前纯文本内容的长度
  7530. * @method getContentLength
  7531. * @param { Boolean } ingoneHtml 传入true时,只按照纯文本来计算
  7532. * @return { Number } 返回计算的长度,内容中有hr/img/iframe标签,长度加1
  7533. * @example
  7534. * ```javascript
  7535. * //编辑器html内容<p><strong>132</strong></p>
  7536. * editor.getContentLength() //返回3
  7537. * ```
  7538. */
  7539. getContentLength: function (ingoneHtml, tagNames) {
  7540. var count = this.getContent(false,false,true).length;
  7541. if (ingoneHtml) {
  7542. tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']);
  7543. count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length;
  7544. for (var i = 0, ci; ci = tagNames[i++];) {
  7545. count += this.document.getElementsByTagName(ci).length;
  7546. }
  7547. }
  7548. return count;
  7549. },
  7550. /**
  7551. * 注册输入过滤规则
  7552. * @method addInputRule
  7553. * @param { Function } rule 要添加的过滤规则
  7554. * @example
  7555. * ```javascript
  7556. * editor.addInputRule(function(root){
  7557. * $.each(root.getNodesByTagName('div'),function(i,node){
  7558. * node.tagName="p";
  7559. * });
  7560. * });
  7561. * ```
  7562. */
  7563. addInputRule: function (rule) {
  7564. this.inputRules.push(rule);
  7565. },
  7566. /**
  7567. * 执行注册的过滤规则
  7568. * @method filterInputRule
  7569. * @param { UE.uNode } root 要过滤的uNode节点
  7570. * @remind 执行editor.setContent方法和执行'inserthtml'命令后,会运行该过滤函数
  7571. * @example
  7572. * ```javascript
  7573. * editor.filterInputRule(editor.body);
  7574. * ```
  7575. * @see UE.Editor:addInputRule
  7576. */
  7577. filterInputRule: function (root) {
  7578. for (var i = 0, ci; ci = this.inputRules[i++];) {
  7579. ci.call(this, root)
  7580. }
  7581. },
  7582. /**
  7583. * 注册输出过滤规则
  7584. * @method addOutputRule
  7585. * @param { Function } rule 要添加的过滤规则
  7586. * @example
  7587. * ```javascript
  7588. * editor.addOutputRule(function(root){
  7589. * $.each(root.getNodesByTagName('p'),function(i,node){
  7590. * node.tagName="div";
  7591. * });
  7592. * });
  7593. * ```
  7594. */
  7595. addOutputRule: function (rule) {
  7596. this.outputRules.push(rule)
  7597. },
  7598. /**
  7599. * 根据输出过滤规则,过滤编辑器内容
  7600. * @method filterOutputRule
  7601. * @remind 执行editor.getContent方法的时候,会先运行该过滤函数
  7602. * @param { UE.uNode } root 要过滤的uNode节点
  7603. * @example
  7604. * ```javascript
  7605. * editor.filterOutputRule(editor.body);
  7606. * ```
  7607. * @see UE.Editor:addOutputRule
  7608. */
  7609. filterOutputRule: function (root) {
  7610. for (var i = 0, ci; ci = this.outputRules[i++];) {
  7611. ci.call(this, root)
  7612. }
  7613. },
  7614. /**
  7615. * 根据action名称获取请求的路径
  7616. * @method getActionUrl
  7617. * @remind 假如没有设置serverUrl,会根据imageUrl设置默认的controller路径
  7618. * @param { String } action action名称
  7619. * @example
  7620. * ```javascript
  7621. * editor.getActionUrl('config'); //返回 "/ueditor/php/controller.php?action=config"
  7622. * editor.getActionUrl('image'); //返回 "/ueditor/php/controller.php?action=uplaodimage"
  7623. * editor.getActionUrl('scrawl'); //返回 "/ueditor/php/controller.php?action=uplaodscrawl"
  7624. * editor.getActionUrl('imageManager'); //返回 "/ueditor/php/controller.php?action=listimage"
  7625. * ```
  7626. */
  7627. getActionUrl: function(action){
  7628. var actionName = this.getOpt(action) || action,
  7629. imageUrl = this.getOpt('imageUrl'),
  7630. serverUrl = this.getOpt('serverUrl');
  7631. if(!serverUrl && imageUrl) {
  7632. serverUrl = imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2');
  7633. }
  7634. if (actionName == 'uploadimage' || actionName == 'uploadscrawl' || actionName == 'listfile' || actionName =='uploadfile') {
  7635. // const url = serverUrl;
  7636. // console.log(this.getOpt('uploadUrl'))
  7637. // const domain = url.split('/').slice(0, 3).join('/');
  7638. return this.getOpt('uploadUrl');
  7639. }
  7640. if(serverUrl) {
  7641. serverUrl = serverUrl + (serverUrl.indexOf('?') == -1 ? '?':'&') + 'action=' + (actionName || '');
  7642. return utils.formatUrl(serverUrl);
  7643. } else {
  7644. return '';
  7645. }
  7646. }
  7647. };
  7648. utils.inherits(Editor, EventBase);
  7649. })();
  7650. // core/Editor.defaultoptions.js
  7651. //维护编辑器一下默认的不在插件中的配置项
  7652. UE.Editor.defaultOptions = function(editor){
  7653. var _url = editor.options.UEDITOR_HOME_URL;
  7654. return {
  7655. isShow: true,
  7656. initialContent: '',
  7657. initialStyle:'',
  7658. autoClearinitialContent: false,
  7659. iframeCssUrl: _url + 'themes/iframe.css',
  7660. textarea: 'editorValue',
  7661. focus: false,
  7662. focusInEnd: true,
  7663. autoClearEmptyNode: true,
  7664. fullscreen: false,
  7665. readonly: false,
  7666. zIndex: 999,
  7667. imagePopup: true,
  7668. enterTag: 'p',
  7669. customDomain: false,
  7670. lang: 'zh-cn',
  7671. langPath: _url + 'lang/',
  7672. theme: 'default',
  7673. themePath: _url + 'themes/',
  7674. allHtmlEnabled: false,
  7675. scaleEnabled: false,
  7676. tableNativeEditInFF: false,
  7677. autoSyncData : true,
  7678. fileNameFormat: '{time}{rand:6}'
  7679. }
  7680. };
  7681. // core/loadconfig.js
  7682. (function(){
  7683. UE.Editor.prototype.loadServerConfig = function(){
  7684. var me = this;
  7685. setTimeout(function(){
  7686. try{
  7687. me.options.imageUrl && me.setOpt('serverUrl', me.options.imageUrl.replace(/^(.*[\/]).+([\.].+)$/, '$1controller$2'));
  7688. var configUrl = me.getActionUrl('config'),
  7689. isJsonp = false //utils.isCrossDomainUrl(configUrl);
  7690. /* 发出ajax请求 */
  7691. me._serverConfigLoaded = false;
  7692. configUrl && UE.ajax.request(configUrl,{
  7693. 'method': 'GET',
  7694. 'dataType': isJsonp ? 'jsonp':'',
  7695. 'onsuccess':function(r){
  7696. try {
  7697. var config = isJsonp ? r:eval("("+r.responseText+")");
  7698. utils.extend(me.options, config);
  7699. me.fireEvent('serverConfigLoaded');
  7700. me._serverConfigLoaded = true;
  7701. } catch (e) {
  7702. showErrorMsg(me.getLang('loadconfigFormatError'));
  7703. }
  7704. },
  7705. 'onerror':function(){
  7706. console.log(2222)
  7707. showErrorMsg(me.getLang('loadconfigHttpError'));
  7708. }
  7709. });
  7710. } catch(e){
  7711. showErrorMsg(me.getLang('loadconfigError'));
  7712. }
  7713. });
  7714. function showErrorMsg(msg) {
  7715. console && console.error(msg);
  7716. //me.fireEvent('showMessage', {
  7717. // 'title': msg,
  7718. // 'type': 'error'
  7719. //});
  7720. }
  7721. };
  7722. UE.Editor.prototype.isServerConfigLoaded = function(){
  7723. var me = this;
  7724. return me._serverConfigLoaded || false;
  7725. };
  7726. UE.Editor.prototype.afterConfigReady = function(handler){
  7727. if (!handler || !utils.isFunction(handler)) return;
  7728. var me = this;
  7729. var readyHandler = function(){
  7730. handler.apply(me, arguments);
  7731. me.removeListener('serverConfigLoaded', readyHandler);
  7732. };
  7733. if (me.isServerConfigLoaded()) {
  7734. handler.call(me, 'serverConfigLoaded');
  7735. } else {
  7736. me.addListener('serverConfigLoaded', readyHandler);
  7737. }
  7738. };
  7739. })();
  7740. // core/ajax.js
  7741. /**
  7742. * @file
  7743. * @module UE.ajax
  7744. * @since 1.2.6.1
  7745. */
  7746. /**
  7747. * 提供对ajax请求的支持
  7748. * @module UE.ajax
  7749. */
  7750. UE.ajax = function() {
  7751. //创建一个ajaxRequest对象
  7752. var fnStr = 'XMLHttpRequest()';
  7753. try {
  7754. new ActiveXObject("Msxml2.XMLHTTP");
  7755. fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')';
  7756. } catch (e) {
  7757. try {
  7758. new ActiveXObject("Microsoft.XMLHTTP");
  7759. fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')'
  7760. } catch (e) {
  7761. }
  7762. }
  7763. var creatAjaxRequest = new Function('return new ' + fnStr);
  7764. /**
  7765. * 将json参数转化成适合ajax提交的参数列表
  7766. * @param json
  7767. */
  7768. function json2str(json) {
  7769. var strArr = [];
  7770. for (var i in json) {
  7771. //忽略默认的几个参数
  7772. if(i=="method" || i=="timeout" || i=="async" || i=="dataType" || i=="callback") continue;
  7773. //忽略控制
  7774. if(json[i] == undefined || json[i] == null) continue;
  7775. //传递过来的对象和函数不在提交之列
  7776. if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) {
  7777. strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) );
  7778. } else if (utils.isArray(json[i])) {
  7779. //支持传数组内容
  7780. for(var j = 0; j < json[i].length; j++) {
  7781. strArr.push( encodeURIComponent(i) + "[]="+encodeURIComponent(json[i][j]) );
  7782. }
  7783. }
  7784. }
  7785. return strArr.join("&");
  7786. }
  7787. function doAjax(url, ajaxOptions) {
  7788. var xhr = creatAjaxRequest(),
  7789. //是否超时
  7790. timeIsOut = false,
  7791. //默认参数
  7792. defaultAjaxOptions = {
  7793. method:"POST",
  7794. timeout:5000,
  7795. async:true,
  7796. data:{},//需要传递对象的话只能覆盖
  7797. onsuccess:function() {
  7798. },
  7799. onerror:function() {
  7800. }
  7801. };
  7802. if (typeof url === "object") {
  7803. ajaxOptions = url;
  7804. url = ajaxOptions.url;
  7805. }
  7806. if (!xhr || !url) return;
  7807. var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions;
  7808. var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7809. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7810. if (!utils.isEmptyObject(ajaxOpts.data)){
  7811. submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data);
  7812. }
  7813. //超时检测
  7814. var timerID = setTimeout(function() {
  7815. if (xhr.readyState != 4) {
  7816. timeIsOut = true;
  7817. xhr.abort();
  7818. clearTimeout(timerID);
  7819. }
  7820. }, ajaxOpts.timeout);
  7821. var method = ajaxOpts.method.toUpperCase();
  7822. var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date);
  7823. xhr.open(method, str, ajaxOpts.async);
  7824. xhr.onreadystatechange = function() {
  7825. if (xhr.readyState == 4) {
  7826. if (!timeIsOut && xhr.status == 200) {
  7827. ajaxOpts.onsuccess(xhr);
  7828. } else {
  7829. ajaxOpts.onerror(xhr);
  7830. }
  7831. }
  7832. };
  7833. if (method == "POST") {
  7834. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  7835. xhr.send(submitStr);
  7836. } else {
  7837. xhr.send(null);
  7838. }
  7839. }
  7840. function doJsonp(url, opts) {
  7841. var successhandler = opts.onsuccess || function(){},
  7842. scr = document.createElement('SCRIPT'),
  7843. options = opts || {},
  7844. charset = options['charset'],
  7845. callbackField = options['jsonp'] || 'callback',
  7846. callbackFnName,
  7847. timeOut = options['timeOut'] || 0,
  7848. timer,
  7849. reg = new RegExp('(\\?|&)' + callbackField + '=([^&]*)'),
  7850. matches;
  7851. if (utils.isFunction(successhandler)) {
  7852. callbackFnName = 'bd__editor__' + Math.floor(Math.random() * 2147483648).toString(36);
  7853. window[callbackFnName] = getCallBack(0);
  7854. } else if(utils.isString(successhandler)){
  7855. callbackFnName = successhandler;
  7856. } else {
  7857. if (matches = reg.exec(url)) {
  7858. callbackFnName = matches[2];
  7859. }
  7860. }
  7861. url = url.replace(reg, '\x241' + callbackField + '=' + callbackFnName);
  7862. if (url.search(reg) < 0) {
  7863. url += (url.indexOf('?') < 0 ? '?' : '&') + callbackField + '=' + callbackFnName;
  7864. }
  7865. var queryStr = json2str(opts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing"
  7866. //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串
  7867. if (!utils.isEmptyObject(opts.data)){
  7868. queryStr += (queryStr? "&":"") + json2str(opts.data);
  7869. }
  7870. if (queryStr) {
  7871. url = url.replace(/\?/, '?' + queryStr + '&');
  7872. }
  7873. scr.onerror = getCallBack(1);
  7874. if( timeOut ){
  7875. timer = setTimeout(getCallBack(1), timeOut);
  7876. }
  7877. createScriptTag(scr, url, charset);
  7878. function createScriptTag(scr, url, charset) {
  7879. scr.setAttribute('type', 'text/javascript');
  7880. scr.setAttribute('defer', 'defer');
  7881. charset && scr.setAttribute('charset', charset);
  7882. scr.setAttribute('src', url);
  7883. document.getElementsByTagName('head')[0].appendChild(scr);
  7884. }
  7885. function getCallBack(onTimeOut){
  7886. return function(){
  7887. try {
  7888. if(onTimeOut){
  7889. options.onerror && options.onerror();
  7890. }else{
  7891. try{
  7892. clearTimeout(timer);
  7893. successhandler.apply(window, arguments);
  7894. } catch (e){}
  7895. }
  7896. } catch (exception) {
  7897. options.onerror && options.onerror.call(window, exception);
  7898. } finally {
  7899. options.oncomplete && options.oncomplete.apply(window, arguments);
  7900. scr.parentNode && scr.parentNode.removeChild(scr);
  7901. window[callbackFnName] = null;
  7902. try {
  7903. delete window[callbackFnName];
  7904. }catch(e){}
  7905. }
  7906. }
  7907. }
  7908. }
  7909. return {
  7910. /**
  7911. * 根据给定的参数项,向指定的url发起一个ajax请求。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7912. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调
  7913. * @method request
  7914. * @param { URLString } url ajax请求的url地址
  7915. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7916. * @example
  7917. * ```javascript
  7918. * //向sayhello.php发起一个异步的Ajax GET请求, 请求超时时间为10s, 请求完成后执行相应的回调。
  7919. * UE.ajax.requeset( 'sayhello.php', {
  7920. *
  7921. * //请求方法。可选值: 'GET', 'POST',默认值是'POST'
  7922. * method: 'GET',
  7923. *
  7924. * //超时时间。 默认为5000, 单位是ms
  7925. * timeout: 10000,
  7926. *
  7927. * //是否是异步请求。 true为异步请求, false为同步请求
  7928. * async: true,
  7929. *
  7930. * //请求携带的数据。如果请求为GET请求, data会经过stringify后附加到请求url之后。
  7931. * data: {
  7932. * name: 'ueditor'
  7933. * },
  7934. *
  7935. * //请求成功后的回调, 该回调接受当前的XMLHttpRequest对象作为参数。
  7936. * onsuccess: function ( xhr ) {
  7937. * console.log( xhr.responseText );
  7938. * },
  7939. *
  7940. * //请求失败或者超时后的回调。
  7941. * onerror: function ( xhr ) {
  7942. * alert( 'Ajax请求失败' );
  7943. * }
  7944. *
  7945. * } );
  7946. * ```
  7947. */
  7948. /**
  7949. * 根据给定的参数项发起一个ajax请求, 参数项里必须包含一个url地址。 ajax请求完成后,会根据请求结果调用相应回调: 如果请求
  7950. * 成功, 则调用onsuccess回调, 失败则调用 onerror 回调。
  7951. * @method request
  7952. * @warning 如果在参数项里未提供一个key为“url”的地址值,则该请求将直接退出。
  7953. * @param { Object } ajaxOptions ajax请求选项的键值对,支持的选项如下:
  7954. * @example
  7955. * ```javascript
  7956. *
  7957. * //向sayhello.php发起一个异步的Ajax POST请求, 请求超时时间为5s, 请求完成后不执行任何回调。
  7958. * UE.ajax.requeset( 'sayhello.php', {
  7959. *
  7960. * //请求的地址, 该项是必须的。
  7961. * url: 'sayhello.php'
  7962. *
  7963. * } );
  7964. * ```
  7965. */
  7966. request:function(url, opts) {
  7967. if (opts && opts.dataType == 'jsonp') {
  7968. doJsonp(url, opts);
  7969. } else {
  7970. doAjax(url, opts);
  7971. }
  7972. },
  7973. getJSONP:function(url, data, fn) {
  7974. var opts = {
  7975. 'data': data,
  7976. 'oncomplete': fn
  7977. };
  7978. doJsonp(url, opts);
  7979. }
  7980. };
  7981. }();
  7982. // core/filterword.js
  7983. /**
  7984. * UE过滤word的静态方法
  7985. * @file
  7986. */
  7987. /**
  7988. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  7989. * @module UE
  7990. */
  7991. /**
  7992. * 根据传入html字符串过滤word
  7993. * @module UE
  7994. * @since 1.2.6.1
  7995. * @method filterWord
  7996. * @param { String } html html字符串
  7997. * @return { String } 已过滤后的结果字符串
  7998. * @example
  7999. * ```javascript
  8000. * UE.filterWord(html);
  8001. * ```
  8002. */
  8003. var filterWord = UE.filterWord = function () {
  8004. //是否是word过来的内容
  8005. function isWordDocument( str ) {
  8006. return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<(v|o):|lang=)/ig.test( str );
  8007. }
  8008. //去掉小数
  8009. function transUnit( v ) {
  8010. v = v.replace( /[\d.]+\w+/g, function ( m ) {
  8011. return utils.transUnitToPx(m);
  8012. } );
  8013. return v;
  8014. }
  8015. function filterPasteWord( str ) {
  8016. return str.replace(/[\t\r\n]+/g,' ')
  8017. .replace( /<!--[\s\S]*?-->/ig, "" )
  8018. //转换图片
  8019. .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){
  8020. //opera能自己解析出image所这里直接返回空
  8021. if(browser.opera){
  8022. return '';
  8023. }
  8024. try{
  8025. //有可能是bitmap占为图,无用,直接过滤掉,主要体现在粘贴excel表格中
  8026. if(/Bitmap/i.test(str)){
  8027. return '';
  8028. }
  8029. var width = str.match(/width:([ \d.]*p[tx])/i)[1],
  8030. height = str.match(/height:([ \d.]*p[tx])/i)[1],
  8031. src = str.match(/src=\s*"([^"]*)"/i)[1];
  8032. return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />';
  8033. } catch(e){
  8034. return '';
  8035. }
  8036. })
  8037. //针对wps添加的多余标签处理
  8038. .replace(/<\/?div[^>]*>/g,'')
  8039. //去掉多余的属性
  8040. .replace( /v:\w+=(["']?)[^'"]+\1/g, '' )
  8041. .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" )
  8042. .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" )
  8043. //去掉多余的属性
  8044. .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){
  8045. //保留list的标示
  8046. return name == 'class' && val == 'MsoListParagraph' ? str : ''
  8047. })
  8048. //清除多余的font/span不能匹配&nbsp;有可能是空格
  8049. .replace( /<(font|span)[^>]*>(\s*)<\/\1>/gi, function(a,b,c){
  8050. return c.replace(/[\t\r\n ]+/g,' ')
  8051. })
  8052. //处理style的问题
  8053. .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) {
  8054. var n = [],
  8055. s = style.replace( /^\s+|\s+$/, '' )
  8056. .replace(/&#39;/g,'\'')
  8057. .replace( /&quot;/gi, "'" )
  8058. .replace(/[\d.]+(cm|pt)/g,function(str){
  8059. return utils.transUnitToPx(str)
  8060. })
  8061. .split( /;\s*/g );
  8062. for ( var i = 0,v; v = s[i];i++ ) {
  8063. var name, value,
  8064. parts = v.split( ":" );
  8065. if ( parts.length == 2 ) {
  8066. name = parts[0].toLowerCase();
  8067. value = parts[1].toLowerCase();
  8068. if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0
  8069. ||
  8070. /^(margin)\w*/.test(name) && /^0\w+$/.test(value)
  8071. ){
  8072. continue;
  8073. }
  8074. switch ( name ) {
  8075. case "mso-padding-alt":
  8076. case "mso-padding-top-alt":
  8077. case "mso-padding-right-alt":
  8078. case "mso-padding-bottom-alt":
  8079. case "mso-padding-left-alt":
  8080. case "mso-margin-alt":
  8081. case "mso-margin-top-alt":
  8082. case "mso-margin-right-alt":
  8083. case "mso-margin-bottom-alt":
  8084. case "mso-margin-left-alt":
  8085. //ie下会出现挤到一起的情况
  8086. //case "mso-table-layout-alt":
  8087. case "mso-height":
  8088. case "mso-width":
  8089. case "mso-vertical-align-alt":
  8090. //trace:1819 ff下会解析出padding在table上
  8091. if(!/<table/.test(tag))
  8092. n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value );
  8093. continue;
  8094. case "horiz-align":
  8095. n[i] = "text-align:" + value;
  8096. continue;
  8097. case "vert-align":
  8098. n[i] = "vertical-align:" + value;
  8099. continue;
  8100. case "font-color":
  8101. case "mso-foreground":
  8102. n[i] = "color:" + value;
  8103. continue;
  8104. case "mso-background":
  8105. case "mso-highlight":
  8106. n[i] = "background:" + value;
  8107. continue;
  8108. case "mso-default-height":
  8109. n[i] = "min-height:" + transUnit( value );
  8110. continue;
  8111. case "mso-default-width":
  8112. n[i] = "min-width:" + transUnit( value );
  8113. continue;
  8114. case "mso-padding-between-alt":
  8115. n[i] = "border-collapse:separate;border-spacing:" + transUnit( value );
  8116. continue;
  8117. case "text-line-through":
  8118. if ( (value == "single") || (value == "double") ) {
  8119. n[i] = "text-decoration:line-through";
  8120. }
  8121. continue;
  8122. case "mso-zero-height":
  8123. if ( value == "yes" ) {
  8124. n[i] = "display:none";
  8125. }
  8126. continue;
  8127. // case 'background':
  8128. // break;
  8129. case 'margin':
  8130. if ( !/[1-9]/.test( value ) ) {
  8131. continue;
  8132. }
  8133. }
  8134. 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 )
  8135. ||
  8136. /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value)
  8137. ) {
  8138. continue;
  8139. }
  8140. n[i] = name + ":" + parts[1];
  8141. }
  8142. }
  8143. return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : '');
  8144. })
  8145. }
  8146. return function ( html ) {
  8147. return (isWordDocument( html ) ? filterPasteWord( html ) : html);
  8148. };
  8149. }();
  8150. // core/node.js
  8151. /**
  8152. * 编辑器模拟的节点类
  8153. * @file
  8154. * @module UE
  8155. * @class uNode
  8156. * @since 1.2.6.1
  8157. */
  8158. /**
  8159. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8160. * @unfile
  8161. * @module UE
  8162. */
  8163. (function () {
  8164. /**
  8165. * 编辑器模拟的节点类
  8166. * @unfile
  8167. * @module UE
  8168. * @class uNode
  8169. */
  8170. /**
  8171. * 通过一个键值对,创建一个uNode对象
  8172. * @constructor
  8173. * @param { Object } attr 传入要创建的uNode的初始属性
  8174. * @example
  8175. * ```javascript
  8176. * var node = new uNode({
  8177. * type:'element',
  8178. * tagName:'span',
  8179. * attrs:{style:'font-size:14px;'}
  8180. * }
  8181. * ```
  8182. */
  8183. var uNode = UE.uNode = function (obj) {
  8184. this.type = obj.type;
  8185. this.data = obj.data;
  8186. this.tagName = obj.tagName;
  8187. this.parentNode = obj.parentNode;
  8188. this.attrs = obj.attrs || {};
  8189. this.children = obj.children;
  8190. };
  8191. var notTransAttrs = {
  8192. 'href':1,
  8193. 'src':1,
  8194. '_src':1,
  8195. '_href':1,
  8196. 'cdata_data':1
  8197. };
  8198. var notTransTagName = {
  8199. style:1,
  8200. script:1
  8201. };
  8202. var indentChar = ' ',
  8203. breakChar = '\n';
  8204. function insertLine(arr, current, begin) {
  8205. arr.push(breakChar);
  8206. return current + (begin ? 1 : -1);
  8207. }
  8208. function insertIndent(arr, current) {
  8209. //插入缩进
  8210. for (var i = 0; i < current; i++) {
  8211. arr.push(indentChar);
  8212. }
  8213. }
  8214. //创建uNode的静态方法
  8215. //支持标签和html
  8216. uNode.createElement = function (html) {
  8217. if (/[<>]/.test(html)) {
  8218. return UE.htmlparser(html).children[0]
  8219. } else {
  8220. return new uNode({
  8221. type:'element',
  8222. children:[],
  8223. tagName:html
  8224. })
  8225. }
  8226. };
  8227. uNode.createText = function (data,noTrans) {
  8228. return new UE.uNode({
  8229. type:'text',
  8230. 'data':noTrans ? data : utils.unhtml(data || '')
  8231. })
  8232. };
  8233. function nodeToHtml(node, arr, formatter, current) {
  8234. switch (node.type) {
  8235. case 'root':
  8236. for (var i = 0, ci; ci = node.children[i++];) {
  8237. //插入新行
  8238. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8239. insertLine(arr, current, true);
  8240. insertIndent(arr, current)
  8241. }
  8242. nodeToHtml(ci, arr, formatter, current)
  8243. }
  8244. break;
  8245. case 'text':
  8246. isText(node, arr);
  8247. break;
  8248. case 'element':
  8249. isElement(node, arr, formatter, current);
  8250. break;
  8251. case 'comment':
  8252. isComment(node, arr, formatter);
  8253. }
  8254. return arr;
  8255. }
  8256. function isText(node, arr) {
  8257. if(node.parentNode.tagName == 'pre'){
  8258. //源码模式下输入html标签,不能做转换处理,直接输出
  8259. arr.push(node.data)
  8260. }else{
  8261. arr.push(notTransTagName[node.parentNode.tagName] ? utils.html(node.data) : node.data.replace(/[ ]{2}/g,' &nbsp;'))
  8262. }
  8263. }
  8264. function isElement(node, arr, formatter, current) {
  8265. var attrhtml = '';
  8266. if (node.attrs) {
  8267. attrhtml = [];
  8268. var attrs = node.attrs;
  8269. for (var a in attrs) {
  8270. //这里就针对
  8271. //<p>'<img src='http://nsclick.baidu.com/u.gif?&asdf=\"sdf&asdfasdfs;asdf'></p>
  8272. //这里边的\"做转换,要不用innerHTML直接被截断了,属性src
  8273. //有可能做的不够
  8274. attrhtml.push(a + (attrs[a] !== undefined ? '="' + (notTransAttrs[a] ? utils.html(attrs[a]).replace(/["]/g, function (a) {
  8275. return '&quot;'
  8276. }) : utils.unhtml(attrs[a])) + '"' : ''))
  8277. }
  8278. attrhtml = attrhtml.join(' ');
  8279. }
  8280. arr.push('<' + node.tagName +
  8281. (attrhtml ? ' ' + attrhtml : '') +
  8282. (dtd.$empty[node.tagName] ? '\/' : '' ) + '>'
  8283. );
  8284. //插入新行
  8285. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8286. if(node.children && node.children.length){
  8287. current = insertLine(arr, current, true);
  8288. insertIndent(arr, current)
  8289. }
  8290. }
  8291. if (node.children && node.children.length) {
  8292. for (var i = 0, ci; ci = node.children[i++];) {
  8293. if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) {
  8294. insertLine(arr, current);
  8295. insertIndent(arr, current)
  8296. }
  8297. nodeToHtml(ci, arr, formatter, current)
  8298. }
  8299. }
  8300. if (!dtd.$empty[node.tagName]) {
  8301. if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') {
  8302. if(node.children && node.children.length){
  8303. current = insertLine(arr, current);
  8304. insertIndent(arr, current)
  8305. }
  8306. }
  8307. arr.push('<\/' + node.tagName + '>');
  8308. }
  8309. }
  8310. function isComment(node, arr) {
  8311. arr.push('<!--' + node.data + '-->');
  8312. }
  8313. function getNodeById(root, id) {
  8314. var node;
  8315. if (root.type == 'element' && root.getAttr('id') == id) {
  8316. return root;
  8317. }
  8318. if (root.children && root.children.length) {
  8319. for (var i = 0, ci; ci = root.children[i++];) {
  8320. if (node = getNodeById(ci, id)) {
  8321. return node;
  8322. }
  8323. }
  8324. }
  8325. }
  8326. function getNodesByTagName(node, tagName, arr) {
  8327. if (node.type == 'element' && node.tagName == tagName) {
  8328. arr.push(node);
  8329. }
  8330. if (node.children && node.children.length) {
  8331. for (var i = 0, ci; ci = node.children[i++];) {
  8332. getNodesByTagName(ci, tagName, arr)
  8333. }
  8334. }
  8335. }
  8336. function nodeTraversal(root,fn){
  8337. if(root.children && root.children.length){
  8338. for(var i= 0,ci;ci=root.children[i];){
  8339. nodeTraversal(ci,fn);
  8340. //ci被替换的情况,这里就不再走 fn了
  8341. if(ci.parentNode ){
  8342. if(ci.children && ci.children.length){
  8343. fn(ci)
  8344. }
  8345. if(ci.parentNode) i++
  8346. }
  8347. }
  8348. }else{
  8349. fn(root)
  8350. }
  8351. }
  8352. uNode.prototype = {
  8353. /**
  8354. * 当前节点对象,转换成html文本
  8355. * @method toHtml
  8356. * @return { String } 返回转换后的html字符串
  8357. * @example
  8358. * ```javascript
  8359. * node.toHtml();
  8360. * ```
  8361. */
  8362. /**
  8363. * 当前节点对象,转换成html文本
  8364. * @method toHtml
  8365. * @param { Boolean } formatter 是否格式化返回值
  8366. * @return { String } 返回转换后的html字符串
  8367. * @example
  8368. * ```javascript
  8369. * node.toHtml( true );
  8370. * ```
  8371. */
  8372. toHtml:function (formatter) {
  8373. var arr = [];
  8374. nodeToHtml(this, arr, formatter, 0);
  8375. return arr.join('')
  8376. },
  8377. /**
  8378. * 获取节点的html内容
  8379. * @method innerHTML
  8380. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8381. * @return { String } 返回节点的html内容
  8382. * @example
  8383. * ```javascript
  8384. * var htmlstr = node.innerHTML();
  8385. * ```
  8386. */
  8387. /**
  8388. * 设置节点的html内容
  8389. * @method innerHTML
  8390. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8391. * @param { String } htmlstr 传入要设置的html内容
  8392. * @return { UE.uNode } 返回节点本身
  8393. * @example
  8394. * ```javascript
  8395. * node.innerHTML('<span>text</span>');
  8396. * ```
  8397. */
  8398. innerHTML:function (htmlstr) {
  8399. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8400. return this;
  8401. }
  8402. if (utils.isString(htmlstr)) {
  8403. if(this.children){
  8404. for (var i = 0, ci; ci = this.children[i++];) {
  8405. ci.parentNode = null;
  8406. }
  8407. }
  8408. this.children = [];
  8409. var tmpRoot = UE.htmlparser(htmlstr);
  8410. for (var i = 0, ci; ci = tmpRoot.children[i++];) {
  8411. this.children.push(ci);
  8412. ci.parentNode = this;
  8413. }
  8414. return this;
  8415. } else {
  8416. var tmpRoot = new UE.uNode({
  8417. type:'root',
  8418. children:this.children
  8419. });
  8420. return tmpRoot.toHtml();
  8421. }
  8422. },
  8423. /**
  8424. * 获取节点的纯文本内容
  8425. * @method innerText
  8426. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8427. * @return { String } 返回节点的存文本内容
  8428. * @example
  8429. * ```javascript
  8430. * var textStr = node.innerText();
  8431. * ```
  8432. */
  8433. /**
  8434. * 设置节点的纯文本内容
  8435. * @method innerText
  8436. * @warning 假如节点的type不是'element',或节点的标签名称不在dtd列表里,直接返回当前节点
  8437. * @param { String } textStr 传入要设置的文本内容
  8438. * @return { UE.uNode } 返回节点本身
  8439. * @example
  8440. * ```javascript
  8441. * node.innerText('<span>text</span>');
  8442. * ```
  8443. */
  8444. innerText:function (textStr,noTrans) {
  8445. if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8446. return this;
  8447. }
  8448. if (textStr) {
  8449. if(this.children){
  8450. for (var i = 0, ci; ci = this.children[i++];) {
  8451. ci.parentNode = null;
  8452. }
  8453. }
  8454. this.children = [];
  8455. this.appendChild(uNode.createText(textStr,noTrans));
  8456. return this;
  8457. } else {
  8458. return this.toHtml().replace(/<[^>]+>/g, '');
  8459. }
  8460. },
  8461. /**
  8462. * 获取当前对象的data属性
  8463. * @method getData
  8464. * @return { Object } 若节点的type值是elemenet,返回空字符串,否则返回节点的data属性
  8465. * @example
  8466. * ```javascript
  8467. * node.getData();
  8468. * ```
  8469. */
  8470. getData:function () {
  8471. if (this.type == 'element')
  8472. return '';
  8473. return this.data
  8474. },
  8475. /**
  8476. * 获取当前节点下的第一个子节点
  8477. * @method firstChild
  8478. * @return { UE.uNode } 返回第一个子节点
  8479. * @example
  8480. * ```javascript
  8481. * node.firstChild(); //返回第一个子节点
  8482. * ```
  8483. */
  8484. firstChild:function () {
  8485. // if (this.type != 'element' || dtd.$empty[this.tagName]) {
  8486. // return this;
  8487. // }
  8488. return this.children ? this.children[0] : null;
  8489. },
  8490. /**
  8491. * 获取当前节点下的最后一个子节点
  8492. * @method lastChild
  8493. * @return { UE.uNode } 返回最后一个子节点
  8494. * @example
  8495. * ```javascript
  8496. * node.lastChild(); //返回最后一个子节点
  8497. * ```
  8498. */
  8499. lastChild:function () {
  8500. // if (this.type != 'element' || dtd.$empty[this.tagName] ) {
  8501. // return this;
  8502. // }
  8503. return this.children ? this.children[this.children.length - 1] : null;
  8504. },
  8505. /**
  8506. * 获取和当前节点有相同父亲节点的前一个节点
  8507. * @method previousSibling
  8508. * @return { UE.uNode } 返回前一个节点
  8509. * @example
  8510. * ```javascript
  8511. * node.children[2].previousSibling(); //返回子节点node.children[1]
  8512. * ```
  8513. */
  8514. previousSibling : function(){
  8515. var parent = this.parentNode;
  8516. for (var i = 0, ci; ci = parent.children[i]; i++) {
  8517. if (ci === this) {
  8518. return i == 0 ? null : parent.children[i-1];
  8519. }
  8520. }
  8521. },
  8522. /**
  8523. * 获取和当前节点有相同父亲节点的后一个节点
  8524. * @method nextSibling
  8525. * @return { UE.uNode } 返回后一个节点,找不到返回null
  8526. * @example
  8527. * ```javascript
  8528. * node.children[2].nextSibling(); //如果有,返回子节点node.children[3]
  8529. * ```
  8530. */
  8531. nextSibling : function(){
  8532. var parent = this.parentNode;
  8533. for (var i = 0, ci; ci = parent.children[i++];) {
  8534. if (ci === this) {
  8535. return parent.children[i];
  8536. }
  8537. }
  8538. },
  8539. /**
  8540. * 用新的节点替换当前节点
  8541. * @method replaceChild
  8542. * @param { UE.uNode } target 要替换成该节点参数
  8543. * @param { UE.uNode } source 要被替换掉的节点
  8544. * @return { UE.uNode } 返回替换之后的节点对象
  8545. * @example
  8546. * ```javascript
  8547. * node.replaceChild(newNode, childNode); //用newNode替换childNode,childNode是node的子节点
  8548. * ```
  8549. */
  8550. replaceChild:function (target, source) {
  8551. if (this.children) {
  8552. if(target.parentNode){
  8553. target.parentNode.removeChild(target);
  8554. }
  8555. for (var i = 0, ci; ci = this.children[i]; i++) {
  8556. if (ci === source) {
  8557. this.children.splice(i, 1, target);
  8558. source.parentNode = null;
  8559. target.parentNode = this;
  8560. return target;
  8561. }
  8562. }
  8563. }
  8564. },
  8565. /**
  8566. * 在节点的子节点列表最后位置插入一个节点
  8567. * @method appendChild
  8568. * @param { UE.uNode } node 要插入的节点
  8569. * @return { UE.uNode } 返回刚插入的子节点
  8570. * @example
  8571. * ```javascript
  8572. * node.appendChild( newNode ); //在node内插入子节点newNode
  8573. * ```
  8574. */
  8575. appendChild:function (node) {
  8576. if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) {
  8577. if (!this.children) {
  8578. this.children = []
  8579. }
  8580. if(node.parentNode){
  8581. node.parentNode.removeChild(node);
  8582. }
  8583. for (var i = 0, ci; ci = this.children[i]; i++) {
  8584. if (ci === node) {
  8585. this.children.splice(i, 1);
  8586. break;
  8587. }
  8588. }
  8589. this.children.push(node);
  8590. node.parentNode = this;
  8591. return node;
  8592. }
  8593. },
  8594. /**
  8595. * 在传入节点的前面插入一个节点
  8596. * @method insertBefore
  8597. * @param { UE.uNode } target 要插入的节点
  8598. * @param { UE.uNode } source 在该参数节点前面插入
  8599. * @return { UE.uNode } 返回刚插入的子节点
  8600. * @example
  8601. * ```javascript
  8602. * node.parentNode.insertBefore(newNode, node); //在node节点后面插入newNode
  8603. * ```
  8604. */
  8605. insertBefore:function (target, source) {
  8606. if (this.children) {
  8607. if(target.parentNode){
  8608. target.parentNode.removeChild(target);
  8609. }
  8610. for (var i = 0, ci; ci = this.children[i]; i++) {
  8611. if (ci === source) {
  8612. this.children.splice(i, 0, target);
  8613. target.parentNode = this;
  8614. return target;
  8615. }
  8616. }
  8617. }
  8618. },
  8619. /**
  8620. * 在传入节点的后面插入一个节点
  8621. * @method insertAfter
  8622. * @param { UE.uNode } target 要插入的节点
  8623. * @param { UE.uNode } source 在该参数节点后面插入
  8624. * @return { UE.uNode } 返回刚插入的子节点
  8625. * @example
  8626. * ```javascript
  8627. * node.parentNode.insertAfter(newNode, node); //在node节点后面插入newNode
  8628. * ```
  8629. */
  8630. insertAfter:function (target, source) {
  8631. if (this.children) {
  8632. if(target.parentNode){
  8633. target.parentNode.removeChild(target);
  8634. }
  8635. for (var i = 0, ci; ci = this.children[i]; i++) {
  8636. if (ci === source) {
  8637. this.children.splice(i + 1, 0, target);
  8638. target.parentNode = this;
  8639. return target;
  8640. }
  8641. }
  8642. }
  8643. },
  8644. /**
  8645. * 从当前节点的子节点列表中,移除节点
  8646. * @method removeChild
  8647. * @param { UE.uNode } node 要移除的节点引用
  8648. * @param { Boolean } keepChildren 是否保留移除节点的子节点,若传入true,自动把移除节点的子节点插入到移除的位置
  8649. * @return { * } 返回刚移除的子节点
  8650. * @example
  8651. * ```javascript
  8652. * node.removeChild(childNode,true); //在node的子节点列表中移除child节点,并且吧child的子节点插入到移除的位置
  8653. * ```
  8654. */
  8655. removeChild:function (node,keepChildren) {
  8656. if (this.children) {
  8657. for (var i = 0, ci; ci = this.children[i]; i++) {
  8658. if (ci === node) {
  8659. this.children.splice(i, 1);
  8660. ci.parentNode = null;
  8661. if(keepChildren && ci.children && ci.children.length){
  8662. for(var j= 0,cj;cj=ci.children[j];j++){
  8663. this.children.splice(i+j,0,cj);
  8664. cj.parentNode = this;
  8665. }
  8666. }
  8667. return ci;
  8668. }
  8669. }
  8670. }
  8671. },
  8672. /**
  8673. * 获取当前节点所代表的元素属性,即获取attrs对象下的属性值
  8674. * @method getAttr
  8675. * @param { String } attrName 要获取的属性名称
  8676. * @return { * } 返回attrs对象下的属性值
  8677. * @example
  8678. * ```javascript
  8679. * node.getAttr('title');
  8680. * ```
  8681. */
  8682. getAttr:function (attrName) {
  8683. return this.attrs && this.attrs[attrName.toLowerCase()]
  8684. },
  8685. /**
  8686. * 设置当前节点所代表的元素属性,即设置attrs对象下的属性值
  8687. * @method setAttr
  8688. * @param { String } attrName 要设置的属性名称
  8689. * @param { * } attrVal 要设置的属性值,类型视设置的属性而定
  8690. * @return { * } 返回attrs对象下的属性值
  8691. * @example
  8692. * ```javascript
  8693. * node.setAttr('title','标题');
  8694. * ```
  8695. */
  8696. setAttr:function (attrName, attrVal) {
  8697. if (!attrName) {
  8698. delete this.attrs;
  8699. return;
  8700. }
  8701. if(!this.attrs){
  8702. this.attrs = {};
  8703. }
  8704. if (utils.isObject(attrName)) {
  8705. for (var a in attrName) {
  8706. if (!attrName[a]) {
  8707. delete this.attrs[a]
  8708. } else {
  8709. this.attrs[a.toLowerCase()] = attrName[a];
  8710. }
  8711. }
  8712. } else {
  8713. if (!attrVal) {
  8714. delete this.attrs[attrName]
  8715. } else {
  8716. this.attrs[attrName.toLowerCase()] = attrVal;
  8717. }
  8718. }
  8719. },
  8720. /**
  8721. * 获取当前节点在父节点下的位置索引
  8722. * @method getIndex
  8723. * @return { Number } 返回索引数值,如果没有父节点,返回-1
  8724. * @example
  8725. * ```javascript
  8726. * node.getIndex();
  8727. * ```
  8728. */
  8729. getIndex:function(){
  8730. var parent = this.parentNode;
  8731. for(var i= 0,ci;ci=parent.children[i];i++){
  8732. if(ci === this){
  8733. return i;
  8734. }
  8735. }
  8736. return -1;
  8737. },
  8738. /**
  8739. * 在当前节点下,根据id查找节点
  8740. * @method getNodeById
  8741. * @param { String } id 要查找的id
  8742. * @return { UE.uNode } 返回找到的节点
  8743. * @example
  8744. * ```javascript
  8745. * node.getNodeById('textId');
  8746. * ```
  8747. */
  8748. getNodeById:function (id) {
  8749. var node;
  8750. if (this.children && this.children.length) {
  8751. for (var i = 0, ci; ci = this.children[i++];) {
  8752. if (node = getNodeById(ci, id)) {
  8753. return node;
  8754. }
  8755. }
  8756. }
  8757. },
  8758. /**
  8759. * 在当前节点下,根据元素名称查找节点列表
  8760. * @method getNodesByTagName
  8761. * @param { String } tagNames 要查找的元素名称
  8762. * @return { Array } 返回找到的节点列表
  8763. * @example
  8764. * ```javascript
  8765. * node.getNodesByTagName('span');
  8766. * ```
  8767. */
  8768. getNodesByTagName:function (tagNames) {
  8769. tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' ');
  8770. var arr = [], me = this;
  8771. utils.each(tagNames, function (tagName) {
  8772. if (me.children && me.children.length) {
  8773. for (var i = 0, ci; ci = me.children[i++];) {
  8774. getNodesByTagName(ci, tagName, arr)
  8775. }
  8776. }
  8777. });
  8778. return arr;
  8779. },
  8780. /**
  8781. * 根据样式名称,获取节点的样式值
  8782. * @method getStyle
  8783. * @param { String } name 要获取的样式名称
  8784. * @return { String } 返回样式值
  8785. * @example
  8786. * ```javascript
  8787. * node.getStyle('font-size');
  8788. * ```
  8789. */
  8790. getStyle:function (name) {
  8791. var cssStyle = this.getAttr('style');
  8792. if (!cssStyle) {
  8793. return ''
  8794. }
  8795. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+)','i');
  8796. var match = cssStyle.match(reg);
  8797. if (match && match[0]) {
  8798. return match[2]
  8799. }
  8800. return '';
  8801. },
  8802. /**
  8803. * 给节点设置样式
  8804. * @method setStyle
  8805. * @param { String } name 要设置的的样式名称
  8806. * @param { String } val 要设置的的样值
  8807. * @example
  8808. * ```javascript
  8809. * node.setStyle('font-size', '12px');
  8810. * ```
  8811. */
  8812. setStyle:function (name, val) {
  8813. function exec(name, val) {
  8814. var reg = new RegExp('(^|;)\\s*' + name + ':([^;]+;?)', 'gi');
  8815. cssStyle = cssStyle.replace(reg, '$1');
  8816. if (val) {
  8817. cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle
  8818. }
  8819. }
  8820. var cssStyle = this.getAttr('style');
  8821. if (!cssStyle) {
  8822. cssStyle = '';
  8823. }
  8824. if (utils.isObject(name)) {
  8825. for (var a in name) {
  8826. exec(a, name[a])
  8827. }
  8828. } else {
  8829. exec(name, val)
  8830. }
  8831. this.setAttr('style', utils.trim(cssStyle))
  8832. },
  8833. /**
  8834. * 传入一个函数,递归遍历当前节点下的所有节点
  8835. * @method traversal
  8836. * @param { Function } fn 遍历到节点的时,传入节点作为参数,运行此函数
  8837. * @example
  8838. * ```javascript
  8839. * traversal(node, function(){
  8840. * console.log(node.type);
  8841. * });
  8842. * ```
  8843. */
  8844. traversal:function(fn){
  8845. if(this.children && this.children.length){
  8846. nodeTraversal(this,fn);
  8847. }
  8848. return this;
  8849. }
  8850. }
  8851. })();
  8852. // core/htmlparser.js
  8853. /**
  8854. * html字符串转换成uNode节点
  8855. * @file
  8856. * @module UE
  8857. * @since 1.2.6.1
  8858. */
  8859. /**
  8860. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  8861. * @unfile
  8862. * @module UE
  8863. */
  8864. /**
  8865. * html字符串转换成uNode节点的静态方法
  8866. * @method htmlparser
  8867. * @param { String } htmlstr 要转换的html代码
  8868. * @param { Boolean } ignoreBlank 若设置为true,转换的时候忽略\n\r\t等空白字符
  8869. * @return { uNode } 给定的html片段转换形成的uNode对象
  8870. * @example
  8871. * ```javascript
  8872. * var root = UE.htmlparser('<p><b>htmlparser</b></p>', true);
  8873. * ```
  8874. */
  8875. var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) {
  8876. //todo 原来的方式 [^"'<>\/] 有\/就不能配对上 <TD vAlign=top background=../AAA.JPG> 这样的标签了
  8877. //先去掉了,加上的原因忘了,这里先记录
  8878. var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/<>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g,
  8879. re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g;
  8880. //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除
  8881. var allowEmptyTags = {
  8882. b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1,
  8883. sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1
  8884. };
  8885. htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), '');
  8886. if(!ignoreBlank){
  8887. htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){
  8888. //br暂时单独处理
  8889. if(b && allowEmptyTags[b.toLowerCase()]){
  8890. return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,'');
  8891. }
  8892. return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),'');
  8893. });
  8894. }
  8895. var notTransAttrs = {
  8896. 'href':1,
  8897. 'src':1
  8898. };
  8899. var uNode = UE.uNode,
  8900. needParentNode = {
  8901. 'td':'tr',
  8902. 'tr':['tbody','thead','tfoot'],
  8903. 'tbody':'table',
  8904. 'th':'tr',
  8905. 'thead':'table',
  8906. 'tfoot':'table',
  8907. 'caption':'table',
  8908. 'li':['ul', 'ol'],
  8909. 'dt':'dl',
  8910. 'dd':'dl',
  8911. 'option':'select'
  8912. },
  8913. needChild = {
  8914. 'ol':'li',
  8915. 'ul':'li'
  8916. };
  8917. function text(parent, data) {
  8918. if(needChild[parent.tagName]){
  8919. var tmpNode = uNode.createElement(needChild[parent.tagName]);
  8920. parent.appendChild(tmpNode);
  8921. tmpNode.appendChild(uNode.createText(data));
  8922. parent = tmpNode;
  8923. }else{
  8924. parent.appendChild(uNode.createText(data));
  8925. }
  8926. }
  8927. function element(parent, tagName, htmlattr) {
  8928. var needParentTag;
  8929. if (needParentTag = needParentNode[tagName]) {
  8930. var tmpParent = parent,hasParent;
  8931. while(tmpParent.type != 'root'){
  8932. if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){
  8933. parent = tmpParent;
  8934. hasParent = true;
  8935. break;
  8936. }
  8937. tmpParent = tmpParent.parentNode;
  8938. }
  8939. if(!hasParent){
  8940. parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag)
  8941. }
  8942. }
  8943. //按dtd处理嵌套
  8944. // if(parent.type != 'root' && !dtd[parent.tagName][tagName])
  8945. // parent = parent.parentNode;
  8946. var elm = new uNode({
  8947. parentNode:parent,
  8948. type:'element',
  8949. tagName:tagName.toLowerCase(),
  8950. //是自闭合的处理一下
  8951. children:dtd.$empty[tagName] ? null : []
  8952. });
  8953. //如果属性存在,处理属性
  8954. if (htmlattr) {
  8955. var attrs = {}, match;
  8956. while (match = re_attr.exec(htmlattr)) {
  8957. attrs[match[1].toLowerCase()] = notTransAttrs[match[1].toLowerCase()] ? (match[2] || match[3] || match[4]) : utils.unhtml(match[2] || match[3] || match[4])
  8958. }
  8959. elm.attrs = attrs;
  8960. }
  8961. //trace:3970
  8962. // //如果parent下不能放elm
  8963. // if(dtd.$inline[parent.tagName] && dtd.$block[elm.tagName] && !dtd[parent.tagName][elm.tagName]){
  8964. // parent = parent.parentNode;
  8965. // elm.parentNode = parent;
  8966. // }
  8967. parent.children.push(elm);
  8968. //如果是自闭合节点返回父亲节点
  8969. return dtd.$empty[tagName] ? parent : elm
  8970. }
  8971. function comment(parent, data) {
  8972. parent.children.push(new uNode({
  8973. type:'comment',
  8974. data:data,
  8975. parentNode:parent
  8976. }));
  8977. }
  8978. var match, currentIndex = 0, nextIndex = 0;
  8979. //设置根节点
  8980. var root = new uNode({
  8981. type:'root',
  8982. children:[]
  8983. });
  8984. var currentParent = root;
  8985. while (match = re_tag.exec(htmlstr)) {
  8986. currentIndex = match.index;
  8987. try{
  8988. if (currentIndex > nextIndex) {
  8989. //text node
  8990. text(currentParent, htmlstr.slice(nextIndex, currentIndex));
  8991. }
  8992. if (match[3]) {
  8993. if(dtd.$cdata[currentParent.tagName]){
  8994. text(currentParent, match[0]);
  8995. }else{
  8996. //start tag
  8997. currentParent = element(currentParent, match[3].toLowerCase(), match[4]);
  8998. }
  8999. } else if (match[1]) {
  9000. if(currentParent.type != 'root'){
  9001. if(dtd.$cdata[currentParent.tagName] && !dtd.$cdata[match[1]]){
  9002. text(currentParent, match[0]);
  9003. }else{
  9004. var tmpParent = currentParent;
  9005. while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){
  9006. currentParent = currentParent.parentNode;
  9007. if(currentParent.type == 'root'){
  9008. currentParent = tmpParent;
  9009. throw 'break'
  9010. }
  9011. }
  9012. //end tag
  9013. currentParent = currentParent.parentNode;
  9014. }
  9015. }
  9016. } else if (match[2]) {
  9017. //comment
  9018. comment(currentParent, match[2])
  9019. }
  9020. }catch(e){}
  9021. nextIndex = re_tag.lastIndex;
  9022. }
  9023. //如果结束是文本,就有可能丢掉,所以这里手动判断一下
  9024. //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf
  9025. if (nextIndex < htmlstr.length) {
  9026. text(currentParent, htmlstr.slice(nextIndex));
  9027. }
  9028. return root;
  9029. };
  9030. // core/filternode.js
  9031. /**
  9032. * UE过滤节点的静态方法
  9033. * @file
  9034. */
  9035. /**
  9036. * UEditor公用空间,UEditor所有的功能都挂载在该空间下
  9037. * @module UE
  9038. */
  9039. /**
  9040. * 根据传入节点和过滤规则过滤相应节点
  9041. * @module UE
  9042. * @since 1.2.6.1
  9043. * @method filterNode
  9044. * @param { Object } root 指定root节点
  9045. * @param { Object } rules 过滤规则json对象
  9046. * @example
  9047. * ```javascript
  9048. * UE.filterNode(root,editor.options.filterRules);
  9049. * ```
  9050. */
  9051. var filterNode = UE.filterNode = function () {
  9052. function filterNode(node,rules){
  9053. switch (node.type) {
  9054. case 'text':
  9055. break;
  9056. case 'element':
  9057. var val;
  9058. if(val = rules[node.tagName]){
  9059. if(val === '-'){
  9060. node.parentNode.removeChild(node)
  9061. }else if(utils.isFunction(val)){
  9062. var parentNode = node.parentNode,
  9063. index = node.getIndex();
  9064. val(node);
  9065. if(node.parentNode){
  9066. if(node.children){
  9067. for(var i = 0,ci;ci=node.children[i];){
  9068. filterNode(ci,rules);
  9069. if(ci.parentNode){
  9070. i++;
  9071. }
  9072. }
  9073. }
  9074. }else{
  9075. for(var i = index,ci;ci=parentNode.children[i];){
  9076. filterNode(ci,rules);
  9077. if(ci.parentNode){
  9078. i++;
  9079. }
  9080. }
  9081. }
  9082. }else{
  9083. var attrs = val['$'];
  9084. if(attrs && node.attrs){
  9085. var tmpAttrs = {},tmpVal;
  9086. for(var a in attrs){
  9087. tmpVal = node.getAttr(a);
  9088. //todo 只先对style单独处理
  9089. if(a == 'style' && utils.isArray(attrs[a])){
  9090. var tmpCssStyle = [];
  9091. utils.each(attrs[a],function(v){
  9092. var tmp;
  9093. if(tmp = node.getStyle(v)){
  9094. tmpCssStyle.push(v + ':' + tmp);
  9095. }
  9096. });
  9097. tmpVal = tmpCssStyle.join(';')
  9098. }
  9099. if(tmpVal){
  9100. tmpAttrs[a] = tmpVal;
  9101. }
  9102. }
  9103. node.attrs = tmpAttrs;
  9104. }
  9105. if(node.children){
  9106. for(var i = 0,ci;ci=node.children[i];){
  9107. filterNode(ci,rules);
  9108. if(ci.parentNode){
  9109. i++;
  9110. }
  9111. }
  9112. }
  9113. }
  9114. }else{
  9115. //如果不在名单里扣出子节点并删除该节点,cdata除外
  9116. if(dtd.$cdata[node.tagName]){
  9117. node.parentNode.removeChild(node)
  9118. }else{
  9119. var parentNode = node.parentNode,
  9120. index = node.getIndex();
  9121. node.parentNode.removeChild(node,true);
  9122. for(var i = index,ci;ci=parentNode.children[i];){
  9123. filterNode(ci,rules);
  9124. if(ci.parentNode){
  9125. i++;
  9126. }
  9127. }
  9128. }
  9129. }
  9130. break;
  9131. case 'comment':
  9132. node.parentNode.removeChild(node)
  9133. }
  9134. }
  9135. return function(root,rules){
  9136. if(utils.isEmptyObject(rules)){
  9137. return root;
  9138. }
  9139. var val;
  9140. if(val = rules['-']){
  9141. utils.each(val.split(' '),function(k){
  9142. rules[k] = '-'
  9143. })
  9144. }
  9145. for(var i= 0,ci;ci=root.children[i];){
  9146. filterNode(ci,rules);
  9147. if(ci.parentNode){
  9148. i++;
  9149. }
  9150. }
  9151. return root;
  9152. }
  9153. }();
  9154. // core/plugin.js
  9155. /**
  9156. * Created with JetBrains PhpStorm.
  9157. * User: campaign
  9158. * Date: 10/8/13
  9159. * Time: 6:15 PM
  9160. * To change this template use File | Settings | File Templates.
  9161. */
  9162. UE.plugin = function(){
  9163. var _plugins = {};
  9164. return {
  9165. register : function(pluginName,fn,oldOptionName,afterDisabled){
  9166. if(oldOptionName && utils.isFunction(oldOptionName)){
  9167. afterDisabled = oldOptionName;
  9168. oldOptionName = null
  9169. }
  9170. _plugins[pluginName] = {
  9171. optionName : oldOptionName || pluginName,
  9172. execFn : fn,
  9173. //当插件被禁用时执行
  9174. afterDisabled : afterDisabled
  9175. }
  9176. },
  9177. load : function(editor){
  9178. utils.each(_plugins,function(plugin){
  9179. var _export = plugin.execFn.call(editor);
  9180. if(editor.options[plugin.optionName] !== false){
  9181. if(_export){
  9182. //后边需要再做扩展
  9183. utils.each(_export,function(v,k){
  9184. switch(k.toLowerCase()){
  9185. case 'shortcutkey':
  9186. editor.addshortcutkey(v);
  9187. break;
  9188. case 'bindevents':
  9189. utils.each(v,function(fn,eventName){
  9190. editor.addListener(eventName,fn);
  9191. });
  9192. break;
  9193. case 'bindmultievents':
  9194. utils.each(utils.isArray(v) ? v:[v],function(event){
  9195. var types = utils.trim(event.type).split(/\s+/);
  9196. utils.each(types,function(eventName){
  9197. editor.addListener(eventName, event.handler);
  9198. });
  9199. });
  9200. break;
  9201. case 'commands':
  9202. utils.each(v,function(execFn,execName){
  9203. editor.commands[execName] = execFn
  9204. });
  9205. break;
  9206. case 'outputrule':
  9207. editor.addOutputRule(v);
  9208. break;
  9209. case 'inputrule':
  9210. editor.addInputRule(v);
  9211. break;
  9212. case 'defaultoptions':
  9213. editor.setOpt(v)
  9214. }
  9215. })
  9216. }
  9217. }else if(plugin.afterDisabled){
  9218. plugin.afterDisabled.call(editor)
  9219. }
  9220. });
  9221. //向下兼容
  9222. utils.each(UE.plugins,function(plugin){
  9223. plugin.call(editor);
  9224. });
  9225. },
  9226. run : function(pluginName,editor){
  9227. var plugin = _plugins[pluginName];
  9228. if(plugin){
  9229. plugin.exeFn.call(editor)
  9230. }
  9231. }
  9232. }
  9233. }();
  9234. // core/keymap.js
  9235. var keymap = UE.keymap = {
  9236. 'Backspace' : 8,
  9237. 'Tab' : 9,
  9238. 'Enter' : 13,
  9239. 'Shift':16,
  9240. 'Control':17,
  9241. 'Alt':18,
  9242. 'CapsLock':20,
  9243. 'Esc':27,
  9244. 'Spacebar':32,
  9245. 'PageUp':33,
  9246. 'PageDown':34,
  9247. 'End':35,
  9248. 'Home':36,
  9249. 'Left':37,
  9250. 'Up':38,
  9251. 'Right':39,
  9252. 'Down':40,
  9253. 'Insert':45,
  9254. 'Del':46,
  9255. 'NumLock':144,
  9256. 'Cmd':91,
  9257. '=':187,
  9258. '-':189,
  9259. "b":66,
  9260. 'i':73,
  9261. //回退
  9262. 'z':90,
  9263. 'y':89,
  9264. //粘贴
  9265. 'v' : 86,
  9266. 'x' : 88,
  9267. 's' : 83,
  9268. 'n' : 78
  9269. };
  9270. // core/localstorage.js
  9271. //存储媒介封装
  9272. var LocalStorage = UE.LocalStorage = (function () {
  9273. var storage = window.localStorage || getUserData() || null,
  9274. LOCAL_FILE = 'localStorage';
  9275. return {
  9276. saveLocalData: function (key, data) {
  9277. if (storage && data) {
  9278. storage.setItem(key, data);
  9279. return true;
  9280. }
  9281. return false;
  9282. },
  9283. getLocalData: function (key) {
  9284. if (storage) {
  9285. return storage.getItem(key);
  9286. }
  9287. return null;
  9288. },
  9289. removeItem: function (key) {
  9290. storage && storage.removeItem(key);
  9291. }
  9292. };
  9293. function getUserData() {
  9294. var container = document.createElement("div");
  9295. container.style.display = "none";
  9296. if (!container.addBehavior) {
  9297. return null;
  9298. }
  9299. container.addBehavior("#default#userdata");
  9300. return {
  9301. getItem: function (key) {
  9302. var result = null;
  9303. try {
  9304. document.body.appendChild(container);
  9305. container.load(LOCAL_FILE);
  9306. result = container.getAttribute(key);
  9307. document.body.removeChild(container);
  9308. } catch (e) {
  9309. }
  9310. return result;
  9311. },
  9312. setItem: function (key, value) {
  9313. document.body.appendChild(container);
  9314. container.setAttribute(key, value);
  9315. container.save(LOCAL_FILE);
  9316. document.body.removeChild(container);
  9317. },
  9318. //// 暂时没有用到
  9319. //clear: function () {
  9320. //
  9321. // var expiresTime = new Date();
  9322. // expiresTime.setFullYear(expiresTime.getFullYear() - 1);
  9323. // document.body.appendChild(container);
  9324. // container.expires = expiresTime.toUTCString();
  9325. // container.save(LOCAL_FILE);
  9326. // document.body.removeChild(container);
  9327. //
  9328. //},
  9329. removeItem: function (key) {
  9330. document.body.appendChild(container);
  9331. container.removeAttribute(key);
  9332. container.save(LOCAL_FILE);
  9333. document.body.removeChild(container);
  9334. }
  9335. };
  9336. }
  9337. })();
  9338. (function () {
  9339. var ROOTKEY = 'ueditor_preference';
  9340. UE.Editor.prototype.setPreferences = function(key,value){
  9341. var obj = {};
  9342. if (utils.isString(key)) {
  9343. obj[ key ] = value;
  9344. } else {
  9345. obj = key;
  9346. }
  9347. var data = LocalStorage.getLocalData(ROOTKEY);
  9348. if (data && (data = utils.str2json(data))) {
  9349. utils.extend(data, obj);
  9350. } else {
  9351. data = obj;
  9352. }
  9353. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9354. };
  9355. UE.Editor.prototype.getPreferences = function(key){
  9356. var data = LocalStorage.getLocalData(ROOTKEY);
  9357. if (data && (data = utils.str2json(data))) {
  9358. return key ? data[key] : data
  9359. }
  9360. return null;
  9361. };
  9362. UE.Editor.prototype.removePreferences = function (key) {
  9363. var data = LocalStorage.getLocalData(ROOTKEY);
  9364. if (data && (data = utils.str2json(data))) {
  9365. data[key] = undefined;
  9366. delete data[key]
  9367. }
  9368. data && LocalStorage.saveLocalData(ROOTKEY, utils.json2str(data));
  9369. };
  9370. })();
  9371. // plugins/defaultfilter.js
  9372. ///import core
  9373. ///plugin 编辑器默认的过滤转换机制
  9374. UE.plugins['defaultfilter'] = function () {
  9375. var me = this;
  9376. me.setOpt({
  9377. 'allowDivTransToP':true,
  9378. 'disabledTableInTable':true
  9379. });
  9380. //默认的过滤处理
  9381. //进入编辑器的内容处理
  9382. me.addInputRule(function (root) {
  9383. var allowDivTransToP = this.options.allowDivTransToP;
  9384. var val;
  9385. function tdParent(node){
  9386. while(node && node.type == 'element'){
  9387. if(node.tagName == 'td'){
  9388. return true;
  9389. }
  9390. node = node.parentNode;
  9391. }
  9392. return false;
  9393. }
  9394. //进行默认的处理
  9395. root.traversal(function (node) {
  9396. if (node.type == 'element') {
  9397. if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9398. if (!node.firstChild()) node.parentNode.removeChild(node);
  9399. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9400. node.parentNode.removeChild(node, true)
  9401. }
  9402. return;
  9403. }
  9404. switch (node.tagName) {
  9405. case 'style':
  9406. case 'script':
  9407. node.setAttr({
  9408. cdata_tag: node.tagName,
  9409. cdata_data: (node.innerHTML() || ''),
  9410. '_ue_custom_node_':'true'
  9411. });
  9412. node.tagName = 'div';
  9413. node.innerHTML('');
  9414. break;
  9415. case 'a':
  9416. if (val = node.getAttr('href')) {
  9417. node.setAttr('_href', val)
  9418. }
  9419. break;
  9420. case 'img':
  9421. //todo base64暂时去掉,后边做远程图片上传后,干掉这个
  9422. if (val = node.getAttr('src')) {
  9423. if (/^data:/.test(val)) {
  9424. node.parentNode.removeChild(node);
  9425. break;
  9426. }
  9427. }
  9428. node.setAttr('_src', node.getAttr('src'));
  9429. break;
  9430. case 'span':
  9431. if (browser.webkit && (val = node.getStyle('white-space'))) {
  9432. if (/nowrap|normal/.test(val)) {
  9433. node.setStyle('white-space', '');
  9434. if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) {
  9435. node.parentNode.removeChild(node, true)
  9436. }
  9437. }
  9438. }
  9439. val = node.getAttr('id');
  9440. if(val && /^_baidu_bookmark_/i.test(val)){
  9441. node.parentNode.removeChild(node)
  9442. }
  9443. break;
  9444. case 'p':
  9445. if (val = node.getAttr('align')) {
  9446. node.setAttr('align');
  9447. node.setStyle('text-align', val)
  9448. }
  9449. //trace:3431
  9450. // var cssStyle = node.getAttr('style');
  9451. // if (cssStyle) {
  9452. // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, '');
  9453. // node.setAttr('style', cssStyle)
  9454. //
  9455. // }
  9456. //p标签不允许嵌套
  9457. utils.each(node.children,function(n){
  9458. if(n.type == 'element' && n.tagName == 'p'){
  9459. var next = n.nextSibling();
  9460. node.parentNode.insertAfter(n,node);
  9461. var last = n;
  9462. while(next){
  9463. var tmp = next.nextSibling();
  9464. node.parentNode.insertAfter(next,last);
  9465. last = next;
  9466. next = tmp;
  9467. }
  9468. return false;
  9469. }
  9470. });
  9471. if (!node.firstChild()) {
  9472. node.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  9473. }
  9474. break;
  9475. case 'div':
  9476. if(node.getAttr('cdata_tag')){
  9477. break;
  9478. }
  9479. //针对代码这里不处理插入代码的div
  9480. val = node.getAttr('class');
  9481. if(val && /^line number\d+/.test(val)){
  9482. break;
  9483. }
  9484. if(!allowDivTransToP){
  9485. break;
  9486. }
  9487. var tmpNode, p = UE.uNode.createElement('p');
  9488. while (tmpNode = node.firstChild()) {
  9489. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  9490. p.appendChild(tmpNode);
  9491. } else {
  9492. if (p.firstChild()) {
  9493. node.parentNode.insertBefore(p, node);
  9494. p = UE.uNode.createElement('p');
  9495. } else {
  9496. node.parentNode.insertBefore(tmpNode, node);
  9497. }
  9498. }
  9499. }
  9500. if (p.firstChild()) {
  9501. node.parentNode.insertBefore(p, node);
  9502. }
  9503. node.parentNode.removeChild(node);
  9504. break;
  9505. case 'dl':
  9506. node.tagName = 'ul';
  9507. break;
  9508. case 'dt':
  9509. case 'dd':
  9510. node.tagName = 'li';
  9511. break;
  9512. case 'li':
  9513. var className = node.getAttr('class');
  9514. if (!className || !/list\-/.test(className)) {
  9515. node.setAttr()
  9516. }
  9517. var tmpNodes = node.getNodesByTagName('ol ul');
  9518. UE.utils.each(tmpNodes, function (n) {
  9519. node.parentNode.insertAfter(n, node);
  9520. });
  9521. break;
  9522. case 'td':
  9523. case 'th':
  9524. case 'caption':
  9525. if(!node.children || !node.children.length){
  9526. node.appendChild(browser.ie11below ? UE.uNode.createText(' ') : UE.uNode.createElement('br'))
  9527. }
  9528. break;
  9529. case 'table':
  9530. if(me.options.disabledTableInTable && tdParent(node)){
  9531. node.parentNode.insertBefore(UE.uNode.createText(node.innerText()),node);
  9532. node.parentNode.removeChild(node)
  9533. }
  9534. }
  9535. }
  9536. // if(node.type == 'comment'){
  9537. // node.parentNode.removeChild(node);
  9538. // }
  9539. })
  9540. });
  9541. //从编辑器出去的内容处理
  9542. me.addOutputRule(function (root) {
  9543. var val;
  9544. root.traversal(function (node) {
  9545. if (node.type == 'element') {
  9546. if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9547. if (!node.firstChild()) node.parentNode.removeChild(node);
  9548. else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) {
  9549. node.parentNode.removeChild(node, true)
  9550. }
  9551. return;
  9552. }
  9553. switch (node.tagName) {
  9554. case 'div':
  9555. if (val = node.getAttr('cdata_tag')) {
  9556. node.tagName = val;
  9557. node.appendChild(UE.uNode.createText(node.getAttr('cdata_data')));
  9558. node.setAttr({cdata_tag: '', cdata_data: '','_ue_custom_node_':''});
  9559. }
  9560. break;
  9561. case 'a':
  9562. if (val = node.getAttr('_href')) {
  9563. node.setAttr({
  9564. 'href': utils.html(val),
  9565. '_href': ''
  9566. })
  9567. }
  9568. break;
  9569. break;
  9570. case 'span':
  9571. val = node.getAttr('id');
  9572. if(val && /^_baidu_bookmark_/i.test(val)){
  9573. node.parentNode.removeChild(node)
  9574. }
  9575. break;
  9576. case 'img':
  9577. if (val = node.getAttr('_src')) {
  9578. node.setAttr({
  9579. 'src': node.getAttr('_src'),
  9580. '_src': ''
  9581. })
  9582. }
  9583. }
  9584. }
  9585. })
  9586. });
  9587. };
  9588. // plugins/inserthtml.js
  9589. /**
  9590. * 插入html字符串插件
  9591. * @file
  9592. * @since 1.2.6.1
  9593. */
  9594. /**
  9595. * 插入html代码
  9596. * @command inserthtml
  9597. * @method execCommand
  9598. * @param { String } cmd 命令字符串
  9599. * @param { String } html 插入的html字符串
  9600. * @remaind 插入的标签内容是在当前的选区位置上插入,如果当前是闭合状态,那直接插入内容, 如果当前是选中状态,将先清除当前选中内容后,再做插入
  9601. * @warning 注意:该命令会对当前选区的位置,对插入的内容进行过滤转换处理。 过滤的规则遵循html语意化的原则。
  9602. * @example
  9603. * ```javascript
  9604. * //xxx[BB]xxx 当前选区为非闭合选区,选中BB这两个文本
  9605. * //执行命令,插入<b>CC</b>
  9606. * //插入后的效果 xxx<b>CC</b>xxx
  9607. * //<p>xx|xxx</p> 当前选区为闭合状态
  9608. * //插入<p>CC</p>
  9609. * //结果 <p>xx</p><p>CC</p><p>xxx</p>
  9610. * //<p>xxxx</p>|</p>xxx</p> 当前选区在两个p标签之间
  9611. * //插入 xxxx
  9612. * //结果 <p>xxxx</p><p>xxxx</p></p>xxx</p>
  9613. * ```
  9614. */
  9615. UE.commands['inserthtml'] = {
  9616. execCommand: function (command,html,notNeedFilter){
  9617. var me = this,
  9618. range,
  9619. div;
  9620. if(!html){
  9621. return;
  9622. }
  9623. if(me.fireEvent('beforeinserthtml',html) === true){
  9624. return;
  9625. }
  9626. range = me.selection.getRange();
  9627. div = range.document.createElement( 'div' );
  9628. div.style.display = 'inline';
  9629. if (!notNeedFilter) {
  9630. var root = UE.htmlparser(html);
  9631. //如果给了过滤规则就先进行过滤
  9632. if(me.options.filterRules){
  9633. UE.filterNode(root,me.options.filterRules);
  9634. }
  9635. //执行默认的处理
  9636. me.filterInputRule(root);
  9637. html = root.toHtml()
  9638. }
  9639. div.innerHTML = utils.trim( html );
  9640. if ( !range.collapsed ) {
  9641. var tmpNode = range.startContainer;
  9642. if(domUtils.isFillChar(tmpNode)){
  9643. range.setStartBefore(tmpNode)
  9644. }
  9645. tmpNode = range.endContainer;
  9646. if(domUtils.isFillChar(tmpNode)){
  9647. range.setEndAfter(tmpNode)
  9648. }
  9649. range.txtToElmBoundary();
  9650. //结束边界可能放到了br的前边,要把br包含进来
  9651. // x[xxx]<br/>
  9652. if(range.endContainer && range.endContainer.nodeType == 1){
  9653. tmpNode = range.endContainer.childNodes[range.endOffset];
  9654. if(tmpNode && domUtils.isBr(tmpNode)){
  9655. range.setEndAfter(tmpNode);
  9656. }
  9657. }
  9658. if(range.startOffset == 0){
  9659. tmpNode = range.startContainer;
  9660. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  9661. tmpNode = range.endContainer;
  9662. if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  9663. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  9664. range.setStart(me.body.firstChild,0).collapse(true)
  9665. }
  9666. }
  9667. }
  9668. !range.collapsed && range.deleteContents();
  9669. if(range.startContainer.nodeType == 1){
  9670. var child = range.startContainer.childNodes[range.startOffset],pre;
  9671. if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){
  9672. range.setEnd(pre,pre.childNodes.length).collapse();
  9673. while(child.firstChild){
  9674. pre.appendChild(child.firstChild);
  9675. }
  9676. domUtils.remove(child);
  9677. }
  9678. }
  9679. }
  9680. var child,parent,pre,tmp,hadBreak = 0, nextNode;
  9681. //如果当前位置选中了fillchar要干掉,要不会产生空行
  9682. if(range.inFillChar()){
  9683. child = range.startContainer;
  9684. if(domUtils.isFillChar(child)){
  9685. range.setStartBefore(child).collapse(true);
  9686. domUtils.remove(child);
  9687. }else if(domUtils.isFillChar(child,true)){
  9688. child.nodeValue = child.nodeValue.replace(fillCharReg,'');
  9689. range.startOffset--;
  9690. range.collapsed && range.collapse(true)
  9691. }
  9692. }
  9693. //列表单独处理
  9694. var li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9695. if(li){
  9696. var next,last;
  9697. while(child = div.firstChild){
  9698. //针对hr单独处理一下先
  9699. while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){
  9700. next = child.nextSibling;
  9701. range.insertNode( child).collapse();
  9702. last = child;
  9703. child = next;
  9704. }
  9705. if(child){
  9706. if(/^(ol|ul)$/i.test(child.tagName)){
  9707. while(child.firstChild){
  9708. last = child.firstChild;
  9709. domUtils.insertAfter(li,child.firstChild);
  9710. li = li.nextSibling;
  9711. }
  9712. domUtils.remove(child)
  9713. }else{
  9714. var tmpLi;
  9715. next = child.nextSibling;
  9716. tmpLi = me.document.createElement('li');
  9717. domUtils.insertAfter(li,tmpLi);
  9718. tmpLi.appendChild(child);
  9719. last = child;
  9720. child = next;
  9721. li = tmpLi;
  9722. }
  9723. }
  9724. }
  9725. li = domUtils.findParentByTagName(range.startContainer,'li',true);
  9726. if(domUtils.isEmptyBlock(li)){
  9727. domUtils.remove(li)
  9728. }
  9729. if(last){
  9730. range.setStartAfter(last).collapse(true).select(true)
  9731. }
  9732. }else{
  9733. while ( child = div.firstChild ) {
  9734. if(hadBreak){
  9735. var p = me.document.createElement('p');
  9736. while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){
  9737. nextNode = child.nextSibling;
  9738. p.appendChild(child);
  9739. child = nextNode;
  9740. }
  9741. if(p.firstChild){
  9742. child = p
  9743. }
  9744. }
  9745. range.insertNode( child );
  9746. nextNode = child.nextSibling;
  9747. if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){
  9748. parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } );
  9749. if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){
  9750. if(!dtd[parent.tagName][child.nodeName]){
  9751. pre = parent;
  9752. }else{
  9753. tmp = child.parentNode;
  9754. while (tmp !== parent){
  9755. pre = tmp;
  9756. tmp = tmp.parentNode;
  9757. }
  9758. }
  9759. domUtils.breakParent( child, pre || tmp );
  9760. //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p>
  9761. var pre = child.previousSibling;
  9762. domUtils.trimWhiteTextNode(pre);
  9763. if(!pre.childNodes.length){
  9764. domUtils.remove(pre);
  9765. }
  9766. //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位
  9767. if(!browser.ie &&
  9768. (next = child.nextSibling) &&
  9769. domUtils.isBlockElm(next) &&
  9770. next.lastChild &&
  9771. !domUtils.isBr(next.lastChild)){
  9772. next.appendChild(me.document.createElement('br'));
  9773. }
  9774. hadBreak = 1;
  9775. }
  9776. }
  9777. var next = child.nextSibling;
  9778. if(!div.firstChild && next && domUtils.isBlockElm(next)){
  9779. range.setStart(next,0).collapse(true);
  9780. break;
  9781. }
  9782. range.setEndAfter( child ).collapse();
  9783. }
  9784. child = range.startContainer;
  9785. if(nextNode && domUtils.isBr(nextNode)){
  9786. domUtils.remove(nextNode)
  9787. }
  9788. //用chrome可能有空白展位符
  9789. if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){
  9790. if(nextNode = child.nextSibling){
  9791. domUtils.remove(child);
  9792. if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){
  9793. range.setStart(nextNode,0).collapse(true).shrinkBoundary()
  9794. }
  9795. }else{
  9796. try{
  9797. child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  9798. }catch(e){
  9799. range.setStartBefore(child);
  9800. domUtils.remove(child)
  9801. }
  9802. }
  9803. }
  9804. //加上true因为在删除表情等时会删两次,第一次是删的fillData
  9805. try{
  9806. range.select(true);
  9807. }catch(e){}
  9808. }
  9809. setTimeout(function(){
  9810. range = me.selection.getRange();
  9811. range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0);
  9812. me.fireEvent('afterinserthtml', html);
  9813. },200);
  9814. }
  9815. };
  9816. // plugins/autotypeset.js
  9817. /**
  9818. * 自动排版
  9819. * @file
  9820. * @since 1.2.6.1
  9821. */
  9822. /**
  9823. * 对当前编辑器的内容执行自动排版, 排版的行为根据config配置文件里的“autotypeset”选项进行控制。
  9824. * @command autotypeset
  9825. * @method execCommand
  9826. * @param { String } cmd 命令字符串
  9827. * @example
  9828. * ```javascript
  9829. * editor.execCommand( 'autotypeset' );
  9830. * ```
  9831. */
  9832. UE.plugins['autotypeset'] = function(){
  9833. this.setOpt({'autotypeset': {
  9834. mergeEmptyline: true, //合并空行
  9835. removeClass: true, //去掉冗余的class
  9836. removeEmptyline: false, //去掉空行
  9837. textAlign:"left", //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
  9838. imageBlockLine: 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
  9839. pasteFilter: false, //根据规则过滤没事粘贴进来的内容
  9840. clearFontSize: false, //去掉所有的内嵌字号,使用编辑器默认的字号
  9841. clearFontFamily: false, //去掉所有的内嵌字体,使用编辑器默认的字体
  9842. removeEmptyNode: false, // 去掉空节点
  9843. //可以去掉的标签
  9844. removeTagNames: utils.extend({div:1},dtd.$removeEmpty),
  9845. indent: false, // 行首缩进
  9846. indentValue : '2em', //行首缩进的大小
  9847. bdc2sb: false,
  9848. tobdc: false
  9849. }});
  9850. var me = this,
  9851. opt = me.options.autotypeset,
  9852. remainClass = {
  9853. 'selectTdClass':1,
  9854. 'pagebreak':1,
  9855. 'anchorclass':1
  9856. },
  9857. remainTag = {
  9858. 'li':1
  9859. },
  9860. tags = {
  9861. div:1,
  9862. p:1,
  9863. //trace:2183 这些也认为是行
  9864. blockquote:1,center:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,
  9865. span:1
  9866. },
  9867. highlightCont;
  9868. //升级了版本,但配置项目里没有autotypeset
  9869. if(!opt){
  9870. return;
  9871. }
  9872. readLocalOpts();
  9873. function isLine(node,notEmpty){
  9874. if(!node || node.nodeType == 3)
  9875. return 0;
  9876. if(domUtils.isBr(node))
  9877. return 1;
  9878. if(node && node.parentNode && tags[node.tagName.toLowerCase()]){
  9879. if(highlightCont && highlightCont.contains(node)
  9880. ||
  9881. node.getAttribute('pagebreak')
  9882. ){
  9883. return 0;
  9884. }
  9885. return notEmpty ? !domUtils.isEmptyBlock(node) : domUtils.isEmptyBlock(node,new RegExp('[\\s'+domUtils.fillChar
  9886. +']','g'));
  9887. }
  9888. }
  9889. function removeNotAttributeSpan(node){
  9890. if(!node.style.cssText){
  9891. domUtils.removeAttributes(node,['style']);
  9892. if(node.tagName.toLowerCase() == 'span' && domUtils.hasNoAttributes(node)){
  9893. domUtils.remove(node,true);
  9894. }
  9895. }
  9896. }
  9897. function autotype(type,html){
  9898. var me = this,cont;
  9899. if(html){
  9900. if(!opt.pasteFilter){
  9901. return;
  9902. }
  9903. cont = me.document.createElement('div');
  9904. cont.innerHTML = html.html;
  9905. }else{
  9906. cont = me.document.body;
  9907. }
  9908. var nodes = domUtils.getElementsByTagName(cont,'*');
  9909. // 行首缩进,段落方向,段间距,段内间距
  9910. for(var i=0,ci;ci=nodes[i++];){
  9911. if(me.fireEvent('excludeNodeinautotype',ci) === true){
  9912. continue;
  9913. }
  9914. //font-size
  9915. if(opt.clearFontSize && ci.style.fontSize){
  9916. domUtils.removeStyle(ci,'font-size');
  9917. removeNotAttributeSpan(ci);
  9918. }
  9919. //font-family
  9920. if(opt.clearFontFamily && ci.style.fontFamily){
  9921. domUtils.removeStyle(ci,'font-family');
  9922. removeNotAttributeSpan(ci);
  9923. }
  9924. if(isLine(ci)){
  9925. //合并空行
  9926. if(opt.mergeEmptyline ){
  9927. var next = ci.nextSibling,tmpNode,isBr = domUtils.isBr(ci);
  9928. while(isLine(next)){
  9929. tmpNode = next;
  9930. next = tmpNode.nextSibling;
  9931. if(isBr && (!next || next && !domUtils.isBr(next))){
  9932. break;
  9933. }
  9934. domUtils.remove(tmpNode);
  9935. }
  9936. }
  9937. //去掉空行,保留占位的空行
  9938. if(opt.removeEmptyline && domUtils.inDoc(ci,cont) && !remainTag[ci.parentNode.tagName.toLowerCase()] ){
  9939. if(domUtils.isBr(ci)){
  9940. next = ci.nextSibling;
  9941. if(next && !domUtils.isBr(next)){
  9942. continue;
  9943. }
  9944. }
  9945. domUtils.remove(ci);
  9946. continue;
  9947. }
  9948. }
  9949. if(isLine(ci,true) && ci.tagName != 'SPAN'){
  9950. if(opt.indent){
  9951. ci.style.textIndent = opt.indentValue;
  9952. }
  9953. if(opt.textAlign){
  9954. ci.style.textAlign = opt.textAlign;
  9955. }
  9956. // if(opt.lineHeight)
  9957. // ci.style.lineHeight = opt.lineHeight + 'cm';
  9958. }
  9959. //去掉class,保留的class不去掉
  9960. if(opt.removeClass && ci.className && !remainClass[ci.className.toLowerCase()]){
  9961. if(highlightCont && highlightCont.contains(ci)){
  9962. continue;
  9963. }
  9964. domUtils.removeAttributes(ci,['class']);
  9965. }
  9966. //表情不处理
  9967. if(opt.imageBlockLine && ci.tagName.toLowerCase() == 'img' && !ci.getAttribute('emotion')){
  9968. if(html){
  9969. var img = ci;
  9970. switch (opt.imageBlockLine){
  9971. case 'left':
  9972. case 'right':
  9973. case 'none':
  9974. var pN = img.parentNode,tmpNode,pre,next;
  9975. while(dtd.$inline[pN.tagName] || pN.tagName == 'A'){
  9976. pN = pN.parentNode;
  9977. }
  9978. tmpNode = pN;
  9979. if(tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode,'text-align') == 'center'){
  9980. if(!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1){
  9981. pre = tmpNode.previousSibling;
  9982. next = tmpNode.nextSibling;
  9983. if(pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)){
  9984. pre.appendChild(tmpNode.firstChild);
  9985. while(next.firstChild){
  9986. pre.appendChild(next.firstChild);
  9987. }
  9988. domUtils.remove(tmpNode);
  9989. domUtils.remove(next);
  9990. }else{
  9991. domUtils.setStyle(tmpNode,'text-align','');
  9992. }
  9993. }
  9994. }
  9995. domUtils.setStyle(img,'float', opt.imageBlockLine);
  9996. break;
  9997. case 'center':
  9998. if(me.queryCommandValue('imagefloat') != 'center'){
  9999. pN = img.parentNode;
  10000. domUtils.setStyle(img,'float','none');
  10001. tmpNode = img;
  10002. while(pN && domUtils.getChildCount(pN,function(node){return !domUtils.isBr(node) && !domUtils.isWhitespace(node)}) == 1
  10003. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')){
  10004. tmpNode = pN;
  10005. pN = pN.parentNode;
  10006. }
  10007. var pNode = me.document.createElement('p');
  10008. domUtils.setAttributes(pNode,{
  10009. style:'text-align:center'
  10010. });
  10011. tmpNode.parentNode.insertBefore(pNode,tmpNode);
  10012. pNode.appendChild(tmpNode);
  10013. domUtils.setStyle(tmpNode,'float','');
  10014. }
  10015. }
  10016. } else {
  10017. var range = me.selection.getRange();
  10018. range.selectNode(ci).select();
  10019. me.execCommand('imagefloat', opt.imageBlockLine);
  10020. }
  10021. }
  10022. //去掉冗余的标签
  10023. if(opt.removeEmptyNode){
  10024. if(opt.removeTagNames[ci.tagName.toLowerCase()] && domUtils.hasNoAttributes(ci) && domUtils.isEmptyBlock(ci)){
  10025. domUtils.remove(ci);
  10026. }
  10027. }
  10028. }
  10029. if(opt.tobdc){
  10030. var root = UE.htmlparser(cont.innerHTML);
  10031. root.traversal(function(node){
  10032. if(node.type == 'text'){
  10033. node.data = ToDBC(node.data)
  10034. }
  10035. });
  10036. cont.innerHTML = root.toHtml()
  10037. }
  10038. if(opt.bdc2sb){
  10039. var root = UE.htmlparser(cont.innerHTML);
  10040. root.traversal(function(node){
  10041. if(node.type == 'text'){
  10042. node.data = DBC2SB(node.data)
  10043. }
  10044. });
  10045. cont.innerHTML = root.toHtml()
  10046. }
  10047. if(html){
  10048. html.html = cont.innerHTML;
  10049. }
  10050. }
  10051. if(opt.pasteFilter){
  10052. me.addListener('beforepaste',autotype);
  10053. }
  10054. function DBC2SB(str) {
  10055. var result = '';
  10056. for (var i = 0; i < str.length; i++) {
  10057. var code = str.charCodeAt(i); //获取当前字符的unicode编码
  10058. if (code >= 65281 && code <= 65373)//在这个unicode编码范围中的是所有的英文字母已经各种字符
  10059. {
  10060. result += String.fromCharCode(str.charCodeAt(i) - 65248); //把全角字符的unicode编码转换为对应半角字符的unicode码
  10061. } else if (code == 12288)//空格
  10062. {
  10063. result += String.fromCharCode(str.charCodeAt(i) - 12288 + 32);
  10064. } else {
  10065. result += str.charAt(i);
  10066. }
  10067. }
  10068. return result;
  10069. }
  10070. function ToDBC(txtstring) {
  10071. txtstring = utils.html(txtstring);
  10072. var tmp = "";
  10073. var mark = "";/*用于判断,如果是html尖括里的标记,则不进行全角的转换*/
  10074. for (var i = 0; i < txtstring.length; i++) {
  10075. if (txtstring.charCodeAt(i) == 32) {
  10076. tmp = tmp + String.fromCharCode(12288);
  10077. }
  10078. else if (txtstring.charCodeAt(i) < 127) {
  10079. tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
  10080. }
  10081. else {
  10082. tmp += txtstring.charAt(i);
  10083. }
  10084. }
  10085. return tmp;
  10086. }
  10087. function readLocalOpts() {
  10088. var cookieOpt = me.getPreferences('autotypeset');
  10089. utils.extend(me.options.autotypeset, cookieOpt);
  10090. }
  10091. me.commands['autotypeset'] = {
  10092. execCommand:function () {
  10093. me.removeListener('beforepaste',autotype);
  10094. if(opt.pasteFilter){
  10095. me.addListener('beforepaste',autotype);
  10096. }
  10097. autotype.call(me)
  10098. }
  10099. };
  10100. };
  10101. // plugins/autosubmit.js
  10102. /**
  10103. * 快捷键提交
  10104. * @file
  10105. * @since 1.2.6.1
  10106. */
  10107. /**
  10108. * 提交表单
  10109. * @command autosubmit
  10110. * @method execCommand
  10111. * @param { String } cmd 命令字符串
  10112. * @example
  10113. * ```javascript
  10114. * editor.execCommand( 'autosubmit' );
  10115. * ```
  10116. */
  10117. UE.plugin.register('autosubmit',function(){
  10118. return {
  10119. shortcutkey:{
  10120. "autosubmit":"ctrl+13" //手动提交
  10121. },
  10122. commands:{
  10123. 'autosubmit':{
  10124. execCommand:function () {
  10125. var me=this,
  10126. form = domUtils.findParentByTagName(me.iframe,"form", false);
  10127. if (form){
  10128. if(me.fireEvent("beforesubmit")===false){
  10129. return;
  10130. }
  10131. me.sync();
  10132. form.submit();
  10133. }
  10134. }
  10135. }
  10136. }
  10137. }
  10138. });
  10139. // plugins/background.js
  10140. /**
  10141. * 背景插件,为UEditor提供设置背景功能
  10142. * @file
  10143. * @since 1.2.6.1
  10144. */
  10145. UE.plugin.register('background', function () {
  10146. var me = this,
  10147. cssRuleId = 'editor_background',
  10148. isSetColored,
  10149. reg = new RegExp('body[\\s]*\\{(.+)\\}', 'i');
  10150. function stringToObj(str) {
  10151. var obj = {}, styles = str.split(';');
  10152. utils.each(styles, function (v) {
  10153. var index = v.indexOf(':'),
  10154. key = utils.trim(v.substr(0, index)).toLowerCase();
  10155. key && (obj[key] = utils.trim(v.substr(index + 1) || ''));
  10156. });
  10157. return obj;
  10158. }
  10159. function setBackground(obj) {
  10160. if (obj) {
  10161. var styles = [];
  10162. for (var name in obj) {
  10163. if (obj.hasOwnProperty(name)) {
  10164. styles.push(name + ":" + obj[name] + '; ');
  10165. }
  10166. }
  10167. utils.cssRule(cssRuleId, styles.length ? ('body{' + styles.join("") + '}') : '', me.document);
  10168. } else {
  10169. utils.cssRule(cssRuleId, '', me.document)
  10170. }
  10171. }
  10172. //重写editor.hasContent方法
  10173. var orgFn = me.hasContents;
  10174. me.hasContents = function(){
  10175. if(me.queryCommandValue('background')){
  10176. return true
  10177. }
  10178. return orgFn.apply(me,arguments);
  10179. };
  10180. return {
  10181. bindEvents: {
  10182. 'getAllHtml': function (type, headHtml) {
  10183. var body = this.body,
  10184. su = domUtils.getComputedStyle(body, "background-image"),
  10185. url = "";
  10186. if (su.indexOf(me.options.imagePath) > 0) {
  10187. url = su.substring(su.indexOf(me.options.imagePath), su.length - 1).replace(/"|\(|\)/ig, "");
  10188. } else {
  10189. url = su != "none" ? su.replace(/url\("?|"?\)/ig, "") : "";
  10190. }
  10191. var html = '<style type="text/css">body{';
  10192. var bgObj = {
  10193. "background-color": domUtils.getComputedStyle(body, "background-color") || "#ffffff",
  10194. 'background-image': url ? 'url(' + url + ')' : '',
  10195. 'background-repeat': domUtils.getComputedStyle(body, "background-repeat") || "",
  10196. 'background-position': browser.ie ? (domUtils.getComputedStyle(body, "background-position-x") + " " + domUtils.getComputedStyle(body, "background-position-y")) : domUtils.getComputedStyle(body, "background-position"),
  10197. 'height': domUtils.getComputedStyle(body, "height")
  10198. };
  10199. for (var name in bgObj) {
  10200. if (bgObj.hasOwnProperty(name)) {
  10201. html += name + ":" + bgObj[name] + "; ";
  10202. }
  10203. }
  10204. html += '}</style> ';
  10205. headHtml.push(html);
  10206. },
  10207. 'aftersetcontent': function () {
  10208. if(isSetColored == false) setBackground();
  10209. }
  10210. },
  10211. inputRule: function (root) {
  10212. isSetColored = false;
  10213. utils.each(root.getNodesByTagName('p'), function (p) {
  10214. var styles = p.getAttr('data-background');
  10215. if (styles) {
  10216. isSetColored = true;
  10217. setBackground(stringToObj(styles));
  10218. p.parentNode.removeChild(p);
  10219. }
  10220. })
  10221. },
  10222. outputRule: function (root) {
  10223. var me = this,
  10224. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10225. if (styles) {
  10226. root.appendChild(UE.uNode.createElement('<p style="display:none;" data-background="' + utils.trim(styles[1].replace(/"/g, '').replace(/[\s]+/g, ' ')) + '"><br/></p>'));
  10227. }
  10228. },
  10229. commands: {
  10230. 'background': {
  10231. execCommand: function (cmd, obj) {
  10232. setBackground(obj);
  10233. },
  10234. queryCommandValue: function () {
  10235. var me = this,
  10236. styles = (utils.cssRule(cssRuleId, me.document) || '').replace(/[\n\r]+/g, '').match(reg);
  10237. return styles ? stringToObj(styles[1]) : null;
  10238. },
  10239. notNeedUndo: true
  10240. }
  10241. }
  10242. }
  10243. });
  10244. // plugins/image.js
  10245. /**
  10246. * 图片插入、排版插件
  10247. * @file
  10248. * @since 1.2.6.1
  10249. */
  10250. /**
  10251. * 图片对齐方式
  10252. * @command imagefloat
  10253. * @method execCommand
  10254. * @remind 值center为独占一行居中
  10255. * @param { String } cmd 命令字符串
  10256. * @param { String } align 对齐方式,可传left、right、none、center
  10257. * @remaind center表示图片独占一行
  10258. * @example
  10259. * ```javascript
  10260. * editor.execCommand( 'imagefloat', 'center' );
  10261. * ```
  10262. */
  10263. /**
  10264. * 如果选区所在位置是图片区域
  10265. * @command imagefloat
  10266. * @method queryCommandValue
  10267. * @param { String } cmd 命令字符串
  10268. * @return { String } 返回图片对齐方式
  10269. * @example
  10270. * ```javascript
  10271. * editor.queryCommandValue( 'imagefloat' );
  10272. * ```
  10273. */
  10274. UE.commands['imagefloat'] = {
  10275. execCommand:function (cmd, align) {
  10276. var me = this,
  10277. range = me.selection.getRange();
  10278. if (!range.collapsed) {
  10279. var img = range.getClosedNode();
  10280. if (img && img.tagName == 'IMG') {
  10281. switch (align) {
  10282. case 'left':
  10283. case 'right':
  10284. case 'none':
  10285. var pN = img.parentNode, tmpNode, pre, next;
  10286. while (dtd.$inline[pN.tagName] || pN.tagName == 'A') {
  10287. pN = pN.parentNode;
  10288. }
  10289. tmpNode = pN;
  10290. if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') {
  10291. if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) {
  10292. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10293. }) == 1) {
  10294. pre = tmpNode.previousSibling;
  10295. next = tmpNode.nextSibling;
  10296. if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) {
  10297. pre.appendChild(tmpNode.firstChild);
  10298. while (next.firstChild) {
  10299. pre.appendChild(next.firstChild);
  10300. }
  10301. domUtils.remove(tmpNode);
  10302. domUtils.remove(next);
  10303. } else {
  10304. domUtils.setStyle(tmpNode, 'text-align', '');
  10305. }
  10306. }
  10307. range.selectNode(img).select();
  10308. }
  10309. domUtils.setStyle(img, 'float', align == 'none' ? '' : align);
  10310. if(align == 'none'){
  10311. domUtils.removeAttributes(img,'align');
  10312. }
  10313. break;
  10314. case 'center':
  10315. if (me.queryCommandValue('imagefloat') != 'center') {
  10316. pN = img.parentNode;
  10317. domUtils.setStyle(img, 'float', '');
  10318. domUtils.removeAttributes(img,'align');
  10319. tmpNode = img;
  10320. while (pN && domUtils.getChildCount(pN, function (node) {
  10321. return !domUtils.isBr(node) && !domUtils.isWhitespace(node);
  10322. }) == 1
  10323. && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) {
  10324. tmpNode = pN;
  10325. pN = pN.parentNode;
  10326. }
  10327. range.setStartBefore(tmpNode).setCursor(false);
  10328. pN = me.document.createElement('div');
  10329. pN.appendChild(tmpNode);
  10330. domUtils.setStyle(tmpNode, 'float', '');
  10331. me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>');
  10332. tmpNode = me.document.getElementById('_img_parent_tmp');
  10333. tmpNode.removeAttribute('id');
  10334. tmpNode = tmpNode.firstChild;
  10335. range.selectNode(tmpNode).select();
  10336. //去掉后边多余的元素
  10337. next = tmpNode.parentNode.nextSibling;
  10338. if (next && domUtils.isEmptyNode(next)) {
  10339. domUtils.remove(next);
  10340. }
  10341. }
  10342. break;
  10343. }
  10344. }
  10345. }
  10346. },
  10347. queryCommandValue:function () {
  10348. var range = this.selection.getRange(),
  10349. startNode, floatStyle;
  10350. if (range.collapsed) {
  10351. return 'none';
  10352. }
  10353. startNode = range.getClosedNode();
  10354. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10355. floatStyle = domUtils.getComputedStyle(startNode, 'float') || startNode.getAttribute('align');
  10356. if (floatStyle == 'none') {
  10357. floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle;
  10358. }
  10359. return {
  10360. left:1,
  10361. right:1,
  10362. center:1
  10363. }[floatStyle] ? floatStyle : 'none';
  10364. }
  10365. return 'none';
  10366. },
  10367. queryCommandState:function () {
  10368. var range = this.selection.getRange(),
  10369. startNode;
  10370. if (range.collapsed) return -1;
  10371. startNode = range.getClosedNode();
  10372. if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') {
  10373. return 0;
  10374. }
  10375. return -1;
  10376. }
  10377. };
  10378. /**
  10379. * 插入图片
  10380. * @command insertimage
  10381. * @method execCommand
  10382. * @param { String } cmd 命令字符串
  10383. * @param { Object } opt 属性键值对,这些属性都将被复制到当前插入图片
  10384. * @remind 该命令第二个参数可接受一个图片配置项对象的数组,可以插入多张图片,
  10385. * 此时数组的每一个元素都是一个Object类型的图片属性集合。
  10386. * @example
  10387. * ```javascript
  10388. * editor.execCommand( 'insertimage', {
  10389. * src:'a/b/c.jpg',
  10390. * width:'100',
  10391. * height:'100'
  10392. * } );
  10393. * ```
  10394. * @example
  10395. * ```javascript
  10396. * editor.execCommand( 'insertimage', [{
  10397. * src:'a/b/c.jpg',
  10398. * width:'100',
  10399. * height:'100'
  10400. * },{
  10401. * src:'a/b/d.jpg',
  10402. * width:'100',
  10403. * height:'100'
  10404. * }] );
  10405. * ```
  10406. */
  10407. UE.commands['insertimage'] = {
  10408. execCommand:function (cmd, opt) {
  10409. opt = utils.isArray(opt) ? opt : [opt];
  10410. if (!opt.length) {
  10411. return;
  10412. }
  10413. var me = this,
  10414. range = me.selection.getRange(),
  10415. img = range.getClosedNode();
  10416. if(me.fireEvent('beforeinsertimage', opt) === true){
  10417. return;
  10418. }
  10419. function unhtmlData(imgCi) {
  10420. utils.each('width,height,border,hspace,vspace'.split(','), function (item) {
  10421. if (imgCi[item]) {
  10422. imgCi[item] = parseInt(imgCi[item], 10) || 0;
  10423. }
  10424. });
  10425. utils.each('src,_src'.split(','), function (item) {
  10426. if (imgCi[item]) {
  10427. imgCi[item] = utils.unhtmlForUrl(imgCi[item]);
  10428. }
  10429. });
  10430. utils.each('title,alt'.split(','), function (item) {
  10431. if (imgCi[item]) {
  10432. imgCi[item] = utils.unhtml(imgCi[item]);
  10433. }
  10434. });
  10435. }
  10436. if (img && /img/i.test(img.tagName) && (img.className != "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1) && !img.getAttribute("word_img")) {
  10437. var first = opt.shift();
  10438. var floatStyle = first['floatStyle'];
  10439. delete first['floatStyle'];
  10440. //// img.style.border = (first.border||0) +"px solid #000";
  10441. //// img.style.margin = (first.margin||0) +"px";
  10442. // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000";
  10443. domUtils.setAttributes(img, first);
  10444. me.execCommand('imagefloat', floatStyle);
  10445. if (opt.length > 0) {
  10446. range.setStartAfter(img).setCursor(false, true);
  10447. me.execCommand('insertimage', opt);
  10448. }
  10449. } else {
  10450. var html = [], str = '', ci;
  10451. ci = opt[0];
  10452. if (opt.length == 1) {
  10453. unhtmlData(ci);
  10454. str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10455. (ci.width ? 'width="' + ci.width + '" ' : '') +
  10456. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10457. (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') +
  10458. (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') +
  10459. (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') +
  10460. (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') +
  10461. (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') +
  10462. (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>';
  10463. if (ci['floatStyle'] == 'center') {
  10464. str = '<p style="text-align: center">' + str + '</p>';
  10465. }
  10466. html.push(str);
  10467. } else {
  10468. for (var i = 0; ci = opt[i++];) {
  10469. unhtmlData(ci);
  10470. str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' +
  10471. (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') +
  10472. (ci.height ? ' height="' + ci.height + '" ' : '') +
  10473. ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') +
  10474. (ci.border || '') + '" ' +
  10475. (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>';
  10476. html.push(str);
  10477. }
  10478. }
  10479. me.execCommand('insertHtml', html.join(''));
  10480. }
  10481. me.fireEvent('afterinsertimage', opt)
  10482. }
  10483. };
  10484. // plugins/justify.js
  10485. /**
  10486. * 段落格式
  10487. * @file
  10488. * @since 1.2.6.1
  10489. */
  10490. /**
  10491. * 段落对齐方式
  10492. * @command justify
  10493. * @method execCommand
  10494. * @param { String } cmd 命令字符串
  10495. * @param { String } align 对齐方式:left => 居左,right => 居右,center => 居中,justify => 两端对齐
  10496. * @example
  10497. * ```javascript
  10498. * editor.execCommand( 'justify', 'center' );
  10499. * ```
  10500. */
  10501. /**
  10502. * 如果选区所在位置是段落区域,返回当前段落对齐方式
  10503. * @command justify
  10504. * @method queryCommandValue
  10505. * @param { String } cmd 命令字符串
  10506. * @return { String } 返回段落对齐方式
  10507. * @example
  10508. * ```javascript
  10509. * editor.queryCommandValue( 'justify' );
  10510. * ```
  10511. */
  10512. UE.plugins['justify']=function(){
  10513. var me=this,
  10514. block = domUtils.isBlockElm,
  10515. defaultValue = {
  10516. left:1,
  10517. right:1,
  10518. center:1,
  10519. justify:1
  10520. },
  10521. doJustify = function (range, style) {
  10522. var bookmark = range.createBookmark(),
  10523. filterFn = function (node) {
  10524. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  10525. };
  10526. range.enlarge(true);
  10527. var bookmark2 = range.createBookmark(),
  10528. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn),
  10529. tmpRange = range.cloneRange(),
  10530. tmpNode;
  10531. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  10532. if (current.nodeType == 3 || !block(current)) {
  10533. tmpRange.setStartBefore(current);
  10534. while (current && current !== bookmark2.end && !block(current)) {
  10535. tmpNode = current;
  10536. current = domUtils.getNextDomNode(current, false, null, function (node) {
  10537. return !block(node);
  10538. });
  10539. }
  10540. tmpRange.setEndAfter(tmpNode);
  10541. var common = tmpRange.getCommonAncestor();
  10542. if (!domUtils.isBody(common) && block(common)) {
  10543. domUtils.setStyles(common, utils.isString(style) ? {'text-align':style} : style);
  10544. current = common;
  10545. } else {
  10546. var p = range.document.createElement('p');
  10547. domUtils.setStyles(p, utils.isString(style) ? {'text-align':style} : style);
  10548. var frag = tmpRange.extractContents();
  10549. p.appendChild(frag);
  10550. tmpRange.insertNode(p);
  10551. current = p;
  10552. }
  10553. current = domUtils.getNextDomNode(current, false, filterFn);
  10554. } else {
  10555. current = domUtils.getNextDomNode(current, true, filterFn);
  10556. }
  10557. }
  10558. return range.moveToBookmark(bookmark2).moveToBookmark(bookmark);
  10559. };
  10560. UE.commands['justify'] = {
  10561. execCommand:function (cmdName, align) {
  10562. var range = this.selection.getRange(),
  10563. txt;
  10564. //闭合时单独处理
  10565. if (range.collapsed) {
  10566. txt = this.document.createTextNode('p');
  10567. range.insertNode(txt);
  10568. }
  10569. doJustify(range, align);
  10570. if (txt) {
  10571. range.setStartBefore(txt).collapse(true);
  10572. domUtils.remove(txt);
  10573. }
  10574. range.select();
  10575. return true;
  10576. },
  10577. queryCommandValue:function () {
  10578. var startNode = this.selection.getStart(),
  10579. value = domUtils.getComputedStyle(startNode, 'text-align');
  10580. return defaultValue[value] ? value : 'left';
  10581. },
  10582. queryCommandState:function () {
  10583. var start = this.selection.getStart(),
  10584. cell = start && domUtils.findParentByTagName(start, ["td", "th","caption"], true);
  10585. return cell? -1:0;
  10586. }
  10587. };
  10588. };
  10589. // plugins/font.js
  10590. /**
  10591. * 字体颜色,背景色,字号,字体,下划线,删除线
  10592. * @file
  10593. * @since 1.2.6.1
  10594. */
  10595. /**
  10596. * 字体颜色
  10597. * @command forecolor
  10598. * @method execCommand
  10599. * @param { String } cmd 命令字符串
  10600. * @param { String } value 色值(必须十六进制)
  10601. * @example
  10602. * ```javascript
  10603. * editor.execCommand( 'forecolor', '#000' );
  10604. * ```
  10605. */
  10606. /**
  10607. * 返回选区字体颜色
  10608. * @command forecolor
  10609. * @method queryCommandValue
  10610. * @param { String } cmd 命令字符串
  10611. * @return { String } 返回字体颜色
  10612. * @example
  10613. * ```javascript
  10614. * editor.queryCommandValue( 'forecolor' );
  10615. * ```
  10616. */
  10617. /**
  10618. * 字体背景颜色
  10619. * @command backcolor
  10620. * @method execCommand
  10621. * @param { String } cmd 命令字符串
  10622. * @param { String } value 色值(必须十六进制)
  10623. * @example
  10624. * ```javascript
  10625. * editor.execCommand( 'backcolor', '#000' );
  10626. * ```
  10627. */
  10628. /**
  10629. * 返回选区字体颜色
  10630. * @command backcolor
  10631. * @method queryCommandValue
  10632. * @param { String } cmd 命令字符串
  10633. * @return { String } 返回字体背景颜色
  10634. * @example
  10635. * ```javascript
  10636. * editor.queryCommandValue( 'backcolor' );
  10637. * ```
  10638. */
  10639. /**
  10640. * 字体大小
  10641. * @command fontsize
  10642. * @method execCommand
  10643. * @param { String } cmd 命令字符串
  10644. * @param { String } value 字体大小
  10645. * @example
  10646. * ```javascript
  10647. * editor.execCommand( 'fontsize', '14px' );
  10648. * ```
  10649. */
  10650. /**
  10651. * 返回选区字体大小
  10652. * @command fontsize
  10653. * @method queryCommandValue
  10654. * @param { String } cmd 命令字符串
  10655. * @return { String } 返回字体大小
  10656. * @example
  10657. * ```javascript
  10658. * editor.queryCommandValue( 'fontsize' );
  10659. * ```
  10660. */
  10661. /**
  10662. * 字体样式
  10663. * @command fontfamily
  10664. * @method execCommand
  10665. * @param { String } cmd 命令字符串
  10666. * @param { String } value 字体样式
  10667. * @example
  10668. * ```javascript
  10669. * editor.execCommand( 'fontfamily', '微软雅黑' );
  10670. * ```
  10671. */
  10672. /**
  10673. * 返回选区字体样式
  10674. * @command fontfamily
  10675. * @method queryCommandValue
  10676. * @param { String } cmd 命令字符串
  10677. * @return { String } 返回字体样式
  10678. * @example
  10679. * ```javascript
  10680. * editor.queryCommandValue( 'fontfamily' );
  10681. * ```
  10682. */
  10683. /**
  10684. * 字体下划线,与删除线互斥
  10685. * @command underline
  10686. * @method execCommand
  10687. * @param { String } cmd 命令字符串
  10688. * @example
  10689. * ```javascript
  10690. * editor.execCommand( 'underline' );
  10691. * ```
  10692. */
  10693. /**
  10694. * 字体删除线,与下划线互斥
  10695. * @command strikethrough
  10696. * @method execCommand
  10697. * @param { String } cmd 命令字符串
  10698. * @example
  10699. * ```javascript
  10700. * editor.execCommand( 'strikethrough' );
  10701. * ```
  10702. */
  10703. /**
  10704. * 字体边框
  10705. * @command fontborder
  10706. * @method execCommand
  10707. * @param { String } cmd 命令字符串
  10708. * @example
  10709. * ```javascript
  10710. * editor.execCommand( 'fontborder' );
  10711. * ```
  10712. */
  10713. UE.plugins['font'] = function () {
  10714. var me = this,
  10715. fonts = {
  10716. 'forecolor': 'color',
  10717. 'backcolor': 'background-color',
  10718. 'fontsize': 'font-size',
  10719. 'fontfamily': 'font-family',
  10720. 'underline': 'text-decoration',
  10721. 'strikethrough': 'text-decoration',
  10722. 'fontborder': 'border'
  10723. },
  10724. needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1},
  10725. needSetChild = {
  10726. 'forecolor': 'color',
  10727. 'backcolor': 'background-color',
  10728. 'fontsize': 'font-size',
  10729. 'fontfamily': 'font-family'
  10730. };
  10731. me.setOpt({
  10732. 'fontfamily': [
  10733. { name: 'songti', val: '宋体,SimSun'},
  10734. { name: 'yahei', val: '微软雅黑,Microsoft YaHei'},
  10735. { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'},
  10736. { name: 'heiti', val: '黑体, SimHei'},
  10737. { name: 'lishu', val: '隶书, SimLi'},
  10738. { name: 'andaleMono', val: 'andale mono'},
  10739. { name: 'arial', val: 'arial, helvetica,sans-serif'},
  10740. { name: 'arialBlack', val: 'arial black,avant garde'},
  10741. { name: 'comicSansMs', val: 'comic sans ms'},
  10742. { name: 'impact', val: 'impact,chicago'},
  10743. { name: 'timesNewRoman', val: 'times new roman'}
  10744. ],
  10745. 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36]
  10746. });
  10747. function mergeWithParent(node){
  10748. var parent;
  10749. while(parent = node.parentNode){
  10750. if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){
  10751. return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child)
  10752. }) == 1) {
  10753. parent.style.cssText += node.style.cssText;
  10754. domUtils.remove(node,true);
  10755. node = parent;
  10756. }else{
  10757. break;
  10758. }
  10759. }
  10760. }
  10761. function mergeChild(rng,cmdName,value){
  10762. if(needSetChild[cmdName]){
  10763. rng.adjustmentBoundary();
  10764. if(!rng.collapsed && rng.startContainer.nodeType == 1){
  10765. var start = rng.startContainer.childNodes[rng.startOffset];
  10766. if(start && domUtils.isTagNode(start,'span')){
  10767. var bk = rng.createBookmark();
  10768. utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) {
  10769. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10770. if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){
  10771. return;
  10772. }
  10773. domUtils.removeStyle(span,needSetChild[cmdName]);
  10774. if(span.style.cssText.replace(/^\s+$/,'').length == 0){
  10775. domUtils.remove(span,true)
  10776. }
  10777. });
  10778. rng.moveToBookmark(bk)
  10779. }
  10780. }
  10781. }
  10782. }
  10783. function mergesibling(rng,cmdName,value) {
  10784. var collapsed = rng.collapsed,
  10785. bk = rng.createBookmark(), common;
  10786. if (collapsed) {
  10787. common = bk.start.parentNode;
  10788. while (dtd.$inline[common.tagName]) {
  10789. common = common.parentNode;
  10790. }
  10791. } else {
  10792. common = domUtils.getCommonAncestor(bk.start, bk.end);
  10793. }
  10794. utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) {
  10795. if (!span.parentNode || domUtils.isBookmarkNode(span))return;
  10796. if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) {
  10797. if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){
  10798. domUtils.remove(span, true);
  10799. }else{
  10800. domUtils.removeStyle(span,'border');
  10801. }
  10802. return
  10803. }
  10804. if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) {
  10805. span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, '');
  10806. }
  10807. if(!(cmdName=='fontborder' && value=='none')){
  10808. var next = span.nextSibling;
  10809. while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) {
  10810. if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') {
  10811. span.appendChild(next);
  10812. next = span.nextSibling;
  10813. continue;
  10814. }
  10815. if (next.style.cssText == span.style.cssText) {
  10816. domUtils.moveChild(next, span);
  10817. domUtils.remove(next);
  10818. }
  10819. if (span.nextSibling === next)
  10820. break;
  10821. next = span.nextSibling;
  10822. }
  10823. }
  10824. mergeWithParent(span);
  10825. if(browser.ie && browser.version > 8 ){
  10826. //拷贝父亲们的特别的属性,这里只做背景颜色的处理
  10827. var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)});
  10828. if(parent && !/background-color/.test(span.style.cssText)){
  10829. span.style.backgroundColor = parent.style.backgroundColor;
  10830. }
  10831. }
  10832. });
  10833. rng.moveToBookmark(bk);
  10834. mergeChild(rng,cmdName,value)
  10835. }
  10836. me.addInputRule(function (root) {
  10837. utils.each(root.getNodesByTagName('u s del font strike'), function (node) {
  10838. if (node.tagName == 'font') {
  10839. var cssStyle = [];
  10840. for (var p in node.attrs) {
  10841. switch (p) {
  10842. case 'size':
  10843. cssStyle.push('font-size:' +
  10844. ({
  10845. '1':'10',
  10846. '2':'12',
  10847. '3':'16',
  10848. '4':'18',
  10849. '5':'24',
  10850. '6':'32',
  10851. '7':'48'
  10852. }[node.attrs[p]] || node.attrs[p]) + 'px');
  10853. break;
  10854. case 'color':
  10855. cssStyle.push('color:' + node.attrs[p]);
  10856. break;
  10857. case 'face':
  10858. cssStyle.push('font-family:' + node.attrs[p]);
  10859. break;
  10860. case 'style':
  10861. cssStyle.push(node.attrs[p]);
  10862. }
  10863. }
  10864. node.attrs = {
  10865. 'style': cssStyle.join(';')
  10866. };
  10867. } else {
  10868. var val = node.tagName == 'u' ? 'underline' : 'line-through';
  10869. node.attrs = {
  10870. 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';'
  10871. }
  10872. }
  10873. node.tagName = 'span';
  10874. });
  10875. // utils.each(root.getNodesByTagName('span'), function (node) {
  10876. // var val;
  10877. // if(val = node.getAttr('class')){
  10878. // if(/fontstrikethrough/.test(val)){
  10879. // node.setStyle('text-decoration','line-through');
  10880. // if(node.attrs['class']){
  10881. // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,'');
  10882. // }else{
  10883. // node.setAttr('class')
  10884. // }
  10885. // }
  10886. // if(/fontborder/.test(val)){
  10887. // node.setStyle('border','1px solid #000');
  10888. // if(node.attrs['class']){
  10889. // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,'');
  10890. // }else{
  10891. // node.setAttr('class')
  10892. // }
  10893. // }
  10894. // }
  10895. // });
  10896. });
  10897. // me.addOutputRule(function(root){
  10898. // utils.each(root.getNodesByTagName('span'), function (node) {
  10899. // var val;
  10900. // if(val = node.getStyle('text-decoration')){
  10901. // if(/line-through/.test(val)){
  10902. // if(node.attrs['class']){
  10903. // node.attrs['class'] += ' fontstrikethrough';
  10904. // }else{
  10905. // node.setAttr('class','fontstrikethrough')
  10906. // }
  10907. // }
  10908. //
  10909. // node.setStyle('text-decoration')
  10910. // }
  10911. // if(val = node.getStyle('border')){
  10912. // if(/1px/.test(val) && /solid/.test(val)){
  10913. // if(node.attrs['class']){
  10914. // node.attrs['class'] += ' fontborder';
  10915. //
  10916. // }else{
  10917. // node.setAttr('class','fontborder')
  10918. // }
  10919. // }
  10920. // node.setStyle('border')
  10921. //
  10922. // }
  10923. // });
  10924. // });
  10925. for (var p in fonts) {
  10926. (function (cmd, style) {
  10927. UE.commands[cmd] = {
  10928. execCommand: function (cmdName, value) {
  10929. value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' :
  10930. cmdName == 'fontborder' ? '1px solid #000' :
  10931. 'line-through');
  10932. var me = this,
  10933. range = this.selection.getRange(),
  10934. text;
  10935. if (value == 'default') {
  10936. if (range.collapsed) {
  10937. text = me.document.createTextNode('font');
  10938. range.insertNode(text).select();
  10939. }
  10940. me.execCommand('removeFormat', 'span,a', style);
  10941. if (text) {
  10942. range.setStartBefore(text).collapse(true);
  10943. domUtils.remove(text);
  10944. }
  10945. mergesibling(range,cmdName,value);
  10946. range.select()
  10947. } else {
  10948. if (!range.collapsed) {
  10949. if (needCmd[cmd] && me.queryCommandValue(cmd)) {
  10950. me.execCommand('removeFormat', 'span,a', style);
  10951. }
  10952. range = me.selection.getRange();
  10953. range.applyInlineStyle('span', {'style': style + ':' + value});
  10954. mergesibling(range, cmdName,value);
  10955. range.select();
  10956. } else {
  10957. var span = domUtils.findParentByTagName(range.startContainer, 'span', true);
  10958. text = me.document.createTextNode('font');
  10959. if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) {
  10960. //for ie hack when enter
  10961. range.insertNode(text);
  10962. if (needCmd[cmd]) {
  10963. range.selectNode(text).select();
  10964. me.execCommand('removeFormat', 'span,a', style, null);
  10965. span = domUtils.findParentByTagName(text, 'span', true);
  10966. range.setStartBefore(text);
  10967. }
  10968. span && (span.style.cssText += ';' + style + ':' + value);
  10969. range.collapse(true).select();
  10970. } else {
  10971. range.insertNode(text);
  10972. range.selectNode(text).select();
  10973. span = range.document.createElement('span');
  10974. if (needCmd[cmd]) {
  10975. //a标签内的不处理跳过
  10976. if (domUtils.findParentByTagName(text, 'a', true)) {
  10977. range.setStartBefore(text).setCursor();
  10978. domUtils.remove(text);
  10979. return;
  10980. }
  10981. me.execCommand('removeFormat', 'span,a', style);
  10982. }
  10983. span.style.cssText = style + ':' + value;
  10984. text.parentNode.insertBefore(span, text);
  10985. //修复,span套span 但样式不继承的问题
  10986. if (!browser.ie || browser.ie && browser.version == 9) {
  10987. var spanParent = span.parentNode;
  10988. while (!domUtils.isBlockElm(spanParent)) {
  10989. if (spanParent.tagName == 'SPAN') {
  10990. //opera合并style不会加入";"
  10991. span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText;
  10992. }
  10993. spanParent = spanParent.parentNode;
  10994. }
  10995. }
  10996. if (opera) {
  10997. setTimeout(function () {
  10998. range.setStart(span, 0).collapse(true);
  10999. mergesibling(range, cmdName,value);
  11000. range.select();
  11001. });
  11002. } else {
  11003. range.setStart(span, 0).collapse(true);
  11004. mergesibling(range,cmdName,value);
  11005. range.select();
  11006. }
  11007. //trace:981
  11008. //domUtils.mergeToParent(span)
  11009. }
  11010. domUtils.remove(text);
  11011. }
  11012. }
  11013. return true;
  11014. },
  11015. queryCommandValue: function (cmdName) {
  11016. var startNode = this.selection.getStart();
  11017. //trace:946
  11018. if (cmdName == 'underline' || cmdName == 'strikethrough') {
  11019. var tmpNode = startNode, value;
  11020. while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) {
  11021. if (tmpNode.nodeType == 1) {
  11022. value = domUtils.getComputedStyle(tmpNode, style);
  11023. if (value != 'none') {
  11024. return value;
  11025. }
  11026. }
  11027. tmpNode = tmpNode.parentNode;
  11028. }
  11029. return 'none';
  11030. }
  11031. if (cmdName == 'fontborder') {
  11032. var tmp = startNode, val;
  11033. while (tmp && dtd.$inline[tmp.tagName]) {
  11034. if (val = domUtils.getComputedStyle(tmp, 'border')) {
  11035. if (/1px/.test(val) && /solid/.test(val)) {
  11036. return val;
  11037. }
  11038. }
  11039. tmp = tmp.parentNode;
  11040. }
  11041. return ''
  11042. }
  11043. if( cmdName == 'FontSize' ) {
  11044. var styleVal = domUtils.getComputedStyle(startNode, style),
  11045. tmp = /^([\d\.]+)(\w+)$/.exec( styleVal );
  11046. if( tmp ) {
  11047. return Math.floor( tmp[1] ) + tmp[2];
  11048. }
  11049. return styleVal;
  11050. }
  11051. return domUtils.getComputedStyle(startNode, style);
  11052. },
  11053. queryCommandState: function (cmdName) {
  11054. if (!needCmd[cmdName])
  11055. return 0;
  11056. var val = this.queryCommandValue(cmdName);
  11057. if (cmdName == 'fontborder') {
  11058. return /1px/.test(val) && /solid/.test(val)
  11059. } else {
  11060. return cmdName == 'underline' ? /underline/.test(val) : /line\-through/.test(val);
  11061. }
  11062. }
  11063. };
  11064. })(p, fonts[p]);
  11065. }
  11066. };
  11067. // plugins/link.js
  11068. /**
  11069. * 超链接
  11070. * @file
  11071. * @since 1.2.6.1
  11072. */
  11073. /**
  11074. * 插入超链接
  11075. * @command link
  11076. * @method execCommand
  11077. * @param { String } cmd 命令字符串
  11078. * @param { Object } options 设置自定义属性,例如:url、title、target
  11079. * @example
  11080. * ```javascript
  11081. * editor.execCommand( 'link', '{
  11082. * url:'ueditor.baidu.com',
  11083. * title:'ueditor',
  11084. * target:'_blank'
  11085. * }' );
  11086. * ```
  11087. */
  11088. /**
  11089. * 返回当前选中的第一个超链接节点
  11090. * @command link
  11091. * @method queryCommandValue
  11092. * @param { String } cmd 命令字符串
  11093. * @return { Element } 超链接节点
  11094. * @example
  11095. * ```javascript
  11096. * editor.queryCommandValue( 'link' );
  11097. * ```
  11098. */
  11099. /**
  11100. * 取消超链接
  11101. * @command unlink
  11102. * @method execCommand
  11103. * @param { String } cmd 命令字符串
  11104. * @example
  11105. * ```javascript
  11106. * editor.execCommand( 'unlink');
  11107. * ```
  11108. */
  11109. UE.plugins['link'] = function(){
  11110. function optimize( range ) {
  11111. var start = range.startContainer,end = range.endContainer;
  11112. if ( start = domUtils.findParentByTagName( start, 'a', true ) ) {
  11113. range.setStartBefore( start );
  11114. }
  11115. if ( end = domUtils.findParentByTagName( end, 'a', true ) ) {
  11116. range.setEndAfter( end );
  11117. }
  11118. }
  11119. UE.commands['unlink'] = {
  11120. execCommand : function() {
  11121. var range = this.selection.getRange(),
  11122. bookmark;
  11123. if(range.collapsed && !domUtils.findParentByTagName( range.startContainer, 'a', true )){
  11124. return;
  11125. }
  11126. bookmark = range.createBookmark();
  11127. optimize( range );
  11128. range.removeInlineStyle( 'a' ).moveToBookmark( bookmark ).select();
  11129. },
  11130. queryCommandState : function(){
  11131. return !this.highlight && this.queryCommandValue('link') ? 0 : -1;
  11132. }
  11133. };
  11134. function doLink(range,opt,me){
  11135. var rngClone = range.cloneRange(),
  11136. link = me.queryCommandValue('link');
  11137. optimize( range = range.adjustmentBoundary() );
  11138. var start = range.startContainer;
  11139. if(start.nodeType == 1 && link){
  11140. start = start.childNodes[range.startOffset];
  11141. if(start && start.nodeType == 1 && start.tagName == 'A' && /^(?:https?|ftp|file)\s*:\s*\/\//.test(start[browser.ie?'innerText':'textContent'])){
  11142. start[browser.ie ? 'innerText' : 'textContent'] = utils.html(opt.textValue||opt.href);
  11143. }
  11144. }
  11145. if( !rngClone.collapsed || link){
  11146. range.removeInlineStyle( 'a' );
  11147. rngClone = range.cloneRange();
  11148. }
  11149. if ( rngClone.collapsed ) {
  11150. var a = range.document.createElement( 'a'),
  11151. text = '';
  11152. if(opt.textValue){
  11153. text = utils.html(opt.textValue);
  11154. delete opt.textValue;
  11155. }else{
  11156. text = utils.html(opt.href);
  11157. }
  11158. domUtils.setAttributes( a, opt );
  11159. start = domUtils.findParentByTagName( rngClone.startContainer, 'a', true );
  11160. if(start && domUtils.isInNodeEndBoundary(rngClone,start)){
  11161. range.setStartAfter(start).collapse(true);
  11162. }
  11163. a[browser.ie ? 'innerText' : 'textContent'] = text;
  11164. range.insertNode(a).selectNode( a );
  11165. } else {
  11166. range.applyInlineStyle( 'a', opt );
  11167. }
  11168. }
  11169. UE.commands['link'] = {
  11170. execCommand : function( cmdName, opt ) {
  11171. var range;
  11172. opt._href && (opt._href = utils.unhtml(opt._href,/[<">]/g));
  11173. opt.href && (opt.href = utils.unhtml(opt.href,/[<">]/g));
  11174. opt.textValue && (opt.textValue = utils.unhtml(opt.textValue,/[<">]/g));
  11175. doLink(range=this.selection.getRange(),opt,this);
  11176. //闭合都不加占位符,如果加了会在a后边多个占位符节点,导致a是图片背景组成的列表,出现空白问题
  11177. range.collapse().select(true);
  11178. },
  11179. queryCommandValue : function() {
  11180. var range = this.selection.getRange(),
  11181. node;
  11182. if ( range.collapsed ) {
  11183. // node = this.selection.getStart();
  11184. //在ie下getstart()取值偏上了
  11185. node = range.startContainer;
  11186. node = node.nodeType == 1 ? node : node.parentNode;
  11187. if ( node && (node = domUtils.findParentByTagName( node, 'a', true )) && ! domUtils.isInNodeEndBoundary(range,node)) {
  11188. return node;
  11189. }
  11190. } else {
  11191. //trace:1111 如果是<p><a>xx</a></p> startContainer是p就会找不到a
  11192. range.shrinkBoundary();
  11193. var start = range.startContainer.nodeType == 3 || !range.startContainer.childNodes[range.startOffset] ? range.startContainer : range.startContainer.childNodes[range.startOffset],
  11194. end = range.endContainer.nodeType == 3 || range.endOffset == 0 ? range.endContainer : range.endContainer.childNodes[range.endOffset-1],
  11195. common = range.getCommonAncestor();
  11196. node = domUtils.findParentByTagName( common, 'a', true );
  11197. if ( !node && common.nodeType == 1){
  11198. var as = common.getElementsByTagName( 'a' ),
  11199. ps,pe;
  11200. for ( var i = 0,ci; ci = as[i++]; ) {
  11201. ps = domUtils.getPosition( ci, start ),pe = domUtils.getPosition( ci,end);
  11202. if ( (ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  11203. &&
  11204. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  11205. ) {
  11206. node = ci;
  11207. break;
  11208. }
  11209. }
  11210. }
  11211. return node;
  11212. }
  11213. },
  11214. queryCommandState : function() {
  11215. //判断如果是视频的话连接不可用
  11216. //fix 853
  11217. var img = this.selection.getRange().getClosedNode(),
  11218. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  11219. return flag ? -1 : 0;
  11220. }
  11221. };
  11222. };
  11223. // plugins/iframe.js
  11224. ///import core
  11225. ///import plugins\inserthtml.js
  11226. ///commands 插入框架
  11227. ///commandsName InsertFrame
  11228. ///commandsTitle 插入Iframe
  11229. ///commandsDialog dialogs\insertframe
  11230. UE.plugins['insertframe'] = function() {
  11231. var me =this;
  11232. function deleteIframe(){
  11233. me._iframe && delete me._iframe;
  11234. }
  11235. me.addListener("selectionchange",function(){
  11236. deleteIframe();
  11237. });
  11238. };
  11239. // plugins/scrawl.js
  11240. ///import core
  11241. ///commands 涂鸦
  11242. ///commandsName Scrawl
  11243. ///commandsTitle 涂鸦
  11244. ///commandsDialog dialogs\scrawl
  11245. UE.commands['scrawl'] = {
  11246. queryCommandState : function(){
  11247. return ( browser.ie && browser.version <= 8 ) ? -1 :0;
  11248. }
  11249. };
  11250. // plugins/removeformat.js
  11251. /**
  11252. * 清除格式
  11253. * @file
  11254. * @since 1.2.6.1
  11255. */
  11256. /**
  11257. * 清除文字样式
  11258. * @command removeformat
  11259. * @method execCommand
  11260. * @param { String } cmd 命令字符串
  11261. * @param {String} tags 以逗号隔开的标签。如:strong
  11262. * @param {String} style 样式如:color
  11263. * @param {String} attrs 属性如:width
  11264. * @example
  11265. * ```javascript
  11266. * editor.execCommand( 'removeformat', 'strong','color','width' );
  11267. * ```
  11268. */
  11269. UE.plugins['removeformat'] = function(){
  11270. var me = this;
  11271. me.setOpt({
  11272. 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var',
  11273. 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign'
  11274. });
  11275. me.commands['removeformat'] = {
  11276. execCommand : function( cmdName, tags, style, attrs,notIncludeA ) {
  11277. var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) ,
  11278. removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ),
  11279. range = new dom.Range( this.document ),
  11280. bookmark,node,parent,
  11281. filter = function( node ) {
  11282. return node.nodeType == 1;
  11283. };
  11284. function isRedundantSpan (node) {
  11285. if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){
  11286. return 0;
  11287. }
  11288. if (browser.ie) {
  11289. //ie 下判断实效,所以只能简单用style来判断
  11290. //return node.style.cssText == '' ? 1 : 0;
  11291. var attrs = node.attributes;
  11292. if ( attrs.length ) {
  11293. for ( var i = 0,l = attrs.length; i<l; i++ ) {
  11294. if ( attrs[i].specified ) {
  11295. return 0;
  11296. }
  11297. }
  11298. return 1;
  11299. }
  11300. }
  11301. return !node.attributes.length;
  11302. }
  11303. function doRemove( range ) {
  11304. var bookmark1 = range.createBookmark();
  11305. if ( range.collapsed ) {
  11306. range.enlarge( true );
  11307. }
  11308. //不能把a标签切了
  11309. if(!notIncludeA){
  11310. var aNode = domUtils.findParentByTagName(range.startContainer,'a',true);
  11311. if(aNode){
  11312. range.setStartBefore(aNode);
  11313. }
  11314. aNode = domUtils.findParentByTagName(range.endContainer,'a',true);
  11315. if(aNode){
  11316. range.setEndAfter(aNode);
  11317. }
  11318. }
  11319. bookmark = range.createBookmark();
  11320. node = bookmark.start;
  11321. //切开始
  11322. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11323. domUtils.breakParent( node, parent );
  11324. domUtils.clearEmptySibling( node );
  11325. }
  11326. if ( bookmark.end ) {
  11327. //切结束
  11328. node = bookmark.end;
  11329. while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) {
  11330. domUtils.breakParent( node, parent );
  11331. domUtils.clearEmptySibling( node );
  11332. }
  11333. //开始去除样式
  11334. var current = domUtils.getNextDomNode( bookmark.start, false, filter ),
  11335. next;
  11336. while ( current ) {
  11337. if ( current == bookmark.end ) {
  11338. break;
  11339. }
  11340. next = domUtils.getNextDomNode( current, true, filter );
  11341. if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) {
  11342. if ( tagReg.test( current.tagName ) ) {
  11343. if ( style ) {
  11344. domUtils.removeStyle( current, style );
  11345. if ( isRedundantSpan( current ) && style != 'text-decoration'){
  11346. domUtils.remove( current, true );
  11347. }
  11348. } else {
  11349. domUtils.remove( current, true );
  11350. }
  11351. } else {
  11352. //trace:939 不能把list上的样式去掉
  11353. if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){
  11354. domUtils.removeAttributes( current, removeFormatAttributes );
  11355. if ( isRedundantSpan( current ) ){
  11356. domUtils.remove( current, true );
  11357. }
  11358. }
  11359. }
  11360. }
  11361. current = next;
  11362. }
  11363. }
  11364. //trace:1035
  11365. //trace:1096 不能把td上的样式去掉,比如边框
  11366. var pN = bookmark.start.parentNode;
  11367. if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){
  11368. domUtils.removeAttributes( pN,removeFormatAttributes );
  11369. }
  11370. pN = bookmark.end.parentNode;
  11371. if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){
  11372. domUtils.removeAttributes( pN,removeFormatAttributes );
  11373. }
  11374. range.moveToBookmark( bookmark ).moveToBookmark(bookmark1);
  11375. //清除冗余的代码 <b><bookmark></b>
  11376. var node = range.startContainer,
  11377. tmp,
  11378. collapsed = range.collapsed;
  11379. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11380. tmp = node.parentNode;
  11381. range.setStartBefore(node);
  11382. //trace:937
  11383. //更新结束边界
  11384. if(range.startContainer === range.endContainer){
  11385. range.endOffset--;
  11386. }
  11387. domUtils.remove(node);
  11388. node = tmp;
  11389. }
  11390. if(!collapsed){
  11391. node = range.endContainer;
  11392. while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){
  11393. tmp = node.parentNode;
  11394. range.setEndBefore(node);
  11395. domUtils.remove(node);
  11396. node = tmp;
  11397. }
  11398. }
  11399. }
  11400. range = this.selection.getRange();
  11401. doRemove( range );
  11402. range.select();
  11403. }
  11404. };
  11405. };
  11406. // plugins/blockquote.js
  11407. /**
  11408. * 添加引用
  11409. * @file
  11410. * @since 1.2.6.1
  11411. */
  11412. /**
  11413. * 添加引用
  11414. * @command blockquote
  11415. * @method execCommand
  11416. * @param { String } cmd 命令字符串
  11417. * @example
  11418. * ```javascript
  11419. * editor.execCommand( 'blockquote' );
  11420. * ```
  11421. */
  11422. /**
  11423. * 添加引用
  11424. * @command blockquote
  11425. * @method execCommand
  11426. * @param { String } cmd 命令字符串
  11427. * @param { Object } attrs 节点属性
  11428. * @example
  11429. * ```javascript
  11430. * editor.execCommand( 'blockquote',{
  11431. * style: "color: red;"
  11432. * } );
  11433. * ```
  11434. */
  11435. UE.plugins['blockquote'] = function(){
  11436. var me = this;
  11437. function getObj(editor){
  11438. return domUtils.filterNodeList(editor.selection.getStartElementPath(),'blockquote');
  11439. }
  11440. me.commands['blockquote'] = {
  11441. execCommand : function( cmdName, attrs ) {
  11442. var range = this.selection.getRange(),
  11443. obj = getObj(this),
  11444. blockquote = dtd.blockquote,
  11445. bookmark = range.createBookmark();
  11446. if ( obj ) {
  11447. var start = range.startContainer,
  11448. startBlock = domUtils.isBlockElm(start) ? start : domUtils.findParent(start,function(node){return domUtils.isBlockElm(node)}),
  11449. end = range.endContainer,
  11450. endBlock = domUtils.isBlockElm(end) ? end : domUtils.findParent(end,function(node){return domUtils.isBlockElm(node)});
  11451. //处理一下li
  11452. startBlock = domUtils.findParentByTagName(startBlock,'li',true) || startBlock;
  11453. endBlock = domUtils.findParentByTagName(endBlock,'li',true) || endBlock;
  11454. if(startBlock.tagName == 'LI' || startBlock.tagName == 'TD' || startBlock === obj || domUtils.isBody(startBlock)){
  11455. domUtils.remove(obj,true);
  11456. }else{
  11457. domUtils.breakParent(startBlock,obj);
  11458. }
  11459. if(startBlock !== endBlock){
  11460. obj = domUtils.findParentByTagName(endBlock,'blockquote');
  11461. if(obj){
  11462. if(endBlock.tagName == 'LI' || endBlock.tagName == 'TD'|| domUtils.isBody(endBlock)){
  11463. obj.parentNode && domUtils.remove(obj,true);
  11464. }else{
  11465. domUtils.breakParent(endBlock,obj);
  11466. }
  11467. }
  11468. }
  11469. var blockquotes = domUtils.getElementsByTagName(this.document,'blockquote');
  11470. for(var i=0,bi;bi=blockquotes[i++];){
  11471. if(!bi.childNodes.length){
  11472. domUtils.remove(bi);
  11473. }else if(domUtils.getPosition(bi,startBlock)&domUtils.POSITION_FOLLOWING && domUtils.getPosition(bi,endBlock)&domUtils.POSITION_PRECEDING){
  11474. domUtils.remove(bi,true);
  11475. }
  11476. }
  11477. } else {
  11478. var tmpRange = range.cloneRange(),
  11479. node = tmpRange.startContainer.nodeType == 1 ? tmpRange.startContainer : tmpRange.startContainer.parentNode,
  11480. preNode = node,
  11481. doEnd = 1;
  11482. //调整开始
  11483. while ( 1 ) {
  11484. if ( domUtils.isBody(node) ) {
  11485. if ( preNode !== node ) {
  11486. if ( range.collapsed ) {
  11487. tmpRange.selectNode( preNode );
  11488. doEnd = 0;
  11489. } else {
  11490. tmpRange.setStartBefore( preNode );
  11491. }
  11492. }else{
  11493. tmpRange.setStart(node,0);
  11494. }
  11495. break;
  11496. }
  11497. if ( !blockquote[node.tagName] ) {
  11498. if ( range.collapsed ) {
  11499. tmpRange.selectNode( preNode );
  11500. } else{
  11501. tmpRange.setStartBefore( preNode);
  11502. }
  11503. break;
  11504. }
  11505. preNode = node;
  11506. node = node.parentNode;
  11507. }
  11508. //调整结束
  11509. if ( doEnd ) {
  11510. preNode = node = node = tmpRange.endContainer.nodeType == 1 ? tmpRange.endContainer : tmpRange.endContainer.parentNode;
  11511. while ( 1 ) {
  11512. if ( domUtils.isBody( node ) ) {
  11513. if ( preNode !== node ) {
  11514. tmpRange.setEndAfter( preNode );
  11515. } else {
  11516. tmpRange.setEnd( node, node.childNodes.length );
  11517. }
  11518. break;
  11519. }
  11520. if ( !blockquote[node.tagName] ) {
  11521. tmpRange.setEndAfter( preNode );
  11522. break;
  11523. }
  11524. preNode = node;
  11525. node = node.parentNode;
  11526. }
  11527. }
  11528. node = range.document.createElement( 'blockquote' );
  11529. domUtils.setAttributes( node, attrs );
  11530. node.appendChild( tmpRange.extractContents() );
  11531. tmpRange.insertNode( node );
  11532. //去除重复的
  11533. var childs = domUtils.getElementsByTagName(node,'blockquote');
  11534. for(var i=0,ci;ci=childs[i++];){
  11535. if(ci.parentNode){
  11536. domUtils.remove(ci,true);
  11537. }
  11538. }
  11539. }
  11540. range.moveToBookmark( bookmark ).select();
  11541. },
  11542. queryCommandState : function() {
  11543. return getObj(this) ? 1 : 0;
  11544. }
  11545. };
  11546. };
  11547. // plugins/convertcase.js
  11548. /**
  11549. * 大小写转换
  11550. * @file
  11551. * @since 1.2.6.1
  11552. */
  11553. /**
  11554. * 把选区内文本变大写,与“tolowercase”命令互斥
  11555. * @command touppercase
  11556. * @method execCommand
  11557. * @param { String } cmd 命令字符串
  11558. * @example
  11559. * ```javascript
  11560. * editor.execCommand( 'touppercase' );
  11561. * ```
  11562. */
  11563. /**
  11564. * 把选区内文本变小写,与“touppercase”命令互斥
  11565. * @command tolowercase
  11566. * @method execCommand
  11567. * @param { String } cmd 命令字符串
  11568. * @example
  11569. * ```javascript
  11570. * editor.execCommand( 'tolowercase' );
  11571. * ```
  11572. */
  11573. UE.commands['touppercase'] =
  11574. UE.commands['tolowercase'] = {
  11575. execCommand:function (cmd) {
  11576. var me = this;
  11577. var rng = me.selection.getRange();
  11578. if(rng.collapsed){
  11579. return rng;
  11580. }
  11581. var bk = rng.createBookmark(),
  11582. bkEnd = bk.end,
  11583. filterFn = function( node ) {
  11584. return !domUtils.isBr(node) && !domUtils.isWhitespace( node );
  11585. },
  11586. curNode = domUtils.getNextDomNode( bk.start, false, filterFn );
  11587. while ( curNode && (domUtils.getPosition( curNode, bkEnd ) & domUtils.POSITION_PRECEDING) ) {
  11588. if ( curNode.nodeType == 3 ) {
  11589. curNode.nodeValue = curNode.nodeValue[cmd == 'touppercase' ? 'toUpperCase' : 'toLowerCase']();
  11590. }
  11591. curNode = domUtils.getNextDomNode( curNode, true, filterFn );
  11592. if(curNode === bkEnd){
  11593. break;
  11594. }
  11595. }
  11596. rng.moveToBookmark(bk).select();
  11597. }
  11598. };
  11599. // plugins/indent.js
  11600. /**
  11601. * 首行缩进
  11602. * @file
  11603. * @since 1.2.6.1
  11604. */
  11605. /**
  11606. * 缩进
  11607. * @command indent
  11608. * @method execCommand
  11609. * @param { String } cmd 命令字符串
  11610. * @example
  11611. * ```javascript
  11612. * editor.execCommand( 'indent' );
  11613. * ```
  11614. */
  11615. UE.commands['indent'] = {
  11616. execCommand : function() {
  11617. var me = this,value = me.queryCommandState("indent") ? "0em" : (me.options.indentValue || '2em');
  11618. me.execCommand('Paragraph','p',{style:'text-indent:'+ value});
  11619. },
  11620. queryCommandState : function() {
  11621. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11622. return pN && pN.style.textIndent && parseInt(pN.style.textIndent) ? 1 : 0;
  11623. }
  11624. };
  11625. // plugins/print.js
  11626. /**
  11627. * 打印
  11628. * @file
  11629. * @since 1.2.6.1
  11630. */
  11631. /**
  11632. * 打印
  11633. * @command print
  11634. * @method execCommand
  11635. * @param { String } cmd 命令字符串
  11636. * @example
  11637. * ```javascript
  11638. * editor.execCommand( 'print' );
  11639. * ```
  11640. */
  11641. UE.commands['print'] = {
  11642. execCommand : function(){
  11643. this.window.print();
  11644. },
  11645. notNeedUndo : 1
  11646. };
  11647. // plugins/preview.js
  11648. /**
  11649. * 预览
  11650. * @file
  11651. * @since 1.2.6.1
  11652. */
  11653. /**
  11654. * 预览
  11655. * @command preview
  11656. * @method execCommand
  11657. * @param { String } cmd 命令字符串
  11658. * @example
  11659. * ```javascript
  11660. * editor.execCommand( 'preview' );
  11661. * ```
  11662. */
  11663. UE.commands['preview'] = {
  11664. execCommand : function(){
  11665. var w = window.open('', '_blank', ''),
  11666. d = w.document;
  11667. d.open();
  11668. d.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><script src="'+this.options.UEDITOR_HOME_URL+'ueditor.parse.js"></script><script>' +
  11669. "setTimeout(function(){uParse('div',{rootPath: '"+ this.options.UEDITOR_HOME_URL +"'})},300)" +
  11670. '</script></head><body><div>'+this.getContent(null,null,true)+'</div></body></html>');
  11671. d.close();
  11672. },
  11673. notNeedUndo : 1
  11674. };
  11675. // plugins/selectall.js
  11676. /**
  11677. * 全选
  11678. * @file
  11679. * @since 1.2.6.1
  11680. */
  11681. /**
  11682. * 选中所有内容
  11683. * @command selectall
  11684. * @method execCommand
  11685. * @param { String } cmd 命令字符串
  11686. * @example
  11687. * ```javascript
  11688. * editor.execCommand( 'selectall' );
  11689. * ```
  11690. */
  11691. UE.plugins['selectall'] = function(){
  11692. var me = this;
  11693. me.commands['selectall'] = {
  11694. execCommand : function(){
  11695. //去掉了原生的selectAll,因为会出现报错和当内容为空时,不能出现闭合状态的光标
  11696. var me = this,body = me.body,
  11697. range = me.selection.getRange();
  11698. range.selectNodeContents(body);
  11699. if(domUtils.isEmptyBlock(body)){
  11700. //opera不能自动合并到元素的里边,要手动处理一下
  11701. if(browser.opera && body.firstChild && body.firstChild.nodeType == 1){
  11702. range.setStartAtFirst(body.firstChild);
  11703. }
  11704. range.collapse(true);
  11705. }
  11706. range.select(true);
  11707. },
  11708. notNeedUndo : 1
  11709. };
  11710. //快捷键
  11711. me.addshortcutkey({
  11712. "selectAll" : "ctrl+65"
  11713. });
  11714. };
  11715. // plugins/paragraph.js
  11716. /**
  11717. * 段落样式
  11718. * @file
  11719. * @since 1.2.6.1
  11720. */
  11721. /**
  11722. * 段落格式
  11723. * @command paragraph
  11724. * @method execCommand
  11725. * @param { String } cmd 命令字符串
  11726. * @param {String} style 标签值为:'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
  11727. * @param {Object} attrs 标签的属性
  11728. * @example
  11729. * ```javascript
  11730. * editor.execCommand( 'Paragraph','h1','{
  11731. * class:'test'
  11732. * }' );
  11733. * ```
  11734. */
  11735. /**
  11736. * 返回选区内节点标签名
  11737. * @command paragraph
  11738. * @method queryCommandValue
  11739. * @param { String } cmd 命令字符串
  11740. * @return { String } 节点标签名
  11741. * @example
  11742. * ```javascript
  11743. * editor.queryCommandValue( 'Paragraph' );
  11744. * ```
  11745. */
  11746. UE.plugins['paragraph'] = function() {
  11747. var me = this,
  11748. block = domUtils.isBlockElm,
  11749. notExchange = ['TD','LI','PRE'],
  11750. doParagraph = function(range,style,attrs,sourceCmdName){
  11751. var bookmark = range.createBookmark(),
  11752. filterFn = function( node ) {
  11753. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' && !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace( node );
  11754. },
  11755. para;
  11756. range.enlarge( true );
  11757. var bookmark2 = range.createBookmark(),
  11758. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11759. tmpRange = range.cloneRange(),
  11760. tmpNode;
  11761. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11762. if ( current.nodeType == 3 || !block( current ) ) {
  11763. tmpRange.setStartBefore( current );
  11764. while ( current && current !== bookmark2.end && !block( current ) ) {
  11765. tmpNode = current;
  11766. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11767. return !block( node );
  11768. } );
  11769. }
  11770. tmpRange.setEndAfter( tmpNode );
  11771. para = range.document.createElement( style );
  11772. if(attrs){
  11773. domUtils.setAttributes(para,attrs);
  11774. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11775. para.style.cssText = attrs.style;
  11776. }
  11777. }
  11778. para.appendChild( tmpRange.extractContents() );
  11779. //需要内容占位
  11780. if(domUtils.isEmptyNode(para)){
  11781. domUtils.fillChar(range.document,para);
  11782. }
  11783. tmpRange.insertNode( para );
  11784. var parent = para.parentNode;
  11785. //如果para上一级是一个block元素且不是body,td就删除它
  11786. if ( block( parent ) && !domUtils.isBody( para.parentNode ) && utils.indexOf(notExchange,parent.tagName)==-1) {
  11787. //存储dir,style
  11788. if(!(sourceCmdName && sourceCmdName == 'customstyle')){
  11789. parent.getAttribute('dir') && para.setAttribute('dir',parent.getAttribute('dir'));
  11790. //trace:1070
  11791. parent.style.cssText && (para.style.cssText = parent.style.cssText + ';' + para.style.cssText);
  11792. //trace:1030
  11793. parent.style.textAlign && !para.style.textAlign && (para.style.textAlign = parent.style.textAlign);
  11794. parent.style.textIndent && !para.style.textIndent && (para.style.textIndent = parent.style.textIndent);
  11795. parent.style.padding && !para.style.padding && (para.style.padding = parent.style.padding);
  11796. }
  11797. //trace:1706 选择的就是h1-6要删除
  11798. if(attrs && /h\d/i.test(parent.tagName) && !/h\d/i.test(para.tagName) ){
  11799. domUtils.setAttributes(parent,attrs);
  11800. if(sourceCmdName && sourceCmdName == 'customstyle' && attrs.style){
  11801. parent.style.cssText = attrs.style;
  11802. }
  11803. domUtils.remove(para,true);
  11804. para = parent;
  11805. }else{
  11806. domUtils.remove( para.parentNode, true );
  11807. }
  11808. }
  11809. if( utils.indexOf(notExchange,parent.tagName)!=-1){
  11810. current = parent;
  11811. }else{
  11812. current = para;
  11813. }
  11814. current = domUtils.getNextDomNode( current, false, filterFn );
  11815. } else {
  11816. current = domUtils.getNextDomNode( current, true, filterFn );
  11817. }
  11818. }
  11819. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11820. };
  11821. me.setOpt('paragraph',{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''});
  11822. me.commands['paragraph'] = {
  11823. execCommand : function( cmdName, style,attrs,sourceCmdName ) {
  11824. var range = this.selection.getRange();
  11825. //闭合时单独处理
  11826. if(range.collapsed){
  11827. var txt = this.document.createTextNode('p');
  11828. range.insertNode(txt);
  11829. //去掉冗余的fillchar
  11830. if(browser.ie){
  11831. var node = txt.previousSibling;
  11832. if(node && domUtils.isWhitespace(node)){
  11833. domUtils.remove(node);
  11834. }
  11835. node = txt.nextSibling;
  11836. if(node && domUtils.isWhitespace(node)){
  11837. domUtils.remove(node);
  11838. }
  11839. }
  11840. }
  11841. range = doParagraph(range,style,attrs,sourceCmdName);
  11842. if(txt){
  11843. range.setStartBefore(txt).collapse(true);
  11844. pN = txt.parentNode;
  11845. domUtils.remove(txt);
  11846. if(domUtils.isBlockElm(pN)&&domUtils.isEmptyNode(pN)){
  11847. domUtils.fillNode(this.document,pN);
  11848. }
  11849. }
  11850. if(browser.gecko && range.collapsed && range.startContainer.nodeType == 1){
  11851. var child = range.startContainer.childNodes[range.startOffset];
  11852. if(child && child.nodeType == 1 && child.tagName.toLowerCase() == style){
  11853. range.setStart(child,0).collapse(true);
  11854. }
  11855. }
  11856. //trace:1097 原来有true,原因忘了,但去了就不能清除多余的占位符了
  11857. range.select();
  11858. return true;
  11859. },
  11860. queryCommandValue : function() {
  11861. var node = domUtils.filterNodeList(this.selection.getStartElementPath(),'p h1 h2 h3 h4 h5 h6');
  11862. return node ? node.tagName.toLowerCase() : '';
  11863. }
  11864. };
  11865. };
  11866. // plugins/directionality.js
  11867. /**
  11868. * 设置文字输入的方向的插件
  11869. * @file
  11870. * @since 1.2.6.1
  11871. */
  11872. (function() {
  11873. var block = domUtils.isBlockElm ,
  11874. getObj = function(editor){
  11875. // var startNode = editor.selection.getStart(),
  11876. // parents;
  11877. // if ( startNode ) {
  11878. // //查找所有的是block的父亲节点
  11879. // parents = domUtils.findParents( startNode, true, block, true );
  11880. // for ( var i = 0,ci; ci = parents[i++]; ) {
  11881. // if ( ci.getAttribute( 'dir' ) ) {
  11882. // return ci;
  11883. // }
  11884. // }
  11885. // }
  11886. return domUtils.filterNodeList(editor.selection.getStartElementPath(),function(n){return n && n.nodeType == 1 && n.getAttribute('dir')});
  11887. },
  11888. doDirectionality = function(range,editor,forward){
  11889. var bookmark,
  11890. filterFn = function( node ) {
  11891. return node.nodeType == 1 ? !domUtils.isBookmarkNode(node) : !domUtils.isWhitespace(node);
  11892. },
  11893. obj = getObj( editor );
  11894. if ( obj && range.collapsed ) {
  11895. obj.setAttribute( 'dir', forward );
  11896. return range;
  11897. }
  11898. bookmark = range.createBookmark();
  11899. range.enlarge( true );
  11900. var bookmark2 = range.createBookmark(),
  11901. current = domUtils.getNextDomNode( bookmark2.start, false, filterFn ),
  11902. tmpRange = range.cloneRange(),
  11903. tmpNode;
  11904. while ( current && !(domUtils.getPosition( current, bookmark2.end ) & domUtils.POSITION_FOLLOWING) ) {
  11905. if ( current.nodeType == 3 || !block( current ) ) {
  11906. tmpRange.setStartBefore( current );
  11907. while ( current && current !== bookmark2.end && !block( current ) ) {
  11908. tmpNode = current;
  11909. current = domUtils.getNextDomNode( current, false, null, function( node ) {
  11910. return !block( node );
  11911. } );
  11912. }
  11913. tmpRange.setEndAfter( tmpNode );
  11914. var common = tmpRange.getCommonAncestor();
  11915. if ( !domUtils.isBody( common ) && block( common ) ) {
  11916. //遍历到了block节点
  11917. common.setAttribute( 'dir', forward );
  11918. current = common;
  11919. } else {
  11920. //没有遍历到,添加一个block节点
  11921. var p = range.document.createElement( 'p' );
  11922. p.setAttribute( 'dir', forward );
  11923. var frag = tmpRange.extractContents();
  11924. p.appendChild( frag );
  11925. tmpRange.insertNode( p );
  11926. current = p;
  11927. }
  11928. current = domUtils.getNextDomNode( current, false, filterFn );
  11929. } else {
  11930. current = domUtils.getNextDomNode( current, true, filterFn );
  11931. }
  11932. }
  11933. return range.moveToBookmark( bookmark2 ).moveToBookmark( bookmark );
  11934. };
  11935. /**
  11936. * 文字输入方向
  11937. * @command directionality
  11938. * @method execCommand
  11939. * @param { String } cmdName 命令字符串
  11940. * @param { String } forward 传入'ltr'表示从左向右输入,传入'rtl'表示从右向左输入
  11941. * @example
  11942. * ```javascript
  11943. * editor.execCommand( 'directionality', 'ltr');
  11944. * ```
  11945. */
  11946. /**
  11947. * 查询当前选区的文字输入方向
  11948. * @command directionality
  11949. * @method queryCommandValue
  11950. * @param { String } cmdName 命令字符串
  11951. * @return { String } 返回'ltr'表示从左向右输入,返回'rtl'表示从右向左输入
  11952. * @example
  11953. * ```javascript
  11954. * editor.queryCommandValue( 'directionality');
  11955. * ```
  11956. */
  11957. UE.commands['directionality'] = {
  11958. execCommand : function( cmdName,forward ) {
  11959. var range = this.selection.getRange();
  11960. //闭合时单独处理
  11961. if(range.collapsed){
  11962. var txt = this.document.createTextNode('d');
  11963. range.insertNode(txt);
  11964. }
  11965. doDirectionality(range,this,forward);
  11966. if(txt){
  11967. range.setStartBefore(txt).collapse(true);
  11968. domUtils.remove(txt);
  11969. }
  11970. range.select();
  11971. return true;
  11972. },
  11973. queryCommandValue : function() {
  11974. var node = getObj(this);
  11975. return node ? node.getAttribute('dir') : 'ltr';
  11976. }
  11977. };
  11978. })();
  11979. // plugins/horizontal.js
  11980. /**
  11981. * 插入分割线插件
  11982. * @file
  11983. * @since 1.2.6.1
  11984. */
  11985. /**
  11986. * 插入分割线
  11987. * @command horizontal
  11988. * @method execCommand
  11989. * @param { String } cmdName 命令字符串
  11990. * @example
  11991. * ```javascript
  11992. * editor.execCommand( 'horizontal' );
  11993. * ```
  11994. */
  11995. UE.plugins['horizontal'] = function(){
  11996. var me = this;
  11997. me.commands['horizontal'] = {
  11998. execCommand : function( cmdName ) {
  11999. var me = this;
  12000. if(me.queryCommandState(cmdName)!==-1){
  12001. me.execCommand('insertHtml','<hr>');
  12002. var range = me.selection.getRange(),
  12003. start = range.startContainer;
  12004. if(start.nodeType == 1 && !start.childNodes[range.startOffset] ){
  12005. var tmp;
  12006. if(tmp = start.childNodes[range.startOffset - 1]){
  12007. if(tmp.nodeType == 1 && tmp.tagName == 'HR'){
  12008. if(me.options.enterTag == 'p'){
  12009. tmp = me.document.createElement('p');
  12010. range.insertNode(tmp);
  12011. range.setStart(tmp,0).setCursor();
  12012. }else{
  12013. tmp = me.document.createElement('br');
  12014. range.insertNode(tmp);
  12015. range.setStartBefore(tmp).setCursor();
  12016. }
  12017. }
  12018. }
  12019. }
  12020. return true;
  12021. }
  12022. },
  12023. //边界在table里不能加分隔线
  12024. queryCommandState : function() {
  12025. return domUtils.filterNodeList(this.selection.getStartElementPath(),'table') ? -1 : 0;
  12026. }
  12027. };
  12028. // me.addListener('delkeyup',function(){
  12029. // var rng = this.selection.getRange();
  12030. // if(browser.ie && browser.version > 8){
  12031. // rng.txtToElmBoundary(true);
  12032. // if(domUtils.isStartInblock(rng)){
  12033. // var tmpNode = rng.startContainer;
  12034. // var pre = tmpNode.previousSibling;
  12035. // if(pre && domUtils.isTagNode(pre,'hr')){
  12036. // domUtils.remove(pre);
  12037. // rng.select();
  12038. // return;
  12039. // }
  12040. // }
  12041. // }
  12042. // if(domUtils.isBody(rng.startContainer)){
  12043. // var hr = rng.startContainer.childNodes[rng.startOffset -1];
  12044. // if(hr && hr.nodeName == 'HR'){
  12045. // var next = hr.nextSibling;
  12046. // if(next){
  12047. // rng.setStart(next,0)
  12048. // }else if(hr.previousSibling){
  12049. // rng.setStartAtLast(hr.previousSibling)
  12050. // }else{
  12051. // var p = this.document.createElement('p');
  12052. // hr.parentNode.insertBefore(p,hr);
  12053. // domUtils.fillNode(this.document,p);
  12054. // rng.setStart(p,0);
  12055. // }
  12056. // domUtils.remove(hr);
  12057. // rng.setCursor(false,true);
  12058. // }
  12059. // }
  12060. // })
  12061. me.addListener('delkeydown',function(name,evt){
  12062. var rng = this.selection.getRange();
  12063. rng.txtToElmBoundary(true);
  12064. if(domUtils.isStartInblock(rng)){
  12065. var tmpNode = rng.startContainer;
  12066. var pre = tmpNode.previousSibling;
  12067. if(pre && domUtils.isTagNode(pre,'hr')){
  12068. domUtils.remove(pre);
  12069. rng.select();
  12070. domUtils.preventDefault(evt);
  12071. return true;
  12072. }
  12073. }
  12074. })
  12075. };
  12076. // plugins/time.js
  12077. /**
  12078. * 插入时间和日期
  12079. * @file
  12080. * @since 1.2.6.1
  12081. */
  12082. /**
  12083. * 插入时间,默认格式:12:59:59
  12084. * @command time
  12085. * @method execCommand
  12086. * @param { String } cmd 命令字符串
  12087. * @example
  12088. * ```javascript
  12089. * editor.execCommand( 'time');
  12090. * ```
  12091. */
  12092. /**
  12093. * 插入日期,默认格式:2013-08-30
  12094. * @command date
  12095. * @method execCommand
  12096. * @param { String } cmd 命令字符串
  12097. * @example
  12098. * ```javascript
  12099. * editor.execCommand( 'date');
  12100. * ```
  12101. */
  12102. UE.commands['time'] = UE.commands["date"] = {
  12103. execCommand : function(cmd, format){
  12104. var date = new Date;
  12105. function formatTime(date, format) {
  12106. var hh = ('0' + date.getHours()).slice(-2),
  12107. ii = ('0' + date.getMinutes()).slice(-2),
  12108. ss = ('0' + date.getSeconds()).slice(-2);
  12109. format = format || 'hh:ii:ss';
  12110. return format.replace(/hh/ig, hh).replace(/ii/ig, ii).replace(/ss/ig, ss);
  12111. }
  12112. function formatDate(date, format) {
  12113. var yyyy = ('000' + date.getFullYear()).slice(-4),
  12114. yy = yyyy.slice(-2),
  12115. mm = ('0' + (date.getMonth()+1)).slice(-2),
  12116. dd = ('0' + date.getDate()).slice(-2);
  12117. format = format || 'yyyy-mm-dd';
  12118. return format.replace(/yyyy/ig, yyyy).replace(/yy/ig, yy).replace(/mm/ig, mm).replace(/dd/ig, dd);
  12119. }
  12120. this.execCommand('insertHtml',cmd == "time" ? formatTime(date, format):formatDate(date, format) );
  12121. }
  12122. };
  12123. // plugins/rowspacing.js
  12124. /**
  12125. * 段前段后间距插件
  12126. * @file
  12127. * @since 1.2.6.1
  12128. */
  12129. /**
  12130. * 设置段间距
  12131. * @command rowspacing
  12132. * @method execCommand
  12133. * @param { String } cmd 命令字符串
  12134. * @param { String } value 段间距的值,以px为单位
  12135. * @param { String } dir 间距位置,top或bottom,分别表示段前和段后
  12136. * @example
  12137. * ```javascript
  12138. * editor.execCommand( 'rowspacing', '10', 'top' );
  12139. * ```
  12140. */
  12141. UE.plugins['rowspacing'] = function(){
  12142. var me = this;
  12143. me.setOpt({
  12144. 'rowspacingtop':['5', '10', '15', '20', '25'],
  12145. 'rowspacingbottom':['5', '10', '15', '20', '25']
  12146. });
  12147. me.commands['rowspacing'] = {
  12148. execCommand : function( cmdName,value,dir ) {
  12149. this.execCommand('paragraph','p',{style:'margin-'+dir+':'+value + 'px'});
  12150. return true;
  12151. },
  12152. queryCommandValue : function(cmdName,dir) {
  12153. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node) }),
  12154. value;
  12155. //trace:1026
  12156. if(pN){
  12157. value = domUtils.getComputedStyle(pN,'margin-'+dir).replace(/[^\d]/g,'');
  12158. return !value ? 0 : value;
  12159. }
  12160. return 0;
  12161. }
  12162. };
  12163. };
  12164. // plugins/lineheight.js
  12165. /**
  12166. * 设置行内间距
  12167. * @file
  12168. * @since 1.2.6.1
  12169. */
  12170. UE.plugins['lineheight'] = function(){
  12171. var me = this;
  12172. me.setOpt({'lineheight':['1', '1.5','1.75','2', '3', '4', '5']});
  12173. /**
  12174. * 行距
  12175. * @command lineheight
  12176. * @method execCommand
  12177. * @param { String } cmdName 命令字符串
  12178. * @param { String } value 传入的行高值, 该值是当前字体的倍数, 例如: 1.5, 1.75
  12179. * @example
  12180. * ```javascript
  12181. * editor.execCommand( 'lineheight', 1.5);
  12182. * ```
  12183. */
  12184. /**
  12185. * 查询当前选区内容的行高大小
  12186. * @command lineheight
  12187. * @method queryCommandValue
  12188. * @param { String } cmd 命令字符串
  12189. * @return { String } 返回当前行高大小
  12190. * @example
  12191. * ```javascript
  12192. * editor.queryCommandValue( 'lineheight' );
  12193. * ```
  12194. */
  12195. me.commands['lineheight'] = {
  12196. execCommand : function( cmdName,value ) {
  12197. this.execCommand('paragraph','p',{style:'line-height:'+ (value == "1" ? "normal" : value + 'em') });
  12198. return true;
  12199. },
  12200. queryCommandValue : function() {
  12201. var pN = domUtils.filterNodeList(this.selection.getStartElementPath(),function(node){return domUtils.isBlockElm(node)});
  12202. if(pN){
  12203. var value = domUtils.getComputedStyle(pN,'line-height');
  12204. return value == 'normal' ? 1 : value.replace(/[^\d.]*/ig,"");
  12205. }
  12206. }
  12207. };
  12208. };
  12209. // plugins/insertcode.js
  12210. /**
  12211. * 插入代码插件
  12212. * @file
  12213. * @since 1.2.6.1
  12214. */
  12215. UE.plugins['insertcode'] = function() {
  12216. var me = this;
  12217. me.ready(function(){
  12218. utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}',
  12219. me.document)
  12220. });
  12221. me.setOpt('insertcode',{
  12222. 'as3':'ActionScript3',
  12223. 'bash':'Bash/Shell',
  12224. 'cpp':'C/C++',
  12225. 'css':'Css',
  12226. 'cf':'CodeFunction',
  12227. 'c#':'C#',
  12228. 'delphi':'Delphi',
  12229. 'diff':'Diff',
  12230. 'erlang':'Erlang',
  12231. 'groovy':'Groovy',
  12232. 'html':'Html',
  12233. 'java':'Java',
  12234. 'jfx':'JavaFx',
  12235. 'js':'Javascript',
  12236. 'pl':'Perl',
  12237. 'php':'Php',
  12238. 'plain':'Plain Text',
  12239. 'ps':'PowerShell',
  12240. 'python':'Python',
  12241. 'ruby':'Ruby',
  12242. 'scala':'Scala',
  12243. 'sql':'Sql',
  12244. 'vb':'Vb',
  12245. 'xml':'Xml'
  12246. });
  12247. /**
  12248. * 插入代码
  12249. * @command insertcode
  12250. * @method execCommand
  12251. * @param { String } cmd 命令字符串
  12252. * @param { String } lang 插入代码的语言
  12253. * @example
  12254. * ```javascript
  12255. * editor.execCommand( 'insertcode', 'javascript' );
  12256. * ```
  12257. */
  12258. /**
  12259. * 如果选区所在位置是插入插入代码区域,返回代码的语言
  12260. * @command insertcode
  12261. * @method queryCommandValue
  12262. * @param { String } cmd 命令字符串
  12263. * @return { String } 返回代码的语言
  12264. * @example
  12265. * ```javascript
  12266. * editor.queryCommandValue( 'insertcode' );
  12267. * ```
  12268. */
  12269. me.commands['insertcode'] = {
  12270. execCommand : function(cmd,lang){
  12271. var me = this,
  12272. rng = me.selection.getRange(),
  12273. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12274. if(pre){
  12275. pre.className = 'brush:'+lang+';toolbar:false;';
  12276. }else{
  12277. var code = '';
  12278. if(rng.collapsed){
  12279. code = browser.ie && browser.ie11below ? (browser.version <= 8 ? '&nbsp;':''):'<br/>';
  12280. }else{
  12281. var frag = rng.extractContents();
  12282. var div = me.document.createElement('div');
  12283. div.appendChild(frag);
  12284. utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){
  12285. if(browser.ie && browser.ie11below && browser.version > 8){
  12286. if(node.type =='element'){
  12287. if(node.tagName == 'br'){
  12288. code += '\n'
  12289. }else if(!dtd.$empty[node.tagName]){
  12290. utils.each(node.children,function(cn){
  12291. if(cn.type =='element'){
  12292. if(cn.tagName == 'br'){
  12293. code += '\n'
  12294. }else if(!dtd.$empty[node.tagName]){
  12295. code += cn.innerText();
  12296. }
  12297. }else{
  12298. code += cn.data
  12299. }
  12300. })
  12301. if(!/\n$/.test(code)){
  12302. code += '\n';
  12303. }
  12304. }
  12305. }else{
  12306. code += node.data + '\n'
  12307. }
  12308. if(!node.nextSibling() && /\n$/.test(code)){
  12309. code = code.replace(/\n$/,'');
  12310. }
  12311. }else{
  12312. if(browser.ie && browser.ie11below){
  12313. if(node.type =='element'){
  12314. if(node.tagName == 'br'){
  12315. code += '<br>'
  12316. }else if(!dtd.$empty[node.tagName]){
  12317. utils.each(node.children,function(cn){
  12318. if(cn.type =='element'){
  12319. if(cn.tagName == 'br'){
  12320. code += '<br>'
  12321. }else if(!dtd.$empty[node.tagName]){
  12322. code += cn.innerText();
  12323. }
  12324. }else{
  12325. code += cn.data
  12326. }
  12327. });
  12328. if(!/br>$/.test(code)){
  12329. code += '<br>';
  12330. }
  12331. }
  12332. }else{
  12333. code += node.data + '<br>'
  12334. }
  12335. if(!node.nextSibling() && /<br>$/.test(code)){
  12336. code = code.replace(/<br>$/,'');
  12337. }
  12338. }else{
  12339. code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data);
  12340. if(!/br\/?\s*>$/.test(code)){
  12341. if(!node.nextSibling())
  12342. return;
  12343. code += '<br>'
  12344. }
  12345. }
  12346. }
  12347. });
  12348. }
  12349. me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true);
  12350. pre = me.document.getElementById('coder');
  12351. domUtils.removeAttributes(pre,'id');
  12352. var tmpNode = pre.previousSibling;
  12353. if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){
  12354. domUtils.remove(tmpNode)
  12355. }
  12356. var rng = me.selection.getRange();
  12357. if(domUtils.isEmptyBlock(pre)){
  12358. rng.setStart(pre,0).setCursor(false,true)
  12359. }else{
  12360. rng.selectNodeContents(pre).select()
  12361. }
  12362. }
  12363. },
  12364. queryCommandValue : function(){
  12365. var path = this.selection.getStartElementPath();
  12366. var lang = '';
  12367. utils.each(path,function(node){
  12368. if(node.nodeName =='PRE'){
  12369. var match = node.className.match(/brush:([^;]+)/);
  12370. lang = match && match[1] ? match[1] : '';
  12371. return false;
  12372. }
  12373. });
  12374. return lang;
  12375. }
  12376. };
  12377. me.addInputRule(function(root){
  12378. utils.each(root.getNodesByTagName('pre'),function(pre){
  12379. var brs = pre.getNodesByTagName('br');
  12380. if(brs.length){
  12381. browser.ie && browser.ie11below && browser.version > 8 && utils.each(brs,function(br){
  12382. var txt = UE.uNode.createText('\n');
  12383. br.parentNode.insertBefore(txt,br);
  12384. br.parentNode.removeChild(br);
  12385. });
  12386. return;
  12387. }
  12388. if(browser.ie && browser.ie11below && browser.version > 8)
  12389. return;
  12390. var code = pre.innerText().split(/\n/);
  12391. pre.innerHTML('');
  12392. utils.each(code,function(c){
  12393. if(c.length){
  12394. pre.appendChild(UE.uNode.createText(c));
  12395. }
  12396. pre.appendChild(UE.uNode.createElement('br'))
  12397. })
  12398. })
  12399. });
  12400. me.addOutputRule(function(root){
  12401. utils.each(root.getNodesByTagName('pre'),function(pre){
  12402. var code = '';
  12403. utils.each(pre.children,function(n){
  12404. if(n.type == 'text'){
  12405. //在ie下文本内容有可能末尾带有\n要去掉
  12406. //trace:3396
  12407. code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,'');
  12408. }else{
  12409. if(n.tagName == 'br'){
  12410. code += '\n'
  12411. }else{
  12412. code += (!dtd.$empty[n.tagName] ? '' : n.innerText());
  12413. }
  12414. }
  12415. });
  12416. pre.innerText(code.replace(/(&nbsp;|\n)+$/,''))
  12417. })
  12418. });
  12419. //不需要判断highlight的command列表
  12420. me.notNeedCodeQuery ={
  12421. help:1,
  12422. undo:1,
  12423. redo:1,
  12424. source:1,
  12425. print:1,
  12426. searchreplace:1,
  12427. fullscreen:1,
  12428. preview:1,
  12429. insertparagraph:1,
  12430. elementpath:1,
  12431. insertcode:1,
  12432. inserthtml:1,
  12433. selectall:1
  12434. };
  12435. //将queyCommamndState重置
  12436. var orgQuery = me.queryCommandState;
  12437. me.queryCommandState = function(cmd){
  12438. var me = this;
  12439. if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){
  12440. return -1;
  12441. }
  12442. return UE.Editor.prototype.queryCommandState.apply(this,arguments)
  12443. };
  12444. me.addListener('beforeenterkeydown',function(){
  12445. var rng = me.selection.getRange();
  12446. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12447. if(pre){
  12448. me.fireEvent('saveScene');
  12449. if(!rng.collapsed){
  12450. rng.deleteContents();
  12451. }
  12452. if(!browser.ie || browser.ie9above){
  12453. var tmpNode = me.document.createElement('br'),pre;
  12454. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true);
  12455. var next = tmpNode.nextSibling;
  12456. if(!next && (!browser.ie || browser.version > 10)){
  12457. rng.insertNode(tmpNode.cloneNode(false));
  12458. }else{
  12459. rng.setStartAfter(tmpNode);
  12460. }
  12461. pre = tmpNode.previousSibling;
  12462. var tmp;
  12463. while(pre ){
  12464. tmp = pre;
  12465. pre = pre.previousSibling;
  12466. if(!pre || pre.nodeName == 'BR'){
  12467. pre = tmp;
  12468. break;
  12469. }
  12470. }
  12471. if(pre){
  12472. var str = '';
  12473. while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12474. str += pre.nodeValue;
  12475. pre = pre.nextSibling;
  12476. }
  12477. if(pre.nodeName != 'BR'){
  12478. var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)'));
  12479. if(match && match[1]){
  12480. str += match[1]
  12481. }
  12482. }
  12483. if(str){
  12484. str = me.document.createTextNode(str);
  12485. rng.insertNode(str).setStartAfter(str);
  12486. }
  12487. }
  12488. rng.collapse(true).select(true);
  12489. }else{
  12490. if(browser.version > 8){
  12491. var txt = me.document.createTextNode('\n');
  12492. var start = rng.startContainer;
  12493. if(rng.startOffset == 0){
  12494. var preNode = start.previousSibling;
  12495. if(preNode){
  12496. rng.insertNode(txt);
  12497. var fillchar = me.document.createTextNode(' ');
  12498. rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12499. }
  12500. }else{
  12501. rng.insertNode(txt).setStartAfter(txt);
  12502. var fillchar = me.document.createTextNode(' ');
  12503. start = rng.startContainer.childNodes[rng.startOffset];
  12504. if(start && !/^\n/.test(start.nodeValue)){
  12505. rng.setStartBefore(txt)
  12506. }
  12507. rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true)
  12508. }
  12509. }else{
  12510. var tmpNode = me.document.createElement('br');
  12511. rng.insertNode(tmpNode);
  12512. rng.insertNode(me.document.createTextNode(domUtils.fillChar));
  12513. rng.setStartAfter(tmpNode);
  12514. pre = tmpNode.previousSibling;
  12515. var tmp;
  12516. while(pre ){
  12517. tmp = pre;
  12518. pre = pre.previousSibling;
  12519. if(!pre || pre.nodeName == 'BR'){
  12520. pre = tmp;
  12521. break;
  12522. }
  12523. }
  12524. if(pre){
  12525. var str = '';
  12526. while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  12527. str += pre.nodeValue;
  12528. pre = pre.nextSibling;
  12529. }
  12530. if(pre.nodeName != 'BR'){
  12531. var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)'));
  12532. if(match && match[1]){
  12533. str += match[1]
  12534. }
  12535. }
  12536. str = me.document.createTextNode(str);
  12537. rng.insertNode(str).setStartAfter(str);
  12538. }
  12539. rng.collapse(true).select();
  12540. }
  12541. }
  12542. me.fireEvent('saveScene');
  12543. return true;
  12544. }
  12545. });
  12546. me.addListener('tabkeydown',function(cmd,evt){
  12547. var rng = me.selection.getRange();
  12548. var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12549. if(pre){
  12550. me.fireEvent('saveScene');
  12551. if(evt.shiftKey){
  12552. }else{
  12553. if(!rng.collapsed){
  12554. var bk = rng.createBookmark();
  12555. var start = bk.start.previousSibling;
  12556. while(start){
  12557. if(pre.firstChild === start && !domUtils.isBr(start)){
  12558. pre.insertBefore(me.document.createTextNode(' '),start);
  12559. break;
  12560. }
  12561. if(domUtils.isBr(start)){
  12562. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling);
  12563. break;
  12564. }
  12565. start = start.previousSibling;
  12566. }
  12567. var end = bk.end;
  12568. start = bk.start.nextSibling;
  12569. if(pre.firstChild === bk.start){
  12570. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12571. }
  12572. while(start && start !== end){
  12573. if(domUtils.isBr(start) && start.nextSibling){
  12574. if(start.nextSibling === end){
  12575. break;
  12576. }
  12577. pre.insertBefore(me.document.createTextNode(' '),start.nextSibling)
  12578. }
  12579. start = start.nextSibling;
  12580. }
  12581. rng.moveToBookmark(bk).select();
  12582. }else{
  12583. var tmpNode = me.document.createTextNode(' ');
  12584. rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true);
  12585. }
  12586. }
  12587. me.fireEvent('saveScene');
  12588. return true;
  12589. }
  12590. });
  12591. me.addListener('beforeinserthtml',function(evtName,html){
  12592. var me = this,
  12593. rng = me.selection.getRange(),
  12594. pre = domUtils.findParentByTagName(rng.startContainer,'pre',true);
  12595. if(pre){
  12596. if(!rng.collapsed){
  12597. rng.deleteContents()
  12598. }
  12599. var htmlstr = '';
  12600. if(browser.ie && browser.version > 8){
  12601. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12602. if(node.type =='element'){
  12603. if(node.tagName == 'br'){
  12604. htmlstr += '\n'
  12605. }else if(!dtd.$empty[node.tagName]){
  12606. utils.each(node.children,function(cn){
  12607. if(cn.type =='element'){
  12608. if(cn.tagName == 'br'){
  12609. htmlstr += '\n'
  12610. }else if(!dtd.$empty[node.tagName]){
  12611. htmlstr += cn.innerText();
  12612. }
  12613. }else{
  12614. htmlstr += cn.data
  12615. }
  12616. })
  12617. if(!/\n$/.test(htmlstr)){
  12618. htmlstr += '\n';
  12619. }
  12620. }
  12621. }else{
  12622. htmlstr += node.data + '\n'
  12623. }
  12624. if(!node.nextSibling() && /\n$/.test(htmlstr)){
  12625. htmlstr = htmlstr.replace(/\n$/,'');
  12626. }
  12627. });
  12628. var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' ')));
  12629. rng.insertNode(tmpNode).selectNode(tmpNode).select();
  12630. }else{
  12631. var frag = me.document.createDocumentFragment();
  12632. utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){
  12633. if(node.type =='element'){
  12634. if(node.tagName == 'br'){
  12635. frag.appendChild(me.document.createElement('br'))
  12636. }else if(!dtd.$empty[node.tagName]){
  12637. utils.each(node.children,function(cn){
  12638. if(cn.type =='element'){
  12639. if(cn.tagName == 'br'){
  12640. frag.appendChild(me.document.createElement('br'))
  12641. }else if(!dtd.$empty[node.tagName]){
  12642. frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' '))));
  12643. }
  12644. }else{
  12645. frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' '))));
  12646. }
  12647. })
  12648. if(frag.lastChild.nodeName != 'BR'){
  12649. frag.appendChild(me.document.createElement('br'))
  12650. }
  12651. }
  12652. }else{
  12653. frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' '))));
  12654. }
  12655. if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){
  12656. frag.removeChild(frag.lastChild)
  12657. }
  12658. });
  12659. rng.insertNode(frag).select();
  12660. }
  12661. return true;
  12662. }
  12663. });
  12664. //方向键的处理
  12665. me.addListener('keydown',function(cmd,evt){
  12666. var me = this,keyCode = evt.keyCode || evt.which;
  12667. if(keyCode == 40){
  12668. var rng = me.selection.getRange(),pre,start = rng.startContainer;
  12669. if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){
  12670. var last = pre.lastChild
  12671. while(last && last.nodeName == 'BR'){
  12672. last = last.previousSibling;
  12673. }
  12674. if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){
  12675. me.execCommand('insertparagraph');
  12676. domUtils.preventDefault(evt)
  12677. }
  12678. }
  12679. }
  12680. });
  12681. //trace:3395
  12682. me.addListener('delkeydown',function(type,evt){
  12683. var rng = this.selection.getRange();
  12684. rng.txtToElmBoundary(true);
  12685. var start = rng.startContainer;
  12686. if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){
  12687. var p = me.document.createElement('p');
  12688. domUtils.fillNode(me.document,p);
  12689. start.parentNode.insertBefore(p,start);
  12690. domUtils.remove(start);
  12691. rng.setStart(p,0).setCursor(false,true);
  12692. domUtils.preventDefault(evt);
  12693. return true;
  12694. }
  12695. })
  12696. };
  12697. // plugins/cleardoc.js
  12698. /**
  12699. * 清空文档插件
  12700. * @file
  12701. * @since 1.2.6.1
  12702. */
  12703. /**
  12704. * 清空文档
  12705. * @command cleardoc
  12706. * @method execCommand
  12707. * @param { String } cmd 命令字符串
  12708. * @example
  12709. * ```javascript
  12710. * //editor 是编辑器实例
  12711. * editor.execCommand('cleardoc');
  12712. * ```
  12713. */
  12714. UE.commands['cleardoc'] = {
  12715. execCommand : function( cmdName) {
  12716. var me = this,
  12717. enterTag = me.options.enterTag,
  12718. range = me.selection.getRange();
  12719. if(enterTag == "br"){
  12720. me.body.innerHTML = "<br/>";
  12721. range.setStart(me.body,0).setCursor();
  12722. }else{
  12723. me.body.innerHTML = "<p>"+(ie ? "" : "<br/>")+"</p>";
  12724. range.setStart(me.body.firstChild,0).setCursor(false,true);
  12725. }
  12726. setTimeout(function(){
  12727. me.fireEvent("clearDoc");
  12728. },0);
  12729. }
  12730. };
  12731. // plugins/anchor.js
  12732. /**
  12733. * 锚点插件,为UEditor提供插入锚点支持
  12734. * @file
  12735. * @since 1.2.6.1
  12736. */
  12737. UE.plugin.register('anchor', function (){
  12738. return {
  12739. bindEvents:{
  12740. 'ready':function(){
  12741. utils.cssRule('anchor',
  12742. '.anchorclass{background: url(\''
  12743. + this.options.themePath
  12744. + this.options.theme +'/images/anchor.gif\') no-repeat scroll left center transparent;cursor: auto;display: inline-block;height: 16px;width: 15px;}',
  12745. this.document);
  12746. }
  12747. },
  12748. outputRule: function(root){
  12749. utils.each(root.getNodesByTagName('img'),function(a){
  12750. var val;
  12751. if(val = a.getAttr('anchorname')){
  12752. a.tagName = 'a';
  12753. a.setAttr({
  12754. anchorname : '',
  12755. name : val,
  12756. 'class' : ''
  12757. })
  12758. }
  12759. })
  12760. },
  12761. inputRule:function(root){
  12762. utils.each(root.getNodesByTagName('a'),function(a){
  12763. var val;
  12764. if((val = a.getAttr('name')) && !a.getAttr('href')){
  12765. a.tagName = 'img';
  12766. a.setAttr({
  12767. anchorname :a.getAttr('name'),
  12768. 'class' : 'anchorclass'
  12769. });
  12770. a.setAttr('name')
  12771. }
  12772. })
  12773. },
  12774. commands:{
  12775. /**
  12776. * 插入锚点
  12777. * @command anchor
  12778. * @method execCommand
  12779. * @param { String } cmd 命令字符串
  12780. * @param { String } name 锚点名称字符串
  12781. * @example
  12782. * ```javascript
  12783. * //editor 是编辑器实例
  12784. * editor.execCommand('anchor', 'anchor1');
  12785. * ```
  12786. */
  12787. 'anchor':{
  12788. execCommand:function (cmd, name) {
  12789. var range = this.selection.getRange(),img = range.getClosedNode();
  12790. if (img && img.getAttribute('anchorname')) {
  12791. if (name) {
  12792. img.setAttribute('anchorname', name);
  12793. } else {
  12794. range.setStartBefore(img).setCursor();
  12795. domUtils.remove(img);
  12796. }
  12797. } else {
  12798. if (name) {
  12799. //只在选区的开始插入
  12800. var anchor = this.document.createElement('img');
  12801. range.collapse(true);
  12802. domUtils.setAttributes(anchor,{
  12803. 'anchorname':name,
  12804. 'class':'anchorclass'
  12805. });
  12806. range.insertNode(anchor).setStartAfter(anchor).setCursor(false,true);
  12807. }
  12808. }
  12809. }
  12810. }
  12811. }
  12812. }
  12813. });
  12814. // plugins/wordcount.js
  12815. ///import core
  12816. ///commands 字数统计
  12817. ///commandsName WordCount,wordCount
  12818. ///commandsTitle 字数统计
  12819. /*
  12820. * Created by JetBrains WebStorm.
  12821. * User: taoqili
  12822. * Date: 11-9-7
  12823. * Time: 下午8:18
  12824. * To change this template use File | Settings | File Templates.
  12825. */
  12826. UE.plugins['wordcount'] = function(){
  12827. var me = this;
  12828. me.setOpt('wordCount',true);
  12829. me.addListener('contentchange',function(){
  12830. me.fireEvent('wordcount');
  12831. });
  12832. var timer;
  12833. me.addListener('ready',function(){
  12834. var me = this;
  12835. domUtils.on(me.body,"keyup",function(evt){
  12836. var code = evt.keyCode||evt.which,
  12837. //忽略的按键,ctr,alt,shift,方向键
  12838. ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1};
  12839. if(code in ignores) return;
  12840. clearTimeout(timer);
  12841. timer = setTimeout(function(){
  12842. me.fireEvent('wordcount');
  12843. },200)
  12844. })
  12845. });
  12846. };
  12847. // plugins/pagebreak.js
  12848. /**
  12849. * 分页功能插件
  12850. * @file
  12851. * @since 1.2.6.1
  12852. */
  12853. UE.plugins['pagebreak'] = function () {
  12854. var me = this,
  12855. notBreakTags = ['td'];
  12856. me.setOpt('pageBreakTag','_ueditor_page_break_tag_');
  12857. function fillNode(node){
  12858. if(domUtils.isEmptyBlock(node)){
  12859. var firstChild = node.firstChild,tmpNode;
  12860. while(firstChild && firstChild.nodeType == 1 && domUtils.isEmptyBlock(firstChild)){
  12861. tmpNode = firstChild;
  12862. firstChild = firstChild.firstChild;
  12863. }
  12864. !tmpNode && (tmpNode = node);
  12865. domUtils.fillNode(me.document,tmpNode);
  12866. }
  12867. }
  12868. //分页符样式添加
  12869. me.ready(function(){
  12870. utils.cssRule('pagebreak','.pagebreak{display:block;clear:both !important;cursor:default !important;width: 100% !important;margin:0;}',me.document);
  12871. });
  12872. function isHr(node){
  12873. return node && node.nodeType == 1 && node.tagName == 'HR' && node.className == 'pagebreak';
  12874. }
  12875. me.addInputRule(function(root){
  12876. root.traversal(function(node){
  12877. if(node.type == 'text' && node.data == me.options.pageBreakTag){
  12878. var hr = UE.uNode.createElement('<hr class="pagebreak" noshade="noshade" size="5" style="-webkit-user-select: none;">');
  12879. node.parentNode.insertBefore(hr,node);
  12880. node.parentNode.removeChild(node)
  12881. }
  12882. })
  12883. });
  12884. me.addOutputRule(function(node){
  12885. utils.each(node.getNodesByTagName('hr'),function(n){
  12886. if(n.getAttr('class') == 'pagebreak'){
  12887. var txt = UE.uNode.createText(me.options.pageBreakTag);
  12888. n.parentNode.insertBefore(txt,n);
  12889. n.parentNode.removeChild(n);
  12890. }
  12891. })
  12892. });
  12893. /**
  12894. * 插入分页符
  12895. * @command pagebreak
  12896. * @method execCommand
  12897. * @param { String } cmd 命令字符串
  12898. * @remind 在表格中插入分页符会把表格切分成两部分
  12899. * @remind 获取编辑器内的数据时, 编辑器会把分页符转换成“_ueditor_page_break_tag_”字符串,
  12900. * 以便于提交数据到服务器端后处理分页。
  12901. * @example
  12902. * ```javascript
  12903. * editor.execCommand( 'pagebreak'); //插入一个hr标签,带有样式类名pagebreak
  12904. * ```
  12905. */
  12906. me.commands['pagebreak'] = {
  12907. execCommand:function () {
  12908. var range = me.selection.getRange(),hr = me.document.createElement('hr');
  12909. domUtils.setAttributes(hr,{
  12910. 'class' : 'pagebreak',
  12911. noshade:"noshade",
  12912. size:"5"
  12913. });
  12914. domUtils.unSelectable(hr);
  12915. //table单独处理
  12916. var node = domUtils.findParentByTagName(range.startContainer, notBreakTags, true),
  12917. parents = [], pN;
  12918. if (node) {
  12919. switch (node.tagName) {
  12920. case 'TD':
  12921. pN = node.parentNode;
  12922. if (!pN.previousSibling) {
  12923. var table = domUtils.findParentByTagName(pN, 'table');
  12924. // var tableWrapDiv = table.parentNode;
  12925. // if(tableWrapDiv && tableWrapDiv.nodeType == 1
  12926. // && tableWrapDiv.tagName == 'DIV'
  12927. // && tableWrapDiv.getAttribute('dropdrag')
  12928. // ){
  12929. // domUtils.remove(tableWrapDiv,true);
  12930. // }
  12931. table.parentNode.insertBefore(hr, table);
  12932. parents = domUtils.findParents(hr, true);
  12933. } else {
  12934. pN.parentNode.insertBefore(hr, pN);
  12935. parents = domUtils.findParents(hr);
  12936. }
  12937. pN = parents[1];
  12938. if (hr !== pN) {
  12939. domUtils.breakParent(hr, pN);
  12940. }
  12941. //table要重写绑定一下拖拽
  12942. me.fireEvent('afteradjusttable',me.document);
  12943. }
  12944. } else {
  12945. if (!range.collapsed) {
  12946. range.deleteContents();
  12947. var start = range.startContainer;
  12948. while ( !domUtils.isBody(start) && domUtils.isBlockElm(start) && domUtils.isEmptyNode(start)) {
  12949. range.setStartBefore(start).collapse(true);
  12950. domUtils.remove(start);
  12951. start = range.startContainer;
  12952. }
  12953. }
  12954. range.insertNode(hr);
  12955. var pN = hr.parentNode, nextNode;
  12956. while (!domUtils.isBody(pN)) {
  12957. domUtils.breakParent(hr, pN);
  12958. nextNode = hr.nextSibling;
  12959. if (nextNode && domUtils.isEmptyBlock(nextNode)) {
  12960. domUtils.remove(nextNode);
  12961. }
  12962. pN = hr.parentNode;
  12963. }
  12964. nextNode = hr.nextSibling;
  12965. var pre = hr.previousSibling;
  12966. if(isHr(pre)){
  12967. domUtils.remove(pre);
  12968. }else{
  12969. pre && fillNode(pre);
  12970. }
  12971. if(!nextNode){
  12972. var p = me.document.createElement('p');
  12973. hr.parentNode.appendChild(p);
  12974. domUtils.fillNode(me.document,p);
  12975. range.setStart(p,0).collapse(true);
  12976. }else{
  12977. if(isHr(nextNode)){
  12978. domUtils.remove(nextNode);
  12979. }else{
  12980. fillNode(nextNode);
  12981. }
  12982. range.setEndAfter(hr).collapse(false);
  12983. }
  12984. range.select(true);
  12985. }
  12986. }
  12987. };
  12988. };
  12989. // plugins/wordimage.js
  12990. ///import core
  12991. ///commands 本地图片引导上传
  12992. ///commandsName WordImage
  12993. ///commandsTitle 本地图片引导上传
  12994. ///commandsDialog dialogs\wordimage
  12995. UE.plugin.register('wordimage',function(){
  12996. var me = this,
  12997. images = [];
  12998. return {
  12999. commands : {
  13000. 'wordimage':{
  13001. execCommand:function () {
  13002. var images = domUtils.getElementsByTagName(me.body, "img");
  13003. var urlList = [];
  13004. for (var i = 0, ci; ci = images[i++];) {
  13005. var url = ci.getAttribute("word_img");
  13006. url && urlList.push(url);
  13007. }
  13008. return urlList;
  13009. },
  13010. queryCommandState:function () {
  13011. images = domUtils.getElementsByTagName(me.body, "img");
  13012. for (var i = 0, ci; ci = images[i++];) {
  13013. if (ci.getAttribute("word_img")) {
  13014. return 1;
  13015. }
  13016. }
  13017. return -1;
  13018. },
  13019. notNeedUndo:true
  13020. }
  13021. },
  13022. inputRule : function (root) {
  13023. utils.each(root.getNodesByTagName('img'), function (img) {
  13024. var attrs = img.attrs,
  13025. flag = parseInt(attrs.width) < 128 || parseInt(attrs.height) < 43,
  13026. opt = me.options,
  13027. src = opt.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif';
  13028. if (attrs['src'] && /^(?:(file:\/+))/.test(attrs['src'])) {
  13029. img.setAttr({
  13030. width:attrs.width,
  13031. height:attrs.height,
  13032. alt:attrs.alt,
  13033. word_img: attrs.src,
  13034. src:src,
  13035. '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'
  13036. })
  13037. }
  13038. })
  13039. }
  13040. }
  13041. });
  13042. // plugins/dragdrop.js
  13043. UE.plugins['dragdrop'] = function (){
  13044. var me = this;
  13045. me.ready(function(){
  13046. domUtils.on(this.body,'dragend',function(){
  13047. var rng = me.selection.getRange();
  13048. var node = rng.getClosedNode()||me.selection.getStart();
  13049. if(node && node.tagName == 'IMG'){
  13050. var pre = node.previousSibling,next;
  13051. while(next = node.nextSibling){
  13052. if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){
  13053. domUtils.remove(next)
  13054. }else{
  13055. break;
  13056. }
  13057. }
  13058. if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){
  13059. if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){
  13060. pre.appendChild(node);
  13061. domUtils.moveChild(next,pre);
  13062. domUtils.remove(next);
  13063. }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){
  13064. next.insertBefore(node,next.firstChild);
  13065. }
  13066. if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){
  13067. domUtils.remove(pre)
  13068. }
  13069. if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){
  13070. domUtils.remove(next)
  13071. }
  13072. rng.selectNode(node).select();
  13073. me.fireEvent('saveScene');
  13074. }
  13075. }
  13076. })
  13077. });
  13078. me.addListener('keyup', function(type, evt) {
  13079. var keyCode = evt.keyCode || evt.which;
  13080. if (keyCode == 13) {
  13081. var rng = me.selection.getRange(),node;
  13082. if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){
  13083. if(domUtils.getComputedStyle(node,'text-align') == 'center'){
  13084. domUtils.removeStyle(node,'text-align')
  13085. }
  13086. }
  13087. }
  13088. })
  13089. };
  13090. // plugins/undo.js
  13091. /**
  13092. * undo redo
  13093. * @file
  13094. * @since 1.2.6.1
  13095. */
  13096. /**
  13097. * 撤销上一次执行的命令
  13098. * @command undo
  13099. * @method execCommand
  13100. * @param { String } cmd 命令字符串
  13101. * @example
  13102. * ```javascript
  13103. * editor.execCommand( 'undo' );
  13104. * ```
  13105. */
  13106. /**
  13107. * 重做上一次执行的命令
  13108. * @command redo
  13109. * @method execCommand
  13110. * @param { String } cmd 命令字符串
  13111. * @example
  13112. * ```javascript
  13113. * editor.execCommand( 'redo' );
  13114. * ```
  13115. */
  13116. UE.plugins['undo'] = function () {
  13117. var saveSceneTimer;
  13118. var me = this,
  13119. maxUndoCount = me.options.maxUndoCount || 20,
  13120. maxInputCount = me.options.maxInputCount || 20,
  13121. fillchar = new RegExp(domUtils.fillChar + '|<\/hr>', 'gi');// ie会产生多余的</hr>
  13122. var noNeedFillCharTags = {
  13123. ol:1,ul:1,table:1,tbody:1,tr:1,body:1
  13124. };
  13125. var orgState = me.options.autoClearEmptyNode;
  13126. function compareAddr(indexA, indexB) {
  13127. if (indexA.length != indexB.length)
  13128. return 0;
  13129. for (var i = 0, l = indexA.length; i < l; i++) {
  13130. if (indexA[i] != indexB[i])
  13131. return 0
  13132. }
  13133. return 1;
  13134. }
  13135. function compareRangeAddress(rngAddrA, rngAddrB) {
  13136. if (rngAddrA.collapsed != rngAddrB.collapsed) {
  13137. return 0;
  13138. }
  13139. if (!compareAddr(rngAddrA.startAddress, rngAddrB.startAddress) || !compareAddr(rngAddrA.endAddress, rngAddrB.endAddress)) {
  13140. return 0;
  13141. }
  13142. return 1;
  13143. }
  13144. function UndoManager() {
  13145. this.list = [];
  13146. this.index = 0;
  13147. this.hasUndo = false;
  13148. this.hasRedo = false;
  13149. this.undo = function () {
  13150. if (this.hasUndo) {
  13151. if (!this.list[this.index - 1] && this.list.length == 1) {
  13152. this.reset();
  13153. return;
  13154. }
  13155. while (this.list[this.index].content == this.list[this.index - 1].content) {
  13156. this.index--;
  13157. if (this.index == 0) {
  13158. return this.restore(0);
  13159. }
  13160. }
  13161. this.restore(--this.index);
  13162. }
  13163. };
  13164. this.redo = function () {
  13165. if (this.hasRedo) {
  13166. while (this.list[this.index].content == this.list[this.index + 1].content) {
  13167. this.index++;
  13168. if (this.index == this.list.length - 1) {
  13169. return this.restore(this.index);
  13170. }
  13171. }
  13172. this.restore(++this.index);
  13173. }
  13174. };
  13175. this.restore = function () {
  13176. var me = this.editor;
  13177. var scene = this.list[this.index];
  13178. var root = UE.htmlparser(scene.content.replace(fillchar, ''));
  13179. me.options.autoClearEmptyNode = false;
  13180. me.filterInputRule(root);
  13181. me.options.autoClearEmptyNode = orgState;
  13182. //trace:873
  13183. //去掉展位符
  13184. me.document.body.innerHTML = root.toHtml();
  13185. me.fireEvent('afterscencerestore');
  13186. //处理undo后空格不展位的问题
  13187. if (browser.ie) {
  13188. utils.each(domUtils.getElementsByTagName(me.document,'td th caption p'),function(node){
  13189. if(domUtils.isEmptyNode(node)){
  13190. domUtils.fillNode(me.document, node);
  13191. }
  13192. })
  13193. }
  13194. try{
  13195. var rng = new dom.Range(me.document).moveToAddress(scene.address);
  13196. rng.select(noNeedFillCharTags[rng.startContainer.nodeName.toLowerCase()]);
  13197. }catch(e){}
  13198. this.update();
  13199. this.clearKey();
  13200. //不能把自己reset了
  13201. me.fireEvent('reset', true);
  13202. };
  13203. this.getScene = function () {
  13204. var me = this.editor;
  13205. var rng = me.selection.getRange(),
  13206. rngAddress = rng.createAddress(false,true);
  13207. me.fireEvent('beforegetscene');
  13208. var root = UE.htmlparser(me.body.innerHTML);
  13209. me.options.autoClearEmptyNode = false;
  13210. me.filterOutputRule(root);
  13211. me.options.autoClearEmptyNode = orgState;
  13212. var cont = root.toHtml();
  13213. //trace:3461
  13214. //这个会引起回退时导致空格丢失的情况
  13215. // browser.ie && (cont = cont.replace(/>&nbsp;</g, '><').replace(/\s*</g, '<').replace(/>\s*/g, '>'));
  13216. me.fireEvent('aftergetscene');
  13217. return {
  13218. address:rngAddress,
  13219. content:cont
  13220. }
  13221. };
  13222. this.save = function (notCompareRange,notSetCursor) {
  13223. clearTimeout(saveSceneTimer);
  13224. var currentScene = this.getScene(notSetCursor),
  13225. lastScene = this.list[this.index];
  13226. if(lastScene && lastScene.content != currentScene.content){
  13227. me.trigger('contentchange')
  13228. }
  13229. //内容相同位置相同不存
  13230. if (lastScene && lastScene.content == currentScene.content &&
  13231. ( notCompareRange ? 1 : compareRangeAddress(lastScene.address, currentScene.address) )
  13232. ) {
  13233. return;
  13234. }
  13235. this.list = this.list.slice(0, this.index + 1);
  13236. this.list.push(currentScene);
  13237. //如果大于最大数量了,就把最前的剔除
  13238. if (this.list.length > maxUndoCount) {
  13239. this.list.shift();
  13240. }
  13241. this.index = this.list.length - 1;
  13242. this.clearKey();
  13243. //跟新undo/redo状态
  13244. this.update();
  13245. };
  13246. this.update = function () {
  13247. this.hasRedo = !!this.list[this.index + 1];
  13248. this.hasUndo = !!this.list[this.index - 1];
  13249. };
  13250. this.reset = function () {
  13251. this.list = [];
  13252. this.index = 0;
  13253. this.hasUndo = false;
  13254. this.hasRedo = false;
  13255. this.clearKey();
  13256. };
  13257. this.clearKey = function () {
  13258. keycont = 0;
  13259. lastKeyCode = null;
  13260. };
  13261. }
  13262. me.undoManger = new UndoManager();
  13263. me.undoManger.editor = me;
  13264. function saveScene() {
  13265. this.undoManger.save();
  13266. }
  13267. me.addListener('saveScene', function () {
  13268. var args = Array.prototype.splice.call(arguments,1);
  13269. this.undoManger.save.apply(this.undoManger,args);
  13270. });
  13271. // me.addListener('beforeexeccommand', saveScene);
  13272. // me.addListener('afterexeccommand', saveScene);
  13273. me.addListener('reset', function (type, exclude) {
  13274. if (!exclude) {
  13275. this.undoManger.reset();
  13276. }
  13277. });
  13278. me.commands['redo'] = me.commands['undo'] = {
  13279. execCommand:function (cmdName) {
  13280. this.undoManger[cmdName]();
  13281. },
  13282. queryCommandState:function (cmdName) {
  13283. return this.undoManger['has' + (cmdName.toLowerCase() == 'undo' ? 'Undo' : 'Redo')] ? 0 : -1;
  13284. },
  13285. notNeedUndo:1
  13286. };
  13287. var keys = {
  13288. // /*Backspace*/ 8:1, /*Delete*/ 46:1,
  13289. /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1,
  13290. 37:1, 38:1, 39:1, 40:1
  13291. },
  13292. keycont = 0,
  13293. lastKeyCode;
  13294. //输入法状态下不计算字符数
  13295. var inputType = false;
  13296. me.addListener('ready', function () {
  13297. domUtils.on(this.body, 'compositionstart', function () {
  13298. inputType = true;
  13299. });
  13300. domUtils.on(this.body, 'compositionend', function () {
  13301. inputType = false;
  13302. })
  13303. });
  13304. //快捷键
  13305. me.addshortcutkey({
  13306. "Undo":"ctrl+90", //undo
  13307. "Redo":"ctrl+89" //redo
  13308. });
  13309. var isCollapsed = true;
  13310. me.addListener('keydown', function (type, evt) {
  13311. var me = this;
  13312. var keyCode = evt.keyCode || evt.which;
  13313. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13314. if (inputType)
  13315. return;
  13316. if(!me.selection.getRange().collapsed){
  13317. me.undoManger.save(false,true);
  13318. isCollapsed = false;
  13319. return;
  13320. }
  13321. if (me.undoManger.list.length == 0) {
  13322. me.undoManger.save(true);
  13323. }
  13324. clearTimeout(saveSceneTimer);
  13325. function save(cont){
  13326. cont.undoManger.save(false,true);
  13327. cont.fireEvent('selectionchange');
  13328. }
  13329. saveSceneTimer = setTimeout(function(){
  13330. if(inputType){
  13331. var interalTimer = setInterval(function(){
  13332. if(!inputType){
  13333. save(me);
  13334. clearInterval(interalTimer)
  13335. }
  13336. },300)
  13337. return;
  13338. }
  13339. save(me);
  13340. },200);
  13341. lastKeyCode = keyCode;
  13342. keycont++;
  13343. if (keycont >= maxInputCount ) {
  13344. save(me)
  13345. }
  13346. }
  13347. });
  13348. me.addListener('keyup', function (type, evt) {
  13349. var keyCode = evt.keyCode || evt.which;
  13350. if (!keys[keyCode] && !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  13351. if (inputType)
  13352. return;
  13353. if(!isCollapsed){
  13354. this.undoManger.save(false,true);
  13355. isCollapsed = true;
  13356. }
  13357. }
  13358. });
  13359. //扩展实例,添加关闭和开启命令undo
  13360. me.stopCmdUndo = function(){
  13361. me.__hasEnterExecCommand = true;
  13362. };
  13363. me.startCmdUndo = function(){
  13364. me.__hasEnterExecCommand = false;
  13365. }
  13366. };
  13367. // plugins/copy.js
  13368. UE.plugin.register('copy', function () {
  13369. var me = this;
  13370. function initZeroClipboard() {
  13371. ZeroClipboard.config({
  13372. debug: false,
  13373. swfPath: me.options.UEDITOR_HOME_URL + 'third-party/zeroclipboard/ZeroClipboard.swf'
  13374. });
  13375. var client = me.zeroclipboard = new ZeroClipboard();
  13376. // 复制内容
  13377. client.on('copy', function (e) {
  13378. var client = e.client,
  13379. rng = me.selection.getRange(),
  13380. div = document.createElement('div');
  13381. div.appendChild(rng.cloneContents());
  13382. client.setText(div.innerText || div.textContent);
  13383. client.setHtml(div.innerHTML);
  13384. rng.select();
  13385. });
  13386. // hover事件传递到target
  13387. client.on('mouseover mouseout', function (e) {
  13388. var target = e.target;
  13389. if (e.type == 'mouseover') {
  13390. domUtils.addClass(target, 'edui-state-hover');
  13391. } else if (e.type == 'mouseout') {
  13392. domUtils.removeClasses(target, 'edui-state-hover');
  13393. }
  13394. });
  13395. // flash加载不成功
  13396. client.on('wrongflash noflash', function () {
  13397. ZeroClipboard.destroy();
  13398. });
  13399. }
  13400. return {
  13401. bindEvents: {
  13402. 'ready': function () {
  13403. if (!browser.ie) {
  13404. if (window.ZeroClipboard) {
  13405. initZeroClipboard();
  13406. } else {
  13407. utils.loadFile(document, {
  13408. src: me.options.UEDITOR_HOME_URL + "third-party/zeroclipboard/ZeroClipboard.js",
  13409. tag: "script",
  13410. type: "text/javascript",
  13411. defer: "defer"
  13412. }, function () {
  13413. initZeroClipboard();
  13414. });
  13415. }
  13416. }
  13417. }
  13418. },
  13419. commands: {
  13420. 'copy': {
  13421. execCommand: function (cmd) {
  13422. if (!me.document.execCommand('copy')) {
  13423. alert(me.getLang('copymsg'));
  13424. }
  13425. }
  13426. }
  13427. }
  13428. }
  13429. });
  13430. // plugins/paste.js
  13431. ///import core
  13432. ///import plugins/inserthtml.js
  13433. ///import plugins/undo.js
  13434. ///import plugins/serialize.js
  13435. ///commands 粘贴
  13436. ///commandsName PastePlain
  13437. ///commandsTitle 纯文本粘贴模式
  13438. /**
  13439. * @description 粘贴
  13440. * @author zhanyi
  13441. */
  13442. UE.plugins['paste'] = function () {
  13443. function getClipboardData(callback) {
  13444. var doc = this.document;
  13445. if (doc.getElementById('baidu_pastebin')) {
  13446. return;
  13447. }
  13448. var range = this.selection.getRange(),
  13449. bk = range.createBookmark(),
  13450. //创建剪贴的容器div
  13451. pastebin = doc.createElement('div');
  13452. pastebin.id = 'baidu_pastebin';
  13453. // Safari 要求div必须有内容,才能粘贴内容进来
  13454. browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar));
  13455. doc.body.appendChild(pastebin);
  13456. //trace:717 隐藏的span不能得到top
  13457. //bk.start.innerHTML = '&nbsp;';
  13458. bk.start.style.display = '';
  13459. pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" +
  13460. //要在现在光标平行的位置加入,否则会出现跳动的问题
  13461. domUtils.getXY(bk.start).y + 'px';
  13462. range.selectNodeContents(pastebin).select(true);
  13463. setTimeout(function () {
  13464. if (browser.webkit) {
  13465. for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) {
  13466. if (domUtils.isEmptyNode(pi)) {
  13467. domUtils.remove(pi);
  13468. } else {
  13469. pastebin = pi;
  13470. break;
  13471. }
  13472. }
  13473. }
  13474. try {
  13475. pastebin.parentNode.removeChild(pastebin);
  13476. } catch (e) {
  13477. }
  13478. range.moveToBookmark(bk).select(true);
  13479. callback(pastebin);
  13480. }, 0);
  13481. }
  13482. var me = this;
  13483. me.setOpt({
  13484. retainOnlyLabelPasted : false
  13485. });
  13486. var txtContent, htmlContent, address;
  13487. function getPureHtml(html){
  13488. return html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) {
  13489. tagName = tagName.toLowerCase();
  13490. if ({img: 1}[tagName]) {
  13491. return a;
  13492. }
  13493. attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) {
  13494. if ({
  13495. 'src': 1,
  13496. 'href': 1,
  13497. 'name': 1
  13498. }[atr.toLowerCase()]) {
  13499. return atr + '=' + val + ' '
  13500. }
  13501. return ''
  13502. });
  13503. if ({
  13504. 'span': 1,
  13505. 'div': 1
  13506. }[tagName]) {
  13507. return ''
  13508. } else {
  13509. return '<' + b + tagName + ' ' + utils.trim(attrs) + '>'
  13510. }
  13511. });
  13512. }
  13513. function filter(div) {
  13514. var html;
  13515. if (div.firstChild) {
  13516. //去掉cut中添加的边界值
  13517. var nodes = domUtils.getElementsByTagName(div, 'span');
  13518. for (var i = 0, ni; ni = nodes[i++];) {
  13519. if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') {
  13520. domUtils.remove(ni);
  13521. }
  13522. }
  13523. if (browser.webkit) {
  13524. var brs = div.querySelectorAll('div br');
  13525. for (var i = 0, bi; bi = brs[i++];) {
  13526. var pN = bi.parentNode;
  13527. if (pN.tagName == 'DIV' && pN.childNodes.length == 1) {
  13528. pN.innerHTML = '<p><br/></p>';
  13529. domUtils.remove(pN);
  13530. }
  13531. }
  13532. var divs = div.querySelectorAll('#baidu_pastebin');
  13533. for (var i = 0, di; di = divs[i++];) {
  13534. var tmpP = me.document.createElement('p');
  13535. di.parentNode.insertBefore(tmpP, di);
  13536. while (di.firstChild) {
  13537. tmpP.appendChild(di.firstChild);
  13538. }
  13539. domUtils.remove(di);
  13540. }
  13541. var metas = div.querySelectorAll('meta');
  13542. for (var i = 0, ci; ci = metas[i++];) {
  13543. domUtils.remove(ci);
  13544. }
  13545. var brs = div.querySelectorAll('br');
  13546. for (i = 0; ci = brs[i++];) {
  13547. if (/^apple-/i.test(ci.className)) {
  13548. domUtils.remove(ci);
  13549. }
  13550. }
  13551. }
  13552. if (browser.gecko) {
  13553. var dirtyNodes = div.querySelectorAll('[_moz_dirty]');
  13554. for (i = 0; ci = dirtyNodes[i++];) {
  13555. ci.removeAttribute('_moz_dirty');
  13556. }
  13557. }
  13558. if (!browser.ie) {
  13559. var spans = div.querySelectorAll('span.Apple-style-span');
  13560. for (var i = 0, ci; ci = spans[i++];) {
  13561. domUtils.remove(ci, true);
  13562. }
  13563. }
  13564. //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉
  13565. html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><');
  13566. //过滤word粘贴过来的冗余属性
  13567. html = UE.filterWord(html);
  13568. //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签
  13569. var root = UE.htmlparser(html);
  13570. //如果给了过滤规则就先进行过滤
  13571. if (me.options.filterRules) {
  13572. UE.filterNode(root, me.options.filterRules);
  13573. }
  13574. //执行默认的处理
  13575. me.filterInputRule(root);
  13576. //针对chrome的处理
  13577. if (browser.webkit) {
  13578. var br = root.lastChild();
  13579. if (br && br.type == 'element' && br.tagName == 'br') {
  13580. root.removeChild(br)
  13581. }
  13582. utils.each(me.body.querySelectorAll('div'), function (node) {
  13583. if (domUtils.isEmptyBlock(node)) {
  13584. domUtils.remove(node,true)
  13585. }
  13586. })
  13587. }
  13588. html = {'html': root.toHtml()};
  13589. me.fireEvent('beforepaste', html, root);
  13590. //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴
  13591. if(!html.html){
  13592. return;
  13593. }
  13594. root = UE.htmlparser(html.html,true);
  13595. //如果开启了纯文本模式
  13596. if (me.queryCommandState('pasteplain') === 1) {
  13597. me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true);
  13598. } else {
  13599. //文本模式
  13600. UE.filterNode(root, me.options.filterTxtRules);
  13601. txtContent = root.toHtml();
  13602. //完全模式
  13603. htmlContent = html.html;
  13604. address = me.selection.getRange().createAddress(true);
  13605. me.execCommand('insertHtml', me.getOpt('retainOnlyLabelPasted') === true ? getPureHtml(htmlContent) : htmlContent, true);
  13606. }
  13607. me.fireEvent("afterpaste", html);
  13608. }
  13609. }
  13610. me.addListener('pasteTransfer', function (cmd, plainType) {
  13611. if (address && txtContent && htmlContent && txtContent != htmlContent) {
  13612. var range = me.selection.getRange();
  13613. range.moveToAddress(address, true);
  13614. if (!range.collapsed) {
  13615. while (!domUtils.isBody(range.startContainer)
  13616. ) {
  13617. var start = range.startContainer;
  13618. if(start.nodeType == 1){
  13619. start = start.childNodes[range.startOffset];
  13620. if(!start){
  13621. range.setStartBefore(range.startContainer);
  13622. continue;
  13623. }
  13624. var pre = start.previousSibling;
  13625. if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){
  13626. range.setStartBefore(pre)
  13627. }
  13628. }
  13629. if(range.startOffset == 0){
  13630. range.setStartBefore(range.startContainer);
  13631. }else{
  13632. break;
  13633. }
  13634. }
  13635. while (!domUtils.isBody(range.endContainer)
  13636. ) {
  13637. var end = range.endContainer;
  13638. if(end.nodeType == 1){
  13639. end = end.childNodes[range.endOffset];
  13640. if(!end){
  13641. range.setEndAfter(range.endContainer);
  13642. continue;
  13643. }
  13644. var next = end.nextSibling;
  13645. if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){
  13646. range.setEndAfter(next)
  13647. }
  13648. }
  13649. if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){
  13650. range.setEndAfter(range.endContainer);
  13651. }else{
  13652. break;
  13653. }
  13654. }
  13655. }
  13656. range.deleteContents();
  13657. range.select(true);
  13658. me.__hasEnterExecCommand = true;
  13659. var html = htmlContent;
  13660. if (plainType === 2 ) {
  13661. html = getPureHtml(html);
  13662. } else if (plainType) {
  13663. html = txtContent;
  13664. }
  13665. me.execCommand('inserthtml', html, true);
  13666. me.__hasEnterExecCommand = false;
  13667. var rng = me.selection.getRange();
  13668. while (!domUtils.isBody(rng.startContainer) && !rng.startOffset &&
  13669. rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length
  13670. ) {
  13671. rng.setStartBefore(rng.startContainer);
  13672. }
  13673. var tmpAddress = rng.createAddress(true);
  13674. address.endAddress = tmpAddress.startAddress;
  13675. }
  13676. });
  13677. me.addListener('ready', function () {
  13678. domUtils.on(me.body, 'cut', function () {
  13679. var range = me.selection.getRange();
  13680. if (!range.collapsed && me.undoManger) {
  13681. me.undoManger.save();
  13682. }
  13683. });
  13684. //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理
  13685. domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) {
  13686. if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) {
  13687. return;
  13688. }
  13689. getClipboardData.call(me, function (div) {
  13690. filter(div);
  13691. });
  13692. });
  13693. });
  13694. me.commands['paste'] = {
  13695. execCommand: function (cmd) {
  13696. if (browser.ie) {
  13697. getClipboardData.call(me, function (div) {
  13698. filter(div);
  13699. });
  13700. me.document.execCommand('paste');
  13701. } else {
  13702. alert(me.getLang('pastemsg'));
  13703. }
  13704. }
  13705. }
  13706. };
  13707. // plugins/puretxtpaste.js
  13708. /**
  13709. * 纯文本粘贴插件
  13710. * @file
  13711. * @since 1.2.6.1
  13712. */
  13713. UE.plugins['pasteplain'] = function(){
  13714. var me = this;
  13715. me.setOpt({
  13716. 'pasteplain':false,
  13717. 'filterTxtRules' : function(){
  13718. function transP(node){
  13719. node.tagName = 'p';
  13720. node.setStyle();
  13721. }
  13722. function removeNode(node){
  13723. node.parentNode.removeChild(node,true)
  13724. }
  13725. return {
  13726. //直接删除及其字节点内容
  13727. '-' : 'script style object iframe embed input select',
  13728. 'p': {$:{}},
  13729. 'br':{$:{}},
  13730. div: function (node) {
  13731. var tmpNode, p = UE.uNode.createElement('p');
  13732. while (tmpNode = node.firstChild()) {
  13733. if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) {
  13734. p.appendChild(tmpNode);
  13735. } else {
  13736. if (p.firstChild()) {
  13737. node.parentNode.insertBefore(p, node);
  13738. p = UE.uNode.createElement('p');
  13739. } else {
  13740. node.parentNode.insertBefore(tmpNode, node);
  13741. }
  13742. }
  13743. }
  13744. if (p.firstChild()) {
  13745. node.parentNode.insertBefore(p, node);
  13746. }
  13747. node.parentNode.removeChild(node);
  13748. },
  13749. ol: removeNode,
  13750. ul: removeNode,
  13751. dl:removeNode,
  13752. dt:removeNode,
  13753. dd:removeNode,
  13754. 'li':removeNode,
  13755. 'caption':transP,
  13756. 'th':transP,
  13757. 'tr':transP,
  13758. 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
  13759. 'td':function(node){
  13760. //没有内容的td直接删掉
  13761. var txt = !!node.innerText();
  13762. if(txt){
  13763. node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node);
  13764. }
  13765. node.parentNode.removeChild(node,node.innerText())
  13766. }
  13767. }
  13768. }()
  13769. });
  13770. //暂时这里支持一下老版本的属性
  13771. var pasteplain = me.options.pasteplain;
  13772. /**
  13773. * 启用或取消纯文本粘贴模式
  13774. * @command pasteplain
  13775. * @method execCommand
  13776. * @param { String } cmd 命令字符串
  13777. * @example
  13778. * ```javascript
  13779. * editor.queryCommandState( 'pasteplain' );
  13780. * ```
  13781. */
  13782. /**
  13783. * 查询当前是否处于纯文本粘贴模式
  13784. * @command pasteplain
  13785. * @method queryCommandState
  13786. * @param { String } cmd 命令字符串
  13787. * @return { int } 如果处于纯文本模式,返回1,否则,返回0
  13788. * @example
  13789. * ```javascript
  13790. * editor.queryCommandState( 'pasteplain' );
  13791. * ```
  13792. */
  13793. me.commands['pasteplain'] = {
  13794. queryCommandState: function (){
  13795. return pasteplain ? 1 : 0;
  13796. },
  13797. execCommand: function (){
  13798. pasteplain = !pasteplain|0;
  13799. },
  13800. notNeedUndo : 1
  13801. };
  13802. };
  13803. // plugins/list.js
  13804. /**
  13805. * 有序列表,无序列表插件
  13806. * @file
  13807. * @since 1.2.6.1
  13808. */
  13809. UE.plugins['list'] = function () {
  13810. var me = this,
  13811. notExchange = {
  13812. 'TD':1,
  13813. 'PRE':1,
  13814. 'BLOCKQUOTE':1
  13815. };
  13816. var customStyle = {
  13817. 'cn' : 'cn-1-',
  13818. 'cn1' : 'cn-2-',
  13819. 'cn2' : 'cn-3-',
  13820. 'num': 'num-1-',
  13821. 'num1' : 'num-2-',
  13822. 'num2' : 'num-3-',
  13823. 'dash' : 'dash',
  13824. 'dot':'dot'
  13825. };
  13826. me.setOpt( {
  13827. 'autoTransWordToList':false,
  13828. 'insertorderedlist':{
  13829. 'num':'',
  13830. 'num1':'',
  13831. 'num2':'',
  13832. 'cn':'',
  13833. 'cn1':'',
  13834. 'cn2':'',
  13835. 'decimal':'',
  13836. 'lower-alpha':'',
  13837. 'lower-roman':'',
  13838. 'upper-alpha':'',
  13839. 'upper-roman':''
  13840. },
  13841. 'insertunorderedlist':{
  13842. 'circle':'',
  13843. 'disc':'',
  13844. 'square':'',
  13845. 'dash' : '',
  13846. 'dot':''
  13847. },
  13848. listDefaultPaddingLeft : '30',
  13849. listiconpath : 'http://bs.baidu.com/listicon/',
  13850. maxListLevel : -1,//-1不限制
  13851. disablePInList:false
  13852. } );
  13853. function listToArray(list){
  13854. var arr = [];
  13855. for(var p in list){
  13856. arr.push(p)
  13857. }
  13858. return arr;
  13859. }
  13860. var listStyle = {
  13861. 'OL':listToArray(me.options.insertorderedlist),
  13862. 'UL':listToArray(me.options.insertunorderedlist)
  13863. };
  13864. var liiconpath = me.options.listiconpath;
  13865. //根据用户配置,调整customStyle
  13866. for(var s in customStyle){
  13867. if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){
  13868. delete customStyle[s];
  13869. }
  13870. }
  13871. me.ready(function () {
  13872. var customCss = [];
  13873. for(var p in customStyle){
  13874. if(p == 'dash' || p == 'dot'){
  13875. customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}');
  13876. customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13877. }else{
  13878. for(var i= 0;i<99;i++){
  13879. customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}')
  13880. }
  13881. customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}');
  13882. }
  13883. switch(p){
  13884. case 'cn':
  13885. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13886. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13887. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13888. break;
  13889. case 'cn1':
  13890. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}');
  13891. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13892. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}');
  13893. break;
  13894. case 'cn2':
  13895. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}');
  13896. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}');
  13897. customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}');
  13898. break;
  13899. case 'num':
  13900. case 'num1':
  13901. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}');
  13902. break;
  13903. case 'num2':
  13904. customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}');
  13905. customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}');
  13906. break;
  13907. case 'dash':
  13908. customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}');
  13909. break;
  13910. case 'dot':
  13911. customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}');
  13912. }
  13913. }
  13914. customCss.push('.list-paddingleft-1{padding-left:0}');
  13915. customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}');
  13916. customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}');
  13917. //如果不给宽度会在自定应样式里出现滚动条
  13918. utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document);
  13919. });
  13920. //单独处理剪切的问题
  13921. me.ready(function(){
  13922. domUtils.on(me.body,'cut',function(){
  13923. setTimeout(function(){
  13924. var rng = me.selection.getRange(),li;
  13925. //trace:3416
  13926. if(!rng.collapsed){
  13927. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13928. if(!li.nextSibling && domUtils.isEmptyBlock(li)){
  13929. var pn = li.parentNode,node;
  13930. if(node = pn.previousSibling){
  13931. domUtils.remove(pn);
  13932. rng.setStartAtLast(node).collapse(true);
  13933. rng.select(true);
  13934. }else if(node = pn.nextSibling){
  13935. domUtils.remove(pn);
  13936. rng.setStartAtFirst(node).collapse(true);
  13937. rng.select(true);
  13938. }else{
  13939. var tmpNode = me.document.createElement('p');
  13940. domUtils.fillNode(me.document,tmpNode);
  13941. pn.parentNode.insertBefore(tmpNode,pn);
  13942. domUtils.remove(pn);
  13943. rng.setStart(tmpNode,0).collapse(true);
  13944. rng.select(true);
  13945. }
  13946. }
  13947. }
  13948. }
  13949. })
  13950. })
  13951. });
  13952. function getStyle(node){
  13953. var cls = node.className;
  13954. if(domUtils.hasClass(node,/custom_/)){
  13955. return cls.match(/custom_(\w+)/)[1]
  13956. }
  13957. return domUtils.getStyle(node, 'list-style-type')
  13958. }
  13959. me.addListener('beforepaste',function(type,html){
  13960. var me = this,
  13961. rng = me.selection.getRange(),li;
  13962. var root = UE.htmlparser(html.html,true);
  13963. if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){
  13964. var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol';
  13965. utils.each(root.getNodesByTagName(tagName),function(n){
  13966. n.tagName = list.tagName;
  13967. n.setAttr();
  13968. if(n.parentNode === root){
  13969. type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc')
  13970. }else{
  13971. var className = n.parentNode.getAttr('class');
  13972. if(className && /custom_/.test(className)){
  13973. type = className.match(/custom_(\w+)/)[1]
  13974. }else{
  13975. type = n.parentNode.getStyle('list-style-type');
  13976. }
  13977. if(!type){
  13978. type = list.tagName == 'OL' ? 'decimal' : 'disc';
  13979. }
  13980. }
  13981. var index = utils.indexOf(listStyle[list.tagName], type);
  13982. if(n.parentNode !== root)
  13983. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  13984. var currentStyle = listStyle[list.tagName][index];
  13985. if(customStyle[currentStyle]){
  13986. n.setAttr('class', 'custom_' + currentStyle)
  13987. }else{
  13988. n.setStyle('list-style-type',currentStyle)
  13989. }
  13990. })
  13991. }
  13992. html.html = root.toHtml();
  13993. });
  13994. //导出时,去掉p标签
  13995. me.getOpt('disablePInList') === true && me.addOutputRule(function(root){
  13996. utils.each(root.getNodesByTagName('li'),function(li){
  13997. var newChildrens = [],index=0;
  13998. utils.each(li.children,function(n){
  13999. if(n.tagName == 'p'){
  14000. var tmpNode;
  14001. while(tmpNode = n.children.pop()) {
  14002. newChildrens.splice(index,0,tmpNode);
  14003. tmpNode.parentNode = li;
  14004. lastNode = tmpNode;
  14005. }
  14006. tmpNode = newChildrens[newChildrens.length-1];
  14007. if(!tmpNode || tmpNode.type != 'element' || tmpNode.tagName != 'br'){
  14008. var br = UE.uNode.createElement('br');
  14009. br.parentNode = li;
  14010. newChildrens.push(br);
  14011. }
  14012. index = newChildrens.length;
  14013. }
  14014. });
  14015. if(newChildrens.length){
  14016. li.children = newChildrens;
  14017. }
  14018. });
  14019. });
  14020. //进入编辑器的li要套p标签
  14021. me.addInputRule(function(root){
  14022. utils.each(root.getNodesByTagName('li'),function(li){
  14023. var tmpP = UE.uNode.createElement('p');
  14024. for(var i= 0,ci;ci=li.children[i];){
  14025. if(ci.type == 'text' || dtd.p[ci.tagName]){
  14026. tmpP.appendChild(ci);
  14027. }else{
  14028. if(tmpP.firstChild()){
  14029. li.insertBefore(tmpP,ci);
  14030. tmpP = UE.uNode.createElement('p');
  14031. i = i + 2;
  14032. }else{
  14033. i++;
  14034. }
  14035. }
  14036. }
  14037. if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){
  14038. li.appendChild(tmpP);
  14039. }
  14040. //trace:3357
  14041. //p不能为空
  14042. if (!tmpP.firstChild()) {
  14043. tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>')
  14044. }
  14045. //去掉末尾的空白
  14046. var p = li.firstChild();
  14047. var lastChild = p.lastChild();
  14048. if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){
  14049. p.removeChild(lastChild)
  14050. }
  14051. });
  14052. if(me.options.autoTransWordToList){
  14053. var orderlisttype = {
  14054. 'num1':/^\d+\)/,
  14055. 'decimal':/^\d+\./,
  14056. 'lower-alpha':/^[a-z]+\)/,
  14057. 'upper-alpha':/^[A-Z]+\./,
  14058. 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/,
  14059. 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/
  14060. },
  14061. unorderlisttype = {
  14062. 'square':'n'
  14063. };
  14064. function checkListType(content,container){
  14065. var span = container.firstChild();
  14066. if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){
  14067. for(var p in unorderlisttype){
  14068. if(unorderlisttype[p] == span.data){
  14069. return p
  14070. }
  14071. }
  14072. return 'disc'
  14073. }
  14074. for(var p in orderlisttype){
  14075. if(orderlisttype[p].test(content)){
  14076. return p;
  14077. }
  14078. }
  14079. }
  14080. utils.each(root.getNodesByTagName('p'),function(node){
  14081. if(node.getAttr('class') != 'MsoListParagraph'){
  14082. return
  14083. }
  14084. //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视
  14085. node.setStyle('margin','');
  14086. node.setStyle('margin-left','');
  14087. node.setAttr('class','');
  14088. function appendLi(list,p,type){
  14089. if(list.tagName == 'ol'){
  14090. if(browser.ie){
  14091. var first = p.firstChild();
  14092. if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){
  14093. p.removeChild(first);
  14094. }
  14095. }else{
  14096. p.innerHTML(p.innerHTML().replace(orderlisttype[type],''));
  14097. }
  14098. }else{
  14099. p.removeChild(p.firstChild())
  14100. }
  14101. var li = UE.uNode.createElement('li');
  14102. li.appendChild(p);
  14103. list.appendChild(li);
  14104. }
  14105. var tmp = node,type,cacheNode = node;
  14106. if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){
  14107. var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul');
  14108. if(customStyle[type]){
  14109. list.setAttr('class','custom_'+type)
  14110. }else{
  14111. list.setStyle('list-style-type',type)
  14112. }
  14113. while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){
  14114. tmp = node.nextSibling();
  14115. if(!tmp){
  14116. node.parentNode.insertBefore(list,node)
  14117. }
  14118. appendLi(list,node,type);
  14119. node = tmp;
  14120. }
  14121. if(!list.parentNode && node && node.parentNode){
  14122. node.parentNode.insertBefore(list,node)
  14123. }
  14124. }
  14125. var span = cacheNode.firstChild();
  14126. if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){
  14127. span.parentNode.removeChild(span)
  14128. }
  14129. })
  14130. }
  14131. });
  14132. //调整索引标签
  14133. me.addListener('contentchange',function(){
  14134. adjustListStyle(me.document)
  14135. });
  14136. function adjustListStyle(doc,ignore){
  14137. utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){
  14138. if(!domUtils.inDoc(node,doc))
  14139. return;
  14140. var parent = node.parentNode;
  14141. if(parent.tagName == node.tagName){
  14142. var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'),
  14143. parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc');
  14144. if(nodeStyleType == parentStyleType){
  14145. var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType);
  14146. styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1;
  14147. setListStyle(node,listStyle[node.tagName][styleIndex])
  14148. }
  14149. }
  14150. var index = 0,type = 2;
  14151. if( domUtils.hasClass(node,/custom_/)){
  14152. if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){
  14153. type = 1;
  14154. }
  14155. }else{
  14156. if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){
  14157. type = 3;
  14158. }
  14159. }
  14160. var style = domUtils.getStyle(node, 'list-style-type');
  14161. style && (node.style.cssText = 'list-style-type:' + style);
  14162. node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type;
  14163. utils.each(domUtils.getElementsByTagName(node,'li'),function(li){
  14164. li.style.cssText && (li.style.cssText = '');
  14165. if(!li.firstChild){
  14166. domUtils.remove(li);
  14167. return;
  14168. }
  14169. if(li.parentNode !== node){
  14170. return;
  14171. }
  14172. index++;
  14173. if(domUtils.hasClass(node,/custom_/) ){
  14174. var paddingLeft = 1,currentStyle = getStyle(node);
  14175. if(node.tagName == 'OL'){
  14176. if(currentStyle){
  14177. switch(currentStyle){
  14178. case 'cn' :
  14179. case 'cn1':
  14180. case 'cn2':
  14181. if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){
  14182. paddingLeft = 2
  14183. }else if(index > 20){
  14184. paddingLeft = 3
  14185. }
  14186. break;
  14187. case 'num2' :
  14188. if(index > 9){
  14189. paddingLeft = 2
  14190. }
  14191. }
  14192. }
  14193. li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft;
  14194. }else{
  14195. li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft';
  14196. }
  14197. }else{
  14198. li.className = li.className.replace(/list-[\w\-]+/gi,'');
  14199. }
  14200. var className = li.getAttribute('class');
  14201. if(className !== null && !className.replace(/\s/g,'')){
  14202. domUtils.removeAttributes(li,'class')
  14203. }
  14204. });
  14205. !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true);
  14206. })
  14207. }
  14208. function adjustList(list, tag, style,ignoreEmpty) {
  14209. var nextList = list.nextSibling;
  14210. if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14211. domUtils.moveChild(nextList, list);
  14212. if (nextList.childNodes.length == 0) {
  14213. domUtils.remove(nextList);
  14214. }
  14215. }
  14216. if(nextList && domUtils.isFillChar(nextList)){
  14217. domUtils.remove(nextList);
  14218. }
  14219. var preList = list.previousSibling;
  14220. if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) {
  14221. domUtils.moveChild(list, preList);
  14222. }
  14223. if(preList && domUtils.isFillChar(preList)){
  14224. domUtils.remove(preList);
  14225. }
  14226. !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list);
  14227. if(getStyle(list)){
  14228. adjustListStyle(list.ownerDocument,true)
  14229. }
  14230. }
  14231. function setListStyle(list,style){
  14232. if(customStyle[style]){
  14233. list.className = 'custom_' + style;
  14234. }
  14235. try{
  14236. domUtils.setStyle(list, 'list-style-type', style);
  14237. }catch(e){}
  14238. }
  14239. function clearEmptySibling(node) {
  14240. var tmpNode = node.previousSibling;
  14241. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14242. domUtils.remove(tmpNode);
  14243. }
  14244. tmpNode = node.nextSibling;
  14245. if (tmpNode && domUtils.isEmptyBlock(tmpNode)) {
  14246. domUtils.remove(tmpNode);
  14247. }
  14248. }
  14249. me.addListener('keydown', function (type, evt) {
  14250. function preventAndSave() {
  14251. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  14252. me.fireEvent('contentchange');
  14253. me.undoManger && me.undoManger.save();
  14254. }
  14255. function findList(node,filterFn){
  14256. while(node && !domUtils.isBody(node)){
  14257. if(filterFn(node)){
  14258. return null
  14259. }
  14260. if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){
  14261. return node;
  14262. }
  14263. node = node.parentNode;
  14264. }
  14265. return null;
  14266. }
  14267. var keyCode = evt.keyCode || evt.which;
  14268. if (keyCode == 13 && !evt.shiftKey) {//回车
  14269. var rng = me.selection.getRange(),
  14270. parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true),
  14271. li = domUtils.findParentByTagName(rng.startContainer,'li',true);
  14272. if(parent && parent.tagName != 'PRE' && !li){
  14273. var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),'');
  14274. if(/^\s*1\s*\.[^\d]/.test(html)){
  14275. parent.innerHTML = html.replace(/^\s*1\s*\./,'');
  14276. rng.setStartAtLast(parent).collapse(true).select();
  14277. me.__hasEnterExecCommand = true;
  14278. me.execCommand('insertorderedlist');
  14279. me.__hasEnterExecCommand = false;
  14280. }
  14281. }
  14282. var range = me.selection.getRange(),
  14283. start = findList(range.startContainer,function (node) {
  14284. return node.tagName == 'TABLE';
  14285. }),
  14286. end = range.collapsed ? start : findList(range.endContainer,function (node) {
  14287. return node.tagName == 'TABLE';
  14288. });
  14289. if (start && end && start === end) {
  14290. if (!range.collapsed) {
  14291. start = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14292. end = domUtils.findParentByTagName(range.endContainer, 'li', true);
  14293. if (start && end && start === end) {
  14294. range.deleteContents();
  14295. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14296. if (li && domUtils.isEmptyBlock(li)) {
  14297. pre = li.previousSibling;
  14298. next = li.nextSibling;
  14299. p = me.document.createElement('p');
  14300. domUtils.fillNode(me.document, p);
  14301. parentList = li.parentNode;
  14302. if (pre && next) {
  14303. range.setStart(next, 0).collapse(true).select(true);
  14304. domUtils.remove(li);
  14305. } else {
  14306. if (!pre && !next || !pre) {
  14307. parentList.parentNode.insertBefore(p, parentList);
  14308. } else {
  14309. li.parentNode.parentNode.insertBefore(p, parentList.nextSibling);
  14310. }
  14311. domUtils.remove(li);
  14312. if (!parentList.firstChild) {
  14313. domUtils.remove(parentList);
  14314. }
  14315. range.setStart(p, 0).setCursor();
  14316. }
  14317. preventAndSave();
  14318. return;
  14319. }
  14320. } else {
  14321. var tmpRange = range.cloneRange(),
  14322. bk = tmpRange.collapse(false).createBookmark();
  14323. range.deleteContents();
  14324. tmpRange.moveToBookmark(bk);
  14325. var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true);
  14326. clearEmptySibling(li);
  14327. tmpRange.select();
  14328. preventAndSave();
  14329. return;
  14330. }
  14331. }
  14332. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14333. if (li) {
  14334. if (domUtils.isEmptyBlock(li)) {
  14335. bk = range.createBookmark();
  14336. var parentList = li.parentNode;
  14337. if (li !== parentList.lastChild) {
  14338. domUtils.breakParent(li, parentList);
  14339. clearEmptySibling(li);
  14340. } else {
  14341. parentList.parentNode.insertBefore(li, parentList.nextSibling);
  14342. if (domUtils.isEmptyNode(parentList)) {
  14343. domUtils.remove(parentList);
  14344. }
  14345. }
  14346. //嵌套不处理
  14347. if (!dtd.$list[li.parentNode.tagName]) {
  14348. if (!domUtils.isBlockElm(li.firstChild)) {
  14349. p = me.document.createElement('p');
  14350. li.parentNode.insertBefore(p, li);
  14351. while (li.firstChild) {
  14352. p.appendChild(li.firstChild);
  14353. }
  14354. domUtils.remove(li);
  14355. } else {
  14356. domUtils.remove(li, true);
  14357. }
  14358. }
  14359. range.moveToBookmark(bk).select();
  14360. } else {
  14361. var first = li.firstChild;
  14362. if (!first || !domUtils.isBlockElm(first)) {
  14363. var p = me.document.createElement('p');
  14364. !li.firstChild && domUtils.fillNode(me.document, p);
  14365. while (li.firstChild) {
  14366. p.appendChild(li.firstChild);
  14367. }
  14368. li.appendChild(p);
  14369. first = p;
  14370. }
  14371. var span = me.document.createElement('span');
  14372. range.insertNode(span);
  14373. domUtils.breakParent(span, li);
  14374. var nextLi = span.nextSibling;
  14375. first = nextLi.firstChild;
  14376. if (!first) {
  14377. p = me.document.createElement('p');
  14378. domUtils.fillNode(me.document, p);
  14379. nextLi.appendChild(p);
  14380. first = p;
  14381. }
  14382. if (domUtils.isEmptyNode(first)) {
  14383. first.innerHTML = '';
  14384. domUtils.fillNode(me.document, first);
  14385. }
  14386. range.setStart(first, 0).collapse(true).shrinkBoundary().select();
  14387. domUtils.remove(span);
  14388. var pre = nextLi.previousSibling;
  14389. if (pre && domUtils.isEmptyBlock(pre)) {
  14390. pre.innerHTML = '<p></p>';
  14391. domUtils.fillNode(me.document, pre.firstChild);
  14392. }
  14393. }
  14394. // }
  14395. preventAndSave();
  14396. }
  14397. }
  14398. }
  14399. if (keyCode == 8) {
  14400. //修中ie中li下的问题
  14401. range = me.selection.getRange();
  14402. if (range.collapsed && domUtils.isStartInblock(range)) {
  14403. tmpRange = range.cloneRange().trimBoundary();
  14404. li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14405. //要在li的最左边,才能处理
  14406. if (li && domUtils.isStartInblock(tmpRange)) {
  14407. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  14408. if (start && start !== li.firstChild) {
  14409. var parentList = domUtils.findParentByTagName(start,['ol','ul']);
  14410. domUtils.breakParent(start,parentList);
  14411. clearEmptySibling(start);
  14412. me.fireEvent('contentchange');
  14413. range.setStart(start,0).setCursor(false,true);
  14414. me.fireEvent('saveScene');
  14415. domUtils.preventDefault(evt);
  14416. return;
  14417. }
  14418. if (li && (pre = li.previousSibling)) {
  14419. if (keyCode == 46 && li.childNodes.length) {
  14420. return;
  14421. }
  14422. //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li
  14423. if (dtd.$list[pre.tagName]) {
  14424. pre = pre.lastChild;
  14425. }
  14426. me.undoManger && me.undoManger.save();
  14427. first = li.firstChild;
  14428. if (domUtils.isBlockElm(first)) {
  14429. if (domUtils.isEmptyNode(first)) {
  14430. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14431. pre.appendChild(first);
  14432. range.setStart(first, 0).setCursor(false, true);
  14433. //first不是唯一的节点
  14434. while (li.firstChild) {
  14435. pre.appendChild(li.firstChild);
  14436. }
  14437. } else {
  14438. span = me.document.createElement('span');
  14439. range.insertNode(span);
  14440. //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位
  14441. if (domUtils.isEmptyBlock(pre)) {
  14442. pre.innerHTML = '';
  14443. }
  14444. domUtils.moveChild(li, pre);
  14445. range.setStartBefore(span).collapse(true).select(true);
  14446. domUtils.remove(span);
  14447. }
  14448. } else {
  14449. if (domUtils.isEmptyNode(li)) {
  14450. var p = me.document.createElement('p');
  14451. pre.appendChild(p);
  14452. range.setStart(p, 0).setCursor();
  14453. // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true);
  14454. } else {
  14455. range.setEnd(pre, pre.childNodes.length).collapse().select(true);
  14456. while (li.firstChild) {
  14457. pre.appendChild(li.firstChild);
  14458. }
  14459. }
  14460. }
  14461. domUtils.remove(li);
  14462. me.fireEvent('contentchange');
  14463. me.fireEvent('saveScene');
  14464. domUtils.preventDefault(evt);
  14465. return;
  14466. }
  14467. //trace:980
  14468. if (li && !li.previousSibling) {
  14469. var parentList = li.parentNode;
  14470. var bk = range.createBookmark();
  14471. if(domUtils.isTagNode(parentList.parentNode,'ol ul')){
  14472. parentList.parentNode.insertBefore(li,parentList);
  14473. if(domUtils.isEmptyNode(parentList)){
  14474. domUtils.remove(parentList)
  14475. }
  14476. }else{
  14477. while(li.firstChild){
  14478. parentList.parentNode.insertBefore(li.firstChild,parentList);
  14479. }
  14480. domUtils.remove(li);
  14481. if(domUtils.isEmptyNode(parentList)){
  14482. domUtils.remove(parentList)
  14483. }
  14484. }
  14485. range.moveToBookmark(bk).setCursor(false,true);
  14486. me.fireEvent('contentchange');
  14487. me.fireEvent('saveScene');
  14488. domUtils.preventDefault(evt);
  14489. return;
  14490. }
  14491. }
  14492. }
  14493. }
  14494. });
  14495. me.addListener('keyup',function(type, evt){
  14496. var keyCode = evt.keyCode || evt.which;
  14497. if (keyCode == 8) {
  14498. var rng = me.selection.getRange(),list;
  14499. if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){
  14500. adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true)
  14501. }
  14502. }
  14503. });
  14504. //处理tab键
  14505. me.addListener('tabkeydown',function(){
  14506. var range = me.selection.getRange();
  14507. //控制级数
  14508. function checkLevel(li){
  14509. if(me.options.maxListLevel != -1){
  14510. var level = li.parentNode,levelNum = 0;
  14511. while(/[ou]l/i.test(level.tagName)){
  14512. levelNum++;
  14513. level = level.parentNode;
  14514. }
  14515. if(levelNum >= me.options.maxListLevel){
  14516. return true;
  14517. }
  14518. }
  14519. }
  14520. //只以开始为准
  14521. //todo 后续改进
  14522. var li = domUtils.findParentByTagName(range.startContainer, 'li', true);
  14523. if(li){
  14524. var bk;
  14525. if(range.collapsed){
  14526. if(checkLevel(li))
  14527. return true;
  14528. var parentLi = li.parentNode,
  14529. list = me.document.createElement(parentLi.tagName),
  14530. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14531. index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14532. var currentStyle = listStyle[list.tagName][index];
  14533. setListStyle(list,currentStyle);
  14534. if(domUtils.isStartInblock(range)){
  14535. me.fireEvent('saveScene');
  14536. bk = range.createBookmark();
  14537. parentLi.insertBefore(list, li);
  14538. list.appendChild(li);
  14539. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14540. me.fireEvent('contentchange');
  14541. range.moveToBookmark(bk).select(true);
  14542. return true;
  14543. }
  14544. }else{
  14545. me.fireEvent('saveScene');
  14546. bk = range.createBookmark();
  14547. for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){
  14548. if(domUtils.isTagNode(ci,'ol ul')){
  14549. closeList = ci;
  14550. break;
  14551. }
  14552. }
  14553. var current = li;
  14554. if(bk.end){
  14555. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14556. if(checkLevel(current)){
  14557. current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14558. continue;
  14559. }
  14560. var parentLi = current.parentNode,
  14561. list = me.document.createElement(parentLi.tagName),
  14562. index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type'));
  14563. var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1;
  14564. var currentStyle = listStyle[list.tagName][currentIndex];
  14565. setListStyle(list,currentStyle);
  14566. parentLi.insertBefore(list, current);
  14567. while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){
  14568. li = current.nextSibling;
  14569. list.appendChild(current);
  14570. if(!li || domUtils.isTagNode(li,'ol ul')){
  14571. if(li){
  14572. while(li = li.firstChild){
  14573. if(li.tagName == 'LI'){
  14574. break;
  14575. }
  14576. }
  14577. }else{
  14578. li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList});
  14579. }
  14580. break;
  14581. }
  14582. current = li;
  14583. }
  14584. adjustList(list,list.tagName.toLowerCase(),currentStyle);
  14585. current = li;
  14586. }
  14587. }
  14588. me.fireEvent('contentchange');
  14589. range.moveToBookmark(bk).select();
  14590. return true;
  14591. }
  14592. }
  14593. });
  14594. function getLi(start){
  14595. while(start && !domUtils.isBody(start)){
  14596. if(start.nodeName == 'TABLE'){
  14597. return null;
  14598. }
  14599. if(start.nodeName == 'LI'){
  14600. return start
  14601. }
  14602. start = start.parentNode;
  14603. }
  14604. }
  14605. /**
  14606. * 有序列表,与“insertunorderedlist”命令互斥
  14607. * @command insertorderedlist
  14608. * @method execCommand
  14609. * @param { String } command 命令字符串
  14610. * @param { String } style 插入的有序列表类型,值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14611. * @example
  14612. * ```javascript
  14613. * editor.execCommand( 'insertorderedlist','decimal');
  14614. * ```
  14615. */
  14616. /**
  14617. * 查询当前选区内容是否有序列表
  14618. * @command insertorderedlist
  14619. * @method queryCommandState
  14620. * @param { String } cmd 命令字符串
  14621. * @return { int } 如果当前选区是有序列表返回1,否则返回0
  14622. * @example
  14623. * ```javascript
  14624. * editor.queryCommandState( 'insertorderedlist' );
  14625. * ```
  14626. */
  14627. /**
  14628. * 查询当前选区内容是否有序列表
  14629. * @command insertorderedlist
  14630. * @method queryCommandValue
  14631. * @param { String } cmd 命令字符串
  14632. * @return { String } 返回当前有序列表的类型,值为null或decimal,lower-alpha,lower-roman,upper-alpha,upper-roman,cn,cn1,cn2,num,num1,num2
  14633. * @example
  14634. * ```javascript
  14635. * editor.queryCommandValue( 'insertorderedlist' );
  14636. * ```
  14637. */
  14638. /**
  14639. * 无序列表,与“insertorderedlist”命令互斥
  14640. * @command insertunorderedlist
  14641. * @method execCommand
  14642. * @param { String } command 命令字符串
  14643. * @param { String } style 插入的无序列表类型,值为:circle,disc,square,dash,dot
  14644. * @example
  14645. * ```javascript
  14646. * editor.execCommand( 'insertunorderedlist','circle');
  14647. * ```
  14648. */
  14649. /**
  14650. * 查询当前是否有word文档粘贴进来的图片
  14651. * @command insertunorderedlist
  14652. * @method insertunorderedlist
  14653. * @param { String } command 命令字符串
  14654. * @return { int } 如果当前选区是无序列表返回1,否则返回0
  14655. * @example
  14656. * ```javascript
  14657. * editor.queryCommandState( 'insertunorderedlist' );
  14658. * ```
  14659. */
  14660. /**
  14661. * 查询当前选区内容是否有序列表
  14662. * @command insertunorderedlist
  14663. * @method queryCommandValue
  14664. * @param { String } command 命令字符串
  14665. * @return { String } 返回当前无序列表的类型,值为null或circle,disc,square,dash,dot
  14666. * @example
  14667. * ```javascript
  14668. * editor.queryCommandValue( 'insertunorderedlist' );
  14669. * ```
  14670. */
  14671. me.commands['insertorderedlist'] =
  14672. me.commands['insertunorderedlist'] = {
  14673. execCommand:function (command, style) {
  14674. if (!style) {
  14675. style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc';
  14676. }
  14677. var me = this,
  14678. range = this.selection.getRange(),
  14679. filterFn = function (node) {
  14680. return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node);
  14681. },
  14682. tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul',
  14683. frag = me.document.createDocumentFragment();
  14684. //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置
  14685. //range.shrinkBoundary();//.adjustmentBoundary();
  14686. range.adjustmentBoundary().shrinkBoundary();
  14687. var bko = range.createBookmark(true),
  14688. start = getLi(me.document.getElementById(bko.start)),
  14689. modifyStart = 0,
  14690. end = getLi(me.document.getElementById(bko.end)),
  14691. modifyEnd = 0,
  14692. startParent, endParent,
  14693. list, tmp;
  14694. if (start || end) {
  14695. start && (startParent = start.parentNode);
  14696. if (!bko.end) {
  14697. end = start;
  14698. }
  14699. end && (endParent = end.parentNode);
  14700. if (startParent === endParent) {
  14701. while (start !== end) {
  14702. tmp = start;
  14703. start = start.nextSibling;
  14704. if (!domUtils.isBlockElm(tmp.firstChild)) {
  14705. var p = me.document.createElement('p');
  14706. while (tmp.firstChild) {
  14707. p.appendChild(tmp.firstChild);
  14708. }
  14709. tmp.appendChild(p);
  14710. }
  14711. frag.appendChild(tmp);
  14712. }
  14713. tmp = me.document.createElement('span');
  14714. startParent.insertBefore(tmp, end);
  14715. if (!domUtils.isBlockElm(end.firstChild)) {
  14716. p = me.document.createElement('p');
  14717. while (end.firstChild) {
  14718. p.appendChild(end.firstChild);
  14719. }
  14720. end.appendChild(p);
  14721. }
  14722. frag.appendChild(end);
  14723. domUtils.breakParent(tmp, startParent);
  14724. if (domUtils.isEmptyNode(tmp.previousSibling)) {
  14725. domUtils.remove(tmp.previousSibling);
  14726. }
  14727. if (domUtils.isEmptyNode(tmp.nextSibling)) {
  14728. domUtils.remove(tmp.nextSibling)
  14729. }
  14730. var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc');
  14731. if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) {
  14732. for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.firstChild;) {
  14733. if(domUtils.isTagNode(ci,'ol ul')){
  14734. // 删除时,子列表不处理
  14735. // utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){
  14736. // while(li.firstChild){
  14737. // tmpFrag.appendChild(li.firstChild);
  14738. // }
  14739. //
  14740. // });
  14741. tmpFrag.appendChild(ci);
  14742. }else{
  14743. while (ci.firstChild) {
  14744. tmpFrag.appendChild(ci.firstChild);
  14745. domUtils.remove(ci);
  14746. }
  14747. }
  14748. }
  14749. tmp.parentNode.insertBefore(tmpFrag, tmp);
  14750. } else {
  14751. list = me.document.createElement(tag);
  14752. setListStyle(list,style);
  14753. list.appendChild(frag);
  14754. tmp.parentNode.insertBefore(list, tmp);
  14755. }
  14756. domUtils.remove(tmp);
  14757. list && adjustList(list, tag, style);
  14758. range.moveToBookmark(bko).select();
  14759. return;
  14760. }
  14761. //开始
  14762. if (start) {
  14763. while (start) {
  14764. tmp = start.nextSibling;
  14765. if (domUtils.isTagNode(start, 'ol ul')) {
  14766. frag.appendChild(start);
  14767. } else {
  14768. var tmpfrag = me.document.createDocumentFragment(),
  14769. hasBlock = 0;
  14770. while (start.firstChild) {
  14771. if (domUtils.isBlockElm(start.firstChild)) {
  14772. hasBlock = 1;
  14773. }
  14774. tmpfrag.appendChild(start.firstChild);
  14775. }
  14776. if (!hasBlock) {
  14777. var tmpP = me.document.createElement('p');
  14778. tmpP.appendChild(tmpfrag);
  14779. frag.appendChild(tmpP);
  14780. } else {
  14781. frag.appendChild(tmpfrag);
  14782. }
  14783. domUtils.remove(start);
  14784. }
  14785. start = tmp;
  14786. }
  14787. startParent.parentNode.insertBefore(frag, startParent.nextSibling);
  14788. if (domUtils.isEmptyNode(startParent)) {
  14789. range.setStartBefore(startParent);
  14790. domUtils.remove(startParent);
  14791. } else {
  14792. range.setStartAfter(startParent);
  14793. }
  14794. modifyStart = 1;
  14795. }
  14796. if (end && domUtils.inDoc(endParent, me.document)) {
  14797. //结束
  14798. start = endParent.firstChild;
  14799. while (start && start !== end) {
  14800. tmp = start.nextSibling;
  14801. if (domUtils.isTagNode(start, 'ol ul')) {
  14802. frag.appendChild(start);
  14803. } else {
  14804. tmpfrag = me.document.createDocumentFragment();
  14805. hasBlock = 0;
  14806. while (start.firstChild) {
  14807. if (domUtils.isBlockElm(start.firstChild)) {
  14808. hasBlock = 1;
  14809. }
  14810. tmpfrag.appendChild(start.firstChild);
  14811. }
  14812. if (!hasBlock) {
  14813. tmpP = me.document.createElement('p');
  14814. tmpP.appendChild(tmpfrag);
  14815. frag.appendChild(tmpP);
  14816. } else {
  14817. frag.appendChild(tmpfrag);
  14818. }
  14819. domUtils.remove(start);
  14820. }
  14821. start = tmp;
  14822. }
  14823. var tmpDiv = domUtils.createElement(me.document, 'div', {
  14824. 'tmpDiv':1
  14825. });
  14826. domUtils.moveChild(end, tmpDiv);
  14827. frag.appendChild(tmpDiv);
  14828. domUtils.remove(end);
  14829. endParent.parentNode.insertBefore(frag, endParent);
  14830. range.setEndBefore(endParent);
  14831. if (domUtils.isEmptyNode(endParent)) {
  14832. domUtils.remove(endParent);
  14833. }
  14834. modifyEnd = 1;
  14835. }
  14836. }
  14837. if (!modifyStart) {
  14838. range.setStartBefore(me.document.getElementById(bko.start));
  14839. }
  14840. if (bko.end && !modifyEnd) {
  14841. range.setEndAfter(me.document.getElementById(bko.end));
  14842. }
  14843. range.enlarge(true, function (node) {
  14844. return notExchange[node.tagName];
  14845. });
  14846. frag = me.document.createDocumentFragment();
  14847. var bk = range.createBookmark(),
  14848. current = domUtils.getNextDomNode(bk.start, false, filterFn),
  14849. tmpRange = range.cloneRange(),
  14850. tmpNode,
  14851. block = domUtils.isBlockElm;
  14852. while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) {
  14853. if (current.nodeType == 3 || dtd.li[current.tagName]) {
  14854. if (current.nodeType == 1 && dtd.$list[current.tagName]) {
  14855. while (current.firstChild) {
  14856. frag.appendChild(current.firstChild);
  14857. }
  14858. tmpNode = domUtils.getNextDomNode(current, false, filterFn);
  14859. domUtils.remove(current);
  14860. current = tmpNode;
  14861. continue;
  14862. }
  14863. tmpNode = current;
  14864. tmpRange.setStartBefore(current);
  14865. while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) {
  14866. tmpNode = current;
  14867. current = domUtils.getNextDomNode(current, false, null, function (node) {
  14868. return !notExchange[node.tagName];
  14869. });
  14870. }
  14871. if (current && block(current)) {
  14872. tmp = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14873. if (tmp && domUtils.isBookmarkNode(tmp)) {
  14874. current = domUtils.getNextDomNode(tmp, false, filterFn);
  14875. tmpNode = tmp;
  14876. }
  14877. }
  14878. tmpRange.setEndAfter(tmpNode);
  14879. current = domUtils.getNextDomNode(tmpNode, false, filterFn);
  14880. var li = range.document.createElement('li');
  14881. li.appendChild(tmpRange.extractContents());
  14882. if(domUtils.isEmptyNode(li)){
  14883. var tmpNode = range.document.createElement('p');
  14884. while(li.firstChild){
  14885. tmpNode.appendChild(li.firstChild)
  14886. }
  14887. li.appendChild(tmpNode);
  14888. }
  14889. frag.appendChild(li);
  14890. } else {
  14891. current = domUtils.getNextDomNode(current, true, filterFn);
  14892. }
  14893. }
  14894. range.moveToBookmark(bk).collapse(true);
  14895. list = me.document.createElement(tag);
  14896. setListStyle(list,style);
  14897. list.appendChild(frag);
  14898. range.insertNode(list);
  14899. //当前list上下看能否合并
  14900. adjustList(list, tag, style);
  14901. //去掉冗余的tmpDiv
  14902. for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) {
  14903. if (ci.getAttribute('tmpDiv')) {
  14904. domUtils.remove(ci, true)
  14905. }
  14906. }
  14907. range.moveToBookmark(bko).select();
  14908. },
  14909. queryCommandState:function (command) {
  14910. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14911. var path = this.selection.getStartElementPath();
  14912. for(var i= 0,ci;ci = path[i++];){
  14913. if(ci.nodeName == 'TABLE'){
  14914. return 0
  14915. }
  14916. if(tag == ci.nodeName.toLowerCase()){
  14917. return 1
  14918. };
  14919. }
  14920. return 0;
  14921. },
  14922. queryCommandValue:function (command) {
  14923. var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul';
  14924. var path = this.selection.getStartElementPath(),
  14925. node;
  14926. for(var i= 0,ci;ci = path[i++];){
  14927. if(ci.nodeName == 'TABLE'){
  14928. node = null;
  14929. break;
  14930. }
  14931. if(tag == ci.nodeName.toLowerCase()){
  14932. node = ci;
  14933. break;
  14934. };
  14935. }
  14936. return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null;
  14937. }
  14938. };
  14939. };
  14940. // plugins/source.js
  14941. /**
  14942. * 源码编辑插件
  14943. * @file
  14944. * @since 1.2.6.1
  14945. */
  14946. (function (){
  14947. var sourceEditors = {
  14948. textarea: function (editor, holder){
  14949. var textarea = holder.ownerDocument.createElement('textarea');
  14950. textarea.style.cssText = 'position:absolute;resize:none;width:100%;height:100%;border:0;padding:0;margin:0;overflow-y:auto;';
  14951. // todo: IE下只有onresize属性可用... 很纠结
  14952. if (browser.ie && browser.version < 8) {
  14953. textarea.style.width = holder.offsetWidth + 'px';
  14954. textarea.style.height = holder.offsetHeight + 'px';
  14955. holder.onresize = function (){
  14956. textarea.style.width = holder.offsetWidth + 'px';
  14957. textarea.style.height = holder.offsetHeight + 'px';
  14958. };
  14959. }
  14960. holder.appendChild(textarea);
  14961. return {
  14962. setContent: function (content){
  14963. textarea.value = content;
  14964. },
  14965. getContent: function (){
  14966. return textarea.value;
  14967. },
  14968. select: function (){
  14969. var range;
  14970. if (browser.ie) {
  14971. range = textarea.createTextRange();
  14972. range.collapse(true);
  14973. range.select();
  14974. } else {
  14975. //todo: chrome下无法设置焦点
  14976. textarea.setSelectionRange(0, 0);
  14977. textarea.focus();
  14978. }
  14979. },
  14980. dispose: function (){
  14981. holder.removeChild(textarea);
  14982. // todo
  14983. holder.onresize = null;
  14984. textarea = null;
  14985. holder = null;
  14986. }
  14987. };
  14988. },
  14989. codemirror: function (editor, holder){
  14990. var codeEditor = window.CodeMirror(holder, {
  14991. mode: "text/html",
  14992. tabMode: "indent",
  14993. lineNumbers: true,
  14994. lineWrapping:true
  14995. });
  14996. var dom = codeEditor.getWrapperElement();
  14997. dom.style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;font-family:consolas,"Courier new",monospace;font-size:13px;';
  14998. codeEditor.getScrollerElement().style.cssText = 'position:absolute;left:0;top:0;width:100%;height:100%;';
  14999. codeEditor.refresh();
  15000. return {
  15001. getCodeMirror:function(){
  15002. return codeEditor;
  15003. },
  15004. setContent: function (content){
  15005. codeEditor.setValue(content);
  15006. },
  15007. getContent: function (){
  15008. return codeEditor.getValue();
  15009. },
  15010. select: function (){
  15011. codeEditor.focus();
  15012. },
  15013. dispose: function (){
  15014. holder.removeChild(dom);
  15015. dom = null;
  15016. codeEditor = null;
  15017. }
  15018. };
  15019. }
  15020. };
  15021. UE.plugins['source'] = function (){
  15022. var me = this;
  15023. var opt = this.options;
  15024. var sourceMode = false;
  15025. var sourceEditor;
  15026. var orgSetContent;
  15027. opt.sourceEditor = browser.ie ? 'textarea' : (opt.sourceEditor || 'codemirror');
  15028. me.setOpt({
  15029. sourceEditorFirst:false
  15030. });
  15031. function createSourceEditor(holder){
  15032. return sourceEditors[opt.sourceEditor == 'codemirror' && window.CodeMirror ? 'codemirror' : 'textarea'](me, holder);
  15033. }
  15034. var bakCssText;
  15035. //解决在源码模式下getContent不能得到最新的内容问题
  15036. var oldGetContent,
  15037. bakAddress;
  15038. /**
  15039. * 切换源码模式和编辑模式
  15040. * @command source
  15041. * @method execCommand
  15042. * @param { String } cmd 命令字符串
  15043. * @example
  15044. * ```javascript
  15045. * editor.execCommand( 'source');
  15046. * ```
  15047. */
  15048. /**
  15049. * 查询当前编辑区域的状态是源码模式还是可视化模式
  15050. * @command source
  15051. * @method queryCommandState
  15052. * @param { String } cmd 命令字符串
  15053. * @return { int } 如果当前是源码编辑模式,返回1,否则返回0
  15054. * @example
  15055. * ```javascript
  15056. * editor.queryCommandState( 'source' );
  15057. * ```
  15058. */
  15059. me.commands['source'] = {
  15060. execCommand: function (){
  15061. sourceMode = !sourceMode;
  15062. if (sourceMode) {
  15063. bakAddress = me.selection.getRange().createAddress(false,true);
  15064. me.undoManger && me.undoManger.save(true);
  15065. if(browser.gecko){
  15066. me.body.contentEditable = false;
  15067. }
  15068. bakCssText = me.iframe.style.cssText;
  15069. me.iframe.style.cssText += 'position:absolute;left:-32768px;top:-32768px;';
  15070. me.fireEvent('beforegetcontent');
  15071. var root = UE.htmlparser(me.body.innerHTML);
  15072. me.filterOutputRule(root);
  15073. root.traversal(function (node) {
  15074. if (node.type == 'element') {
  15075. switch (node.tagName) {
  15076. case 'td':
  15077. case 'th':
  15078. case 'caption':
  15079. if(node.children && node.children.length == 1){
  15080. if(node.firstChild().tagName == 'br' ){
  15081. node.removeChild(node.firstChild())
  15082. }
  15083. };
  15084. break;
  15085. case 'pre':
  15086. node.innerText(node.innerText().replace(/&nbsp;/g,' '))
  15087. }
  15088. }
  15089. });
  15090. me.fireEvent('aftergetcontent');
  15091. var content = root.toHtml(true);
  15092. sourceEditor = createSourceEditor(me.iframe.parentNode);
  15093. sourceEditor.setContent(content);
  15094. orgSetContent = me.setContent;
  15095. me.setContent = function(html){
  15096. //这里暂时不触发事件,防止报错
  15097. var root = UE.htmlparser(html);
  15098. me.filterInputRule(root);
  15099. html = root.toHtml();
  15100. sourceEditor.setContent(html);
  15101. };
  15102. setTimeout(function (){
  15103. sourceEditor.select();
  15104. me.addListener('fullscreenchanged', function(){
  15105. try{
  15106. sourceEditor.getCodeMirror().refresh()
  15107. }catch(e){}
  15108. });
  15109. });
  15110. //重置getContent,源码模式下取值也能是最新的数据
  15111. oldGetContent = me.getContent;
  15112. me.getContent = function (){
  15113. return sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15114. };
  15115. } else {
  15116. me.iframe.style.cssText = bakCssText;
  15117. var cont = sourceEditor.getContent() || '<p>' + (browser.ie ? '' : '<br/>')+'</p>';
  15118. //处理掉block节点前后的空格,有可能会误命中,暂时不考虑
  15119. cont = cont.replace(new RegExp('[\\r\\t\\n ]*<\/?(\\w+)\\s*(?:[^>]*)>','g'), function(a,b){
  15120. if(b && !dtd.$inlineWithA[b.toLowerCase()]){
  15121. return a.replace(/(^[\n\r\t ]*)|([\n\r\t ]*$)/g,'');
  15122. }
  15123. return a.replace(/(^[\n\r\t]*)|([\n\r\t]*$)/g,'')
  15124. });
  15125. me.setContent = orgSetContent;
  15126. me.setContent(cont);
  15127. sourceEditor.dispose();
  15128. sourceEditor = null;
  15129. //还原getContent方法
  15130. me.getContent = oldGetContent;
  15131. var first = me.body.firstChild;
  15132. //trace:1106 都删除空了,下边会报错,所以补充一个p占位
  15133. if(!first){
  15134. me.body.innerHTML = '<p>'+(browser.ie?'':'<br/>')+'</p>';
  15135. first = me.body.firstChild;
  15136. }
  15137. //要在ifm为显示时ff才能取到selection,否则报错
  15138. //这里不能比较位置了
  15139. me.undoManger && me.undoManger.save(true);
  15140. if(browser.gecko){
  15141. var input = document.createElement('input');
  15142. input.style.cssText = 'position:absolute;left:0;top:-32768px';
  15143. document.body.appendChild(input);
  15144. me.body.contentEditable = false;
  15145. setTimeout(function(){
  15146. domUtils.setViewportOffset(input, { left: -32768, top: 0 });
  15147. input.focus();
  15148. setTimeout(function(){
  15149. me.body.contentEditable = true;
  15150. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15151. domUtils.remove(input);
  15152. });
  15153. });
  15154. }else{
  15155. //ie下有可能报错,比如在代码顶头的情况
  15156. try{
  15157. me.selection.getRange().moveToAddress(bakAddress).select(true);
  15158. }catch(e){}
  15159. }
  15160. }
  15161. this.fireEvent('sourcemodechanged', sourceMode);
  15162. },
  15163. queryCommandState: function (){
  15164. return sourceMode|0;
  15165. },
  15166. notNeedUndo : 1
  15167. };
  15168. var oldQueryCommandState = me.queryCommandState;
  15169. me.queryCommandState = function (cmdName){
  15170. cmdName = cmdName.toLowerCase();
  15171. if (sourceMode) {
  15172. //源码模式下可以开启的命令
  15173. return cmdName in {
  15174. 'source' : 1,
  15175. 'fullscreen' : 1
  15176. } ? 1 : -1
  15177. }
  15178. return oldQueryCommandState.apply(this, arguments);
  15179. };
  15180. if(opt.sourceEditor == "codemirror"){
  15181. me.addListener("ready",function(){
  15182. utils.loadFile(document,{
  15183. src : opt.codeMirrorJsUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.js",
  15184. tag : "script",
  15185. type : "text/javascript",
  15186. defer : "defer"
  15187. },function(){
  15188. if(opt.sourceEditorFirst){
  15189. setTimeout(function(){
  15190. me.execCommand("source");
  15191. },0);
  15192. }
  15193. });
  15194. utils.loadFile(document,{
  15195. tag : "link",
  15196. rel : "stylesheet",
  15197. type : "text/css",
  15198. href : opt.codeMirrorCssUrl || opt.UEDITOR_HOME_URL + "third-party/codemirror/codemirror.css"
  15199. });
  15200. });
  15201. }
  15202. };
  15203. })();
  15204. // plugins/enterkey.js
  15205. ///import core
  15206. ///import plugins/undo.js
  15207. ///commands 设置回车标签p或br
  15208. ///commandsName EnterKey
  15209. ///commandsTitle 设置回车标签p或br
  15210. /**
  15211. * @description 处理回车
  15212. * @author zhanyi
  15213. */
  15214. UE.plugins['enterkey'] = function() {
  15215. var hTag,
  15216. me = this,
  15217. tag = me.options.enterTag;
  15218. me.addListener('keyup', function(type, evt) {
  15219. var keyCode = evt.keyCode || evt.which;
  15220. if (keyCode == 13) {
  15221. var range = me.selection.getRange(),
  15222. start = range.startContainer,
  15223. doSave;
  15224. //修正在h1-h6里边回车后不能嵌套p的问题
  15225. if (!browser.ie) {
  15226. if (/h\d/i.test(hTag)) {
  15227. if (browser.gecko) {
  15228. var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true);
  15229. if (!h) {
  15230. me.document.execCommand('formatBlock', false, '<p>');
  15231. doSave = 1;
  15232. }
  15233. } else {
  15234. //chrome remove div
  15235. if (start.nodeType == 1) {
  15236. var tmp = me.document.createTextNode(''),div;
  15237. range.insertNode(tmp);
  15238. div = domUtils.findParentByTagName(tmp, 'div', true);
  15239. if (div) {
  15240. var p = me.document.createElement('p');
  15241. while (div.firstChild) {
  15242. p.appendChild(div.firstChild);
  15243. }
  15244. div.parentNode.insertBefore(p, div);
  15245. domUtils.remove(div);
  15246. range.setStartBefore(tmp).setCursor();
  15247. doSave = 1;
  15248. }
  15249. domUtils.remove(tmp);
  15250. }
  15251. }
  15252. if (me.undoManger && doSave) {
  15253. me.undoManger.save();
  15254. }
  15255. }
  15256. //没有站位符,会出现多行的问题
  15257. browser.opera && range.select();
  15258. }else{
  15259. me.fireEvent('saveScene',true,true)
  15260. }
  15261. }
  15262. });
  15263. me.addListener('keydown', function(type, evt) {
  15264. var keyCode = evt.keyCode || evt.which;
  15265. if (keyCode == 13) {//回车
  15266. if(me.fireEvent('beforeenterkeydown')){
  15267. domUtils.preventDefault(evt);
  15268. return;
  15269. }
  15270. me.fireEvent('saveScene',true,true);
  15271. hTag = '';
  15272. var range = me.selection.getRange();
  15273. if (!range.collapsed) {
  15274. //跨td不能删
  15275. var start = range.startContainer,
  15276. end = range.endContainer,
  15277. startTd = domUtils.findParentByTagName(start, 'td', true),
  15278. endTd = domUtils.findParentByTagName(end, 'td', true);
  15279. if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) {
  15280. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15281. return;
  15282. }
  15283. }
  15284. if (tag == 'p') {
  15285. if (!browser.ie) {
  15286. start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true);
  15287. //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command
  15288. //trace:2431
  15289. if (!start && !browser.opera) {
  15290. me.document.execCommand('formatBlock', false, '<p>');
  15291. if (browser.gecko) {
  15292. range = me.selection.getRange();
  15293. start = domUtils.findParentByTagName(range.startContainer, 'p', true);
  15294. start && domUtils.removeDirtyAttr(start);
  15295. }
  15296. } else {
  15297. hTag = start.tagName;
  15298. start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start);
  15299. }
  15300. }
  15301. } else {
  15302. evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false);
  15303. if (!range.collapsed) {
  15304. range.deleteContents();
  15305. start = range.startContainer;
  15306. if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) {
  15307. while (start.nodeType == 1) {
  15308. if (dtd.$empty[start.tagName]) {
  15309. range.setStartBefore(start).setCursor();
  15310. if (me.undoManger) {
  15311. me.undoManger.save();
  15312. }
  15313. return false;
  15314. }
  15315. if (!start.firstChild) {
  15316. var br = range.document.createElement('br');
  15317. start.appendChild(br);
  15318. range.setStart(start, 0).setCursor();
  15319. if (me.undoManger) {
  15320. me.undoManger.save();
  15321. }
  15322. return false;
  15323. }
  15324. start = start.firstChild;
  15325. }
  15326. if (start === range.startContainer.childNodes[range.startOffset]) {
  15327. br = range.document.createElement('br');
  15328. range.insertNode(br).setCursor();
  15329. } else {
  15330. range.setStart(start, 0).setCursor();
  15331. }
  15332. } else {
  15333. br = range.document.createElement('br');
  15334. range.insertNode(br).setStartAfter(br).setCursor();
  15335. }
  15336. } else {
  15337. br = range.document.createElement('br');
  15338. range.insertNode(br);
  15339. var parent = br.parentNode;
  15340. if (parent.lastChild === br) {
  15341. br.parentNode.insertBefore(br.cloneNode(true), br);
  15342. range.setStartBefore(br);
  15343. } else {
  15344. range.setStartAfter(br);
  15345. }
  15346. range.setCursor();
  15347. }
  15348. }
  15349. }
  15350. });
  15351. };
  15352. // plugins/keystrokes.js
  15353. /* 处理特殊键的兼容性问题 */
  15354. UE.plugins['keystrokes'] = function() {
  15355. var me = this;
  15356. var collapsed = true;
  15357. me.addListener('keydown', function(type, evt) {
  15358. var keyCode = evt.keyCode || evt.which,
  15359. rng = me.selection.getRange();
  15360. //处理全选的情况
  15361. if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90
  15362. || keyCode >= 48 && keyCode <= 57 ||
  15363. keyCode >= 96 && keyCode <= 111 || {
  15364. 13:1,
  15365. 8:1,
  15366. 46:1
  15367. }[keyCode])
  15368. ){
  15369. var tmpNode = rng.startContainer;
  15370. if(domUtils.isFillChar(tmpNode)){
  15371. rng.setStartBefore(tmpNode)
  15372. }
  15373. tmpNode = rng.endContainer;
  15374. if(domUtils.isFillChar(tmpNode)){
  15375. rng.setEndAfter(tmpNode)
  15376. }
  15377. rng.txtToElmBoundary();
  15378. //结束边界可能放到了br的前边,要把br包含进来
  15379. // x[xxx]<br/>
  15380. if(rng.endContainer && rng.endContainer.nodeType == 1){
  15381. tmpNode = rng.endContainer.childNodes[rng.endOffset];
  15382. if(tmpNode && domUtils.isBr(tmpNode)){
  15383. rng.setEndAfter(tmpNode);
  15384. }
  15385. }
  15386. if(rng.startOffset == 0){
  15387. tmpNode = rng.startContainer;
  15388. if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){
  15389. tmpNode = rng.endContainer;
  15390. if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){
  15391. me.fireEvent('saveScene');
  15392. me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>';
  15393. rng.setStart(me.body.firstChild,0).setCursor(false,true);
  15394. me._selectionChange();
  15395. return;
  15396. }
  15397. }
  15398. }
  15399. }
  15400. //处理backspace
  15401. if (keyCode == keymap.Backspace) {
  15402. rng = me.selection.getRange();
  15403. collapsed = rng.collapsed;
  15404. if(me.fireEvent('delkeydown',evt)){
  15405. return;
  15406. }
  15407. var start,end;
  15408. //避免按两次删除才能生效的问题
  15409. if(rng.collapsed && rng.inFillChar()){
  15410. start = rng.startContainer;
  15411. if(domUtils.isFillChar(start)){
  15412. rng.setStartBefore(start).shrinkBoundary(true).collapse(true);
  15413. domUtils.remove(start)
  15414. }else{
  15415. start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),'');
  15416. rng.startOffset--;
  15417. rng.collapse(true).select(true)
  15418. }
  15419. }
  15420. //解决选中control元素不能删除的问题
  15421. if (start = rng.getClosedNode()) {
  15422. me.fireEvent('saveScene');
  15423. rng.setStartBefore(start);
  15424. domUtils.remove(start);
  15425. rng.setCursor();
  15426. me.fireEvent('saveScene');
  15427. domUtils.preventDefault(evt);
  15428. return;
  15429. }
  15430. //阻止在table上的删除
  15431. if (!browser.ie) {
  15432. start = domUtils.findParentByTagName(rng.startContainer, 'table', true);
  15433. end = domUtils.findParentByTagName(rng.endContainer, 'table', true);
  15434. if (start && !end || !start && end || start !== end) {
  15435. evt.preventDefault();
  15436. return;
  15437. }
  15438. }
  15439. }
  15440. //处理tab键的逻辑
  15441. if (keyCode == keymap.Tab) {
  15442. //不处理以下标签
  15443. var excludeTagNameForTabKey = {
  15444. 'ol' : 1,
  15445. 'ul' : 1,
  15446. 'table':1
  15447. };
  15448. //处理组件里的tab按下事件
  15449. if(me.fireEvent('tabkeydown',evt)){
  15450. domUtils.preventDefault(evt);
  15451. return;
  15452. }
  15453. var range = me.selection.getRange();
  15454. me.fireEvent('saveScene');
  15455. for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) {
  15456. txt += tabNode;
  15457. }
  15458. var span = me.document.createElement('span');
  15459. span.innerHTML = txt + domUtils.fillChar;
  15460. if (range.collapsed) {
  15461. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15462. } else {
  15463. var filterFn = function(node) {
  15464. return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()]
  15465. };
  15466. //普通的情况
  15467. start = domUtils.findParent(range.startContainer, filterFn,true);
  15468. end = domUtils.findParent(range.endContainer, filterFn,true);
  15469. if (start && end && start === end) {
  15470. range.deleteContents();
  15471. range.insertNode(span.cloneNode(true).firstChild).setCursor(true);
  15472. } else {
  15473. var bookmark = range.createBookmark();
  15474. range.enlarge(true);
  15475. var bookmark2 = range.createBookmark(),
  15476. current = domUtils.getNextDomNode(bookmark2.start, false, filterFn);
  15477. while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) {
  15478. current.insertBefore(span.cloneNode(true).firstChild, current.firstChild);
  15479. current = domUtils.getNextDomNode(current, false, filterFn);
  15480. }
  15481. range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select();
  15482. }
  15483. }
  15484. domUtils.preventDefault(evt)
  15485. }
  15486. //trace:1634
  15487. //ff的del键在容器空的时候,也会删除
  15488. if(browser.gecko && keyCode == 46){
  15489. range = me.selection.getRange();
  15490. if(range.collapsed){
  15491. start = range.startContainer;
  15492. if(domUtils.isEmptyBlock(start)){
  15493. var parent = start.parentNode;
  15494. while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){
  15495. start = parent;
  15496. parent = parent.parentNode;
  15497. }
  15498. if(start === parent.lastChild)
  15499. evt.preventDefault();
  15500. return;
  15501. }
  15502. }
  15503. }
  15504. });
  15505. me.addListener('keyup', function(type, evt) {
  15506. var keyCode = evt.keyCode || evt.which,
  15507. rng,me = this;
  15508. if(keyCode == keymap.Backspace){
  15509. if(me.fireEvent('delkeyup')){
  15510. return;
  15511. }
  15512. rng = me.selection.getRange();
  15513. if(rng.collapsed){
  15514. var tmpNode,
  15515. autoClearTagName = ['h1','h2','h3','h4','h5','h6'];
  15516. if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){
  15517. if(domUtils.isEmptyBlock(tmpNode)){
  15518. var pre = tmpNode.previousSibling;
  15519. if(pre && pre.nodeName != 'TABLE'){
  15520. domUtils.remove(tmpNode);
  15521. rng.setStartAtLast(pre).setCursor(false,true);
  15522. return;
  15523. }else{
  15524. var next = tmpNode.nextSibling;
  15525. if(next && next.nodeName != 'TABLE'){
  15526. domUtils.remove(tmpNode);
  15527. rng.setStartAtFirst(next).setCursor(false,true);
  15528. return;
  15529. }
  15530. }
  15531. }
  15532. }
  15533. //处理当删除到body时,要重新给p标签展位
  15534. if(domUtils.isBody(rng.startContainer)){
  15535. var tmpNode = domUtils.createElement(me.document,'p',{
  15536. 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>'
  15537. });
  15538. rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true);
  15539. }
  15540. }
  15541. //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了
  15542. if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){
  15543. if(browser.ie){
  15544. var span = rng.document.createElement('span');
  15545. rng.insertNode(span).setStartBefore(span).collapse(true);
  15546. rng.select();
  15547. domUtils.remove(span)
  15548. }else{
  15549. rng.select()
  15550. }
  15551. }
  15552. }
  15553. })
  15554. };
  15555. // plugins/fiximgclick.js
  15556. ///import core
  15557. ///commands 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15558. ///commandsName FixImgClick
  15559. ///commandsTitle 修复chrome下图片不能点击的问题,出现八个角可改变大小
  15560. //修复chrome下图片不能点击的问题,出现八个角可改变大小
  15561. UE.plugins['fiximgclick'] = (function () {
  15562. var elementUpdated = false;
  15563. function Scale() {
  15564. this.editor = null;
  15565. this.resizer = null;
  15566. this.cover = null;
  15567. this.doc = document;
  15568. this.prePos = {x: 0, y: 0};
  15569. this.startPos = {x: 0, y: 0};
  15570. }
  15571. (function () {
  15572. var rect = [
  15573. //[left, top, width, height]
  15574. [0, 0, -1, -1],
  15575. [0, 0, 0, -1],
  15576. [0, 0, 1, -1],
  15577. [0, 0, -1, 0],
  15578. [0, 0, 1, 0],
  15579. [0, 0, -1, 1],
  15580. [0, 0, 0, 1],
  15581. [0, 0, 1, 1]
  15582. ];
  15583. Scale.prototype = {
  15584. init: function (editor) {
  15585. var me = this;
  15586. me.editor = editor;
  15587. me.startPos = this.prePos = {x: 0, y: 0};
  15588. me.dragId = -1;
  15589. var hands = [],
  15590. cover = me.cover = document.createElement('div'),
  15591. resizer = me.resizer = document.createElement('div');
  15592. cover.id = me.editor.ui.id + '_imagescale_cover';
  15593. cover.style.cssText = 'position:absolute;display:none;z-index:' + (me.editor.options.zIndex) + ';filter:alpha(opacity=0); opacity:0;background:#CCC;';
  15594. domUtils.on(cover, 'mousedown click', function () {
  15595. me.hide();
  15596. });
  15597. for (i = 0; i < 8; i++) {
  15598. hands.push('<span class="edui-editor-imagescale-hand' + i + '"></span>');
  15599. }
  15600. resizer.id = me.editor.ui.id + '_imagescale';
  15601. resizer.className = 'edui-editor-imagescale';
  15602. resizer.innerHTML = hands.join('');
  15603. resizer.style.cssText += ';display:none;border:1px solid #3b77ff;z-index:' + (me.editor.options.zIndex) + ';';
  15604. me.editor.ui.getDom().appendChild(cover);
  15605. me.editor.ui.getDom().appendChild(resizer);
  15606. me.initStyle();
  15607. me.initEvents();
  15608. },
  15609. initStyle: function () {
  15610. utils.cssRule('imagescale', '.edui-editor-imagescale{display:none;position:absolute;border:1px solid #38B2CE;cursor:hand;-webkit-box-sizing: content-box;-moz-box-sizing: content-box;box-sizing: content-box;}' +
  15611. '.edui-editor-imagescale span{position:absolute;width:6px;height:6px;overflow:hidden;font-size:0px;display:block;background-color:#3C9DD0;}'
  15612. + '.edui-editor-imagescale .edui-editor-imagescale-hand0{cursor:nw-resize;top:0;margin-top:-4px;left:0;margin-left:-4px;}'
  15613. + '.edui-editor-imagescale .edui-editor-imagescale-hand1{cursor:n-resize;top:0;margin-top:-4px;left:50%;margin-left:-4px;}'
  15614. + '.edui-editor-imagescale .edui-editor-imagescale-hand2{cursor:ne-resize;top:0;margin-top:-4px;left:100%;margin-left:-3px;}'
  15615. + '.edui-editor-imagescale .edui-editor-imagescale-hand3{cursor:w-resize;top:50%;margin-top:-4px;left:0;margin-left:-4px;}'
  15616. + '.edui-editor-imagescale .edui-editor-imagescale-hand4{cursor:e-resize;top:50%;margin-top:-4px;left:100%;margin-left:-3px;}'
  15617. + '.edui-editor-imagescale .edui-editor-imagescale-hand5{cursor:sw-resize;top:100%;margin-top:-3px;left:0;margin-left:-4px;}'
  15618. + '.edui-editor-imagescale .edui-editor-imagescale-hand6{cursor:s-resize;top:100%;margin-top:-3px;left:50%;margin-left:-4px;}'
  15619. + '.edui-editor-imagescale .edui-editor-imagescale-hand7{cursor:se-resize;top:100%;margin-top:-3px;left:100%;margin-left:-3px;}');
  15620. },
  15621. initEvents: function () {
  15622. var me = this;
  15623. me.startPos.x = me.startPos.y = 0;
  15624. me.isDraging = false;
  15625. },
  15626. _eventHandler: function (e) {
  15627. var me = this;
  15628. switch (e.type) {
  15629. case 'mousedown':
  15630. var hand = e.target || e.srcElement, hand;
  15631. if (hand.className.indexOf('edui-editor-imagescale-hand') != -1 && me.dragId == -1) {
  15632. me.dragId = hand.className.slice(-1);
  15633. me.startPos.x = me.prePos.x = e.clientX;
  15634. me.startPos.y = me.prePos.y = e.clientY;
  15635. domUtils.on(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15636. }
  15637. break;
  15638. case 'mousemove':
  15639. if (me.dragId != -1) {
  15640. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15641. me.prePos.x = e.clientX;
  15642. me.prePos.y = e.clientY;
  15643. elementUpdated = true;
  15644. me.updateTargetElement();
  15645. }
  15646. break;
  15647. case 'mouseup':
  15648. if (me.dragId != -1) {
  15649. me.updateContainerStyle(me.dragId, {x: e.clientX - me.prePos.x, y: e.clientY - me.prePos.y});
  15650. me.updateTargetElement();
  15651. if (me.target.parentNode) me.attachTo(me.target);
  15652. me.dragId = -1;
  15653. }
  15654. domUtils.un(me.doc,'mousemove', me.proxy(me._eventHandler, me));
  15655. //修复只是点击挪动点,但没有改变大小,不应该触发contentchange
  15656. if(elementUpdated){
  15657. elementUpdated = false;
  15658. me.editor.fireEvent('contentchange');
  15659. }
  15660. break;
  15661. default:
  15662. break;
  15663. }
  15664. },
  15665. updateTargetElement: function () {
  15666. var me = this;
  15667. domUtils.setStyles(me.target, {
  15668. 'width': me.resizer.style.width,
  15669. 'height': me.resizer.style.height
  15670. });
  15671. me.target.width = parseInt(me.resizer.style.width);
  15672. me.target.height = parseInt(me.resizer.style.height);
  15673. me.attachTo(me.target);
  15674. },
  15675. updateContainerStyle: function (dir, offset) {
  15676. var me = this,
  15677. dom = me.resizer, tmp;
  15678. if (rect[dir][0] != 0) {
  15679. tmp = parseInt(dom.style.left) + offset.x;
  15680. dom.style.left = me._validScaledProp('left', tmp) + 'px';
  15681. }
  15682. if (rect[dir][1] != 0) {
  15683. tmp = parseInt(dom.style.top) + offset.y;
  15684. dom.style.top = me._validScaledProp('top', tmp) + 'px';
  15685. }
  15686. if (rect[dir][2] != 0) {
  15687. tmp = dom.clientWidth + rect[dir][2] * offset.x;
  15688. dom.style.width = me._validScaledProp('width', tmp) + 'px';
  15689. }
  15690. if (rect[dir][3] != 0) {
  15691. tmp = dom.clientHeight + rect[dir][3] * offset.y;
  15692. dom.style.height = me._validScaledProp('height', tmp) + 'px';
  15693. }
  15694. },
  15695. _validScaledProp: function (prop, value) {
  15696. var ele = this.resizer,
  15697. wrap = document;
  15698. value = isNaN(value) ? 0 : value;
  15699. switch (prop) {
  15700. case 'left':
  15701. return value < 0 ? 0 : (value + ele.clientWidth) > wrap.clientWidth ? wrap.clientWidth - ele.clientWidth : value;
  15702. case 'top':
  15703. return value < 0 ? 0 : (value + ele.clientHeight) > wrap.clientHeight ? wrap.clientHeight - ele.clientHeight : value;
  15704. case 'width':
  15705. return value <= 0 ? 1 : (value + ele.offsetLeft) > wrap.clientWidth ? wrap.clientWidth - ele.offsetLeft : value;
  15706. case 'height':
  15707. return value <= 0 ? 1 : (value + ele.offsetTop) > wrap.clientHeight ? wrap.clientHeight - ele.offsetTop : value;
  15708. }
  15709. },
  15710. hideCover: function () {
  15711. this.cover.style.display = 'none';
  15712. },
  15713. showCover: function () {
  15714. var me = this,
  15715. editorPos = domUtils.getXY(me.editor.ui.getDom()),
  15716. iframePos = domUtils.getXY(me.editor.iframe);
  15717. domUtils.setStyles(me.cover, {
  15718. 'width': me.editor.iframe.offsetWidth + 'px',
  15719. 'height': me.editor.iframe.offsetHeight + 'px',
  15720. 'top': iframePos.y - editorPos.y + 'px',
  15721. 'left': iframePos.x - editorPos.x + 'px',
  15722. 'position': 'absolute',
  15723. 'display': ''
  15724. })
  15725. },
  15726. show: function (targetObj) {
  15727. var me = this;
  15728. me.resizer.style.display = 'block';
  15729. if(targetObj) me.attachTo(targetObj);
  15730. domUtils.on(this.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15731. domUtils.on(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15732. me.showCover();
  15733. me.editor.fireEvent('afterscaleshow', me);
  15734. me.editor.fireEvent('saveScene');
  15735. },
  15736. hide: function () {
  15737. var me = this;
  15738. me.hideCover();
  15739. me.resizer.style.display = 'none';
  15740. domUtils.un(me.resizer, 'mousedown', me.proxy(me._eventHandler, me));
  15741. domUtils.un(me.doc, 'mouseup', me.proxy(me._eventHandler, me));
  15742. me.editor.fireEvent('afterscalehide', me);
  15743. },
  15744. proxy: function( fn, context ) {
  15745. return function(e) {
  15746. return fn.apply( context || this, arguments);
  15747. };
  15748. },
  15749. attachTo: function (targetObj) {
  15750. var me = this,
  15751. target = me.target = targetObj,
  15752. resizer = this.resizer,
  15753. imgPos = domUtils.getXY(target),
  15754. iframePos = domUtils.getXY(me.editor.iframe),
  15755. editorPos = domUtils.getXY(resizer.parentNode);
  15756. domUtils.setStyles(resizer, {
  15757. 'width': target.width + 'px',
  15758. 'height': target.height + 'px',
  15759. 'left': iframePos.x + imgPos.x - me.editor.document.body.scrollLeft - editorPos.x - parseInt(resizer.style.borderLeftWidth) + 'px',
  15760. 'top': iframePos.y + imgPos.y - me.editor.document.body.scrollTop - editorPos.y - parseInt(resizer.style.borderTopWidth) + 'px'
  15761. });
  15762. }
  15763. }
  15764. })();
  15765. return function () {
  15766. var me = this,
  15767. imageScale;
  15768. me.setOpt('imageScaleEnabled', true);
  15769. if ( !browser.ie && me.options.imageScaleEnabled) {
  15770. me.addListener('click', function (type, e) {
  15771. var range = me.selection.getRange(),
  15772. img = range.getClosedNode();
  15773. if (img && img.tagName == 'IMG' && me.body.contentEditable!="false") {
  15774. if (img.className.indexOf("edui-faked-music") != -1 ||
  15775. img.getAttribute("anchorname") ||
  15776. domUtils.hasClass(img, 'loadingclass') ||
  15777. domUtils.hasClass(img, 'loaderrorclass')) { return }
  15778. if (!imageScale) {
  15779. imageScale = new Scale();
  15780. imageScale.init(me);
  15781. me.ui.getDom().appendChild(imageScale.resizer);
  15782. var _keyDownHandler = function (e) {
  15783. imageScale.hide();
  15784. if(imageScale.target) me.selection.getRange().selectNode(imageScale.target).select();
  15785. }, _mouseDownHandler = function (e) {
  15786. var ele = e.target || e.srcElement;
  15787. if (ele && (ele.className===undefined || ele.className.indexOf('edui-editor-imagescale') == -1)) {
  15788. _keyDownHandler(e);
  15789. }
  15790. }, timer;
  15791. me.addListener('afterscaleshow', function (e) {
  15792. me.addListener('beforekeydown', _keyDownHandler);
  15793. me.addListener('beforemousedown', _mouseDownHandler);
  15794. domUtils.on(document, 'keydown', _keyDownHandler);
  15795. domUtils.on(document,'mousedown', _mouseDownHandler);
  15796. me.selection.getNative().removeAllRanges();
  15797. });
  15798. me.addListener('afterscalehide', function (e) {
  15799. me.removeListener('beforekeydown', _keyDownHandler);
  15800. me.removeListener('beforemousedown', _mouseDownHandler);
  15801. domUtils.un(document, 'keydown', _keyDownHandler);
  15802. domUtils.un(document,'mousedown', _mouseDownHandler);
  15803. var target = imageScale.target;
  15804. if (target.parentNode) {
  15805. me.selection.getRange().selectNode(target).select();
  15806. }
  15807. });
  15808. //TODO 有iframe的情况,mousedown不能往下传。。
  15809. domUtils.on(imageScale.resizer, 'mousedown', function (e) {
  15810. me.selection.getNative().removeAllRanges();
  15811. var ele = e.target || e.srcElement;
  15812. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15813. timer = setTimeout(function () {
  15814. imageScale.hide();
  15815. if(imageScale.target) me.selection.getRange().selectNode(ele).select();
  15816. }, 200);
  15817. }
  15818. });
  15819. domUtils.on(imageScale.resizer, 'mouseup', function (e) {
  15820. var ele = e.target || e.srcElement;
  15821. if (ele && ele.className.indexOf('edui-editor-imagescale-hand') == -1) {
  15822. clearTimeout(timer);
  15823. }
  15824. });
  15825. }
  15826. imageScale.show(img);
  15827. } else {
  15828. if (imageScale && imageScale.resizer.style.display != 'none') imageScale.hide();
  15829. }
  15830. });
  15831. }
  15832. if (browser.webkit) {
  15833. me.addListener('click', function (type, e) {
  15834. if (e.target.tagName == 'IMG' && me.body.contentEditable!="false") {
  15835. var range = new dom.Range(me.document);
  15836. range.selectNode(e.target).select();
  15837. }
  15838. });
  15839. }
  15840. }
  15841. })();
  15842. // plugins/autolink.js
  15843. ///import core
  15844. ///commands 为非ie浏览器自动添加a标签
  15845. ///commandsName AutoLink
  15846. ///commandsTitle 自动增加链接
  15847. /**
  15848. * @description 为非ie浏览器自动添加a标签
  15849. * @author zhanyi
  15850. */
  15851. UE.plugin.register('autolink',function(){
  15852. var cont = 0;
  15853. return !browser.ie ? {
  15854. bindEvents:{
  15855. 'reset' : function(){
  15856. cont = 0;
  15857. },
  15858. 'keydown':function(type, evt) {
  15859. var me = this;
  15860. var keyCode = evt.keyCode || evt.which;
  15861. if (keyCode == 32 || keyCode == 13) {
  15862. var sel = me.selection.getNative(),
  15863. range = sel.getRangeAt(0).cloneRange(),
  15864. offset,
  15865. charCode;
  15866. var start = range.startContainer;
  15867. while (start.nodeType == 1 && range.startOffset > 0) {
  15868. start = range.startContainer.childNodes[range.startOffset - 1];
  15869. if (!start){
  15870. break;
  15871. }
  15872. range.setStart(start, start.nodeType == 1 ? start.childNodes.length : start.nodeValue.length);
  15873. range.collapse(true);
  15874. start = range.startContainer;
  15875. }
  15876. do{
  15877. if (range.startOffset == 0) {
  15878. start = range.startContainer.previousSibling;
  15879. while (start && start.nodeType == 1) {
  15880. start = start.lastChild;
  15881. }
  15882. if (!start || domUtils.isFillChar(start)){
  15883. break;
  15884. }
  15885. offset = start.nodeValue.length;
  15886. } else {
  15887. start = range.startContainer;
  15888. offset = range.startOffset;
  15889. }
  15890. range.setStart(start, offset - 1);
  15891. charCode = range.toString().charCodeAt(0);
  15892. } while (charCode != 160 && charCode != 32);
  15893. if (range.toString().replace(new RegExp(domUtils.fillChar, 'g'), '').match(/(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i)) {
  15894. while(range.toString().length){
  15895. if(/^(?:https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.)/i.test(range.toString())){
  15896. break;
  15897. }
  15898. try{
  15899. range.setStart(range.startContainer,range.startOffset+1);
  15900. }catch(e){
  15901. //trace:2121
  15902. var start = range.startContainer;
  15903. while(!(next = start.nextSibling)){
  15904. if(domUtils.isBody(start)){
  15905. return;
  15906. }
  15907. start = start.parentNode;
  15908. }
  15909. range.setStart(next,0);
  15910. }
  15911. }
  15912. //range的开始边界已经在a标签里的不再处理
  15913. if(domUtils.findParentByTagName(range.startContainer,'a',true)){
  15914. return;
  15915. }
  15916. var a = me.document.createElement('a'),text = me.document.createTextNode(' '),href;
  15917. me.undoManger && me.undoManger.save();
  15918. a.appendChild(range.extractContents());
  15919. a.href = a.innerHTML = a.innerHTML.replace(/<[^>]+>/g,'');
  15920. href = a.getAttribute("href").replace(new RegExp(domUtils.fillChar,'g'),'');
  15921. href = /^(?:https?:\/\/)/ig.test(href) ? href : "http://"+ href;
  15922. a.setAttribute('_src',utils.html(href));
  15923. a.href = utils.html(href);
  15924. range.insertNode(a);
  15925. a.parentNode.insertBefore(text, a.nextSibling);
  15926. range.setStart(text, 0);
  15927. range.collapse(true);
  15928. sel.removeAllRanges();
  15929. sel.addRange(range);
  15930. me.undoManger && me.undoManger.save();
  15931. }
  15932. }
  15933. }
  15934. }
  15935. }:{}
  15936. },function(){
  15937. var keyCodes = {
  15938. 37:1, 38:1, 39:1, 40:1,
  15939. 13:1,32:1
  15940. };
  15941. function checkIsCludeLink(node){
  15942. if(node.nodeType == 3){
  15943. return null
  15944. }
  15945. if(node.nodeName == 'A'){
  15946. return node;
  15947. }
  15948. var lastChild = node.lastChild;
  15949. while(lastChild){
  15950. if(lastChild.nodeName == 'A'){
  15951. return lastChild;
  15952. }
  15953. if(lastChild.nodeType == 3){
  15954. if(domUtils.isWhitespace(lastChild)){
  15955. lastChild = lastChild.previousSibling;
  15956. continue;
  15957. }
  15958. return null
  15959. }
  15960. lastChild = lastChild.lastChild;
  15961. }
  15962. }
  15963. browser.ie && this.addListener('keyup',function(cmd,evt){
  15964. var me = this,keyCode = evt.keyCode;
  15965. if(keyCodes[keyCode]){
  15966. var rng = me.selection.getRange();
  15967. var start = rng.startContainer;
  15968. if(keyCode == 13){
  15969. while(start && !domUtils.isBody(start) && !domUtils.isBlockElm(start)){
  15970. start = start.parentNode;
  15971. }
  15972. if(start && !domUtils.isBody(start) && start.nodeName == 'P'){
  15973. var pre = start.previousSibling;
  15974. if(pre && pre.nodeType == 1){
  15975. var pre = checkIsCludeLink(pre);
  15976. if(pre && !pre.getAttribute('_href')){
  15977. domUtils.remove(pre,true);
  15978. }
  15979. }
  15980. }
  15981. }else if(keyCode == 32 ){
  15982. if(start.nodeType == 3 && /^\s$/.test(start.nodeValue)){
  15983. start = start.previousSibling;
  15984. if(start && start.nodeName == 'A' && !start.getAttribute('_href')){
  15985. domUtils.remove(start,true);
  15986. }
  15987. }
  15988. }else {
  15989. start = domUtils.findParentByTagName(start,'a',true);
  15990. if(start && !start.getAttribute('_href')){
  15991. var bk = rng.createBookmark();
  15992. domUtils.remove(start,true);
  15993. rng.moveToBookmark(bk).select(true)
  15994. }
  15995. }
  15996. }
  15997. });
  15998. }
  15999. );
  16000. // plugins/autoheight.js
  16001. ///import core
  16002. ///commands 当输入内容超过编辑器高度时,编辑器自动增高
  16003. ///commandsName AutoHeight,autoHeightEnabled
  16004. ///commandsTitle 自动增高
  16005. /**
  16006. * @description 自动伸展
  16007. * @author zhanyi
  16008. */
  16009. UE.plugins['autoheight'] = function () {
  16010. var me = this;
  16011. //提供开关,就算加载也可以关闭
  16012. me.autoHeightEnabled = me.options.autoHeightEnabled !== false;
  16013. if (!me.autoHeightEnabled) {
  16014. return;
  16015. }
  16016. var bakOverflow,
  16017. lastHeight = 0,
  16018. options = me.options,
  16019. currentHeight,
  16020. timer;
  16021. function adjustHeight() {
  16022. var me = this;
  16023. clearTimeout(timer);
  16024. if(isFullscreen)return;
  16025. if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) {
  16026. timer = setTimeout(function(){
  16027. var node = me.body.lastChild;
  16028. while(node && node.nodeType != 1){
  16029. node = node.previousSibling;
  16030. }
  16031. if(node && node.nodeType == 1){
  16032. node.style.clear = 'both';
  16033. currentHeight = Math.max(domUtils.getXY(node).y + node.offsetHeight + 25 ,Math.max(options.minFrameHeight, options.initialFrameHeight)) ;
  16034. if (currentHeight != lastHeight) {
  16035. if (currentHeight !== parseInt(me.iframe.parentNode.style.height)) {
  16036. me.iframe.parentNode.style.height = currentHeight + 'px';
  16037. }
  16038. me.body.style.height = currentHeight + 'px';
  16039. lastHeight = currentHeight;
  16040. }
  16041. domUtils.removeStyle(node,'clear');
  16042. }
  16043. },50)
  16044. }
  16045. }
  16046. var isFullscreen;
  16047. me.addListener('fullscreenchanged',function(cmd,f){
  16048. isFullscreen = f
  16049. });
  16050. me.addListener('destroy', function () {
  16051. me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight)
  16052. });
  16053. me.enableAutoHeight = function () {
  16054. var me = this;
  16055. if (!me.autoHeightEnabled) {
  16056. return;
  16057. }
  16058. var doc = me.document;
  16059. me.autoHeightEnabled = true;
  16060. bakOverflow = doc.body.style.overflowY;
  16061. doc.body.style.overflowY = 'hidden';
  16062. me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight);
  16063. //ff不给事件算得不对
  16064. setTimeout(function () {
  16065. adjustHeight.call(me);
  16066. }, browser.gecko ? 100 : 0);
  16067. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16068. };
  16069. me.disableAutoHeight = function () {
  16070. me.body.style.overflowY = bakOverflow || '';
  16071. me.removeListener('contentchange', adjustHeight);
  16072. me.removeListener('keyup', adjustHeight);
  16073. me.removeListener('mouseup', adjustHeight);
  16074. me.autoHeightEnabled = false;
  16075. me.fireEvent('autoheightchanged', me.autoHeightEnabled);
  16076. };
  16077. me.on('setHeight',function(){
  16078. me.disableAutoHeight()
  16079. });
  16080. me.addListener('ready', function () {
  16081. me.enableAutoHeight();
  16082. //trace:1764
  16083. var timer;
  16084. domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () {
  16085. clearTimeout(timer);
  16086. timer = setTimeout(function () {
  16087. //trace:3681
  16088. adjustHeight.call(me);
  16089. }, 100);
  16090. });
  16091. //修复内容过多时,回到顶部,顶部内容被工具栏遮挡问题
  16092. var lastScrollY;
  16093. window.onscroll = function(){
  16094. if(lastScrollY === null){
  16095. lastScrollY = this.scrollY
  16096. }else if(this.scrollY == 0 && lastScrollY != 0){
  16097. me.window.scrollTo(0,0);
  16098. lastScrollY = null;
  16099. }
  16100. }
  16101. });
  16102. };
  16103. // plugins/autofloat.js
  16104. ///import core
  16105. ///commands 悬浮工具栏
  16106. ///commandsName AutoFloat,autoFloatEnabled
  16107. ///commandsTitle 悬浮工具栏
  16108. /**
  16109. * modified by chengchao01
  16110. * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉!
  16111. */
  16112. UE.plugins['autofloat'] = function() {
  16113. var me = this,
  16114. lang = me.getLang();
  16115. me.setOpt({
  16116. topOffset:0
  16117. });
  16118. var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false,
  16119. topOffset = me.options.topOffset;
  16120. //如果不固定toolbar的位置,则直接退出
  16121. if(!optsAutoFloatEnabled){
  16122. return;
  16123. }
  16124. var uiUtils = UE.ui.uiUtils,
  16125. LteIE6 = browser.ie && browser.version <= 6,
  16126. quirks = browser.quirks;
  16127. function checkHasUI(){
  16128. if(!UE.ui){
  16129. alert(lang.autofloatMsg);
  16130. return 0;
  16131. }
  16132. return 1;
  16133. }
  16134. function fixIE6FixedPos(){
  16135. var docStyle = document.body.style;
  16136. docStyle.backgroundImage = 'url("about:blank")';
  16137. docStyle.backgroundAttachment = 'fixed';
  16138. }
  16139. var bakCssText,
  16140. placeHolder = document.createElement('div'),
  16141. toolbarBox,orgTop,
  16142. getPosition,
  16143. flag =true; //ie7模式下需要偏移
  16144. function setFloating(){
  16145. var toobarBoxPos = domUtils.getXY(toolbarBox),
  16146. origalFloat = domUtils.getComputedStyle(toolbarBox,'position'),
  16147. origalLeft = domUtils.getComputedStyle(toolbarBox,'left');
  16148. toolbarBox.style.width = toolbarBox.offsetWidth + 'px';
  16149. toolbarBox.style.zIndex = me.options.zIndex * 1 + 1;
  16150. toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox);
  16151. if (LteIE6 || (quirks && browser.ie)) {
  16152. if(toolbarBox.style.position != 'absolute'){
  16153. toolbarBox.style.position = 'absolute';
  16154. }
  16155. toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px';
  16156. } else {
  16157. if (browser.ie7Compat && flag) {
  16158. flag = false;
  16159. toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px';
  16160. }
  16161. if(toolbarBox.style.position != 'fixed'){
  16162. toolbarBox.style.position = 'fixed';
  16163. toolbarBox.style.top = topOffset +"px";
  16164. ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px');
  16165. }
  16166. }
  16167. }
  16168. function unsetFloating(){
  16169. flag = true;
  16170. if(placeHolder.parentNode){
  16171. placeHolder.parentNode.removeChild(placeHolder);
  16172. }
  16173. toolbarBox.style.cssText = bakCssText;
  16174. }
  16175. function updateFloating(){
  16176. var rect3 = getPosition(me.container);
  16177. var offset=me.options.toolbarTopOffset||0;
  16178. if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) {
  16179. setFloating();
  16180. }else{
  16181. unsetFloating();
  16182. }
  16183. }
  16184. var defer_updateFloating = utils.defer(function(){
  16185. updateFloating();
  16186. },browser.ie ? 200 : 100,true);
  16187. me.addListener('destroy',function(){
  16188. domUtils.un(window, ['scroll','resize'], updateFloating);
  16189. me.removeListener('keydown', defer_updateFloating);
  16190. });
  16191. me.addListener('ready', function(){
  16192. if(checkHasUI(me)){
  16193. //加载了ui组件,但在new时,没有加载ui,导致编辑器实例上没有ui类,所以这里做判断
  16194. if(!me.ui){
  16195. return;
  16196. }
  16197. getPosition = uiUtils.getClientRect;
  16198. toolbarBox = me.ui.getDom('toolbarbox');
  16199. orgTop = getPosition(toolbarBox).top;
  16200. bakCssText = toolbarBox.style.cssText;
  16201. placeHolder.style.height = toolbarBox.offsetHeight + 'px';
  16202. if(LteIE6){
  16203. fixIE6FixedPos();
  16204. }
  16205. domUtils.on(window, ['scroll','resize'], updateFloating);
  16206. me.addListener('keydown', defer_updateFloating);
  16207. me.addListener('beforefullscreenchange', function (t, enabled){
  16208. if (enabled) {
  16209. unsetFloating();
  16210. }
  16211. });
  16212. me.addListener('fullscreenchanged', function (t, enabled){
  16213. if (!enabled) {
  16214. updateFloating();
  16215. }
  16216. });
  16217. me.addListener('sourcemodechanged', function (t, enabled){
  16218. setTimeout(function (){
  16219. updateFloating();
  16220. },0);
  16221. });
  16222. me.addListener("clearDoc",function(){
  16223. setTimeout(function(){
  16224. updateFloating();
  16225. },0);
  16226. })
  16227. }
  16228. });
  16229. };
  16230. // plugins/video.js
  16231. /**
  16232. * video插件, 为UEditor提供视频插入支持
  16233. * @file
  16234. * @since 1.2.6.1
  16235. */
  16236. UE.plugins['video'] = function (){
  16237. var me =this;
  16238. /**
  16239. * 创建插入视频字符窜
  16240. * @param url 视频地址
  16241. * @param width 视频宽度
  16242. * @param height 视频高度
  16243. * @param align 视频对齐
  16244. * @param toEmbed 是否以flash代替显示
  16245. * @param addParagraph 是否需要添加P 标签
  16246. */
  16247. function creatInsertStr(url,width,height,id,align,classname,type){
  16248. url = utils.unhtmlForUrl(url);
  16249. align = utils.unhtml(align);
  16250. classname = utils.unhtml(classname);
  16251. width = parseInt(width, 10) || 0;
  16252. height = parseInt(height, 10) || 0;
  16253. var str;
  16254. switch (type){
  16255. case 'image':
  16256. str = '<img ' + (id ? 'id="' + id+'"' : '') + ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="' + classname.replace(/\bvideo-js\b/, '') + '"' +
  16257. ' 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 + ';': '')+'" />'
  16258. break;
  16259. case 'embed':
  16260. str = '<embed type="application/x-shockwave-flash" class="' + classname + '" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  16261. ' src="' + utils.html(url) + '" width="' + width + '" height="' + height + '"' + (align ? ' style="float:' + align + '"': '') +
  16262. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  16263. break;
  16264. case 'video':
  16265. var ext = url.substr(url.lastIndexOf('.') + 1);
  16266. if(ext == 'ogv') ext = 'ogg';
  16267. str = '<video' + (id ? ' id="' + id + '"' : '') + ' class="' + classname + ' video-js" ' + (align ? ' style="float:' + align + '"': '') +
  16268. ' controls preload="none" width="' + width + '" height="' + height + '" src="' + url + '" data-setup="{}">' +
  16269. '<source src="' + url + '" type="video/' + ext + '" /></video>';
  16270. break;
  16271. }
  16272. return str;
  16273. }
  16274. function switchImgAndVideo(root,img2video){
  16275. utils.each(root.getNodesByTagName(img2video ? 'img' : 'embed video'),function(node){
  16276. var className = node.getAttr('class');
  16277. if(className && className.indexOf('edui-faked-video') != -1){
  16278. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'embed':'image');
  16279. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16280. }
  16281. if(className && className.indexOf('edui-upload-video') != -1){
  16282. var html = creatInsertStr( img2video ? node.getAttr('_url') : node.getAttr('src'),node.getAttr('width'),node.getAttr('height'),null,node.getStyle('float') || '',className,img2video ? 'video':'image');
  16283. node.parentNode.replaceChild(UE.uNode.createElement(html),node);
  16284. }
  16285. })
  16286. }
  16287. me.addOutputRule(function(root){
  16288. switchImgAndVideo(root,true)
  16289. });
  16290. me.addInputRule(function(root){
  16291. switchImgAndVideo(root)
  16292. });
  16293. /**
  16294. * 插入视频
  16295. * @command insertvideo
  16296. * @method execCommand
  16297. * @param { String } cmd 命令字符串
  16298. * @param { Object } videoAttr 键值对对象, 描述一个视频的所有属性
  16299. * @example
  16300. * ```javascript
  16301. *
  16302. * var videoAttr = {
  16303. * //视频地址
  16304. * url: 'http://www.youku.com/xxx',
  16305. * //视频宽高值, 单位px
  16306. * width: 200,
  16307. * height: 100
  16308. * };
  16309. *
  16310. * //editor 是编辑器实例
  16311. * //向编辑器插入单个视频
  16312. * editor.execCommand( 'insertvideo', videoAttr );
  16313. * ```
  16314. */
  16315. /**
  16316. * 插入视频
  16317. * @command insertvideo
  16318. * @method execCommand
  16319. * @param { String } cmd 命令字符串
  16320. * @param { Array } videoArr 需要插入的视频的数组, 其中的每一个元素都是一个键值对对象, 描述了一个视频的所有属性
  16321. * @example
  16322. * ```javascript
  16323. *
  16324. * var videoAttr1 = {
  16325. * //视频地址
  16326. * url: 'http://www.youku.com/xxx',
  16327. * //视频宽高值, 单位px
  16328. * width: 200,
  16329. * height: 100
  16330. * },
  16331. * videoAttr2 = {
  16332. * //视频地址
  16333. * url: 'http://www.youku.com/xxx',
  16334. * //视频宽高值, 单位px
  16335. * width: 200,
  16336. * height: 100
  16337. * }
  16338. *
  16339. * //editor 是编辑器实例
  16340. * //该方法将会向编辑器内插入两个视频
  16341. * editor.execCommand( 'insertvideo', [ videoAttr1, videoAttr2 ] );
  16342. * ```
  16343. */
  16344. /**
  16345. * 查询当前光标所在处是否是一个视频
  16346. * @command insertvideo
  16347. * @method queryCommandState
  16348. * @param { String } cmd 需要查询的命令字符串
  16349. * @return { int } 如果当前光标所在处的元素是一个视频对象, 则返回1,否则返回0
  16350. * @example
  16351. * ```javascript
  16352. *
  16353. * //editor 是编辑器实例
  16354. * editor.queryCommandState( 'insertvideo' );
  16355. * ```
  16356. */
  16357. me.commands["insertvideo"] = {
  16358. execCommand: function (cmd, videoObjs, type){
  16359. videoObjs = utils.isArray(videoObjs)?videoObjs:[videoObjs];
  16360. var html = [],id = 'tmpVedio', cl;
  16361. for(var i=0,vi,len = videoObjs.length;i<len;i++){
  16362. vi = videoObjs[i];
  16363. cl = (type == 'upload' ? 'edui-upload-video video-js vjs-default-skin':'edui-faked-video');
  16364. html.push(creatInsertStr( vi.url, vi.width || 420, vi.height || 280, id + i, null, cl, 'image'));
  16365. }
  16366. me.execCommand("inserthtml",html.join(""),true);
  16367. var rng = this.selection.getRange();
  16368. for(var i= 0,len=videoObjs.length;i<len;i++){
  16369. var img = this.document.getElementById('tmpVedio'+i);
  16370. domUtils.removeAttributes(img,'id');
  16371. rng.selectNode(img).select();
  16372. me.execCommand('imagefloat',videoObjs[i].align)
  16373. }
  16374. },
  16375. queryCommandState : function(){
  16376. var img = me.selection.getRange().getClosedNode(),
  16377. flag = img && (img.className == "edui-faked-video" || img.className.indexOf("edui-upload-video")!=-1);
  16378. return flag ? 1 : 0;
  16379. }
  16380. };
  16381. };
  16382. // plugins/table.core.js
  16383. /**
  16384. * Created with JetBrains WebStorm.
  16385. * User: taoqili
  16386. * Date: 13-1-18
  16387. * Time: 上午11:09
  16388. * To change this template use File | Settings | File Templates.
  16389. */
  16390. /**
  16391. * UE表格操作类
  16392. * @param table
  16393. * @constructor
  16394. */
  16395. (function () {
  16396. var UETable = UE.UETable = function (table) {
  16397. this.table = table;
  16398. this.indexTable = [];
  16399. this.selectedTds = [];
  16400. this.cellsRange = {};
  16401. this.update(table);
  16402. };
  16403. //===以下为静态工具方法===
  16404. UETable.removeSelectedClass = function (cells) {
  16405. utils.each(cells, function (cell) {
  16406. domUtils.removeClasses(cell, "selectTdClass");
  16407. })
  16408. };
  16409. UETable.addSelectedClass = function (cells) {
  16410. utils.each(cells, function (cell) {
  16411. domUtils.addClass(cell, "selectTdClass");
  16412. })
  16413. };
  16414. UETable.isEmptyBlock = function (node) {
  16415. var reg = new RegExp(domUtils.fillChar, 'g');
  16416. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  16417. return 0;
  16418. }
  16419. for (var i in dtd.$isNotEmpty) if (dtd.$isNotEmpty.hasOwnProperty(i)) {
  16420. if (node.getElementsByTagName(i).length) {
  16421. return 0;
  16422. }
  16423. }
  16424. return 1;
  16425. };
  16426. UETable.getWidth = function (cell) {
  16427. if (!cell)return 0;
  16428. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  16429. };
  16430. /**
  16431. * 获取单元格或者单元格组的“对齐”状态。 如果当前的检测对象是一个单元格组, 只有在满足所有单元格的 水平和竖直 对齐属性都相同的
  16432. * 条件时才会返回其状态值,否则将返回null; 如果当前只检测了一个单元格, 则直接返回当前单元格的对齐状态;
  16433. * @param table cell or table cells , 支持单个单元格dom对象 或者 单元格dom对象数组
  16434. * @return { align: 'left' || 'right' || 'center', valign: 'top' || 'middle' || 'bottom' } 或者 null
  16435. */
  16436. UETable.getTableCellAlignState = function ( cells ) {
  16437. !utils.isArray( cells ) && ( cells = [cells] );
  16438. var result = {},
  16439. status = ['align', 'valign'],
  16440. tempStatus = null,
  16441. isSame = true;//状态是否相同
  16442. utils.each( cells, function( cellNode ){
  16443. utils.each( status, function( currentState ){
  16444. tempStatus = cellNode.getAttribute( currentState );
  16445. if( !result[ currentState ] && tempStatus ) {
  16446. result[ currentState ] = tempStatus;
  16447. } else if( !result[ currentState ] || ( tempStatus !== result[ currentState ] ) ) {
  16448. isSame = false;
  16449. return false;
  16450. }
  16451. } );
  16452. return isSame;
  16453. });
  16454. return isSame ? result : null;
  16455. };
  16456. /**
  16457. * 根据当前选区获取相关的table信息
  16458. * @return {Object}
  16459. */
  16460. UETable.getTableItemsByRange = function (editor) {
  16461. var start = editor.selection.getStart();
  16462. //ff下会选中bookmark
  16463. if( start && start.id && start.id.indexOf('_baidu_bookmark_start_') === 0 && start.nextSibling) {
  16464. start = start.nextSibling;
  16465. }
  16466. //在table或者td边缘有可能存在选中tr的情况
  16467. var cell = start && domUtils.findParentByTagName(start, ["td", "th"], true),
  16468. tr = cell && cell.parentNode,
  16469. caption = start && domUtils.findParentByTagName(start, 'caption', true),
  16470. table = caption ? caption.parentNode : tr && tr.parentNode.parentNode;
  16471. return {
  16472. cell:cell,
  16473. tr:tr,
  16474. table:table,
  16475. caption:caption
  16476. }
  16477. };
  16478. UETable.getUETableBySelected = function (editor) {
  16479. var table = UETable.getTableItemsByRange(editor).table;
  16480. if (table && table.ueTable && table.ueTable.selectedTds.length) {
  16481. return table.ueTable;
  16482. }
  16483. return null;
  16484. };
  16485. UETable.getDefaultValue = function (editor, table) {
  16486. var borderMap = {
  16487. thin:'0px',
  16488. medium:'1px',
  16489. thick:'2px'
  16490. },
  16491. tableBorder, tdPadding, tdBorder, tmpValue;
  16492. if (!table) {
  16493. table = editor.document.createElement('table');
  16494. table.insertRow(0).insertCell(0).innerHTML = 'xxx';
  16495. editor.body.appendChild(table);
  16496. var td = table.getElementsByTagName('td')[0];
  16497. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16498. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16499. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16500. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16501. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16502. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16503. domUtils.remove(table);
  16504. return {
  16505. tableBorder:tableBorder,
  16506. tdPadding:tdPadding,
  16507. tdBorder:tdBorder
  16508. };
  16509. } else {
  16510. td = table.getElementsByTagName('td')[0];
  16511. tmpValue = domUtils.getComputedStyle(table, 'border-left-width');
  16512. tableBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16513. tmpValue = domUtils.getComputedStyle(td, 'padding-left');
  16514. tdPadding = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16515. tmpValue = domUtils.getComputedStyle(td, 'border-left-width');
  16516. tdBorder = parseInt(borderMap[tmpValue] || tmpValue, 10);
  16517. return {
  16518. tableBorder:tableBorder,
  16519. tdPadding:tdPadding,
  16520. tdBorder:tdBorder
  16521. };
  16522. }
  16523. };
  16524. /**
  16525. * 根据当前点击的td或者table获取索引对象
  16526. * @param tdOrTable
  16527. */
  16528. UETable.getUETable = function (tdOrTable) {
  16529. var tag = tdOrTable.tagName.toLowerCase();
  16530. tdOrTable = (tag == "td" || tag == "th" || tag == 'caption') ? domUtils.findParentByTagName(tdOrTable, "table", true) : tdOrTable;
  16531. if (!tdOrTable.ueTable) {
  16532. tdOrTable.ueTable = new UETable(tdOrTable);
  16533. }
  16534. return tdOrTable.ueTable;
  16535. };
  16536. UETable.cloneCell = function(cell,ignoreMerge,keepPro){
  16537. if (!cell || utils.isString(cell)) {
  16538. return this.table.ownerDocument.createElement(cell || 'td');
  16539. }
  16540. var flag = domUtils.hasClass(cell, "selectTdClass");
  16541. flag && domUtils.removeClasses(cell, "selectTdClass");
  16542. var tmpCell = cell.cloneNode(true);
  16543. if (ignoreMerge) {
  16544. tmpCell.rowSpan = tmpCell.colSpan = 1;
  16545. }
  16546. //去掉宽高
  16547. !keepPro && domUtils.removeAttributes(tmpCell,'width height');
  16548. !keepPro && domUtils.removeAttributes(tmpCell,'style');
  16549. tmpCell.style.borderLeftStyle = "";
  16550. tmpCell.style.borderTopStyle = "";
  16551. tmpCell.style.borderLeftColor = cell.style.borderRightColor;
  16552. tmpCell.style.borderLeftWidth = cell.style.borderRightWidth;
  16553. tmpCell.style.borderTopColor = cell.style.borderBottomColor;
  16554. tmpCell.style.borderTopWidth = cell.style.borderBottomWidth;
  16555. flag && domUtils.addClass(cell, "selectTdClass");
  16556. return tmpCell;
  16557. }
  16558. UETable.prototype = {
  16559. getMaxRows:function () {
  16560. var rows = this.table.rows, maxLen = 1;
  16561. for (var i = 0, row; row = rows[i]; i++) {
  16562. var currentMax = 1;
  16563. for (var j = 0, cj; cj = row.cells[j++];) {
  16564. currentMax = Math.max(cj.rowSpan || 1, currentMax);
  16565. }
  16566. maxLen = Math.max(currentMax + i, maxLen);
  16567. }
  16568. return maxLen;
  16569. },
  16570. /**
  16571. * 获取当前表格的最大列数
  16572. */
  16573. getMaxCols:function () {
  16574. var rows = this.table.rows, maxLen = 0, cellRows = {};
  16575. for (var i = 0, row; row = rows[i]; i++) {
  16576. var cellsNum = 0;
  16577. for (var j = 0, cj; cj = row.cells[j++];) {
  16578. cellsNum += (cj.colSpan || 1);
  16579. if (cj.rowSpan && cj.rowSpan > 1) {
  16580. for (var k = 1; k < cj.rowSpan; k++) {
  16581. if (!cellRows['row_' + (i + k)]) {
  16582. cellRows['row_' + (i + k)] = (cj.colSpan || 1);
  16583. } else {
  16584. cellRows['row_' + (i + k)]++
  16585. }
  16586. }
  16587. }
  16588. }
  16589. cellsNum += cellRows['row_' + i] || 0;
  16590. maxLen = Math.max(cellsNum, maxLen);
  16591. }
  16592. return maxLen;
  16593. },
  16594. getCellColIndex:function (cell) {
  16595. },
  16596. /**
  16597. * 获取当前cell旁边的单元格,
  16598. * @param cell
  16599. * @param right
  16600. */
  16601. getHSideCell:function (cell, right) {
  16602. try {
  16603. var cellInfo = this.getCellInfo(cell),
  16604. previewRowIndex, previewColIndex;
  16605. var len = this.selectedTds.length,
  16606. range = this.cellsRange;
  16607. //首行或者首列没有前置单元格
  16608. if ((!right && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (right && (!len ? (cellInfo.colIndex == (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  16609. previewRowIndex = !len ? cellInfo.rowIndex : range.beginRowIndex;
  16610. previewColIndex = !right ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  16611. : ( !len ? cellInfo.colIndex + 1 : range.endColIndex + 1);
  16612. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  16613. } catch (e) {
  16614. showError(e);
  16615. }
  16616. },
  16617. getTabNextCell:function (cell, preRowIndex) {
  16618. var cellInfo = this.getCellInfo(cell),
  16619. rowIndex = preRowIndex || cellInfo.rowIndex,
  16620. colIndex = cellInfo.colIndex + 1 + (cellInfo.colSpan - 1),
  16621. nextCell;
  16622. try {
  16623. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16624. } catch (e) {
  16625. try {
  16626. rowIndex = rowIndex * 1 + 1;
  16627. colIndex = 0;
  16628. nextCell = this.getCell(this.indexTable[rowIndex][colIndex].rowIndex, this.indexTable[rowIndex][colIndex].cellIndex);
  16629. } catch (e) {
  16630. }
  16631. }
  16632. return nextCell;
  16633. },
  16634. /**
  16635. * 获取视觉上的后置单元格
  16636. * @param cell
  16637. * @param bottom
  16638. */
  16639. getVSideCell:function (cell, bottom, ignoreRange) {
  16640. try {
  16641. var cellInfo = this.getCellInfo(cell),
  16642. nextRowIndex, nextColIndex;
  16643. var len = this.selectedTds.length && !ignoreRange,
  16644. range = this.cellsRange;
  16645. //末行或者末列没有后置单元格
  16646. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16647. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16648. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16649. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16650. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16651. } catch (e) {
  16652. showError(e);
  16653. }
  16654. },
  16655. /**
  16656. * 获取相同结束位置的单元格,xOrY指代了是获取x轴相同还是y轴相同
  16657. */
  16658. getSameEndPosCells:function (cell, xOrY) {
  16659. try {
  16660. var flag = (xOrY.toLowerCase() === "x"),
  16661. end = domUtils.getXY(cell)[flag ? 'x' : 'y'] + cell["offset" + (flag ? 'Width' : 'Height')],
  16662. rows = this.table.rows,
  16663. cells = null, returns = [];
  16664. for (var i = 0; i < this.rowsNum; i++) {
  16665. cells = rows[i].cells;
  16666. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16667. var tmpEnd = domUtils.getXY(tmpCell)[flag ? 'x' : 'y'] + tmpCell["offset" + (flag ? 'Width' : 'Height')];
  16668. //对应行的td已经被上面行rowSpan了
  16669. if (tmpEnd > end && flag) break;
  16670. if (cell == tmpCell || end == tmpEnd) {
  16671. //只获取单一的单元格
  16672. //todo 仅获取单一单元格在特定情况下会造成returns为空,从而影响后续的拖拽实现,修正这个。需考虑性能
  16673. if (tmpCell[flag ? "colSpan" : "rowSpan"] == 1) {
  16674. returns.push(tmpCell);
  16675. }
  16676. if (flag) break;
  16677. }
  16678. }
  16679. }
  16680. return returns;
  16681. } catch (e) {
  16682. showError(e);
  16683. }
  16684. },
  16685. setCellContent:function (cell, content) {
  16686. cell.innerHTML = content || (browser.ie ? domUtils.fillChar : "<br />");
  16687. },
  16688. cloneCell:UETable.cloneCell,
  16689. /**
  16690. * 获取跟当前单元格的右边竖线为左边的所有未合并单元格
  16691. */
  16692. getSameStartPosXCells:function (cell) {
  16693. try {
  16694. var start = domUtils.getXY(cell).x + cell.offsetWidth,
  16695. rows = this.table.rows, cells , returns = [];
  16696. for (var i = 0; i < this.rowsNum; i++) {
  16697. cells = rows[i].cells;
  16698. for (var j = 0, tmpCell; tmpCell = cells[j++];) {
  16699. var tmpStart = domUtils.getXY(tmpCell).x;
  16700. if (tmpStart > start) break;
  16701. if (tmpStart == start && tmpCell.colSpan == 1) {
  16702. returns.push(tmpCell);
  16703. break;
  16704. }
  16705. }
  16706. }
  16707. return returns;
  16708. } catch (e) {
  16709. showError(e);
  16710. }
  16711. },
  16712. /**
  16713. * 更新table对应的索引表
  16714. */
  16715. update:function (table) {
  16716. this.table = table || this.table;
  16717. this.selectedTds = [];
  16718. this.cellsRange = {};
  16719. this.indexTable = [];
  16720. var rows = this.table.rows,
  16721. rowsNum = this.getMaxRows(),
  16722. dNum = rowsNum - rows.length,
  16723. colsNum = this.getMaxCols();
  16724. while (dNum--) {
  16725. this.table.insertRow(rows.length);
  16726. }
  16727. this.rowsNum = rowsNum;
  16728. this.colsNum = colsNum;
  16729. for (var i = 0, len = rows.length; i < len; i++) {
  16730. this.indexTable[i] = new Array(colsNum);
  16731. }
  16732. //填充索引表
  16733. for (var rowIndex = 0, row; row = rows[rowIndex]; rowIndex++) {
  16734. for (var cellIndex = 0, cell, cells = row.cells; cell = cells[cellIndex]; cellIndex++) {
  16735. //修正整行被rowSpan时导致的行数计算错误
  16736. if (cell.rowSpan > rowsNum) {
  16737. cell.rowSpan = rowsNum;
  16738. }
  16739. var colIndex = cellIndex,
  16740. rowSpan = cell.rowSpan || 1,
  16741. colSpan = cell.colSpan || 1;
  16742. //当已经被上一行rowSpan或者被前一列colSpan了,则跳到下一个单元格进行
  16743. while (this.indexTable[rowIndex][colIndex]) colIndex++;
  16744. for (var j = 0; j < rowSpan; j++) {
  16745. for (var k = 0; k < colSpan; k++) {
  16746. this.indexTable[rowIndex + j][colIndex + k] = {
  16747. rowIndex:rowIndex,
  16748. cellIndex:cellIndex,
  16749. colIndex:colIndex,
  16750. rowSpan:rowSpan,
  16751. colSpan:colSpan
  16752. }
  16753. }
  16754. }
  16755. }
  16756. }
  16757. //修复残缺td
  16758. for (j = 0; j < rowsNum; j++) {
  16759. for (k = 0; k < colsNum; k++) {
  16760. if (this.indexTable[j][k] === undefined) {
  16761. row = rows[j];
  16762. cell = row.cells[row.cells.length - 1];
  16763. cell = cell ? cell.cloneNode(true) : this.table.ownerDocument.createElement("td");
  16764. this.setCellContent(cell);
  16765. if (cell.colSpan !== 1)cell.colSpan = 1;
  16766. if (cell.rowSpan !== 1)cell.rowSpan = 1;
  16767. row.appendChild(cell);
  16768. this.indexTable[j][k] = {
  16769. rowIndex:j,
  16770. cellIndex:cell.cellIndex,
  16771. colIndex:k,
  16772. rowSpan:1,
  16773. colSpan:1
  16774. }
  16775. }
  16776. }
  16777. }
  16778. //当框选后删除行或者列后撤销,需要重建选区。
  16779. var tds = domUtils.getElementsByTagName(this.table, "td"),
  16780. selectTds = [];
  16781. utils.each(tds, function (td) {
  16782. if (domUtils.hasClass(td, "selectTdClass")) {
  16783. selectTds.push(td);
  16784. }
  16785. });
  16786. if (selectTds.length) {
  16787. var start = selectTds[0],
  16788. end = selectTds[selectTds.length - 1],
  16789. startInfo = this.getCellInfo(start),
  16790. endInfo = this.getCellInfo(end);
  16791. this.selectedTds = selectTds;
  16792. this.cellsRange = {
  16793. beginRowIndex:startInfo.rowIndex,
  16794. beginColIndex:startInfo.colIndex,
  16795. endRowIndex:endInfo.rowIndex + endInfo.rowSpan - 1,
  16796. endColIndex:endInfo.colIndex + endInfo.colSpan - 1
  16797. };
  16798. }
  16799. //给第一行设置firstRow的样式名称,在排序图标的样式上使用到
  16800. if(!domUtils.hasClass(this.table.rows[0], "firstRow")) {
  16801. domUtils.addClass(this.table.rows[0], "firstRow");
  16802. for(var i = 1; i< this.table.rows.length; i++) {
  16803. domUtils.removeClasses(this.table.rows[i], "firstRow");
  16804. }
  16805. }
  16806. },
  16807. /**
  16808. * 获取单元格的索引信息
  16809. */
  16810. getCellInfo:function (cell) {
  16811. if (!cell) return;
  16812. var cellIndex = cell.cellIndex,
  16813. rowIndex = cell.parentNode.rowIndex,
  16814. rowInfo = this.indexTable[rowIndex],
  16815. numCols = this.colsNum;
  16816. for (var colIndex = cellIndex; colIndex < numCols; colIndex++) {
  16817. var cellInfo = rowInfo[colIndex];
  16818. if (cellInfo.rowIndex === rowIndex && cellInfo.cellIndex === cellIndex) {
  16819. return cellInfo;
  16820. }
  16821. }
  16822. },
  16823. /**
  16824. * 根据行列号获取单元格
  16825. */
  16826. getCell:function (rowIndex, cellIndex) {
  16827. return rowIndex < this.rowsNum && this.table.rows[rowIndex].cells[cellIndex] || null;
  16828. },
  16829. /**
  16830. * 删除单元格
  16831. */
  16832. deleteCell:function (cell, rowIndex) {
  16833. rowIndex = typeof rowIndex == 'number' ? rowIndex : cell.parentNode.rowIndex;
  16834. var row = this.table.rows[rowIndex];
  16835. row.deleteCell(cell.cellIndex);
  16836. },
  16837. /**
  16838. * 根据始末两个单元格获取被框选的所有单元格范围
  16839. */
  16840. getCellsRange:function (cellA, cellB) {
  16841. function checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex) {
  16842. var tmpBeginRowIndex = beginRowIndex,
  16843. tmpBeginColIndex = beginColIndex,
  16844. tmpEndRowIndex = endRowIndex,
  16845. tmpEndColIndex = endColIndex,
  16846. cellInfo, colIndex, rowIndex;
  16847. // 通过indexTable检查是否存在超出TableRange上边界的情况
  16848. if (beginRowIndex > 0) {
  16849. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16850. cellInfo = me.indexTable[beginRowIndex][colIndex];
  16851. rowIndex = cellInfo.rowIndex;
  16852. if (rowIndex < beginRowIndex) {
  16853. tmpBeginRowIndex = Math.min(rowIndex, tmpBeginRowIndex);
  16854. }
  16855. }
  16856. }
  16857. // 通过indexTable检查是否存在超出TableRange右边界的情况
  16858. if (endColIndex < me.colsNum) {
  16859. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16860. cellInfo = me.indexTable[rowIndex][endColIndex];
  16861. colIndex = cellInfo.colIndex + cellInfo.colSpan - 1;
  16862. if (colIndex > endColIndex) {
  16863. tmpEndColIndex = Math.max(colIndex, tmpEndColIndex);
  16864. }
  16865. }
  16866. }
  16867. // 检查是否有超出TableRange下边界的情况
  16868. if (endRowIndex < me.rowsNum) {
  16869. for (colIndex = beginColIndex; colIndex < endColIndex; colIndex++) {
  16870. cellInfo = me.indexTable[endRowIndex][colIndex];
  16871. rowIndex = cellInfo.rowIndex + cellInfo.rowSpan - 1;
  16872. if (rowIndex > endRowIndex) {
  16873. tmpEndRowIndex = Math.max(rowIndex, tmpEndRowIndex);
  16874. }
  16875. }
  16876. }
  16877. // 检查是否有超出TableRange左边界的情况
  16878. if (beginColIndex > 0) {
  16879. for (rowIndex = beginRowIndex; rowIndex < endRowIndex; rowIndex++) {
  16880. cellInfo = me.indexTable[rowIndex][beginColIndex];
  16881. colIndex = cellInfo.colIndex;
  16882. if (colIndex < beginColIndex) {
  16883. tmpBeginColIndex = Math.min(cellInfo.colIndex, tmpBeginColIndex);
  16884. }
  16885. }
  16886. }
  16887. //递归调用直至所有完成所有框选单元格的扩展
  16888. if (tmpBeginRowIndex != beginRowIndex || tmpBeginColIndex != beginColIndex || tmpEndRowIndex != endRowIndex || tmpEndColIndex != endColIndex) {
  16889. return checkRange(tmpBeginRowIndex, tmpBeginColIndex, tmpEndRowIndex, tmpEndColIndex);
  16890. } else {
  16891. // 不需要扩展TableRange的情况
  16892. return {
  16893. beginRowIndex:beginRowIndex,
  16894. beginColIndex:beginColIndex,
  16895. endRowIndex:endRowIndex,
  16896. endColIndex:endColIndex
  16897. };
  16898. }
  16899. }
  16900. try {
  16901. var me = this,
  16902. cellAInfo = me.getCellInfo(cellA);
  16903. if (cellA === cellB) {
  16904. return {
  16905. beginRowIndex:cellAInfo.rowIndex,
  16906. beginColIndex:cellAInfo.colIndex,
  16907. endRowIndex:cellAInfo.rowIndex + cellAInfo.rowSpan - 1,
  16908. endColIndex:cellAInfo.colIndex + cellAInfo.colSpan - 1
  16909. };
  16910. }
  16911. var cellBInfo = me.getCellInfo(cellB);
  16912. // 计算TableRange的四个边
  16913. var beginRowIndex = Math.min(cellAInfo.rowIndex, cellBInfo.rowIndex),
  16914. beginColIndex = Math.min(cellAInfo.colIndex, cellBInfo.colIndex),
  16915. endRowIndex = Math.max(cellAInfo.rowIndex + cellAInfo.rowSpan - 1, cellBInfo.rowIndex + cellBInfo.rowSpan - 1),
  16916. endColIndex = Math.max(cellAInfo.colIndex + cellAInfo.colSpan - 1, cellBInfo.colIndex + cellBInfo.colSpan - 1);
  16917. return checkRange(beginRowIndex, beginColIndex, endRowIndex, endColIndex);
  16918. } catch (e) {
  16919. //throw e;
  16920. }
  16921. },
  16922. /**
  16923. * 依据cellsRange获取对应的单元格集合
  16924. */
  16925. getCells:function (range) {
  16926. //每次获取cells之前必须先清除上次的选择,否则会对后续获取操作造成影响
  16927. this.clearSelected();
  16928. var beginRowIndex = range.beginRowIndex,
  16929. beginColIndex = range.beginColIndex,
  16930. endRowIndex = range.endRowIndex,
  16931. endColIndex = range.endColIndex,
  16932. cellInfo, rowIndex, colIndex, tdHash = {}, returnTds = [];
  16933. for (var i = beginRowIndex; i <= endRowIndex; i++) {
  16934. for (var j = beginColIndex; j <= endColIndex; j++) {
  16935. cellInfo = this.indexTable[i][j];
  16936. rowIndex = cellInfo.rowIndex;
  16937. colIndex = cellInfo.colIndex;
  16938. // 如果Cells里已经包含了此Cell则跳过
  16939. var key = rowIndex + '|' + colIndex;
  16940. if (tdHash[key]) continue;
  16941. tdHash[key] = 1;
  16942. if (rowIndex < i || colIndex < j || rowIndex + cellInfo.rowSpan - 1 > endRowIndex || colIndex + cellInfo.colSpan - 1 > endColIndex) {
  16943. return null;
  16944. }
  16945. returnTds.push(this.getCell(rowIndex, cellInfo.cellIndex));
  16946. }
  16947. }
  16948. return returnTds;
  16949. },
  16950. /**
  16951. * 清理已经选中的单元格
  16952. */
  16953. clearSelected:function () {
  16954. UETable.removeSelectedClass(this.selectedTds);
  16955. this.selectedTds = [];
  16956. this.cellsRange = {};
  16957. },
  16958. /**
  16959. * 根据range设置已经选中的单元格
  16960. */
  16961. setSelected:function (range) {
  16962. var cells = this.getCells(range);
  16963. UETable.addSelectedClass(cells);
  16964. this.selectedTds = cells;
  16965. this.cellsRange = range;
  16966. },
  16967. isFullRow:function () {
  16968. var range = this.cellsRange;
  16969. return (range.endColIndex - range.beginColIndex + 1) == this.colsNum;
  16970. },
  16971. isFullCol:function () {
  16972. var range = this.cellsRange,
  16973. table = this.table,
  16974. ths = table.getElementsByTagName("th"),
  16975. rows = range.endRowIndex - range.beginRowIndex + 1;
  16976. return !ths.length ? rows == this.rowsNum : rows == this.rowsNum || (rows == this.rowsNum - 1);
  16977. },
  16978. /**
  16979. * 获取视觉上的前置单元格,默认是左边,top传入时
  16980. * @param cell
  16981. * @param top
  16982. */
  16983. getNextCell:function (cell, bottom, ignoreRange) {
  16984. try {
  16985. var cellInfo = this.getCellInfo(cell),
  16986. nextRowIndex, nextColIndex;
  16987. var len = this.selectedTds.length && !ignoreRange,
  16988. range = this.cellsRange;
  16989. //末行或者末列没有后置单元格
  16990. if ((!bottom && (cellInfo.rowIndex == 0)) || (bottom && (!len ? (cellInfo.rowIndex + cellInfo.rowSpan > this.rowsNum - 1) : (range.endRowIndex == this.rowsNum - 1)))) return null;
  16991. nextRowIndex = !bottom ? ( !len ? cellInfo.rowIndex - 1 : range.beginRowIndex - 1)
  16992. : ( !len ? (cellInfo.rowIndex + cellInfo.rowSpan) : range.endRowIndex + 1);
  16993. nextColIndex = !len ? cellInfo.colIndex : range.beginColIndex;
  16994. return this.getCell(this.indexTable[nextRowIndex][nextColIndex].rowIndex, this.indexTable[nextRowIndex][nextColIndex].cellIndex);
  16995. } catch (e) {
  16996. showError(e);
  16997. }
  16998. },
  16999. getPreviewCell:function (cell, top) {
  17000. try {
  17001. var cellInfo = this.getCellInfo(cell),
  17002. previewRowIndex, previewColIndex;
  17003. var len = this.selectedTds.length,
  17004. range = this.cellsRange;
  17005. //首行或者首列没有前置单元格
  17006. if ((!top && (!len ? !cellInfo.colIndex : !range.beginColIndex)) || (top && (!len ? (cellInfo.rowIndex > (this.colsNum - 1)) : (range.endColIndex == this.colsNum - 1)))) return null;
  17007. previewRowIndex = !top ? ( !len ? cellInfo.rowIndex : range.beginRowIndex )
  17008. : ( !len ? (cellInfo.rowIndex < 1 ? 0 : (cellInfo.rowIndex - 1)) : range.beginRowIndex);
  17009. previewColIndex = !top ? ( !len ? (cellInfo.colIndex < 1 ? 0 : (cellInfo.colIndex - 1)) : range.beginColIndex - 1)
  17010. : ( !len ? cellInfo.colIndex : range.endColIndex + 1);
  17011. return this.getCell(this.indexTable[previewRowIndex][previewColIndex].rowIndex, this.indexTable[previewRowIndex][previewColIndex].cellIndex);
  17012. } catch (e) {
  17013. showError(e);
  17014. }
  17015. },
  17016. /**
  17017. * 移动单元格中的内容
  17018. */
  17019. moveContent:function (cellTo, cellFrom) {
  17020. if (UETable.isEmptyBlock(cellFrom)) return;
  17021. if (UETable.isEmptyBlock(cellTo)) {
  17022. cellTo.innerHTML = cellFrom.innerHTML;
  17023. return;
  17024. }
  17025. var child = cellTo.lastChild;
  17026. if (child.nodeType == 3 || !dtd.$block[child.tagName]) {
  17027. cellTo.appendChild(cellTo.ownerDocument.createElement('br'))
  17028. }
  17029. while (child = cellFrom.firstChild) {
  17030. cellTo.appendChild(child);
  17031. }
  17032. },
  17033. /**
  17034. * 向右合并单元格
  17035. */
  17036. mergeRight:function (cell) {
  17037. var cellInfo = this.getCellInfo(cell),
  17038. rightColIndex = cellInfo.colIndex + cellInfo.colSpan,
  17039. rightCellInfo = this.indexTable[cellInfo.rowIndex][rightColIndex],
  17040. rightCell = this.getCell(rightCellInfo.rowIndex, rightCellInfo.cellIndex);
  17041. //合并
  17042. cell.colSpan = cellInfo.colSpan + rightCellInfo.colSpan;
  17043. //被合并的单元格不应存在宽度属性
  17044. cell.removeAttribute("width");
  17045. //移动内容
  17046. this.moveContent(cell, rightCell);
  17047. //删掉被合并的Cell
  17048. this.deleteCell(rightCell, rightCellInfo.rowIndex);
  17049. this.update();
  17050. },
  17051. /**
  17052. * 向下合并单元格
  17053. */
  17054. mergeDown:function (cell) {
  17055. var cellInfo = this.getCellInfo(cell),
  17056. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan,
  17057. downCellInfo = this.indexTable[downRowIndex][cellInfo.colIndex],
  17058. downCell = this.getCell(downCellInfo.rowIndex, downCellInfo.cellIndex);
  17059. cell.rowSpan = cellInfo.rowSpan + downCellInfo.rowSpan;
  17060. cell.removeAttribute("height");
  17061. this.moveContent(cell, downCell);
  17062. this.deleteCell(downCell, downCellInfo.rowIndex);
  17063. this.update();
  17064. },
  17065. /**
  17066. * 合并整个range中的内容
  17067. */
  17068. mergeRange:function () {
  17069. //由于合并操作可以在任意时刻进行,所以无法通过鼠标位置等信息实时生成range,只能通过缓存实例中的cellsRange对象来访问
  17070. var range = this.cellsRange,
  17071. leftTopCell = this.getCell(range.beginRowIndex, this.indexTable[range.beginRowIndex][range.beginColIndex].cellIndex);
  17072. if (leftTopCell.tagName == "TH" && range.endRowIndex !== range.beginRowIndex) {
  17073. var index = this.indexTable,
  17074. info = this.getCellInfo(leftTopCell);
  17075. leftTopCell = this.getCell(1, index[1][info.colIndex].cellIndex);
  17076. range = this.getCellsRange(leftTopCell, this.getCell(index[this.rowsNum - 1][info.colIndex].rowIndex, index[this.rowsNum - 1][info.colIndex].cellIndex));
  17077. }
  17078. // 删除剩余的Cells
  17079. var cells = this.getCells(range);
  17080. for(var i= 0,ci;ci=cells[i++];){
  17081. if (ci !== leftTopCell) {
  17082. this.moveContent(leftTopCell, ci);
  17083. this.deleteCell(ci);
  17084. }
  17085. }
  17086. // 修改左上角Cell的rowSpan和colSpan,并调整宽度属性设置
  17087. leftTopCell.rowSpan = range.endRowIndex - range.beginRowIndex + 1;
  17088. leftTopCell.rowSpan > 1 && leftTopCell.removeAttribute("height");
  17089. leftTopCell.colSpan = range.endColIndex - range.beginColIndex + 1;
  17090. leftTopCell.colSpan > 1 && leftTopCell.removeAttribute("width");
  17091. if (leftTopCell.rowSpan == this.rowsNum && leftTopCell.colSpan != 1) {
  17092. leftTopCell.colSpan = 1;
  17093. }
  17094. if (leftTopCell.colSpan == this.colsNum && leftTopCell.rowSpan != 1) {
  17095. var rowIndex = leftTopCell.parentNode.rowIndex;
  17096. //解决IE下的表格操作问题
  17097. if( this.table.deleteRow ) {
  17098. for (var i = rowIndex+ 1, curIndex=rowIndex+ 1, len=leftTopCell.rowSpan; i < len; i++) {
  17099. this.table.deleteRow(curIndex);
  17100. }
  17101. } else {
  17102. for (var i = 0, len=leftTopCell.rowSpan - 1; i < len; i++) {
  17103. var row = this.table.rows[rowIndex + 1];
  17104. row.parentNode.removeChild(row);
  17105. }
  17106. }
  17107. leftTopCell.rowSpan = 1;
  17108. }
  17109. this.update();
  17110. },
  17111. /**
  17112. * 插入一行单元格
  17113. */
  17114. insertRow:function (rowIndex, sourceCell) {
  17115. var numCols = this.colsNum,
  17116. table = this.table,
  17117. row = table.insertRow(rowIndex), cell,
  17118. isInsertTitle = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17119. function replaceTdToTh(colIndex, cell, tableRow) {
  17120. if (colIndex == 0) {
  17121. var tr = tableRow.nextSibling || tableRow.previousSibling,
  17122. th = tr.cells[colIndex];
  17123. if (th.tagName == 'TH') {
  17124. th = cell.ownerDocument.createElement("th");
  17125. th.appendChild(cell.firstChild);
  17126. tableRow.insertBefore(th, cell);
  17127. domUtils.remove(cell)
  17128. }
  17129. }else{
  17130. if (cell.tagName == 'TH') {
  17131. var td = cell.ownerDocument.createElement("td");
  17132. td.appendChild(cell.firstChild);
  17133. tableRow.insertBefore(td, cell);
  17134. domUtils.remove(cell)
  17135. }
  17136. }
  17137. }
  17138. //首行直接插入,无需考虑部分单元格被rowspan的情况
  17139. if (rowIndex == 0 || rowIndex == this.rowsNum) {
  17140. for (var colIndex = 0; colIndex < numCols; colIndex++) {
  17141. cell = this.cloneCell(sourceCell, true);
  17142. this.setCellContent(cell);
  17143. cell.getAttribute('vAlign') && cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17144. row.appendChild(cell);
  17145. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17146. }
  17147. } else {
  17148. var infoRow = this.indexTable[rowIndex],
  17149. cellIndex = 0;
  17150. for (colIndex = 0; colIndex < numCols; colIndex++) {
  17151. var cellInfo = infoRow[colIndex];
  17152. //如果存在某个单元格的rowspan穿过待插入行的位置,则修改该单元格的rowspan即可,无需插入单元格
  17153. if (cellInfo.rowIndex < rowIndex) {
  17154. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17155. cell.rowSpan = cellInfo.rowSpan + 1;
  17156. } else {
  17157. cell = this.cloneCell(sourceCell, true);
  17158. this.setCellContent(cell);
  17159. row.appendChild(cell);
  17160. }
  17161. if(!isInsertTitle) replaceTdToTh(colIndex, cell, row);
  17162. }
  17163. }
  17164. //框选时插入不触发contentchange,需要手动更新索引。
  17165. this.update();
  17166. return row;
  17167. },
  17168. /**
  17169. * 删除一行单元格
  17170. * @param rowIndex
  17171. */
  17172. deleteRow:function (rowIndex) {
  17173. var row = this.table.rows[rowIndex],
  17174. infoRow = this.indexTable[rowIndex],
  17175. colsNum = this.colsNum,
  17176. count = 0; //处理计数
  17177. for (var colIndex = 0; colIndex < colsNum;) {
  17178. var cellInfo = infoRow[colIndex],
  17179. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17180. if (cell.rowSpan > 1) {
  17181. if (cellInfo.rowIndex == rowIndex) {
  17182. var clone = cell.cloneNode(true);
  17183. clone.rowSpan = cell.rowSpan - 1;
  17184. clone.innerHTML = "";
  17185. cell.rowSpan = 1;
  17186. var nextRowIndex = rowIndex + 1,
  17187. nextRow = this.table.rows[nextRowIndex],
  17188. insertCellIndex,
  17189. preMerged = this.getPreviewMergedCellsNum(nextRowIndex, colIndex) - count;
  17190. if (preMerged < colIndex) {
  17191. insertCellIndex = colIndex - preMerged - 1;
  17192. //nextRow.insertCell(insertCellIndex);
  17193. domUtils.insertAfter(nextRow.cells[insertCellIndex], clone);
  17194. } else {
  17195. if (nextRow.cells.length) nextRow.insertBefore(clone, nextRow.cells[0])
  17196. }
  17197. count += 1;
  17198. //cell.parentNode.removeChild(cell);
  17199. }
  17200. }
  17201. colIndex += cell.colSpan || 1;
  17202. }
  17203. var deleteTds = [], cacheMap = {};
  17204. for (colIndex = 0; colIndex < colsNum; colIndex++) {
  17205. var tmpRowIndex = infoRow[colIndex].rowIndex,
  17206. tmpCellIndex = infoRow[colIndex].cellIndex,
  17207. key = tmpRowIndex + "_" + tmpCellIndex;
  17208. if (cacheMap[key])continue;
  17209. cacheMap[key] = 1;
  17210. cell = this.getCell(tmpRowIndex, tmpCellIndex);
  17211. deleteTds.push(cell);
  17212. }
  17213. var mergeTds = [];
  17214. utils.each(deleteTds, function (td) {
  17215. if (td.rowSpan == 1) {
  17216. td.parentNode.removeChild(td);
  17217. } else {
  17218. mergeTds.push(td);
  17219. }
  17220. });
  17221. utils.each(mergeTds, function (td) {
  17222. td.rowSpan--;
  17223. });
  17224. row.parentNode.removeChild(row);
  17225. //浏览器方法本身存在bug,采用自定义方法删除
  17226. //this.table.deleteRow(rowIndex);
  17227. this.update();
  17228. },
  17229. insertCol:function (colIndex, sourceCell, defaultValue) {
  17230. var rowsNum = this.rowsNum,
  17231. rowIndex = 0,
  17232. tableRow, cell,
  17233. backWidth = parseInt((this.table.offsetWidth - (this.colsNum + 1) * 20 - (this.colsNum + 1)) / (this.colsNum + 1), 10),
  17234. isInsertTitleCol = typeof sourceCell == 'string' && sourceCell.toUpperCase() == 'TH';
  17235. function replaceTdToTh(rowIndex, cell, tableRow) {
  17236. if (rowIndex == 0) {
  17237. var th = cell.nextSibling || cell.previousSibling;
  17238. if (th.tagName == 'TH') {
  17239. th = cell.ownerDocument.createElement("th");
  17240. th.appendChild(cell.firstChild);
  17241. tableRow.insertBefore(th, cell);
  17242. domUtils.remove(cell)
  17243. }
  17244. }else{
  17245. if (cell.tagName == 'TH') {
  17246. var td = cell.ownerDocument.createElement("td");
  17247. td.appendChild(cell.firstChild);
  17248. tableRow.insertBefore(td, cell);
  17249. domUtils.remove(cell)
  17250. }
  17251. }
  17252. }
  17253. var preCell;
  17254. if (colIndex == 0 || colIndex == this.colsNum) {
  17255. for (; rowIndex < rowsNum; rowIndex++) {
  17256. tableRow = this.table.rows[rowIndex];
  17257. preCell = tableRow.cells[colIndex == 0 ? colIndex : tableRow.cells.length];
  17258. cell = this.cloneCell(sourceCell, true); //tableRow.insertCell(colIndex == 0 ? colIndex : tableRow.cells.length);
  17259. this.setCellContent(cell);
  17260. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17261. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17262. if (!colIndex) {
  17263. tableRow.insertBefore(cell, tableRow.cells[0]);
  17264. } else {
  17265. domUtils.insertAfter(tableRow.cells[tableRow.cells.length - 1], cell);
  17266. }
  17267. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow)
  17268. }
  17269. } else {
  17270. for (; rowIndex < rowsNum; rowIndex++) {
  17271. var cellInfo = this.indexTable[rowIndex][colIndex];
  17272. if (cellInfo.colIndex < colIndex) {
  17273. cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17274. cell.colSpan = cellInfo.colSpan + 1;
  17275. } else {
  17276. tableRow = this.table.rows[rowIndex];
  17277. preCell = tableRow.cells[cellInfo.cellIndex];
  17278. cell = this.cloneCell(sourceCell, true);//tableRow.insertCell(cellInfo.cellIndex);
  17279. this.setCellContent(cell);
  17280. cell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17281. preCell && cell.setAttribute('width', preCell.getAttribute('width'));
  17282. //防止IE下报错
  17283. preCell ? tableRow.insertBefore(cell, preCell) : tableRow.appendChild(cell);
  17284. }
  17285. if(!isInsertTitleCol) replaceTdToTh(rowIndex, cell, tableRow);
  17286. }
  17287. }
  17288. //框选时插入不触发contentchange,需要手动更新索引
  17289. this.update();
  17290. this.updateWidth(backWidth, defaultValue || {tdPadding:10, tdBorder:1});
  17291. },
  17292. updateWidth:function (width, defaultValue) {
  17293. var table = this.table,
  17294. tmpWidth = UETable.getWidth(table) - defaultValue.tdPadding * 2 - defaultValue.tdBorder + width;
  17295. if (tmpWidth < table.ownerDocument.body.offsetWidth) {
  17296. table.setAttribute("width", tmpWidth);
  17297. return;
  17298. }
  17299. var tds = domUtils.getElementsByTagName(this.table, "td th");
  17300. utils.each(tds, function (td) {
  17301. td.setAttribute("width", width);
  17302. })
  17303. },
  17304. deleteCol:function (colIndex) {
  17305. var indexTable = this.indexTable,
  17306. tableRows = this.table.rows,
  17307. backTableWidth = this.table.getAttribute("width"),
  17308. backTdWidth = 0,
  17309. rowsNum = this.rowsNum,
  17310. cacheMap = {};
  17311. for (var rowIndex = 0; rowIndex < rowsNum;) {
  17312. var infoRow = indexTable[rowIndex],
  17313. cellInfo = infoRow[colIndex],
  17314. key = cellInfo.rowIndex + '_' + cellInfo.colIndex;
  17315. // 跳过已经处理过的Cell
  17316. if (cacheMap[key])continue;
  17317. cacheMap[key] = 1;
  17318. var cell = this.getCell(cellInfo.rowIndex, cellInfo.cellIndex);
  17319. if (!backTdWidth) backTdWidth = cell && parseInt(cell.offsetWidth / cell.colSpan, 10).toFixed(0);
  17320. // 如果Cell的colSpan大于1, 就修改colSpan, 否则就删掉这个Cell
  17321. if (cell.colSpan > 1) {
  17322. cell.colSpan--;
  17323. } else {
  17324. tableRows[rowIndex].deleteCell(cellInfo.cellIndex);
  17325. }
  17326. rowIndex += cellInfo.rowSpan || 1;
  17327. }
  17328. this.table.setAttribute("width", backTableWidth - backTdWidth);
  17329. this.update();
  17330. },
  17331. splitToCells:function (cell) {
  17332. var me = this,
  17333. cells = this.splitToRows(cell);
  17334. utils.each(cells, function (cell) {
  17335. me.splitToCols(cell);
  17336. })
  17337. },
  17338. splitToRows:function (cell) {
  17339. var cellInfo = this.getCellInfo(cell),
  17340. rowIndex = cellInfo.rowIndex,
  17341. colIndex = cellInfo.colIndex,
  17342. results = [];
  17343. // 修改Cell的rowSpan
  17344. cell.rowSpan = 1;
  17345. results.push(cell);
  17346. // 补齐单元格
  17347. for (var i = rowIndex, endRow = rowIndex + cellInfo.rowSpan; i < endRow; i++) {
  17348. if (i == rowIndex)continue;
  17349. var tableRow = this.table.rows[i],
  17350. tmpCell = tableRow.insertCell(colIndex - this.getPreviewMergedCellsNum(i, colIndex));
  17351. tmpCell.colSpan = cellInfo.colSpan;
  17352. this.setCellContent(tmpCell);
  17353. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17354. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17355. if (cell.style.cssText) {
  17356. tmpCell.style.cssText = cell.style.cssText;
  17357. }
  17358. results.push(tmpCell);
  17359. }
  17360. this.update();
  17361. return results;
  17362. },
  17363. getPreviewMergedCellsNum:function (rowIndex, colIndex) {
  17364. var indexRow = this.indexTable[rowIndex],
  17365. num = 0;
  17366. for (var i = 0; i < colIndex;) {
  17367. var colSpan = indexRow[i].colSpan,
  17368. tmpRowIndex = indexRow[i].rowIndex;
  17369. num += (colSpan - (tmpRowIndex == rowIndex ? 1 : 0));
  17370. i += colSpan;
  17371. }
  17372. return num;
  17373. },
  17374. splitToCols:function (cell) {
  17375. var backWidth = (cell.offsetWidth / cell.colSpan - 22).toFixed(0),
  17376. cellInfo = this.getCellInfo(cell),
  17377. rowIndex = cellInfo.rowIndex,
  17378. colIndex = cellInfo.colIndex,
  17379. results = [];
  17380. // 修改Cell的rowSpan
  17381. cell.colSpan = 1;
  17382. cell.setAttribute("width", backWidth);
  17383. results.push(cell);
  17384. // 补齐单元格
  17385. for (var j = colIndex, endCol = colIndex + cellInfo.colSpan; j < endCol; j++) {
  17386. if (j == colIndex)continue;
  17387. var tableRow = this.table.rows[rowIndex],
  17388. tmpCell = tableRow.insertCell(this.indexTable[rowIndex][j].cellIndex + 1);
  17389. tmpCell.rowSpan = cellInfo.rowSpan;
  17390. this.setCellContent(tmpCell);
  17391. tmpCell.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17392. tmpCell.setAttribute('align', cell.getAttribute('align'));
  17393. tmpCell.setAttribute('width', backWidth);
  17394. if (cell.style.cssText) {
  17395. tmpCell.style.cssText = cell.style.cssText;
  17396. }
  17397. //处理th的情况
  17398. if (cell.tagName == 'TH') {
  17399. var th = cell.ownerDocument.createElement('th');
  17400. th.appendChild(tmpCell.firstChild);
  17401. th.setAttribute('vAlign', cell.getAttribute('vAlign'));
  17402. th.rowSpan = tmpCell.rowSpan;
  17403. tableRow.insertBefore(th, tmpCell);
  17404. domUtils.remove(tmpCell);
  17405. }
  17406. results.push(tmpCell);
  17407. }
  17408. this.update();
  17409. return results;
  17410. },
  17411. isLastCell:function (cell, rowsNum, colsNum) {
  17412. rowsNum = rowsNum || this.rowsNum;
  17413. colsNum = colsNum || this.colsNum;
  17414. var cellInfo = this.getCellInfo(cell);
  17415. return ((cellInfo.rowIndex + cellInfo.rowSpan) == rowsNum) &&
  17416. ((cellInfo.colIndex + cellInfo.colSpan) == colsNum);
  17417. },
  17418. getLastCell:function (cells) {
  17419. cells = cells || this.table.getElementsByTagName("td");
  17420. var firstInfo = this.getCellInfo(cells[0]);
  17421. var me = this, last = cells[0],
  17422. tr = last.parentNode,
  17423. cellsNum = 0, cols = 0, rows;
  17424. utils.each(cells, function (cell) {
  17425. if (cell.parentNode == tr)cols += cell.colSpan || 1;
  17426. cellsNum += cell.rowSpan * cell.colSpan || 1;
  17427. });
  17428. rows = cellsNum / cols;
  17429. utils.each(cells, function (cell) {
  17430. if (me.isLastCell(cell, rows, cols)) {
  17431. last = cell;
  17432. return false;
  17433. }
  17434. });
  17435. return last;
  17436. },
  17437. selectRow:function (rowIndex) {
  17438. var indexRow = this.indexTable[rowIndex],
  17439. start = this.getCell(indexRow[0].rowIndex, indexRow[0].cellIndex),
  17440. end = this.getCell(indexRow[this.colsNum - 1].rowIndex, indexRow[this.colsNum - 1].cellIndex),
  17441. range = this.getCellsRange(start, end);
  17442. this.setSelected(range);
  17443. },
  17444. selectTable:function () {
  17445. var tds = this.table.getElementsByTagName("td"),
  17446. range = this.getCellsRange(tds[0], tds[tds.length - 1]);
  17447. this.setSelected(range);
  17448. },
  17449. setBackground:function (cells, value) {
  17450. if (typeof value === "string") {
  17451. utils.each(cells, function (cell) {
  17452. cell.style.backgroundColor = value;
  17453. })
  17454. } else if (typeof value === "object") {
  17455. value = utils.extend({
  17456. repeat:true,
  17457. colorList:["#ddd", "#fff"]
  17458. }, value);
  17459. var rowIndex = this.getCellInfo(cells[0]).rowIndex,
  17460. count = 0,
  17461. colors = value.colorList,
  17462. getColor = function (list, index, repeat) {
  17463. return list[index] ? list[index] : repeat ? list[index % list.length] : "";
  17464. };
  17465. for (var i = 0, cell; cell = cells[i++];) {
  17466. var cellInfo = this.getCellInfo(cell);
  17467. cell.style.backgroundColor = getColor(colors, ((rowIndex + count) == cellInfo.rowIndex) ? count : ++count, value.repeat);
  17468. }
  17469. }
  17470. },
  17471. removeBackground:function (cells) {
  17472. utils.each(cells, function (cell) {
  17473. cell.style.backgroundColor = "";
  17474. })
  17475. }
  17476. };
  17477. function showError(e) {
  17478. }
  17479. })();
  17480. // plugins/table.cmds.js
  17481. /**
  17482. * Created with JetBrains PhpStorm.
  17483. * User: taoqili
  17484. * Date: 13-2-20
  17485. * Time: 下午6:25
  17486. * To change this template use File | Settings | File Templates.
  17487. */
  17488. ;
  17489. (function () {
  17490. var UT = UE.UETable,
  17491. getTableItemsByRange = function (editor) {
  17492. return UT.getTableItemsByRange(editor);
  17493. },
  17494. getUETableBySelected = function (editor) {
  17495. return UT.getUETableBySelected(editor)
  17496. },
  17497. getDefaultValue = function (editor, table) {
  17498. return UT.getDefaultValue(editor, table);
  17499. },
  17500. getUETable = function (tdOrTable) {
  17501. return UT.getUETable(tdOrTable);
  17502. };
  17503. UE.commands['inserttable'] = {
  17504. queryCommandState: function () {
  17505. return getTableItemsByRange(this).table ? -1 : 0;
  17506. },
  17507. execCommand: function (cmd, opt) {
  17508. function createTable(opt, tdWidth) {
  17509. var html = [],
  17510. rowsNum = opt.numRows,
  17511. colsNum = opt.numCols;
  17512. for (var r = 0; r < rowsNum; r++) {
  17513. html.push('<tr' + (r == 0 ? ' class="firstRow"':'') + '>');
  17514. for (var c = 0; c < colsNum; c++) {
  17515. html.push('<td width="' + tdWidth + '" vAlign="' + opt.tdvalign + '" >' + (browser.ie && browser.version < 11 ? domUtils.fillChar : '<br/>') + '</td>')
  17516. }
  17517. html.push('</tr>')
  17518. }
  17519. //禁止指定table-width
  17520. return '<table><tbody>' + html.join('') + '</tbody></table>'
  17521. }
  17522. if (!opt) {
  17523. opt = utils.extend({}, {
  17524. numCols: this.options.defaultCols,
  17525. numRows: this.options.defaultRows,
  17526. tdvalign: this.options.tdvalign
  17527. })
  17528. }
  17529. var me = this;
  17530. var range = this.selection.getRange(),
  17531. start = range.startContainer,
  17532. firstParentBlock = domUtils.findParent(start, function (node) {
  17533. return domUtils.isBlockElm(node);
  17534. }, true) || me.body;
  17535. var defaultValue = getDefaultValue(me),
  17536. tableWidth = firstParentBlock.offsetWidth,
  17537. tdWidth = Math.floor(tableWidth / opt.numCols - defaultValue.tdPadding * 2 - defaultValue.tdBorder);
  17538. //todo其他属性
  17539. !opt.tdvalign && (opt.tdvalign = me.options.tdvalign);
  17540. me.execCommand("inserthtml", createTable(opt, tdWidth));
  17541. }
  17542. };
  17543. UE.commands['insertparagraphbeforetable'] = {
  17544. queryCommandState: function () {
  17545. return getTableItemsByRange(this).cell ? 0 : -1;
  17546. },
  17547. execCommand: function () {
  17548. var table = getTableItemsByRange(this).table;
  17549. if (table) {
  17550. var p = this.document.createElement("p");
  17551. p.innerHTML = browser.ie ? '&nbsp;' : '<br />';
  17552. table.parentNode.insertBefore(p, table);
  17553. this.selection.getRange().setStart(p, 0).setCursor();
  17554. }
  17555. }
  17556. };
  17557. UE.commands['deletetable'] = {
  17558. queryCommandState: function () {
  17559. var rng = this.selection.getRange();
  17560. return domUtils.findParentByTagName(rng.startContainer, 'table', true) ? 0 : -1;
  17561. },
  17562. execCommand: function (cmd, table) {
  17563. var rng = this.selection.getRange();
  17564. table = table || domUtils.findParentByTagName(rng.startContainer, 'table', true);
  17565. if (table) {
  17566. var next = table.nextSibling;
  17567. if (!next) {
  17568. next = domUtils.createElement(this.document, 'p', {
  17569. 'innerHTML': browser.ie ? domUtils.fillChar : '<br/>'
  17570. });
  17571. table.parentNode.insertBefore(next, table);
  17572. }
  17573. domUtils.remove(table);
  17574. rng = this.selection.getRange();
  17575. if (next.nodeType == 3) {
  17576. rng.setStartBefore(next)
  17577. } else {
  17578. rng.setStart(next, 0)
  17579. }
  17580. rng.setCursor(false, true)
  17581. this.fireEvent("tablehasdeleted")
  17582. }
  17583. }
  17584. };
  17585. UE.commands['cellalign'] = {
  17586. queryCommandState: function () {
  17587. return getSelectedArr(this).length ? 0 : -1
  17588. },
  17589. execCommand: function (cmd, align) {
  17590. var selectedTds = getSelectedArr(this);
  17591. if (selectedTds.length) {
  17592. for (var i = 0, ci; ci = selectedTds[i++];) {
  17593. ci.setAttribute('align', align);
  17594. }
  17595. }
  17596. }
  17597. };
  17598. UE.commands['cellvalign'] = {
  17599. queryCommandState: function () {
  17600. return getSelectedArr(this).length ? 0 : -1;
  17601. },
  17602. execCommand: function (cmd, valign) {
  17603. var selectedTds = getSelectedArr(this);
  17604. if (selectedTds.length) {
  17605. for (var i = 0, ci; ci = selectedTds[i++];) {
  17606. ci.setAttribute('vAlign', valign);
  17607. }
  17608. }
  17609. }
  17610. };
  17611. UE.commands['insertcaption'] = {
  17612. queryCommandState: function () {
  17613. var table = getTableItemsByRange(this).table;
  17614. if (table) {
  17615. return table.getElementsByTagName('caption').length == 0 ? 1 : -1;
  17616. }
  17617. return -1;
  17618. },
  17619. execCommand: function () {
  17620. var table = getTableItemsByRange(this).table;
  17621. if (table) {
  17622. var caption = this.document.createElement('caption');
  17623. caption.innerHTML = browser.ie ? domUtils.fillChar : '<br/>';
  17624. table.insertBefore(caption, table.firstChild);
  17625. var range = this.selection.getRange();
  17626. range.setStart(caption, 0).setCursor();
  17627. }
  17628. }
  17629. };
  17630. UE.commands['deletecaption'] = {
  17631. queryCommandState: function () {
  17632. var rng = this.selection.getRange(),
  17633. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17634. if (table) {
  17635. return table.getElementsByTagName('caption').length == 0 ? -1 : 1;
  17636. }
  17637. return -1;
  17638. },
  17639. execCommand: function () {
  17640. var rng = this.selection.getRange(),
  17641. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  17642. if (table) {
  17643. domUtils.remove(table.getElementsByTagName('caption')[0]);
  17644. var range = this.selection.getRange();
  17645. range.setStart(table.rows[0].cells[0], 0).setCursor();
  17646. }
  17647. }
  17648. };
  17649. UE.commands['inserttitle'] = {
  17650. queryCommandState: function () {
  17651. var table = getTableItemsByRange(this).table;
  17652. if (table) {
  17653. var firstRow = table.rows[0];
  17654. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() != 'th' ? 0 : -1
  17655. }
  17656. return -1;
  17657. },
  17658. execCommand: function () {
  17659. var table = getTableItemsByRange(this).table;
  17660. if (table) {
  17661. getUETable(table).insertRow(0, 'th');
  17662. }
  17663. var th = table.getElementsByTagName('th')[0];
  17664. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17665. }
  17666. };
  17667. UE.commands['deletetitle'] = {
  17668. queryCommandState: function () {
  17669. var table = getTableItemsByRange(this).table;
  17670. if (table) {
  17671. var firstRow = table.rows[0];
  17672. return firstRow.cells[firstRow.cells.length-1].tagName.toLowerCase() == 'th' ? 0 : -1
  17673. }
  17674. return -1;
  17675. },
  17676. execCommand: function () {
  17677. var table = getTableItemsByRange(this).table;
  17678. if (table) {
  17679. domUtils.remove(table.rows[0])
  17680. }
  17681. var td = table.getElementsByTagName('td')[0];
  17682. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17683. }
  17684. };
  17685. UE.commands['inserttitlecol'] = {
  17686. queryCommandState: function () {
  17687. var table = getTableItemsByRange(this).table;
  17688. if (table) {
  17689. var lastRow = table.rows[table.rows.length-1];
  17690. return lastRow.getElementsByTagName('th').length ? -1 : 0;
  17691. }
  17692. return -1;
  17693. },
  17694. execCommand: function (cmd) {
  17695. var table = getTableItemsByRange(this).table;
  17696. if (table) {
  17697. getUETable(table).insertCol(0, 'th');
  17698. }
  17699. resetTdWidth(table, this);
  17700. var th = table.getElementsByTagName('th')[0];
  17701. this.selection.getRange().setStart(th, 0).setCursor(false, true);
  17702. }
  17703. };
  17704. UE.commands['deletetitlecol'] = {
  17705. queryCommandState: function () {
  17706. var table = getTableItemsByRange(this).table;
  17707. if (table) {
  17708. var lastRow = table.rows[table.rows.length-1];
  17709. return lastRow.getElementsByTagName('th').length ? 0 : -1;
  17710. }
  17711. return -1;
  17712. },
  17713. execCommand: function () {
  17714. var table = getTableItemsByRange(this).table;
  17715. if (table) {
  17716. for(var i = 0; i< table.rows.length; i++ ){
  17717. domUtils.remove(table.rows[i].children[0])
  17718. }
  17719. }
  17720. resetTdWidth(table, this);
  17721. var td = table.getElementsByTagName('td')[0];
  17722. this.selection.getRange().setStart(td, 0).setCursor(false, true);
  17723. }
  17724. };
  17725. UE.commands["mergeright"] = {
  17726. queryCommandState: function (cmd) {
  17727. var tableItems = getTableItemsByRange(this),
  17728. table = tableItems.table,
  17729. cell = tableItems.cell;
  17730. if (!table || !cell) return -1;
  17731. var ut = getUETable(table);
  17732. if (ut.selectedTds.length) return -1;
  17733. var cellInfo = ut.getCellInfo(cell),
  17734. rightColIndex = cellInfo.colIndex + cellInfo.colSpan;
  17735. if (rightColIndex >= ut.colsNum) return -1; // 如果处于最右边则不能向右合并
  17736. var rightCellInfo = ut.indexTable[cellInfo.rowIndex][rightColIndex],
  17737. rightCell = table.rows[rightCellInfo.rowIndex].cells[rightCellInfo.cellIndex];
  17738. if (!rightCell || cell.tagName != rightCell.tagName) return -1; // TH和TD不能相互合并
  17739. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17740. return (rightCellInfo.rowIndex == cellInfo.rowIndex && rightCellInfo.rowSpan == cellInfo.rowSpan) ? 0 : -1;
  17741. },
  17742. execCommand: function (cmd) {
  17743. var rng = this.selection.getRange(),
  17744. bk = rng.createBookmark(true);
  17745. var cell = getTableItemsByRange(this).cell,
  17746. ut = getUETable(cell);
  17747. ut.mergeRight(cell);
  17748. rng.moveToBookmark(bk).select();
  17749. }
  17750. };
  17751. UE.commands["mergedown"] = {
  17752. queryCommandState: function (cmd) {
  17753. var tableItems = getTableItemsByRange(this),
  17754. table = tableItems.table,
  17755. cell = tableItems.cell;
  17756. if (!table || !cell) return -1;
  17757. var ut = getUETable(table);
  17758. if (ut.selectedTds.length)return -1;
  17759. var cellInfo = ut.getCellInfo(cell),
  17760. downRowIndex = cellInfo.rowIndex + cellInfo.rowSpan;
  17761. if (downRowIndex >= ut.rowsNum) return -1; // 如果处于最下边则不能向下合并
  17762. var downCellInfo = ut.indexTable[downRowIndex][cellInfo.colIndex],
  17763. downCell = table.rows[downCellInfo.rowIndex].cells[downCellInfo.cellIndex];
  17764. if (!downCell || cell.tagName != downCell.tagName) return -1; // TH和TD不能相互合并
  17765. // 当且仅当两个Cell的开始列号和结束列号一致时能进行合并
  17766. return (downCellInfo.colIndex == cellInfo.colIndex && downCellInfo.colSpan == cellInfo.colSpan) ? 0 : -1;
  17767. },
  17768. execCommand: function () {
  17769. var rng = this.selection.getRange(),
  17770. bk = rng.createBookmark(true);
  17771. var cell = getTableItemsByRange(this).cell,
  17772. ut = getUETable(cell);
  17773. ut.mergeDown(cell);
  17774. rng.moveToBookmark(bk).select();
  17775. }
  17776. };
  17777. UE.commands["mergecells"] = {
  17778. queryCommandState: function () {
  17779. return getUETableBySelected(this) ? 0 : -1;
  17780. },
  17781. execCommand: function () {
  17782. var ut = getUETableBySelected(this);
  17783. if (ut && ut.selectedTds.length) {
  17784. var cell = ut.selectedTds[0];
  17785. ut.mergeRange();
  17786. var rng = this.selection.getRange();
  17787. if (domUtils.isEmptyBlock(cell)) {
  17788. rng.setStart(cell, 0).collapse(true)
  17789. } else {
  17790. rng.selectNodeContents(cell)
  17791. }
  17792. rng.select();
  17793. }
  17794. }
  17795. };
  17796. UE.commands["insertrow"] = {
  17797. queryCommandState: function () {
  17798. var tableItems = getTableItemsByRange(this),
  17799. cell = tableItems.cell;
  17800. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && tableItems.tr !== tableItems.table.rows[0])) &&
  17801. getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17802. },
  17803. execCommand: function () {
  17804. var rng = this.selection.getRange(),
  17805. bk = rng.createBookmark(true);
  17806. var tableItems = getTableItemsByRange(this),
  17807. cell = tableItems.cell,
  17808. table = tableItems.table,
  17809. ut = getUETable(table),
  17810. cellInfo = ut.getCellInfo(cell);
  17811. //ut.insertRow(!ut.selectedTds.length ? cellInfo.rowIndex:ut.cellsRange.beginRowIndex,'');
  17812. if (!ut.selectedTds.length) {
  17813. ut.insertRow(cellInfo.rowIndex, cell);
  17814. } else {
  17815. var range = ut.cellsRange;
  17816. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17817. ut.insertRow(range.beginRowIndex, cell);
  17818. }
  17819. }
  17820. rng.moveToBookmark(bk).select();
  17821. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17822. }
  17823. };
  17824. //后插入行
  17825. UE.commands["insertrownext"] = {
  17826. queryCommandState: function () {
  17827. var tableItems = getTableItemsByRange(this),
  17828. cell = tableItems.cell;
  17829. return cell && (cell.tagName == "TD") && getUETable(tableItems.table).rowsNum < this.options.maxRowNum ? 0 : -1;
  17830. },
  17831. execCommand: function () {
  17832. var rng = this.selection.getRange(),
  17833. bk = rng.createBookmark(true);
  17834. var tableItems = getTableItemsByRange(this),
  17835. cell = tableItems.cell,
  17836. table = tableItems.table,
  17837. ut = getUETable(table),
  17838. cellInfo = ut.getCellInfo(cell);
  17839. //ut.insertRow(!ut.selectedTds.length? cellInfo.rowIndex + cellInfo.rowSpan : ut.cellsRange.endRowIndex + 1,'');
  17840. if (!ut.selectedTds.length) {
  17841. ut.insertRow(cellInfo.rowIndex + cellInfo.rowSpan, cell);
  17842. } else {
  17843. var range = ut.cellsRange;
  17844. for (var i = 0, len = range.endRowIndex - range.beginRowIndex + 1; i < len; i++) {
  17845. ut.insertRow(range.endRowIndex + 1, cell);
  17846. }
  17847. }
  17848. rng.moveToBookmark(bk).select();
  17849. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17850. }
  17851. };
  17852. UE.commands["deleterow"] = {
  17853. queryCommandState: function () {
  17854. var tableItems = getTableItemsByRange(this);
  17855. return tableItems.cell ? 0 : -1;
  17856. },
  17857. execCommand: function () {
  17858. var cell = getTableItemsByRange(this).cell,
  17859. ut = getUETable(cell),
  17860. cellsRange = ut.cellsRange,
  17861. cellInfo = ut.getCellInfo(cell),
  17862. preCell = ut.getVSideCell(cell),
  17863. nextCell = ut.getVSideCell(cell, true),
  17864. rng = this.selection.getRange();
  17865. if (utils.isEmptyObject(cellsRange)) {
  17866. ut.deleteRow(cellInfo.rowIndex);
  17867. } else {
  17868. for (var i = cellsRange.beginRowIndex; i < cellsRange.endRowIndex + 1; i++) {
  17869. ut.deleteRow(cellsRange.beginRowIndex);
  17870. }
  17871. }
  17872. var table = ut.table;
  17873. if (!table.getElementsByTagName('td').length) {
  17874. var nextSibling = table.nextSibling;
  17875. domUtils.remove(table);
  17876. if (nextSibling) {
  17877. rng.setStart(nextSibling, 0).setCursor(false, true);
  17878. }
  17879. } else {
  17880. if (cellInfo.rowSpan == 1 || cellInfo.rowSpan == cellsRange.endRowIndex - cellsRange.beginRowIndex + 1) {
  17881. if (nextCell || preCell) rng.selectNodeContents(nextCell || preCell).setCursor(false, true);
  17882. } else {
  17883. var newCell = ut.getCell(cellInfo.rowIndex, ut.indexTable[cellInfo.rowIndex][cellInfo.colIndex].cellIndex);
  17884. if (newCell) rng.selectNodeContents(newCell).setCursor(false, true);
  17885. }
  17886. }
  17887. if (table.getAttribute("interlaced") === "enabled")this.fireEvent("interlacetable", table);
  17888. }
  17889. };
  17890. UE.commands["insertcol"] = {
  17891. queryCommandState: function (cmd) {
  17892. var tableItems = getTableItemsByRange(this),
  17893. cell = tableItems.cell;
  17894. return cell && (cell.tagName == "TD" || (cell.tagName == 'TH' && cell !== tableItems.tr.cells[0])) &&
  17895. getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17896. },
  17897. execCommand: function (cmd) {
  17898. var rng = this.selection.getRange(),
  17899. bk = rng.createBookmark(true);
  17900. if (this.queryCommandState(cmd) == -1)return;
  17901. var cell = getTableItemsByRange(this).cell,
  17902. ut = getUETable(cell),
  17903. cellInfo = ut.getCellInfo(cell);
  17904. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex:ut.cellsRange.beginColIndex);
  17905. if (!ut.selectedTds.length) {
  17906. ut.insertCol(cellInfo.colIndex, cell);
  17907. } else {
  17908. var range = ut.cellsRange;
  17909. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17910. ut.insertCol(range.beginColIndex, cell);
  17911. }
  17912. }
  17913. rng.moveToBookmark(bk).select(true);
  17914. }
  17915. };
  17916. UE.commands["insertcolnext"] = {
  17917. queryCommandState: function () {
  17918. var tableItems = getTableItemsByRange(this),
  17919. cell = tableItems.cell;
  17920. return cell && getUETable(tableItems.table).colsNum < this.options.maxColNum ? 0 : -1;
  17921. },
  17922. execCommand: function () {
  17923. var rng = this.selection.getRange(),
  17924. bk = rng.createBookmark(true);
  17925. var cell = getTableItemsByRange(this).cell,
  17926. ut = getUETable(cell),
  17927. cellInfo = ut.getCellInfo(cell);
  17928. //ut.insertCol(!ut.selectedTds.length ? cellInfo.colIndex + cellInfo.colSpan:ut.cellsRange.endColIndex +1);
  17929. if (!ut.selectedTds.length) {
  17930. ut.insertCol(cellInfo.colIndex + cellInfo.colSpan, cell);
  17931. } else {
  17932. var range = ut.cellsRange;
  17933. for (var i = 0, len = range.endColIndex - range.beginColIndex + 1; i < len; i++) {
  17934. ut.insertCol(range.endColIndex + 1, cell);
  17935. }
  17936. }
  17937. rng.moveToBookmark(bk).select();
  17938. }
  17939. };
  17940. UE.commands["deletecol"] = {
  17941. queryCommandState: function () {
  17942. var tableItems = getTableItemsByRange(this);
  17943. return tableItems.cell ? 0 : -1;
  17944. },
  17945. execCommand: function () {
  17946. var cell = getTableItemsByRange(this).cell,
  17947. ut = getUETable(cell),
  17948. range = ut.cellsRange,
  17949. cellInfo = ut.getCellInfo(cell),
  17950. preCell = ut.getHSideCell(cell),
  17951. nextCell = ut.getHSideCell(cell, true);
  17952. if (utils.isEmptyObject(range)) {
  17953. ut.deleteCol(cellInfo.colIndex);
  17954. } else {
  17955. for (var i = range.beginColIndex; i < range.endColIndex + 1; i++) {
  17956. ut.deleteCol(range.beginColIndex);
  17957. }
  17958. }
  17959. var table = ut.table,
  17960. rng = this.selection.getRange();
  17961. if (!table.getElementsByTagName('td').length) {
  17962. var nextSibling = table.nextSibling;
  17963. domUtils.remove(table);
  17964. if (nextSibling) {
  17965. rng.setStart(nextSibling, 0).setCursor(false, true);
  17966. }
  17967. } else {
  17968. if (domUtils.inDoc(cell, this.document)) {
  17969. rng.setStart(cell, 0).setCursor(false, true);
  17970. } else {
  17971. if (nextCell && domUtils.inDoc(nextCell, this.document)) {
  17972. rng.selectNodeContents(nextCell).setCursor(false, true);
  17973. } else {
  17974. if (preCell && domUtils.inDoc(preCell, this.document)) {
  17975. rng.selectNodeContents(preCell).setCursor(true, true);
  17976. }
  17977. }
  17978. }
  17979. }
  17980. }
  17981. };
  17982. UE.commands["splittocells"] = {
  17983. queryCommandState: function () {
  17984. var tableItems = getTableItemsByRange(this),
  17985. cell = tableItems.cell;
  17986. if (!cell) return -1;
  17987. var ut = getUETable(tableItems.table);
  17988. if (ut.selectedTds.length > 0) return -1;
  17989. return cell && (cell.colSpan > 1 || cell.rowSpan > 1) ? 0 : -1;
  17990. },
  17991. execCommand: function () {
  17992. var rng = this.selection.getRange(),
  17993. bk = rng.createBookmark(true);
  17994. var cell = getTableItemsByRange(this).cell,
  17995. ut = getUETable(cell);
  17996. ut.splitToCells(cell);
  17997. rng.moveToBookmark(bk).select();
  17998. }
  17999. };
  18000. UE.commands["splittorows"] = {
  18001. queryCommandState: function () {
  18002. var tableItems = getTableItemsByRange(this),
  18003. cell = tableItems.cell;
  18004. if (!cell) return -1;
  18005. var ut = getUETable(tableItems.table);
  18006. if (ut.selectedTds.length > 0) return -1;
  18007. return cell && cell.rowSpan > 1 ? 0 : -1;
  18008. },
  18009. execCommand: function () {
  18010. var rng = this.selection.getRange(),
  18011. bk = rng.createBookmark(true);
  18012. var cell = getTableItemsByRange(this).cell,
  18013. ut = getUETable(cell);
  18014. ut.splitToRows(cell);
  18015. rng.moveToBookmark(bk).select();
  18016. }
  18017. };
  18018. UE.commands["splittocols"] = {
  18019. queryCommandState: function () {
  18020. var tableItems = getTableItemsByRange(this),
  18021. cell = tableItems.cell;
  18022. if (!cell) return -1;
  18023. var ut = getUETable(tableItems.table);
  18024. if (ut.selectedTds.length > 0) return -1;
  18025. return cell && cell.colSpan > 1 ? 0 : -1;
  18026. },
  18027. execCommand: function () {
  18028. var rng = this.selection.getRange(),
  18029. bk = rng.createBookmark(true);
  18030. var cell = getTableItemsByRange(this).cell,
  18031. ut = getUETable(cell);
  18032. ut.splitToCols(cell);
  18033. rng.moveToBookmark(bk).select();
  18034. }
  18035. };
  18036. UE.commands["adaptbytext"] =
  18037. UE.commands["adaptbywindow"] = {
  18038. queryCommandState: function () {
  18039. return getTableItemsByRange(this).table ? 0 : -1
  18040. },
  18041. execCommand: function (cmd) {
  18042. var tableItems = getTableItemsByRange(this),
  18043. table = tableItems.table;
  18044. if (table) {
  18045. if (cmd == 'adaptbywindow') {
  18046. resetTdWidth(table, this);
  18047. } else {
  18048. var cells = domUtils.getElementsByTagName(table, "td th");
  18049. utils.each(cells, function (cell) {
  18050. cell.removeAttribute("width");
  18051. });
  18052. table.removeAttribute("width");
  18053. }
  18054. }
  18055. }
  18056. };
  18057. //平均分配各列
  18058. UE.commands['averagedistributecol'] = {
  18059. queryCommandState: function () {
  18060. var ut = getUETableBySelected(this);
  18061. if (!ut) return -1;
  18062. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18063. },
  18064. execCommand: function (cmd) {
  18065. var me = this,
  18066. ut = getUETableBySelected(me);
  18067. function getAverageWidth() {
  18068. var tb = ut.table,
  18069. averageWidth, sumWidth = 0, colsNum = 0,
  18070. tbAttr = getDefaultValue(me, tb);
  18071. if (ut.isFullRow()) {
  18072. sumWidth = tb.offsetWidth;
  18073. colsNum = ut.colsNum;
  18074. } else {
  18075. var begin = ut.cellsRange.beginColIndex,
  18076. end = ut.cellsRange.endColIndex,
  18077. node;
  18078. for (var i = begin; i <= end;) {
  18079. node = ut.selectedTds[i];
  18080. sumWidth += node.offsetWidth;
  18081. i += node.colSpan;
  18082. colsNum += 1;
  18083. }
  18084. }
  18085. averageWidth = Math.ceil(sumWidth / colsNum) - tbAttr.tdBorder * 2 - tbAttr.tdPadding * 2;
  18086. return averageWidth;
  18087. }
  18088. function setAverageWidth(averageWidth) {
  18089. utils.each(domUtils.getElementsByTagName(ut.table, "th"), function (node) {
  18090. node.setAttribute("width", "");
  18091. });
  18092. var cells = ut.isFullRow() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18093. utils.each(cells, function (node) {
  18094. if (node.colSpan == 1) {
  18095. node.setAttribute("width", averageWidth);
  18096. }
  18097. });
  18098. }
  18099. if (ut && ut.selectedTds.length) {
  18100. setAverageWidth(getAverageWidth());
  18101. }
  18102. }
  18103. };
  18104. //平均分配各行
  18105. UE.commands['averagedistributerow'] = {
  18106. queryCommandState: function () {
  18107. var ut = getUETableBySelected(this);
  18108. if (!ut) return -1;
  18109. if (ut.selectedTds && /th/ig.test(ut.selectedTds[0].tagName)) return -1;
  18110. return ut.isFullRow() || ut.isFullCol() ? 0 : -1;
  18111. },
  18112. execCommand: function (cmd) {
  18113. var me = this,
  18114. ut = getUETableBySelected(me);
  18115. function getAverageHeight() {
  18116. var averageHeight, rowNum, sumHeight = 0,
  18117. tb = ut.table,
  18118. tbAttr = getDefaultValue(me, tb),
  18119. tdpadding = parseInt(domUtils.getComputedStyle(tb.getElementsByTagName('td')[0], "padding-top"));
  18120. if (ut.isFullCol()) {
  18121. var captionArr = domUtils.getElementsByTagName(tb, "caption"),
  18122. thArr = domUtils.getElementsByTagName(tb, "th"),
  18123. captionHeight, thHeight;
  18124. if (captionArr.length > 0) {
  18125. captionHeight = captionArr[0].offsetHeight;
  18126. }
  18127. if (thArr.length > 0) {
  18128. thHeight = thArr[0].offsetHeight;
  18129. }
  18130. sumHeight = tb.offsetHeight - (captionHeight || 0) - (thHeight || 0);
  18131. rowNum = thArr.length == 0 ? ut.rowsNum : (ut.rowsNum - 1);
  18132. } else {
  18133. var begin = ut.cellsRange.beginRowIndex,
  18134. end = ut.cellsRange.endRowIndex,
  18135. count = 0,
  18136. trs = domUtils.getElementsByTagName(tb, "tr");
  18137. for (var i = begin; i <= end; i++) {
  18138. sumHeight += trs[i].offsetHeight;
  18139. count += 1;
  18140. }
  18141. rowNum = count;
  18142. }
  18143. //ie8下是混杂模式
  18144. if (browser.ie && browser.version < 9) {
  18145. averageHeight = Math.ceil(sumHeight / rowNum);
  18146. } else {
  18147. averageHeight = Math.ceil(sumHeight / rowNum) - tbAttr.tdBorder * 2 - tdpadding * 2;
  18148. }
  18149. return averageHeight;
  18150. }
  18151. function setAverageHeight(averageHeight) {
  18152. var cells = ut.isFullCol() ? domUtils.getElementsByTagName(ut.table, "td") : ut.selectedTds;
  18153. utils.each(cells, function (node) {
  18154. if (node.rowSpan == 1) {
  18155. node.setAttribute("height", averageHeight);
  18156. }
  18157. });
  18158. }
  18159. if (ut && ut.selectedTds.length) {
  18160. setAverageHeight(getAverageHeight());
  18161. }
  18162. }
  18163. };
  18164. //单元格对齐方式
  18165. UE.commands['cellalignment'] = {
  18166. queryCommandState: function () {
  18167. return getTableItemsByRange(this).table ? 0 : -1
  18168. },
  18169. execCommand: function (cmd, data) {
  18170. var me = this,
  18171. ut = getUETableBySelected(me);
  18172. if (!ut) {
  18173. var start = me.selection.getStart(),
  18174. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18175. if (!/caption/ig.test(cell.tagName)) {
  18176. domUtils.setAttributes(cell, data);
  18177. } else {
  18178. cell.style.textAlign = data.align;
  18179. cell.style.verticalAlign = data.vAlign;
  18180. }
  18181. me.selection.getRange().setCursor(true);
  18182. } else {
  18183. utils.each(ut.selectedTds, function (cell) {
  18184. domUtils.setAttributes(cell, data);
  18185. });
  18186. }
  18187. },
  18188. /**
  18189. * 查询当前点击的单元格的对齐状态, 如果当前已经选择了多个单元格, 则会返回所有单元格经过统一协调过后的状态
  18190. * @see UE.UETable.getTableCellAlignState
  18191. */
  18192. queryCommandValue: function (cmd) {
  18193. var activeMenuCell = getTableItemsByRange( this).cell;
  18194. if( !activeMenuCell ) {
  18195. activeMenuCell = getSelectedArr(this)[0];
  18196. }
  18197. if (!activeMenuCell) {
  18198. return null;
  18199. } else {
  18200. //获取同时选中的其他单元格
  18201. var cells = UE.UETable.getUETable(activeMenuCell).selectedTds;
  18202. !cells.length && ( cells = activeMenuCell );
  18203. return UE.UETable.getTableCellAlignState(cells);
  18204. }
  18205. }
  18206. };
  18207. //表格对齐方式
  18208. UE.commands['tablealignment'] = {
  18209. queryCommandState: function () {
  18210. if (browser.ie && browser.version < 8) {
  18211. return -1;
  18212. }
  18213. return getTableItemsByRange(this).table ? 0 : -1
  18214. },
  18215. execCommand: function (cmd, value) {
  18216. var me = this,
  18217. start = me.selection.getStart(),
  18218. table = start && domUtils.findParentByTagName(start, ["table"], true);
  18219. if (table) {
  18220. table.setAttribute("align",value);
  18221. }
  18222. }
  18223. };
  18224. //表格属性
  18225. UE.commands['edittable'] = {
  18226. queryCommandState: function () {
  18227. return getTableItemsByRange(this).table ? 0 : -1
  18228. },
  18229. execCommand: function (cmd, color) {
  18230. var rng = this.selection.getRange(),
  18231. table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18232. if (table) {
  18233. var arr = domUtils.getElementsByTagName(table, "td").concat(
  18234. domUtils.getElementsByTagName(table, "th"),
  18235. domUtils.getElementsByTagName(table, "caption")
  18236. );
  18237. utils.each(arr, function (node) {
  18238. node.style.borderColor = color;
  18239. });
  18240. }
  18241. }
  18242. };
  18243. //单元格属性
  18244. UE.commands['edittd'] = {
  18245. queryCommandState: function () {
  18246. return getTableItemsByRange(this).table ? 0 : -1
  18247. },
  18248. execCommand: function (cmd, bkColor) {
  18249. var me = this,
  18250. ut = getUETableBySelected(me);
  18251. if (!ut) {
  18252. var start = me.selection.getStart(),
  18253. cell = start && domUtils.findParentByTagName(start, ["td", "th", "caption"], true);
  18254. if (cell) {
  18255. cell.style.backgroundColor = bkColor;
  18256. }
  18257. } else {
  18258. utils.each(ut.selectedTds, function (cell) {
  18259. cell.style.backgroundColor = bkColor;
  18260. });
  18261. }
  18262. }
  18263. };
  18264. UE.commands["settablebackground"] = {
  18265. queryCommandState: function () {
  18266. return getSelectedArr(this).length > 1 ? 0 : -1;
  18267. },
  18268. execCommand: function (cmd, value) {
  18269. var cells, ut;
  18270. cells = getSelectedArr(this);
  18271. ut = getUETable(cells[0]);
  18272. ut.setBackground(cells, value);
  18273. }
  18274. };
  18275. UE.commands["cleartablebackground"] = {
  18276. queryCommandState: function () {
  18277. var cells = getSelectedArr(this);
  18278. if (!cells.length)return -1;
  18279. for (var i = 0, cell; cell = cells[i++];) {
  18280. if (cell.style.backgroundColor !== "") return 0;
  18281. }
  18282. return -1;
  18283. },
  18284. execCommand: function () {
  18285. var cells = getSelectedArr(this),
  18286. ut = getUETable(cells[0]);
  18287. ut.removeBackground(cells);
  18288. }
  18289. };
  18290. UE.commands["interlacetable"] = UE.commands["uninterlacetable"] = {
  18291. queryCommandState: function (cmd) {
  18292. var table = getTableItemsByRange(this).table;
  18293. if (!table) return -1;
  18294. var interlaced = table.getAttribute("interlaced");
  18295. if (cmd == "interlacetable") {
  18296. //TODO 待定
  18297. //是否需要待定,如果设置,则命令只能单次执行成功,但反射具备toggle效果;否则可以覆盖前次命令,但反射将不存在toggle效果
  18298. return (interlaced === "enabled") ? -1 : 0;
  18299. } else {
  18300. return (!interlaced || interlaced === "disabled") ? -1 : 0;
  18301. }
  18302. },
  18303. execCommand: function (cmd, classList) {
  18304. var table = getTableItemsByRange(this).table;
  18305. if (cmd == "interlacetable") {
  18306. table.setAttribute("interlaced", "enabled");
  18307. this.fireEvent("interlacetable", table, classList);
  18308. } else {
  18309. table.setAttribute("interlaced", "disabled");
  18310. this.fireEvent("uninterlacetable", table);
  18311. }
  18312. }
  18313. };
  18314. UE.commands["setbordervisible"] = {
  18315. queryCommandState: function (cmd) {
  18316. var table = getTableItemsByRange(this).table;
  18317. if (!table) return -1;
  18318. return 0;
  18319. },
  18320. execCommand: function () {
  18321. var table = getTableItemsByRange(this).table;
  18322. utils.each(domUtils.getElementsByTagName(table,'td'),function(td){
  18323. td.style.borderWidth = '1px';
  18324. td.style.borderStyle = 'solid';
  18325. })
  18326. }
  18327. };
  18328. function resetTdWidth(table, editor) {
  18329. var tds = domUtils.getElementsByTagName(table,'td th');
  18330. utils.each(tds, function (td) {
  18331. td.removeAttribute("width");
  18332. });
  18333. table.setAttribute('width', getTableWidth(editor, true, getDefaultValue(editor, table)));
  18334. var tdsWidths = [];
  18335. setTimeout(function () {
  18336. utils.each(tds, function (td) {
  18337. (td.colSpan == 1) && tdsWidths.push(td.offsetWidth)
  18338. })
  18339. utils.each(tds, function (td,i) {
  18340. (td.colSpan == 1) && td.setAttribute("width", tdsWidths[i] + "");
  18341. })
  18342. }, 0);
  18343. }
  18344. function getTableWidth(editor, needIEHack, defaultValue) {
  18345. var body = editor.body;
  18346. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  18347. }
  18348. function getSelectedArr(editor) {
  18349. var cell = getTableItemsByRange(editor).cell;
  18350. if (cell) {
  18351. var ut = getUETable(cell);
  18352. return ut.selectedTds.length ? ut.selectedTds : [cell];
  18353. } else {
  18354. return [];
  18355. }
  18356. }
  18357. })();
  18358. // plugins/table.action.js
  18359. /**
  18360. * Created with JetBrains PhpStorm.
  18361. * User: taoqili
  18362. * Date: 12-10-12
  18363. * Time: 上午10:05
  18364. * To change this template use File | Settings | File Templates.
  18365. */
  18366. UE.plugins['table'] = function () {
  18367. var me = this,
  18368. tabTimer = null,
  18369. //拖动计时器
  18370. tableDragTimer = null,
  18371. //双击计时器
  18372. tableResizeTimer = null,
  18373. //单元格最小宽度
  18374. cellMinWidth = 5,
  18375. isInResizeBuffer = false,
  18376. //单元格边框大小
  18377. cellBorderWidth = 5,
  18378. //鼠标偏移距离
  18379. offsetOfTableCell = 10,
  18380. //记录在有限时间内的点击状态, 共有3个取值, 0, 1, 2。 0代表未初始化, 1代表单击了1次,2代表2次
  18381. singleClickState = 0,
  18382. userActionStatus = null,
  18383. //双击允许的时间范围
  18384. dblclickTime = 360,
  18385. UT = UE.UETable,
  18386. getUETable = function (tdOrTable) {
  18387. return UT.getUETable(tdOrTable);
  18388. },
  18389. getUETableBySelected = function (editor) {
  18390. return UT.getUETableBySelected(editor);
  18391. },
  18392. getDefaultValue = function (editor, table) {
  18393. return UT.getDefaultValue(editor, table);
  18394. },
  18395. removeSelectedClass = function (cells) {
  18396. return UT.removeSelectedClass(cells);
  18397. };
  18398. function showError(e) {
  18399. // throw e;
  18400. }
  18401. me.ready(function(){
  18402. var me = this;
  18403. var orgGetText = me.selection.getText;
  18404. me.selection.getText = function(){
  18405. var table = getUETableBySelected(me);
  18406. if(table){
  18407. var str = '';
  18408. utils.each(table.selectedTds,function(td){
  18409. str += td[browser.ie?'innerText':'textContent'];
  18410. })
  18411. return str;
  18412. }else{
  18413. return orgGetText.call(me.selection)
  18414. }
  18415. }
  18416. })
  18417. //处理拖动及框选相关方法
  18418. var startTd = null, //鼠标按下时的锚点td
  18419. currentTd = null, //当前鼠标经过时的td
  18420. onDrag = "", //指示当前拖动状态,其值可为"","h","v" ,分别表示未拖动状态,横向拖动状态,纵向拖动状态,用于鼠标移动过程中的判断
  18421. onBorder = false, //检测鼠标按下时是否处在单元格边缘位置
  18422. dragButton = null,
  18423. dragOver = false,
  18424. dragLine = null, //模拟的拖动线
  18425. dragTd = null; //发生拖动的目标td
  18426. var mousedown = false,
  18427. //todo 判断混乱模式
  18428. needIEHack = true;
  18429. me.setOpt({
  18430. 'maxColNum':20,
  18431. 'maxRowNum':100,
  18432. 'defaultCols':5,
  18433. 'defaultRows':5,
  18434. 'tdvalign':'top',
  18435. 'cursorpath':me.options.UEDITOR_HOME_URL + "themes/default/images/cursor_",
  18436. 'tableDragable':false,
  18437. 'classList':["ue-table-interlace-color-single","ue-table-interlace-color-double"]
  18438. });
  18439. me.getUETable = getUETable;
  18440. var commands = {
  18441. 'deletetable':1,
  18442. 'inserttable':1,
  18443. 'cellvalign':1,
  18444. 'insertcaption':1,
  18445. 'deletecaption':1,
  18446. 'inserttitle':1,
  18447. 'deletetitle':1,
  18448. "mergeright":1,
  18449. "mergedown":1,
  18450. "mergecells":1,
  18451. "insertrow":1,
  18452. "insertrownext":1,
  18453. "deleterow":1,
  18454. "insertcol":1,
  18455. "insertcolnext":1,
  18456. "deletecol":1,
  18457. "splittocells":1,
  18458. "splittorows":1,
  18459. "splittocols":1,
  18460. "adaptbytext":1,
  18461. "adaptbywindow":1,
  18462. "adaptbycustomer":1,
  18463. "insertparagraph":1,
  18464. "insertparagraphbeforetable":1,
  18465. "averagedistributecol":1,
  18466. "averagedistributerow":1
  18467. };
  18468. me.ready(function () {
  18469. utils.cssRule('table',
  18470. //选中的td上的样式
  18471. '.selectTdClass{background-color:#edf5fa !important}' +
  18472. 'table.noBorderTable td,table.noBorderTable th,table.noBorderTable caption{border:1px dashed #ddd !important}' +
  18473. //插入的表格的默认样式
  18474. 'table{margin-bottom:10px;border-collapse:collapse;display:table;}' +
  18475. 'td,th{padding: 5px 10px;border: 1px solid #DDD;}' +
  18476. 'caption{border:1px dashed #DDD;border-bottom:0;padding:3px;text-align:center;}' +
  18477. 'th{border-top:1px solid #BBB;background-color:#F7F7F7;}' +
  18478. 'table tr.firstRow th{border-top-width:2px;}' +
  18479. '.ue-table-interlace-color-single{ background-color: #fcfcfc; } .ue-table-interlace-color-double{ background-color: #f7faff; }' +
  18480. 'td p{margin:0;padding:0;}', me.document);
  18481. var tableCopyList, isFullCol, isFullRow;
  18482. //注册del/backspace事件
  18483. me.addListener('keydown', function (cmd, evt) {
  18484. var me = this;
  18485. var keyCode = evt.keyCode || evt.which;
  18486. if (keyCode == 8) {
  18487. var ut = getUETableBySelected(me);
  18488. if (ut && ut.selectedTds.length) {
  18489. if (ut.isFullCol()) {
  18490. me.execCommand('deletecol')
  18491. } else if (ut.isFullRow()) {
  18492. me.execCommand('deleterow')
  18493. } else {
  18494. me.fireEvent('delcells');
  18495. }
  18496. domUtils.preventDefault(evt);
  18497. }
  18498. var caption = domUtils.findParentByTagName(me.selection.getStart(), 'caption', true),
  18499. range = me.selection.getRange();
  18500. if (range.collapsed && caption && isEmptyBlock(caption)) {
  18501. me.fireEvent('saveScene');
  18502. var table = caption.parentNode;
  18503. domUtils.remove(caption);
  18504. if (table) {
  18505. range.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18506. }
  18507. me.fireEvent('saveScene');
  18508. }
  18509. }
  18510. if (keyCode == 46) {
  18511. ut = getUETableBySelected(me);
  18512. if (ut) {
  18513. me.fireEvent('saveScene');
  18514. for (var i = 0, ci; ci = ut.selectedTds[i++];) {
  18515. domUtils.fillNode(me.document, ci)
  18516. }
  18517. me.fireEvent('saveScene');
  18518. domUtils.preventDefault(evt);
  18519. }
  18520. }
  18521. if (keyCode == 13) {
  18522. var rng = me.selection.getRange(),
  18523. caption = domUtils.findParentByTagName(rng.startContainer, 'caption', true);
  18524. if (caption) {
  18525. var table = domUtils.findParentByTagName(caption, 'table');
  18526. if (!rng.collapsed) {
  18527. rng.deleteContents();
  18528. me.fireEvent('saveScene');
  18529. } else {
  18530. if (caption) {
  18531. rng.setStart(table.rows[0].cells[0], 0).setCursor(false, true);
  18532. }
  18533. }
  18534. domUtils.preventDefault(evt);
  18535. return;
  18536. }
  18537. if (rng.collapsed) {
  18538. var table = domUtils.findParentByTagName(rng.startContainer, 'table');
  18539. if (table) {
  18540. var cell = table.rows[0].cells[0],
  18541. start = domUtils.findParentByTagName(me.selection.getStart(), ['td', 'th'], true),
  18542. preNode = table.previousSibling;
  18543. if (cell === start && (!preNode || preNode.nodeType == 1 && preNode.tagName == 'TABLE' ) && domUtils.isStartInblock(rng)) {
  18544. var first = domUtils.findParent(me.selection.getStart(), function(n){return domUtils.isBlockElm(n)}, true);
  18545. if(first && ( /t(h|d)/i.test(first.tagName) || first === start.firstChild )){
  18546. me.execCommand('insertparagraphbeforetable');
  18547. domUtils.preventDefault(evt);
  18548. }
  18549. }
  18550. }
  18551. }
  18552. }
  18553. if ((evt.ctrlKey || evt.metaKey) && evt.keyCode == '67') {
  18554. tableCopyList = null;
  18555. var ut = getUETableBySelected(me);
  18556. if (ut) {
  18557. var tds = ut.selectedTds;
  18558. isFullCol = ut.isFullCol();
  18559. isFullRow = ut.isFullRow();
  18560. tableCopyList = [
  18561. [ut.cloneCell(tds[0],null,true)]
  18562. ];
  18563. for (var i = 1, ci; ci = tds[i]; i++) {
  18564. if (ci.parentNode !== tds[i - 1].parentNode) {
  18565. tableCopyList.push([ut.cloneCell(ci,null,true)]);
  18566. } else {
  18567. tableCopyList[tableCopyList.length - 1].push(ut.cloneCell(ci,null,true));
  18568. }
  18569. }
  18570. }
  18571. }
  18572. });
  18573. me.addListener("tablehasdeleted",function(){
  18574. toggleDraggableState(this, false, "", null);
  18575. if (dragButton)domUtils.remove(dragButton);
  18576. });
  18577. me.addListener('beforepaste', function (cmd, html) {
  18578. var me = this;
  18579. var rng = me.selection.getRange();
  18580. if (domUtils.findParentByTagName(rng.startContainer, 'caption', true)) {
  18581. var div = me.document.createElement("div");
  18582. div.innerHTML = html.html;
  18583. //trace:3729
  18584. html.html = div[browser.ie9below ? 'innerText' : 'textContent'];
  18585. return;
  18586. }
  18587. var table = getUETableBySelected(me);
  18588. if (tableCopyList) {
  18589. me.fireEvent('saveScene');
  18590. var rng = me.selection.getRange();
  18591. var td = domUtils.findParentByTagName(rng.startContainer, ['td', 'th'], true), tmpNode, preNode;
  18592. if (td) {
  18593. var ut = getUETable(td);
  18594. if (isFullRow) {
  18595. var rowIndex = ut.getCellInfo(td).rowIndex;
  18596. if (td.tagName == 'TH') {
  18597. rowIndex++;
  18598. }
  18599. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18600. var tr = ut.insertRow(rowIndex++, "td");
  18601. for (var j = 0, cj; cj = ci[j]; j++) {
  18602. var cell = tr.cells[j];
  18603. if (!cell) {
  18604. cell = tr.insertCell(j)
  18605. }
  18606. cell.innerHTML = cj.innerHTML;
  18607. cj.getAttribute('width') && cell.setAttribute('width', cj.getAttribute('width'));
  18608. cj.getAttribute('vAlign') && cell.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18609. cj.getAttribute('align') && cell.setAttribute('align', cj.getAttribute('align'));
  18610. cj.style.cssText && (cell.style.cssText = cj.style.cssText)
  18611. }
  18612. for (var j = 0, cj; cj = tr.cells[j]; j++) {
  18613. if (!ci[j])
  18614. break;
  18615. cj.innerHTML = ci[j].innerHTML;
  18616. ci[j].getAttribute('width') && cj.setAttribute('width', ci[j].getAttribute('width'));
  18617. ci[j].getAttribute('vAlign') && cj.setAttribute('vAlign', ci[j].getAttribute('vAlign'));
  18618. ci[j].getAttribute('align') && cj.setAttribute('align', ci[j].getAttribute('align'));
  18619. ci[j].style.cssText && (cj.style.cssText = ci[j].style.cssText)
  18620. }
  18621. }
  18622. } else {
  18623. if (isFullCol) {
  18624. cellInfo = ut.getCellInfo(td);
  18625. var maxColNum = 0;
  18626. for (var j = 0, ci = tableCopyList[0], cj; cj = ci[j++];) {
  18627. maxColNum += cj.colSpan || 1;
  18628. }
  18629. me.__hasEnterExecCommand = true;
  18630. for (i = 0; i < maxColNum; i++) {
  18631. me.execCommand('insertcol');
  18632. }
  18633. me.__hasEnterExecCommand = false;
  18634. td = ut.table.rows[0].cells[cellInfo.cellIndex];
  18635. if (td.tagName == 'TH') {
  18636. td = ut.table.rows[1].cells[cellInfo.cellIndex];
  18637. }
  18638. }
  18639. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18640. tmpNode = td;
  18641. for (var j = 0, cj; cj = ci[j++];) {
  18642. if (td) {
  18643. td.innerHTML = cj.innerHTML;
  18644. //todo 定制处理
  18645. cj.getAttribute('width') && td.setAttribute('width', cj.getAttribute('width'));
  18646. cj.getAttribute('vAlign') && td.setAttribute('vAlign', cj.getAttribute('vAlign'));
  18647. cj.getAttribute('align') && td.setAttribute('align', cj.getAttribute('align'));
  18648. cj.style.cssText && (td.style.cssText = cj.style.cssText);
  18649. preNode = td;
  18650. td = td.nextSibling;
  18651. } else {
  18652. var cloneTd = cj.cloneNode(true);
  18653. domUtils.removeAttributes(cloneTd, ['class', 'rowSpan', 'colSpan']);
  18654. preNode.parentNode.appendChild(cloneTd)
  18655. }
  18656. }
  18657. td = ut.getNextCell(tmpNode, true, true);
  18658. if (!tableCopyList[i])
  18659. break;
  18660. if (!td) {
  18661. var cellInfo = ut.getCellInfo(tmpNode);
  18662. ut.table.insertRow(ut.table.rows.length);
  18663. ut.update();
  18664. td = ut.getVSideCell(tmpNode, true);
  18665. }
  18666. }
  18667. }
  18668. ut.update();
  18669. } else {
  18670. table = me.document.createElement('table');
  18671. for (var i = 0, ci; ci = tableCopyList[i++];) {
  18672. var tr = table.insertRow(table.rows.length);
  18673. for (var j = 0, cj; cj = ci[j++];) {
  18674. cloneTd = UT.cloneCell(cj,null,true);
  18675. domUtils.removeAttributes(cloneTd, ['class']);
  18676. tr.appendChild(cloneTd)
  18677. }
  18678. if (j == 2 && cloneTd.rowSpan > 1) {
  18679. cloneTd.rowSpan = 1;
  18680. }
  18681. }
  18682. var defaultValue = getDefaultValue(me),
  18683. width = me.body.offsetWidth -
  18684. (needIEHack ? parseInt(domUtils.getComputedStyle(me.body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (me.options.offsetWidth || 0);
  18685. me.execCommand('insertHTML', '<table ' +
  18686. ( isFullCol && isFullRow ? 'width="' + width + '"' : '') +
  18687. '>' + table.innerHTML.replace(/>\s*</g, '><').replace(/\bth\b/gi, "td") + '</table>')
  18688. }
  18689. me.fireEvent('contentchange');
  18690. me.fireEvent('saveScene');
  18691. html.html = '';
  18692. return true;
  18693. } else {
  18694. var div = me.document.createElement("div"), tables;
  18695. div.innerHTML = html.html;
  18696. tables = div.getElementsByTagName("table");
  18697. if (domUtils.findParentByTagName(me.selection.getStart(), 'table')) {
  18698. utils.each(tables, function (t) {
  18699. domUtils.remove(t)
  18700. });
  18701. if (domUtils.findParentByTagName(me.selection.getStart(), 'caption', true)) {
  18702. div.innerHTML = div[browser.ie ? 'innerText' : 'textContent'];
  18703. }
  18704. } else {
  18705. utils.each(tables, function (table) {
  18706. removeStyleSize(table, true);
  18707. domUtils.removeAttributes(table, ['style', 'border']);
  18708. utils.each(domUtils.getElementsByTagName(table, "td"), function (td) {
  18709. if (isEmptyBlock(td)) {
  18710. domUtils.fillNode(me.document, td);
  18711. }
  18712. removeStyleSize(td, true);
  18713. // domUtils.removeAttributes(td, ['style'])
  18714. });
  18715. });
  18716. }
  18717. html.html = div.innerHTML;
  18718. }
  18719. });
  18720. me.addListener('afterpaste', function () {
  18721. utils.each(domUtils.getElementsByTagName(me.body, "table"), function (table) {
  18722. if (table.offsetWidth > me.body.offsetWidth) {
  18723. var defaultValue = getDefaultValue(me, table);
  18724. 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'
  18725. }
  18726. })
  18727. });
  18728. me.addListener('blur', function () {
  18729. tableCopyList = null;
  18730. });
  18731. var timer;
  18732. me.addListener('keydown', function () {
  18733. clearTimeout(timer);
  18734. timer = setTimeout(function () {
  18735. var rng = me.selection.getRange(),
  18736. cell = domUtils.findParentByTagName(rng.startContainer, ['th', 'td'], true);
  18737. if (cell) {
  18738. var table = cell.parentNode.parentNode.parentNode;
  18739. if (table.offsetWidth > table.getAttribute("width")) {
  18740. cell.style.wordBreak = "break-all";
  18741. }
  18742. }
  18743. }, 100);
  18744. });
  18745. me.addListener("selectionchange", function () {
  18746. toggleDraggableState(me, false, "", null);
  18747. });
  18748. //内容变化时触发索引更新
  18749. //todo 可否考虑标记检测,如果不涉及表格的变化就不进行索引重建和更新
  18750. me.addListener("contentchange", function () {
  18751. var me = this;
  18752. //尽可能排除一些不需要更新的状况
  18753. hideDragLine(me);
  18754. if (getUETableBySelected(me))return;
  18755. var rng = me.selection.getRange();
  18756. var start = rng.startContainer;
  18757. start = domUtils.findParentByTagName(start, ['td', 'th'], true);
  18758. utils.each(domUtils.getElementsByTagName(me.document, 'table'), function (table) {
  18759. if (me.fireEvent("excludetable", table) === true) return;
  18760. table.ueTable = new UT(table);
  18761. //trace:3742
  18762. // utils.each(domUtils.getElementsByTagName(me.document, 'td'), function (td) {
  18763. //
  18764. // if (domUtils.isEmptyBlock(td) && td !== start) {
  18765. // domUtils.fillNode(me.document, td);
  18766. // if (browser.ie && browser.version == 6) {
  18767. // td.innerHTML = '&nbsp;'
  18768. // }
  18769. // }
  18770. // });
  18771. // utils.each(domUtils.getElementsByTagName(me.document, 'th'), function (th) {
  18772. // if (domUtils.isEmptyBlock(th) && th !== start) {
  18773. // domUtils.fillNode(me.document, th);
  18774. // if (browser.ie && browser.version == 6) {
  18775. // th.innerHTML = '&nbsp;'
  18776. // }
  18777. // }
  18778. // });
  18779. table.onmouseover = function () {
  18780. me.fireEvent('tablemouseover', table);
  18781. };
  18782. table.onmousemove = function () {
  18783. me.fireEvent('tablemousemove', table);
  18784. me.options.tableDragable && toggleDragButton(true, this, me);
  18785. utils.defer(function(){
  18786. me.fireEvent('contentchange',50)
  18787. },true)
  18788. };
  18789. table.onmouseout = function () {
  18790. me.fireEvent('tablemouseout', table);
  18791. toggleDraggableState(me, false, "", null);
  18792. hideDragLine(me);
  18793. };
  18794. table.onclick = function (evt) {
  18795. evt = me.window.event || evt;
  18796. var target = getParentTdOrTh(evt.target || evt.srcElement);
  18797. if (!target)return;
  18798. var ut = getUETable(target),
  18799. table = ut.table,
  18800. cellInfo = ut.getCellInfo(target),
  18801. cellsRange,
  18802. rng = me.selection.getRange();
  18803. // if ("topLeft" == inPosition(table, mouseCoords(evt))) {
  18804. // cellsRange = ut.getCellsRange(ut.table.rows[0].cells[0], ut.getLastCell());
  18805. // ut.setSelected(cellsRange);
  18806. // return;
  18807. // }
  18808. // if ("bottomRight" == inPosition(table, mouseCoords(evt))) {
  18809. //
  18810. // return;
  18811. // }
  18812. if (inTableSide(table, target, evt, true)) {
  18813. var endTdCol = ut.getCell(ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].rowIndex, ut.indexTable[ut.rowsNum - 1][cellInfo.colIndex].cellIndex);
  18814. if (evt.shiftKey && ut.selectedTds.length) {
  18815. if (ut.selectedTds[0] !== endTdCol) {
  18816. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdCol);
  18817. ut.setSelected(cellsRange);
  18818. } else {
  18819. rng && rng.selectNodeContents(endTdCol).select();
  18820. }
  18821. } else {
  18822. if (target !== endTdCol) {
  18823. cellsRange = ut.getCellsRange(target, endTdCol);
  18824. ut.setSelected(cellsRange);
  18825. } else {
  18826. rng && rng.selectNodeContents(endTdCol).select();
  18827. }
  18828. }
  18829. return;
  18830. }
  18831. if (inTableSide(table, target, evt)) {
  18832. var endTdRow = ut.getCell(ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].rowIndex, ut.indexTable[cellInfo.rowIndex][ut.colsNum - 1].cellIndex);
  18833. if (evt.shiftKey && ut.selectedTds.length) {
  18834. if (ut.selectedTds[0] !== endTdRow) {
  18835. cellsRange = ut.getCellsRange(ut.selectedTds[0], endTdRow);
  18836. ut.setSelected(cellsRange);
  18837. } else {
  18838. rng && rng.selectNodeContents(endTdRow).select();
  18839. }
  18840. } else {
  18841. if (target !== endTdRow) {
  18842. cellsRange = ut.getCellsRange(target, endTdRow);
  18843. ut.setSelected(cellsRange);
  18844. } else {
  18845. rng && rng.selectNodeContents(endTdRow).select();
  18846. }
  18847. }
  18848. }
  18849. };
  18850. });
  18851. switchBorderColor(me, true);
  18852. });
  18853. domUtils.on(me.document, "mousemove", mouseMoveEvent);
  18854. domUtils.on(me.document, "mouseout", function (evt) {
  18855. var target = evt.target || evt.srcElement;
  18856. if (target.tagName == "TABLE") {
  18857. toggleDraggableState(me, false, "", null);
  18858. }
  18859. });
  18860. /**
  18861. * 表格隔行变色
  18862. */
  18863. me.addListener("interlacetable",function(type,table,classList){
  18864. if(!table) return;
  18865. var me = this,
  18866. rows = table.rows,
  18867. len = rows.length,
  18868. getClass = function(list,index,repeat){
  18869. return list[index] ? list[index] : repeat ? list[index % list.length]: "";
  18870. };
  18871. for(var i = 0;i<len;i++){
  18872. rows[i].className = getClass( classList|| me.options.classList,i,true);
  18873. }
  18874. });
  18875. me.addListener("uninterlacetable",function(type,table){
  18876. if(!table) return;
  18877. var me = this,
  18878. rows = table.rows,
  18879. classList = me.options.classList,
  18880. len = rows.length;
  18881. for(var i = 0;i<len;i++){
  18882. domUtils.removeClasses( rows[i], classList );
  18883. }
  18884. });
  18885. me.addListener("mousedown", mouseDownEvent);
  18886. me.addListener("mouseup", mouseUpEvent);
  18887. //拖动的时候触发mouseup
  18888. domUtils.on( me.body, 'dragstart', function( evt ){
  18889. mouseUpEvent.call( me, 'dragstart', evt );
  18890. });
  18891. me.addOutputRule(function(root){
  18892. utils.each(root.getNodesByTagName('div'),function(n){
  18893. if (n.getAttr('id') == 'ue_tableDragLine') {
  18894. n.parentNode.removeChild(n);
  18895. }
  18896. });
  18897. });
  18898. var currentRowIndex = 0;
  18899. me.addListener("mousedown", function () {
  18900. currentRowIndex = 0;
  18901. });
  18902. me.addListener('tabkeydown', function () {
  18903. var range = this.selection.getRange(),
  18904. common = range.getCommonAncestor(true, true),
  18905. table = domUtils.findParentByTagName(common, 'table');
  18906. if (table) {
  18907. if (domUtils.findParentByTagName(common, 'caption', true)) {
  18908. var cell = domUtils.getElementsByTagName(table, 'th td');
  18909. if (cell && cell.length) {
  18910. range.setStart(cell[0], 0).setCursor(false, true)
  18911. }
  18912. } else {
  18913. var cell = domUtils.findParentByTagName(common, ['td', 'th'], true),
  18914. ua = getUETable(cell);
  18915. currentRowIndex = cell.rowSpan > 1 ? currentRowIndex : ua.getCellInfo(cell).rowIndex;
  18916. var nextCell = ua.getTabNextCell(cell, currentRowIndex);
  18917. if (nextCell) {
  18918. if (isEmptyBlock(nextCell)) {
  18919. range.setStart(nextCell, 0).setCursor(false, true)
  18920. } else {
  18921. range.selectNodeContents(nextCell).select()
  18922. }
  18923. } else {
  18924. me.fireEvent('saveScene');
  18925. me.__hasEnterExecCommand = true;
  18926. this.execCommand('insertrownext');
  18927. me.__hasEnterExecCommand = false;
  18928. range = this.selection.getRange();
  18929. range.setStart(table.rows[table.rows.length - 1].cells[0], 0).setCursor();
  18930. me.fireEvent('saveScene');
  18931. }
  18932. }
  18933. return true;
  18934. }
  18935. });
  18936. browser.ie && me.addListener('selectionchange', function () {
  18937. toggleDraggableState(this, false, "", null);
  18938. });
  18939. me.addListener("keydown", function (type, evt) {
  18940. var me = this;
  18941. //处理在表格的最后一个输入tab产生新的表格
  18942. var keyCode = evt.keyCode || evt.which;
  18943. if (keyCode == 8 || keyCode == 46) {
  18944. return;
  18945. }
  18946. var notCtrlKey = !evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey;
  18947. notCtrlKey && removeSelectedClass(domUtils.getElementsByTagName(me.body, "td"));
  18948. var ut = getUETableBySelected(me);
  18949. if (!ut) return;
  18950. notCtrlKey && ut.clearSelected();
  18951. });
  18952. me.addListener("beforegetcontent", function () {
  18953. switchBorderColor(this, false);
  18954. browser.ie && utils.each(this.document.getElementsByTagName('caption'), function (ci) {
  18955. if (domUtils.isEmptyNode(ci)) {
  18956. ci.innerHTML = '&nbsp;'
  18957. }
  18958. });
  18959. });
  18960. me.addListener("aftergetcontent", function () {
  18961. switchBorderColor(this, true);
  18962. });
  18963. me.addListener("getAllHtml", function () {
  18964. removeSelectedClass(me.document.getElementsByTagName("td"));
  18965. });
  18966. //修正全屏状态下插入的表格宽度在非全屏状态下撑开编辑器的情况
  18967. me.addListener("fullscreenchanged", function (type, fullscreen) {
  18968. if (!fullscreen) {
  18969. var ratio = this.body.offsetWidth / document.body.offsetWidth,
  18970. tables = domUtils.getElementsByTagName(this.body, "table");
  18971. utils.each(tables, function (table) {
  18972. if (table.offsetWidth < me.body.offsetWidth) return false;
  18973. var tds = domUtils.getElementsByTagName(table, "td"),
  18974. backWidths = [];
  18975. utils.each(tds, function (td) {
  18976. backWidths.push(td.offsetWidth);
  18977. });
  18978. for (var i = 0, td; td = tds[i]; i++) {
  18979. td.setAttribute("width", Math.floor(backWidths[i] * ratio));
  18980. }
  18981. table.setAttribute("width", Math.floor(getTableWidth(me, needIEHack, getDefaultValue(me))))
  18982. });
  18983. }
  18984. });
  18985. //重写execCommand命令,用于处理框选时的处理
  18986. var oldExecCommand = me.execCommand;
  18987. me.execCommand = function (cmd, datatat) {
  18988. var me = this,
  18989. args = arguments;
  18990. cmd = cmd.toLowerCase();
  18991. var ut = getUETableBySelected(me), tds,
  18992. range = new dom.Range(me.document),
  18993. cmdFun = me.commands[cmd] || UE.commands[cmd],
  18994. result;
  18995. if (!cmdFun) return;
  18996. if (ut && !commands[cmd] && !cmdFun.notNeedUndo && !me.__hasEnterExecCommand) {
  18997. me.__hasEnterExecCommand = true;
  18998. me.fireEvent("beforeexeccommand", cmd);
  18999. tds = ut.selectedTds;
  19000. var lastState = -2, lastValue = -2, value, state;
  19001. for (var i = 0, td; td = tds[i]; i++) {
  19002. if (isEmptyBlock(td)) {
  19003. range.setStart(td, 0).setCursor(false, true)
  19004. } else {
  19005. range.selectNode(td).select(true);
  19006. }
  19007. state = me.queryCommandState(cmd);
  19008. value = me.queryCommandValue(cmd);
  19009. if (state != -1) {
  19010. if (lastState !== state || lastValue !== value) {
  19011. me._ignoreContentChange = true;
  19012. result = oldExecCommand.apply(me, arguments);
  19013. me._ignoreContentChange = false;
  19014. }
  19015. lastState = me.queryCommandState(cmd);
  19016. lastValue = me.queryCommandValue(cmd);
  19017. if (domUtils.isEmptyBlock(td)) {
  19018. domUtils.fillNode(me.document, td)
  19019. }
  19020. }
  19021. }
  19022. range.setStart(tds[0], 0).shrinkBoundary(true).setCursor(false, true);
  19023. me.fireEvent('contentchange');
  19024. me.fireEvent("afterexeccommand", cmd);
  19025. me.__hasEnterExecCommand = false;
  19026. me._selectionChange();
  19027. } else {
  19028. result = oldExecCommand.apply(me, arguments);
  19029. }
  19030. return result;
  19031. };
  19032. });
  19033. /**
  19034. * 删除obj的宽高style,改成属性宽高
  19035. * @param obj
  19036. * @param replaceToProperty
  19037. */
  19038. function removeStyleSize(obj, replaceToProperty) {
  19039. removeStyle(obj, "width", true);
  19040. removeStyle(obj, "height", true);
  19041. }
  19042. function removeStyle(obj, styleName, replaceToProperty) {
  19043. if (obj.style[styleName]) {
  19044. replaceToProperty && obj.setAttribute(styleName, parseInt(obj.style[styleName], 10));
  19045. obj.style[styleName] = "";
  19046. }
  19047. }
  19048. function getParentTdOrTh(ele) {
  19049. if (ele.tagName == "TD" || ele.tagName == "TH") return ele;
  19050. var td;
  19051. if (td = domUtils.findParentByTagName(ele, "td", true) || domUtils.findParentByTagName(ele, "th", true)) return td;
  19052. return null;
  19053. }
  19054. function isEmptyBlock(node) {
  19055. var reg = new RegExp(domUtils.fillChar, 'g');
  19056. if (node[browser.ie ? 'innerText' : 'textContent'].replace(/^\s*$/, '').replace(reg, '').length > 0) {
  19057. return 0;
  19058. }
  19059. for (var n in dtd.$isNotEmpty) {
  19060. if (node.getElementsByTagName(n).length) {
  19061. return 0;
  19062. }
  19063. }
  19064. return 1;
  19065. }
  19066. function mouseCoords(evt) {
  19067. if (evt.pageX || evt.pageY) {
  19068. return { x:evt.pageX, y:evt.pageY };
  19069. }
  19070. return {
  19071. x:evt.clientX + me.document.body.scrollLeft - me.document.body.clientLeft,
  19072. y:evt.clientY + me.document.body.scrollTop - me.document.body.clientTop
  19073. };
  19074. }
  19075. function mouseMoveEvent(evt) {
  19076. if( isEditorDisabled() ) {
  19077. return;
  19078. }
  19079. try {
  19080. //普通状态下鼠标移动
  19081. var target = getParentTdOrTh(evt.target || evt.srcElement),
  19082. pos;
  19083. //区分用户的行为是拖动还是双击
  19084. if( isInResizeBuffer ) {
  19085. me.body.style.webkitUserSelect = 'none';
  19086. if( Math.abs( userActionStatus.x - evt.clientX ) > offsetOfTableCell || Math.abs( userActionStatus.y - evt.clientY ) > offsetOfTableCell ) {
  19087. clearTableDragTimer();
  19088. isInResizeBuffer = false;
  19089. singleClickState = 0;
  19090. //drag action
  19091. tableBorderDrag(evt);
  19092. }
  19093. }
  19094. //修改单元格大小时的鼠标移动
  19095. if (onDrag && dragTd) {
  19096. singleClickState = 0;
  19097. me.body.style.webkitUserSelect = 'none';
  19098. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19099. pos = mouseCoords(evt);
  19100. toggleDraggableState(me, true, onDrag, pos, target);
  19101. if (onDrag == "h") {
  19102. dragLine.style.left = getPermissionX(dragTd, evt) + "px";
  19103. } else if (onDrag == "v") {
  19104. dragLine.style.top = getPermissionY(dragTd, evt) + "px";
  19105. }
  19106. return;
  19107. }
  19108. //当鼠标处于table上时,修改移动过程中的光标状态
  19109. if (target) {
  19110. //针对使用table作为容器的组件不触发拖拽效果
  19111. if (me.fireEvent('excludetable', target) === true)
  19112. return;
  19113. pos = mouseCoords(evt);
  19114. var state = getRelation(target, pos),
  19115. table = domUtils.findParentByTagName(target, "table", true);
  19116. if (inTableSide(table, target, evt, true)) {
  19117. if (me.fireEvent("excludetable", table) === true) return;
  19118. me.body.style.cursor = "url(" + me.options.cursorpath + "h.png),pointer";
  19119. } else if (inTableSide(table, target, evt)) {
  19120. if (me.fireEvent("excludetable", table) === true) return;
  19121. me.body.style.cursor = "url(" + me.options.cursorpath + "v.png),pointer";
  19122. } else {
  19123. me.body.style.cursor = "text";
  19124. var curCell = target;
  19125. if (/\d/.test(state)) {
  19126. state = state.replace(/\d/, '');
  19127. target = getUETable(target).getPreviewCell(target, state == "v");
  19128. }
  19129. //位于第一行的顶部或者第一列的左边时不可拖动
  19130. toggleDraggableState(me, target ? !!state : false, target ? state : '', pos, target);
  19131. }
  19132. } else {
  19133. toggleDragButton(false, table, me);
  19134. }
  19135. } catch (e) {
  19136. showError(e);
  19137. }
  19138. }
  19139. var dragButtonTimer;
  19140. function toggleDragButton(show, table, editor) {
  19141. if (!show) {
  19142. if (dragOver)return;
  19143. dragButtonTimer = setTimeout(function () {
  19144. !dragOver && dragButton && dragButton.parentNode && dragButton.parentNode.removeChild(dragButton);
  19145. }, 2000);
  19146. } else {
  19147. createDragButton(table, editor);
  19148. }
  19149. }
  19150. function createDragButton(table, editor) {
  19151. var pos = domUtils.getXY(table),
  19152. doc = table.ownerDocument;
  19153. if (dragButton && dragButton.parentNode)return dragButton;
  19154. dragButton = doc.createElement("div");
  19155. dragButton.contentEditable = false;
  19156. dragButton.innerHTML = "";
  19157. 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;";
  19158. domUtils.unSelectable(dragButton);
  19159. dragButton.onmouseover = function (evt) {
  19160. dragOver = true;
  19161. };
  19162. dragButton.onmouseout = function (evt) {
  19163. dragOver = false;
  19164. };
  19165. domUtils.on(dragButton, 'click', function (type, evt) {
  19166. doClick(evt, this);
  19167. });
  19168. domUtils.on(dragButton, 'dblclick', function (type, evt) {
  19169. doDblClick(evt);
  19170. });
  19171. domUtils.on(dragButton, 'dragstart', function (type, evt) {
  19172. domUtils.preventDefault(evt);
  19173. });
  19174. var timer;
  19175. function doClick(evt, button) {
  19176. // 部分浏览器下需要清理
  19177. clearTimeout(timer);
  19178. timer = setTimeout(function () {
  19179. editor.fireEvent("tableClicked", table, button);
  19180. }, 300);
  19181. }
  19182. function doDblClick(evt) {
  19183. clearTimeout(timer);
  19184. var ut = getUETable(table),
  19185. start = table.rows[0].cells[0],
  19186. end = ut.getLastCell(),
  19187. range = ut.getCellsRange(start, end);
  19188. editor.selection.getRange().setStart(start, 0).setCursor(false, true);
  19189. ut.setSelected(range);
  19190. }
  19191. doc.body.appendChild(dragButton);
  19192. }
  19193. // function inPosition(table, pos) {
  19194. // var tablePos = domUtils.getXY(table),
  19195. // width = table.offsetWidth,
  19196. // height = table.offsetHeight;
  19197. // if (pos.x - tablePos.x < 5 && pos.y - tablePos.y < 5) {
  19198. // return "topLeft";
  19199. // } else if (tablePos.x + width - pos.x < 5 && tablePos.y + height - pos.y < 5) {
  19200. // return "bottomRight";
  19201. // }
  19202. // }
  19203. function inTableSide(table, cell, evt, top) {
  19204. var pos = mouseCoords(evt),
  19205. state = getRelation(cell, pos);
  19206. if (top) {
  19207. var caption = table.getElementsByTagName("caption")[0],
  19208. capHeight = caption ? caption.offsetHeight : 0;
  19209. return (state == "v1") && ((pos.y - domUtils.getXY(table).y - capHeight) < 8);
  19210. } else {
  19211. return (state == "h1") && ((pos.x - domUtils.getXY(table).x) < 8);
  19212. }
  19213. }
  19214. /**
  19215. * 获取拖动时允许的X轴坐标
  19216. * @param dragTd
  19217. * @param evt
  19218. */
  19219. function getPermissionX(dragTd, evt) {
  19220. var ut = getUETable(dragTd);
  19221. if (ut) {
  19222. var preTd = ut.getSameEndPosCells(dragTd, "x")[0],
  19223. nextTd = ut.getSameStartPosXCells(dragTd)[0],
  19224. mouseX = mouseCoords(evt).x,
  19225. left = (preTd ? domUtils.getXY(preTd).x : domUtils.getXY(ut.table).x) + 20 ,
  19226. right = nextTd ? domUtils.getXY(nextTd).x + nextTd.offsetWidth - 20 : (me.body.offsetWidth + 5 || parseInt(domUtils.getComputedStyle(me.body, "width"), 10));
  19227. left += cellMinWidth;
  19228. right -= cellMinWidth;
  19229. return mouseX < left ? left : mouseX > right ? right : mouseX;
  19230. }
  19231. }
  19232. /**
  19233. * 获取拖动时允许的Y轴坐标
  19234. */
  19235. function getPermissionY(dragTd, evt) {
  19236. try {
  19237. var top = domUtils.getXY(dragTd).y,
  19238. mousePosY = mouseCoords(evt).y;
  19239. return mousePosY < top ? top : mousePosY;
  19240. } catch (e) {
  19241. showError(e);
  19242. }
  19243. }
  19244. /**
  19245. * 移动状态切换
  19246. */
  19247. function toggleDraggableState(editor, draggable, dir, mousePos, cell) {
  19248. try {
  19249. editor.body.style.cursor = dir == "h" ? "col-resize" : dir == "v" ? "row-resize" : "text";
  19250. if (browser.ie) {
  19251. if (dir && !mousedown && !getUETableBySelected(editor)) {
  19252. getDragLine(editor, editor.document);
  19253. showDragLineAt(dir, cell);
  19254. } else {
  19255. hideDragLine(editor)
  19256. }
  19257. }
  19258. onBorder = draggable;
  19259. } catch (e) {
  19260. showError(e);
  19261. }
  19262. }
  19263. /**
  19264. * 获取与UETable相关的resize line
  19265. * @param uetable UETable对象
  19266. */
  19267. function getResizeLineByUETable() {
  19268. var lineId = '_UETableResizeLine',
  19269. line = this.document.getElementById( lineId );
  19270. if( !line ) {
  19271. line = this.document.createElement("div");
  19272. line.id = lineId;
  19273. line.contnetEditable = false;
  19274. line.setAttribute("unselectable", "on");
  19275. var styles = {
  19276. width: 2*cellBorderWidth + 1 + 'px',
  19277. position: 'absolute',
  19278. 'z-index': 100000,
  19279. cursor: 'col-resize',
  19280. background: 'red',
  19281. display: 'none'
  19282. };
  19283. //切换状态
  19284. line.onmouseout = function(){
  19285. this.style.display = 'none';
  19286. };
  19287. utils.extend( line.style, styles );
  19288. this.document.body.appendChild( line );
  19289. }
  19290. return line;
  19291. }
  19292. /**
  19293. * 更新resize-line
  19294. */
  19295. function updateResizeLine( cell, uetable ) {
  19296. var line = getResizeLineByUETable.call( this ),
  19297. table = uetable.table,
  19298. styles = {
  19299. top: domUtils.getXY( table ).y + 'px',
  19300. left: domUtils.getXY( cell).x + cell.offsetWidth - cellBorderWidth + 'px',
  19301. display: 'block',
  19302. height: table.offsetHeight + 'px'
  19303. };
  19304. utils.extend( line.style, styles );
  19305. }
  19306. /**
  19307. * 显示resize-line
  19308. */
  19309. function showResizeLine( cell ) {
  19310. var uetable = getUETable( cell );
  19311. updateResizeLine.call( this, cell, uetable );
  19312. }
  19313. /**
  19314. * 获取鼠标与当前单元格的相对位置
  19315. * @param ele
  19316. * @param mousePos
  19317. */
  19318. function getRelation(ele, mousePos) {
  19319. var elePos = domUtils.getXY(ele);
  19320. if( !elePos ) {
  19321. return '';
  19322. }
  19323. if (elePos.x + ele.offsetWidth - mousePos.x < cellBorderWidth) {
  19324. return "h";
  19325. }
  19326. if (mousePos.x - elePos.x < cellBorderWidth) {
  19327. return 'h1'
  19328. }
  19329. if (elePos.y + ele.offsetHeight - mousePos.y < cellBorderWidth) {
  19330. return "v";
  19331. }
  19332. if (mousePos.y - elePos.y < cellBorderWidth) {
  19333. return 'v1'
  19334. }
  19335. return '';
  19336. }
  19337. function mouseDownEvent(type, evt) {
  19338. if( isEditorDisabled() ) {
  19339. return ;
  19340. }
  19341. userActionStatus = {
  19342. x: evt.clientX,
  19343. y: evt.clientY
  19344. };
  19345. //右键菜单单独处理
  19346. if (evt.button == 2) {
  19347. var ut = getUETableBySelected(me),
  19348. flag = false;
  19349. if (ut) {
  19350. var td = getTargetTd(me, evt);
  19351. utils.each(ut.selectedTds, function (ti) {
  19352. if (ti === td) {
  19353. flag = true;
  19354. }
  19355. });
  19356. if (!flag) {
  19357. removeSelectedClass(domUtils.getElementsByTagName(me.body, "th td"));
  19358. ut.clearSelected()
  19359. } else {
  19360. td = ut.selectedTds[0];
  19361. setTimeout(function () {
  19362. me.selection.getRange().setStart(td, 0).setCursor(false, true);
  19363. }, 0);
  19364. }
  19365. }
  19366. } else {
  19367. tableClickHander( evt );
  19368. }
  19369. }
  19370. //清除表格的计时器
  19371. function clearTableTimer() {
  19372. tabTimer && clearTimeout( tabTimer );
  19373. tabTimer = null;
  19374. }
  19375. //双击收缩
  19376. function tableDbclickHandler(evt) {
  19377. singleClickState = 0;
  19378. evt = evt || me.window.event;
  19379. var target = getParentTdOrTh(evt.target || evt.srcElement);
  19380. if (target) {
  19381. var h;
  19382. if (h = getRelation(target, mouseCoords(evt))) {
  19383. hideDragLine( me );
  19384. if (h == 'h1') {
  19385. h = 'h';
  19386. if (inTableSide(domUtils.findParentByTagName(target, "table"), target, evt)) {
  19387. me.execCommand('adaptbywindow');
  19388. } else {
  19389. target = getUETable(target).getPreviewCell(target);
  19390. if (target) {
  19391. var rng = me.selection.getRange();
  19392. rng.selectNodeContents(target).setCursor(true, true)
  19393. }
  19394. }
  19395. }
  19396. if (h == 'h') {
  19397. var ut = getUETable(target),
  19398. table = ut.table,
  19399. cells = getCellsByMoveBorder( target, table, true );
  19400. cells = extractArray( cells, 'left' );
  19401. ut.width = ut.offsetWidth;
  19402. var oldWidth = [],
  19403. newWidth = [];
  19404. utils.each( cells, function( cell ){
  19405. oldWidth.push( cell.offsetWidth );
  19406. } );
  19407. utils.each( cells, function( cell ){
  19408. cell.removeAttribute("width");
  19409. } );
  19410. window.setTimeout( function(){
  19411. //是否允许改变
  19412. var changeable = true;
  19413. utils.each( cells, function( cell, index ){
  19414. var width = cell.offsetWidth;
  19415. if( width > oldWidth[index] ) {
  19416. changeable = false;
  19417. return false;
  19418. }
  19419. newWidth.push( width );
  19420. } );
  19421. var change = changeable ? newWidth : oldWidth;
  19422. utils.each( cells, function( cell, index ){
  19423. cell.width = change[index] - getTabcellSpace();
  19424. } );
  19425. }, 0 );
  19426. // minWidth -= cellMinWidth;
  19427. //
  19428. // table.removeAttribute("width");
  19429. // utils.each(cells, function (cell) {
  19430. // cell.style.width = "";
  19431. // cell.width -= minWidth;
  19432. // });
  19433. }
  19434. }
  19435. }
  19436. }
  19437. function tableClickHander( evt ) {
  19438. removeSelectedClass(domUtils.getElementsByTagName(me.body, "td th"));
  19439. //trace:3113
  19440. //选中单元格,点击table外部,不会清掉table上挂的ueTable,会引起getUETableBySelected方法返回值
  19441. utils.each(me.document.getElementsByTagName('table'), function (t) {
  19442. t.ueTable = null;
  19443. });
  19444. startTd = getTargetTd(me, evt);
  19445. if( !startTd ) return;
  19446. var table = domUtils.findParentByTagName(startTd, "table", true);
  19447. ut = getUETable(table);
  19448. ut && ut.clearSelected();
  19449. //判断当前鼠标状态
  19450. if (!onBorder) {
  19451. me.document.body.style.webkitUserSelect = '';
  19452. mousedown = true;
  19453. me.addListener('mouseover', mouseOverEvent);
  19454. } else {
  19455. //边框上的动作处理
  19456. borderActionHandler( evt );
  19457. }
  19458. }
  19459. //处理表格边框上的动作, 这里做延时处理,避免两种动作互相影响
  19460. function borderActionHandler( evt ) {
  19461. if ( browser.ie ) {
  19462. evt = reconstruct(evt );
  19463. }
  19464. clearTableDragTimer();
  19465. //是否正在等待resize的缓冲中
  19466. isInResizeBuffer = true;
  19467. tableDragTimer = setTimeout(function(){
  19468. tableBorderDrag( evt );
  19469. }, dblclickTime);
  19470. }
  19471. function extractArray( originArr, key ) {
  19472. var result = [],
  19473. tmp = null;
  19474. for( var i = 0, len = originArr.length; i<len; i++ ) {
  19475. tmp = originArr[ i ][ key ];
  19476. if( tmp ) {
  19477. result.push( tmp );
  19478. }
  19479. }
  19480. return result;
  19481. }
  19482. function clearTableDragTimer() {
  19483. tableDragTimer && clearTimeout(tableDragTimer);
  19484. tableDragTimer = null;
  19485. }
  19486. function reconstruct( obj ) {
  19487. var attrs = ['pageX', 'pageY', 'clientX', 'clientY', 'srcElement', 'target'],
  19488. newObj = {};
  19489. if( obj ) {
  19490. for( var i = 0, key, val; key = attrs[i]; i++ ) {
  19491. val=obj[ key ];
  19492. val && (newObj[ key ] = val);
  19493. }
  19494. }
  19495. return newObj;
  19496. }
  19497. //边框拖动
  19498. function tableBorderDrag( evt ) {
  19499. isInResizeBuffer = false;
  19500. startTd = evt.target || evt.srcElement;
  19501. if( !startTd ) return;
  19502. var state = getRelation(startTd, mouseCoords(evt));
  19503. if (/\d/.test(state)) {
  19504. state = state.replace(/\d/, '');
  19505. startTd = getUETable(startTd).getPreviewCell(startTd, state == 'v');
  19506. }
  19507. hideDragLine(me);
  19508. getDragLine(me, me.document);
  19509. me.fireEvent('saveScene');
  19510. showDragLineAt(state, startTd);
  19511. mousedown = true;
  19512. //拖动开始
  19513. onDrag = state;
  19514. dragTd = startTd;
  19515. }
  19516. function mouseUpEvent(type, evt) {
  19517. if( isEditorDisabled() ) {
  19518. return ;
  19519. }
  19520. clearTableDragTimer();
  19521. isInResizeBuffer = false;
  19522. if( onBorder ) {
  19523. singleClickState = ++singleClickState % 3;
  19524. userActionStatus = {
  19525. x: evt.clientX,
  19526. y: evt.clientY
  19527. };
  19528. tableResizeTimer = setTimeout(function(){
  19529. singleClickState > 0 && singleClickState--;
  19530. }, dblclickTime );
  19531. if( singleClickState === 2 ) {
  19532. singleClickState = 0;
  19533. tableDbclickHandler(evt);
  19534. return;
  19535. }
  19536. }
  19537. if (evt.button == 2)return;
  19538. var me = this;
  19539. //清除表格上原生跨选问题
  19540. var range = me.selection.getRange(),
  19541. start = domUtils.findParentByTagName(range.startContainer, 'table', true),
  19542. end = domUtils.findParentByTagName(range.endContainer, 'table', true);
  19543. if (start || end) {
  19544. if (start === end) {
  19545. start = domUtils.findParentByTagName(range.startContainer, ['td', 'th', 'caption'], true);
  19546. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th', 'caption'], true);
  19547. if (start !== end) {
  19548. me.selection.clearRange()
  19549. }
  19550. } else {
  19551. me.selection.clearRange()
  19552. }
  19553. }
  19554. mousedown = false;
  19555. me.document.body.style.webkitUserSelect = '';
  19556. //拖拽状态下的mouseUP
  19557. if ( onDrag && dragTd ) {
  19558. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19559. singleClickState = 0;
  19560. dragLine = me.document.getElementById('ue_tableDragLine');
  19561. // trace 3973
  19562. if (dragLine) {
  19563. var dragTdPos = domUtils.getXY(dragTd),
  19564. dragLinePos = domUtils.getXY(dragLine);
  19565. switch (onDrag) {
  19566. case "h":
  19567. changeColWidth(dragTd, dragLinePos.x - dragTdPos.x);
  19568. break;
  19569. case "v":
  19570. changeRowHeight(dragTd, dragLinePos.y - dragTdPos.y - dragTd.offsetHeight);
  19571. break;
  19572. default:
  19573. }
  19574. onDrag = "";
  19575. dragTd = null;
  19576. hideDragLine(me);
  19577. me.fireEvent('saveScene');
  19578. return;
  19579. }
  19580. }
  19581. //正常状态下的mouseup
  19582. if (!startTd) {
  19583. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, "td", true);
  19584. if (!target) target = domUtils.findParentByTagName(evt.target || evt.srcElement, "th", true);
  19585. if (target && (target.tagName == "TD" || target.tagName == "TH")) {
  19586. if (me.fireEvent("excludetable", target) === true) return;
  19587. range = new dom.Range(me.document);
  19588. range.setStart(target, 0).setCursor(false, true);
  19589. }
  19590. } else {
  19591. var ut = getUETable(startTd),
  19592. cell = ut ? ut.selectedTds[0] : null;
  19593. if (cell) {
  19594. range = new dom.Range(me.document);
  19595. if (domUtils.isEmptyBlock(cell)) {
  19596. range.setStart(cell, 0).setCursor(false, true);
  19597. } else {
  19598. range.selectNodeContents(cell).shrinkBoundary().setCursor(false, true);
  19599. }
  19600. } else {
  19601. range = me.selection.getRange().shrinkBoundary();
  19602. if (!range.collapsed) {
  19603. var start = domUtils.findParentByTagName(range.startContainer, ['td', 'th'], true),
  19604. end = domUtils.findParentByTagName(range.endContainer, ['td', 'th'], true);
  19605. //在table里边的不能清除
  19606. if (start && !end || !start && end || start && end && start !== end) {
  19607. range.setCursor(false, true);
  19608. }
  19609. }
  19610. }
  19611. startTd = null;
  19612. me.removeListener('mouseover', mouseOverEvent);
  19613. }
  19614. me._selectionChange(250, evt);
  19615. }
  19616. function mouseOverEvent(type, evt) {
  19617. if( isEditorDisabled() ) {
  19618. return;
  19619. }
  19620. var me = this,
  19621. tar = evt.target || evt.srcElement;
  19622. currentTd = domUtils.findParentByTagName(tar, "td", true) || domUtils.findParentByTagName(tar, "th", true);
  19623. //需要判断两个TD是否位于同一个表格内
  19624. if (startTd && currentTd &&
  19625. ((startTd.tagName == "TD" && currentTd.tagName == "TD") || (startTd.tagName == "TH" && currentTd.tagName == "TH")) &&
  19626. domUtils.findParentByTagName(startTd, 'table') == domUtils.findParentByTagName(currentTd, 'table')) {
  19627. var ut = getUETable(currentTd);
  19628. if (startTd != currentTd) {
  19629. me.document.body.style.webkitUserSelect = 'none';
  19630. me.selection.getNative()[browser.ie9below ? 'empty' : 'removeAllRanges']();
  19631. var range = ut.getCellsRange(startTd, currentTd);
  19632. ut.setSelected(range);
  19633. } else {
  19634. me.document.body.style.webkitUserSelect = '';
  19635. ut.clearSelected();
  19636. }
  19637. }
  19638. evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false);
  19639. }
  19640. function setCellHeight(cell, height, backHeight) {
  19641. var lineHight = parseInt(domUtils.getComputedStyle(cell, "line-height"), 10),
  19642. tmpHeight = backHeight + height;
  19643. height = tmpHeight < lineHight ? lineHight : tmpHeight;
  19644. if (cell.style.height) cell.style.height = "";
  19645. cell.rowSpan == 1 ? cell.setAttribute("height", height) : (cell.removeAttribute && cell.removeAttribute("height"));
  19646. }
  19647. function getWidth(cell) {
  19648. if (!cell)return 0;
  19649. return parseInt(domUtils.getComputedStyle(cell, "width"), 10);
  19650. }
  19651. function changeColWidth(cell, changeValue) {
  19652. var ut = getUETable(cell);
  19653. if (ut) {
  19654. //根据当前移动的边框获取相关的单元格
  19655. var table = ut.table,
  19656. cells = getCellsByMoveBorder( cell, table );
  19657. table.style.width = "";
  19658. table.removeAttribute("width");
  19659. //修正改变量
  19660. changeValue = correctChangeValue( changeValue, cell, cells );
  19661. if (cell.nextSibling) {
  19662. var i=0;
  19663. utils.each( cells, function( cellGroup ){
  19664. cellGroup.left.width = (+cellGroup.left.width)+changeValue;
  19665. cellGroup.right && ( cellGroup.right.width = (+cellGroup.right.width)-changeValue );
  19666. } );
  19667. } else {
  19668. utils.each( cells, function( cellGroup ){
  19669. cellGroup.left.width -= -changeValue;
  19670. } );
  19671. }
  19672. }
  19673. }
  19674. function isEditorDisabled() {
  19675. return me.body.contentEditable === "false";
  19676. }
  19677. function changeRowHeight(td, changeValue) {
  19678. if (Math.abs(changeValue) < 10) return;
  19679. var ut = getUETable(td);
  19680. if (ut) {
  19681. var cells = ut.getSameEndPosCells(td, "y"),
  19682. //备份需要连带变化的td的原始高度,否则后期无法获取正确的值
  19683. backHeight = cells[0] ? cells[0].offsetHeight : 0;
  19684. for (var i = 0, cell; cell = cells[i++];) {
  19685. setCellHeight(cell, changeValue, backHeight);
  19686. }
  19687. }
  19688. }
  19689. /**
  19690. * 获取调整单元格大小的相关单元格
  19691. * @isContainMergeCell 返回的结果中是否包含发生合并后的单元格
  19692. */
  19693. function getCellsByMoveBorder( cell, table, isContainMergeCell ) {
  19694. if( !table ) {
  19695. table = domUtils.findParentByTagName( cell, 'table' );
  19696. }
  19697. if( !table ) {
  19698. return null;
  19699. }
  19700. //获取到该单元格所在行的序列号
  19701. var index = domUtils.getNodeIndex( cell ),
  19702. temp = cell,
  19703. rows = table.rows,
  19704. colIndex = 0;
  19705. while( temp ) {
  19706. //获取到当前单元格在未发生单元格合并时的序列
  19707. if( temp.nodeType === 1 ) {
  19708. colIndex += (temp.colSpan || 1);
  19709. }
  19710. temp = temp.previousSibling;
  19711. }
  19712. temp = null;
  19713. //记录想关的单元格
  19714. var borderCells = [];
  19715. utils.each(rows, function( tabRow ){
  19716. var cells = tabRow.cells,
  19717. currIndex = 0;
  19718. utils.each( cells, function( tabCell ){
  19719. currIndex += (tabCell.colSpan || 1);
  19720. if( currIndex === colIndex ) {
  19721. borderCells.push({
  19722. left: tabCell,
  19723. right: tabCell.nextSibling || null
  19724. });
  19725. return false;
  19726. } else if( currIndex > colIndex ) {
  19727. if( isContainMergeCell ) {
  19728. borderCells.push({
  19729. left: tabCell
  19730. });
  19731. }
  19732. return false;
  19733. }
  19734. } );
  19735. });
  19736. return borderCells;
  19737. }
  19738. /**
  19739. * 通过给定的单元格集合获取最小的单元格width
  19740. */
  19741. function getMinWidthByTableCells( cells ) {
  19742. var minWidth = Number.MAX_VALUE;
  19743. for( var i = 0, curCell; curCell = cells[ i ] ; i++ ) {
  19744. minWidth = Math.min( minWidth, curCell.width || getTableCellWidth( curCell ) );
  19745. }
  19746. return minWidth;
  19747. }
  19748. function correctChangeValue( changeValue, relatedCell, cells ) {
  19749. //为单元格的paading预留空间
  19750. changeValue -= getTabcellSpace();
  19751. if( changeValue < 0 ) {
  19752. return 0;
  19753. }
  19754. changeValue -= getTableCellWidth( relatedCell );
  19755. //确定方向
  19756. var direction = changeValue < 0 ? 'left':'right';
  19757. changeValue = Math.abs(changeValue);
  19758. //只关心非最后一个单元格就可以
  19759. utils.each( cells, function( cellGroup ){
  19760. var curCell = cellGroup[direction];
  19761. //为单元格保留最小空间
  19762. if( curCell ) {
  19763. changeValue = Math.min( changeValue, getTableCellWidth( curCell )-cellMinWidth );
  19764. }
  19765. } );
  19766. //修正越界
  19767. changeValue = changeValue < 0 ? 0 : changeValue;
  19768. return direction === 'left' ? -changeValue : changeValue;
  19769. }
  19770. function getTableCellWidth( cell ) {
  19771. var width = 0,
  19772. //偏移纠正量
  19773. offset = 0,
  19774. width = cell.offsetWidth - getTabcellSpace();
  19775. //最后一个节点纠正一下
  19776. if( !cell.nextSibling ) {
  19777. width -= getTableCellOffset( cell );
  19778. }
  19779. width = width < 0 ? 0 : width;
  19780. try {
  19781. cell.width = width;
  19782. } catch(e) {
  19783. }
  19784. return width;
  19785. }
  19786. /**
  19787. * 获取单元格所在表格的最末单元格的偏移量
  19788. */
  19789. function getTableCellOffset( cell ) {
  19790. tab = domUtils.findParentByTagName( cell, "table", false);
  19791. if( tab.offsetVal === undefined ) {
  19792. var prev = cell.previousSibling;
  19793. if( prev ) {
  19794. //最后一个单元格和前一个单元格的width diff结果 如果恰好为一个border width, 则条件成立
  19795. tab.offsetVal = cell.offsetWidth - prev.offsetWidth === UT.borderWidth ? UT.borderWidth : 0;
  19796. } else {
  19797. tab.offsetVal = 0;
  19798. }
  19799. }
  19800. return tab.offsetVal;
  19801. }
  19802. function getTabcellSpace() {
  19803. if( UT.tabcellSpace === undefined ) {
  19804. var cell = null,
  19805. tab = me.document.createElement("table"),
  19806. tbody = me.document.createElement("tbody"),
  19807. trow = me.document.createElement("tr"),
  19808. tabcell = me.document.createElement("td"),
  19809. mirror = null;
  19810. tabcell.style.cssText = 'border: 0;';
  19811. tabcell.width = 1;
  19812. trow.appendChild( tabcell );
  19813. trow.appendChild( mirror = tabcell.cloneNode( false ) );
  19814. tbody.appendChild( trow );
  19815. tab.appendChild( tbody );
  19816. tab.style.cssText = "visibility: hidden;";
  19817. me.body.appendChild( tab );
  19818. UT.paddingSpace = tabcell.offsetWidth - 1;
  19819. var tmpTabWidth = tab.offsetWidth;
  19820. tabcell.style.cssText = '';
  19821. mirror.style.cssText = '';
  19822. UT.borderWidth = ( tab.offsetWidth - tmpTabWidth ) / 3;
  19823. UT.tabcellSpace = UT.paddingSpace + UT.borderWidth;
  19824. me.body.removeChild( tab );
  19825. }
  19826. getTabcellSpace = function(){ return UT.tabcellSpace; };
  19827. return UT.tabcellSpace;
  19828. }
  19829. function getDragLine(editor, doc) {
  19830. if (mousedown)return;
  19831. dragLine = editor.document.createElement("div");
  19832. domUtils.setAttributes(dragLine, {
  19833. id:"ue_tableDragLine",
  19834. unselectable:'on',
  19835. contenteditable:false,
  19836. 'onresizestart':'return false',
  19837. 'ondragstart':'return false',
  19838. 'onselectstart':'return false',
  19839. style:"background-color:blue;position:absolute;padding:0;margin:0;background-image:none;border:0px none;opacity:0;filter:alpha(opacity=0)"
  19840. });
  19841. editor.body.appendChild(dragLine);
  19842. }
  19843. function hideDragLine(editor) {
  19844. if (mousedown)return;
  19845. var line;
  19846. while (line = editor.document.getElementById('ue_tableDragLine')) {
  19847. domUtils.remove(line)
  19848. }
  19849. }
  19850. /**
  19851. * 依据state(v|h)在cell位置显示横线
  19852. * @param state
  19853. * @param cell
  19854. */
  19855. function showDragLineAt(state, cell) {
  19856. if (!cell) return;
  19857. var table = domUtils.findParentByTagName(cell, "table"),
  19858. caption = table.getElementsByTagName('caption'),
  19859. width = table.offsetWidth,
  19860. height = table.offsetHeight - (caption.length > 0 ? caption[0].offsetHeight : 0),
  19861. tablePos = domUtils.getXY(table),
  19862. cellPos = domUtils.getXY(cell), css;
  19863. switch (state) {
  19864. case "h":
  19865. css = 'height:' + height + 'px;top:' + (tablePos.y + (caption.length > 0 ? caption[0].offsetHeight : 0)) + 'px;left:' + (cellPos.x + cell.offsetWidth);
  19866. dragLine.style.cssText = css + 'px;position: absolute;display:block;background-color:blue;width:1px;border:0; color:blue;opacity:.3;filter:alpha(opacity=30)';
  19867. break;
  19868. case "v":
  19869. css = 'width:' + width + 'px;left:' + tablePos.x + 'px;top:' + (cellPos.y + cell.offsetHeight );
  19870. //必须加上border:0和color:blue,否则低版ie不支持背景色显示
  19871. 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)';
  19872. break;
  19873. default:
  19874. }
  19875. }
  19876. /**
  19877. * 当表格边框颜色为白色时设置为虚线,true为添加虚线
  19878. * @param editor
  19879. * @param flag
  19880. */
  19881. function switchBorderColor(editor, flag) {
  19882. var tableArr = domUtils.getElementsByTagName(editor.body, "table"), color;
  19883. for (var i = 0, node; node = tableArr[i++];) {
  19884. var td = domUtils.getElementsByTagName(node, "td");
  19885. if (td[0]) {
  19886. if (flag) {
  19887. color = (td[0].style.borderColor).replace(/\s/g, "");
  19888. if (/(#ffffff)|(rgb\(255,255,255\))/ig.test(color))
  19889. domUtils.addClass(node, "noBorderTable")
  19890. } else {
  19891. domUtils.removeClasses(node, "noBorderTable")
  19892. }
  19893. }
  19894. }
  19895. }
  19896. function getTableWidth(editor, needIEHack, defaultValue) {
  19897. var body = editor.body;
  19898. return body.offsetWidth - (needIEHack ? parseInt(domUtils.getComputedStyle(body, 'margin-left'), 10) * 2 : 0) - defaultValue.tableBorder * 2 - (editor.options.offsetWidth || 0);
  19899. }
  19900. /**
  19901. * 获取当前拖动的单元格
  19902. */
  19903. function getTargetTd(editor, evt) {
  19904. var target = domUtils.findParentByTagName(evt.target || evt.srcElement, ["td", "th"], true),
  19905. dir = null;
  19906. if( !target ) {
  19907. return null;
  19908. }
  19909. dir = getRelation( target, mouseCoords( evt ) );
  19910. //如果有前一个节点, 需要做一个修正, 否则可能会得到一个错误的td
  19911. if( !target ) {
  19912. return null;
  19913. }
  19914. if( dir === 'h1' && target.previousSibling ) {
  19915. var position = domUtils.getXY( target),
  19916. cellWidth = target.offsetWidth;
  19917. if( Math.abs( position.x + cellWidth - evt.clientX ) > cellWidth / 3 ) {
  19918. target = target.previousSibling;
  19919. }
  19920. } else if( dir === 'v1' && target.parentNode.previousSibling ) {
  19921. var position = domUtils.getXY( target),
  19922. cellHeight = target.offsetHeight;
  19923. if( Math.abs( position.y + cellHeight - evt.clientY ) > cellHeight / 3 ) {
  19924. target = target.parentNode.previousSibling.firstChild;
  19925. }
  19926. }
  19927. //排除了非td内部以及用于代码高亮部分的td
  19928. return target && !(editor.fireEvent("excludetable", target) === true) ? target : null;
  19929. }
  19930. };
  19931. // plugins/table.sort.js
  19932. /**
  19933. * Created with JetBrains PhpStorm.
  19934. * User: Jinqn
  19935. * Date: 13-10-12
  19936. * Time: 上午10:20
  19937. * To change this template use File | Settings | File Templates.
  19938. */
  19939. UE.UETable.prototype.sortTable = function (sortByCellIndex, compareFn) {
  19940. var table = this.table,
  19941. rows = table.rows,
  19942. trArray = [],
  19943. flag = rows[0].cells[0].tagName === "TH",
  19944. lastRowIndex = 0;
  19945. if(this.selectedTds.length){
  19946. var range = this.cellsRange,
  19947. len = range.endRowIndex + 1;
  19948. for (var i = range.beginRowIndex; i < len; i++) {
  19949. trArray[i] = rows[i];
  19950. }
  19951. trArray.splice(0,range.beginRowIndex);
  19952. lastRowIndex = (range.endRowIndex +1) === this.rowsNum ? 0 : range.endRowIndex +1;
  19953. }else{
  19954. for (var i = 0,len = rows.length; i < len; i++) {
  19955. trArray[i] = rows[i];
  19956. }
  19957. }
  19958. var Fn = {
  19959. 'reversecurrent': function(td1,td2){
  19960. return 1;
  19961. },
  19962. 'orderbyasc': function(td1,td2){
  19963. var value1 = td1.innerText||td1.textContent,
  19964. value2 = td2.innerText||td2.textContent;
  19965. return value1.localeCompare(value2);
  19966. },
  19967. 'reversebyasc': function(td1,td2){
  19968. var value1 = td1.innerHTML,
  19969. value2 = td2.innerHTML;
  19970. return value2.localeCompare(value1);
  19971. },
  19972. 'orderbynum': function(td1,td2){
  19973. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19974. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19975. if(value1) value1 = +value1[0];
  19976. if(value2) value2 = +value2[0];
  19977. return (value1||0) - (value2||0);
  19978. },
  19979. 'reversebynum': function(td1,td2){
  19980. var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/),
  19981. value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/);
  19982. if(value1) value1 = +value1[0];
  19983. if(value2) value2 = +value2[0];
  19984. return (value2||0) - (value1||0);
  19985. }
  19986. };
  19987. //对表格设置排序的标记data-sort-type
  19988. table.setAttribute('data-sort-type', compareFn && typeof compareFn === "string" && Fn[compareFn] ? compareFn:'');
  19989. //th不参与排序
  19990. flag && trArray.splice(0, 1);
  19991. trArray = utils.sort(trArray,function (tr1, tr2) {
  19992. var result;
  19993. if (compareFn && typeof compareFn === "function") {
  19994. result = compareFn.call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19995. } else if (compareFn && typeof compareFn === "number") {
  19996. result = 1;
  19997. } else if (compareFn && typeof compareFn === "string" && Fn[compareFn]) {
  19998. result = Fn[compareFn].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  19999. } else {
  20000. result = Fn['orderbyasc'].call(this, tr1.cells[sortByCellIndex], tr2.cells[sortByCellIndex]);
  20001. }
  20002. return result;
  20003. });
  20004. var fragment = table.ownerDocument.createDocumentFragment();
  20005. for (var j = 0, len = trArray.length; j < len; j++) {
  20006. fragment.appendChild(trArray[j]);
  20007. }
  20008. var tbody = table.getElementsByTagName("tbody")[0];
  20009. if(!lastRowIndex){
  20010. tbody.appendChild(fragment);
  20011. }else{
  20012. tbody.insertBefore(fragment,rows[lastRowIndex- range.endRowIndex + range.beginRowIndex - 1])
  20013. }
  20014. };
  20015. UE.plugins['tablesort'] = function () {
  20016. var me = this,
  20017. UT = UE.UETable,
  20018. getUETable = function (tdOrTable) {
  20019. return UT.getUETable(tdOrTable);
  20020. },
  20021. getTableItemsByRange = function (editor) {
  20022. return UT.getTableItemsByRange(editor);
  20023. };
  20024. me.ready(function () {
  20025. //添加表格可排序的样式
  20026. utils.cssRule('tablesort',
  20027. 'table.sortEnabled tr.firstRow th,table.sortEnabled tr.firstRow td{padding-right:20px;background-repeat: no-repeat;background-position: center right;' +
  20028. ' background-image:url(' + me.options.themePath + me.options.theme + '/images/sortable.png);}',
  20029. me.document);
  20030. //做单元格合并操作时,清除可排序标识
  20031. me.addListener("afterexeccommand", function (type, cmd) {
  20032. if( cmd == 'mergeright' || cmd == 'mergedown' || cmd == 'mergecells') {
  20033. this.execCommand('disablesort');
  20034. }
  20035. });
  20036. });
  20037. //表格排序
  20038. UE.commands['sorttable'] = {
  20039. queryCommandState: function () {
  20040. var me = this,
  20041. tableItems = getTableItemsByRange(me);
  20042. if (!tableItems.cell) return -1;
  20043. var table = tableItems.table,
  20044. cells = table.getElementsByTagName("td");
  20045. for (var i = 0, cell; cell = cells[i++];) {
  20046. if (cell.rowSpan != 1 || cell.colSpan != 1) return -1;
  20047. }
  20048. return 0;
  20049. },
  20050. execCommand: function (cmd, fn) {
  20051. var me = this,
  20052. range = me.selection.getRange(),
  20053. bk = range.createBookmark(true),
  20054. tableItems = getTableItemsByRange(me),
  20055. cell = tableItems.cell,
  20056. ut = getUETable(tableItems.table),
  20057. cellInfo = ut.getCellInfo(cell);
  20058. ut.sortTable(cellInfo.cellIndex, fn);
  20059. range.moveToBookmark(bk);
  20060. try{
  20061. range.select();
  20062. }catch(e){}
  20063. }
  20064. };
  20065. //设置表格可排序,清除表格可排序
  20066. UE.commands["enablesort"] = UE.commands["disablesort"] = {
  20067. queryCommandState: function (cmd) {
  20068. var table = getTableItemsByRange(this).table;
  20069. if(table && cmd=='enablesort') {
  20070. var cells = domUtils.getElementsByTagName(table, 'th td');
  20071. for(var i = 0; i<cells.length; i++) {
  20072. if(cells[i].getAttribute('colspan')>1 || cells[i].getAttribute('rowspan')>1) return -1;
  20073. }
  20074. }
  20075. return !table ? -1: cmd=='enablesort' ^ table.getAttribute('data-sort')!='sortEnabled' ? -1:0;
  20076. },
  20077. execCommand: function (cmd) {
  20078. var table = getTableItemsByRange(this).table;
  20079. table.setAttribute("data-sort", cmd == "enablesort" ? "sortEnabled" : "sortDisabled");
  20080. cmd == "enablesort" ? domUtils.addClass(table,"sortEnabled"):domUtils.removeClasses(table,"sortEnabled");
  20081. }
  20082. };
  20083. };
  20084. // plugins/contextmenu.js
  20085. ///import core
  20086. ///commands 右键菜单
  20087. ///commandsName ContextMenu
  20088. ///commandsTitle 右键菜单
  20089. /**
  20090. * 右键菜单
  20091. * @function
  20092. * @name baidu.editor.plugins.contextmenu
  20093. * @author zhanyi
  20094. */
  20095. UE.plugins['contextmenu'] = function () {
  20096. var me = this;
  20097. me.setOpt('enableContextMenu',true);
  20098. if(me.getOpt('enableContextMenu') === false){
  20099. return;
  20100. }
  20101. var lang = me.getLang( "contextMenu" ),
  20102. menu,
  20103. items = me.options.contextMenu || [
  20104. {label:lang['selectall'], cmdName:'selectall'},
  20105. {
  20106. label:lang.cleardoc,
  20107. cmdName:'cleardoc',
  20108. exec:function () {
  20109. if ( confirm( lang.confirmclear ) ) {
  20110. this.execCommand( 'cleardoc' );
  20111. }
  20112. }
  20113. },
  20114. '-',
  20115. {
  20116. label:lang.unlink,
  20117. cmdName:'unlink'
  20118. },
  20119. '-',
  20120. {
  20121. group:lang.paragraph,
  20122. icon:'justifyjustify',
  20123. subMenu:[
  20124. {
  20125. label:lang.justifyleft,
  20126. cmdName:'justify',
  20127. value:'left'
  20128. },
  20129. {
  20130. label:lang.justifyright,
  20131. cmdName:'justify',
  20132. value:'right'
  20133. },
  20134. {
  20135. label:lang.justifycenter,
  20136. cmdName:'justify',
  20137. value:'center'
  20138. },
  20139. {
  20140. label:lang.justifyjustify,
  20141. cmdName:'justify',
  20142. value:'justify'
  20143. }
  20144. ]
  20145. },
  20146. '-',
  20147. {
  20148. group:lang.table,
  20149. icon:'table',
  20150. subMenu:[
  20151. {
  20152. label:lang.inserttable,
  20153. cmdName:'inserttable'
  20154. },
  20155. {
  20156. label:lang.deletetable,
  20157. cmdName:'deletetable'
  20158. },
  20159. '-',
  20160. {
  20161. label:lang.deleterow,
  20162. cmdName:'deleterow'
  20163. },
  20164. {
  20165. label:lang.deletecol,
  20166. cmdName:'deletecol'
  20167. },
  20168. {
  20169. label:lang.insertcol,
  20170. cmdName:'insertcol'
  20171. },
  20172. {
  20173. label:lang.insertcolnext,
  20174. cmdName:'insertcolnext'
  20175. },
  20176. {
  20177. label:lang.insertrow,
  20178. cmdName:'insertrow'
  20179. },
  20180. {
  20181. label:lang.insertrownext,
  20182. cmdName:'insertrownext'
  20183. },
  20184. '-',
  20185. {
  20186. label:lang.insertcaption,
  20187. cmdName:'insertcaption'
  20188. },
  20189. {
  20190. label:lang.deletecaption,
  20191. cmdName:'deletecaption'
  20192. },
  20193. {
  20194. label:lang.inserttitle,
  20195. cmdName:'inserttitle'
  20196. },
  20197. {
  20198. label:lang.deletetitle,
  20199. cmdName:'deletetitle'
  20200. },
  20201. {
  20202. label:lang.inserttitlecol,
  20203. cmdName:'inserttitlecol'
  20204. },
  20205. {
  20206. label:lang.deletetitlecol,
  20207. cmdName:'deletetitlecol'
  20208. },
  20209. '-',
  20210. {
  20211. label:lang.mergecells,
  20212. cmdName:'mergecells'
  20213. },
  20214. {
  20215. label:lang.mergeright,
  20216. cmdName:'mergeright'
  20217. },
  20218. {
  20219. label:lang.mergedown,
  20220. cmdName:'mergedown'
  20221. },
  20222. '-',
  20223. {
  20224. label:lang.splittorows,
  20225. cmdName:'splittorows'
  20226. },
  20227. {
  20228. label:lang.splittocols,
  20229. cmdName:'splittocols'
  20230. },
  20231. {
  20232. label:lang.splittocells,
  20233. cmdName:'splittocells'
  20234. },
  20235. '-',
  20236. {
  20237. label:lang.averageDiseRow,
  20238. cmdName:'averagedistributerow'
  20239. },
  20240. {
  20241. label:lang.averageDisCol,
  20242. cmdName:'averagedistributecol'
  20243. },
  20244. '-',
  20245. {
  20246. label:lang.edittd,
  20247. cmdName:'edittd',
  20248. exec:function () {
  20249. if ( UE.ui['edittd'] ) {
  20250. new UE.ui['edittd']( this );
  20251. }
  20252. this.getDialog('edittd').open();
  20253. }
  20254. },
  20255. {
  20256. label:lang.edittable,
  20257. cmdName:'edittable',
  20258. exec:function () {
  20259. if ( UE.ui['edittable'] ) {
  20260. new UE.ui['edittable']( this );
  20261. }
  20262. this.getDialog('edittable').open();
  20263. }
  20264. },
  20265. {
  20266. label:lang.setbordervisible,
  20267. cmdName:'setbordervisible'
  20268. }
  20269. ]
  20270. },
  20271. {
  20272. group:lang.tablesort,
  20273. icon:'tablesort',
  20274. subMenu:[
  20275. {
  20276. label:lang.enablesort,
  20277. cmdName:'enablesort'
  20278. },
  20279. {
  20280. label:lang.disablesort,
  20281. cmdName:'disablesort'
  20282. },
  20283. '-',
  20284. {
  20285. label:lang.reversecurrent,
  20286. cmdName:'sorttable',
  20287. value:'reversecurrent'
  20288. },
  20289. {
  20290. label:lang.orderbyasc,
  20291. cmdName:'sorttable',
  20292. value:'orderbyasc'
  20293. },
  20294. {
  20295. label:lang.reversebyasc,
  20296. cmdName:'sorttable',
  20297. value:'reversebyasc'
  20298. },
  20299. {
  20300. label:lang.orderbynum,
  20301. cmdName:'sorttable',
  20302. value:'orderbynum'
  20303. },
  20304. {
  20305. label:lang.reversebynum,
  20306. cmdName:'sorttable',
  20307. value:'reversebynum'
  20308. }
  20309. ]
  20310. },
  20311. {
  20312. group:lang.borderbk,
  20313. icon:'borderBack',
  20314. subMenu:[
  20315. {
  20316. label:lang.setcolor,
  20317. cmdName:"interlacetable",
  20318. exec:function(){
  20319. this.execCommand("interlacetable");
  20320. }
  20321. },
  20322. {
  20323. label:lang.unsetcolor,
  20324. cmdName:"uninterlacetable",
  20325. exec:function(){
  20326. this.execCommand("uninterlacetable");
  20327. }
  20328. },
  20329. {
  20330. label:lang.setbackground,
  20331. cmdName:"settablebackground",
  20332. exec:function(){
  20333. this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]});
  20334. }
  20335. },
  20336. {
  20337. label:lang.unsetbackground,
  20338. cmdName:"cleartablebackground",
  20339. exec:function(){
  20340. this.execCommand("cleartablebackground");
  20341. }
  20342. },
  20343. {
  20344. label:lang.redandblue,
  20345. cmdName:"settablebackground",
  20346. exec:function(){
  20347. this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]});
  20348. }
  20349. },
  20350. {
  20351. label:lang.threecolorgradient,
  20352. cmdName:"settablebackground",
  20353. exec:function(){
  20354. this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]});
  20355. }
  20356. }
  20357. ]
  20358. },
  20359. {
  20360. group:lang.aligntd,
  20361. icon:'aligntd',
  20362. subMenu:[
  20363. {
  20364. cmdName:'cellalignment',
  20365. value:{align:'left',vAlign:'top'}
  20366. },
  20367. {
  20368. cmdName:'cellalignment',
  20369. value:{align:'center',vAlign:'top'}
  20370. },
  20371. {
  20372. cmdName:'cellalignment',
  20373. value:{align:'right',vAlign:'top'}
  20374. },
  20375. {
  20376. cmdName:'cellalignment',
  20377. value:{align:'left',vAlign:'middle'}
  20378. },
  20379. {
  20380. cmdName:'cellalignment',
  20381. value:{align:'center',vAlign:'middle'}
  20382. },
  20383. {
  20384. cmdName:'cellalignment',
  20385. value:{align:'right',vAlign:'middle'}
  20386. },
  20387. {
  20388. cmdName:'cellalignment',
  20389. value:{align:'left',vAlign:'bottom'}
  20390. },
  20391. {
  20392. cmdName:'cellalignment',
  20393. value:{align:'center',vAlign:'bottom'}
  20394. },
  20395. {
  20396. cmdName:'cellalignment',
  20397. value:{align:'right',vAlign:'bottom'}
  20398. }
  20399. ]
  20400. },
  20401. {
  20402. group:lang.aligntable,
  20403. icon:'aligntable',
  20404. subMenu:[
  20405. {
  20406. cmdName:'tablealignment',
  20407. className: 'left',
  20408. label:lang.tableleft,
  20409. value:"left"
  20410. },
  20411. {
  20412. cmdName:'tablealignment',
  20413. className: 'center',
  20414. label:lang.tablecenter,
  20415. value:"center"
  20416. },
  20417. {
  20418. cmdName:'tablealignment',
  20419. className: 'right',
  20420. label:lang.tableright,
  20421. value:"right"
  20422. }
  20423. ]
  20424. },
  20425. '-',
  20426. {
  20427. label:lang.insertparagraphbefore,
  20428. cmdName:'insertparagraph',
  20429. value:true
  20430. },
  20431. {
  20432. label:lang.insertparagraphafter,
  20433. cmdName:'insertparagraph'
  20434. },
  20435. {
  20436. label:lang['copy'],
  20437. cmdName:'copy'
  20438. },
  20439. {
  20440. label:lang['paste'],
  20441. cmdName:'paste'
  20442. }
  20443. ];
  20444. if ( !items.length ) {
  20445. return;
  20446. }
  20447. var uiUtils = UE.ui.uiUtils;
  20448. me.addListener( 'contextmenu', function ( type, evt ) {
  20449. var offset = uiUtils.getViewportOffsetByEvent( evt );
  20450. me.fireEvent( 'beforeselectionchange' );
  20451. if ( menu ) {
  20452. menu.destroy();
  20453. }
  20454. for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) {
  20455. var last;
  20456. (function ( item ) {
  20457. if ( item == '-' ) {
  20458. if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) {
  20459. contextItems.push( '-' );
  20460. }
  20461. } else if ( item.hasOwnProperty( "group" ) ) {
  20462. for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) {
  20463. (function ( subItem ) {
  20464. if ( subItem == '-' ) {
  20465. if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) {
  20466. subMenu.push( '-' );
  20467. }else{
  20468. subMenu.splice(subMenu.length-1);
  20469. }
  20470. } else {
  20471. if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) &&
  20472. (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) {
  20473. subMenu.push( {
  20474. 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"",
  20475. 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ),
  20476. onclick:subItem.exec ? function () {
  20477. subItem.exec.call( me );
  20478. } : function () {
  20479. me.execCommand( subItem.cmdName, subItem.value );
  20480. }
  20481. } );
  20482. }
  20483. }
  20484. })( cj );
  20485. }
  20486. if ( subMenu.length ) {
  20487. function getLabel(){
  20488. switch (item.icon){
  20489. case "table":
  20490. return me.getLang( "contextMenu.table" );
  20491. case "justifyjustify":
  20492. return me.getLang( "contextMenu.paragraph" );
  20493. case "aligntd":
  20494. return me.getLang("contextMenu.aligntd");
  20495. case "aligntable":
  20496. return me.getLang("contextMenu.aligntable");
  20497. case "tablesort":
  20498. return lang.tablesort;
  20499. case "borderBack":
  20500. return lang.borderbk;
  20501. default :
  20502. return '';
  20503. }
  20504. }
  20505. contextItems.push( {
  20506. //todo 修正成自动获取方式
  20507. 'label':getLabel(),
  20508. className:'edui-for-' + item.icon,
  20509. 'subMenu':{
  20510. items:subMenu,
  20511. editor:me
  20512. }
  20513. } );
  20514. }
  20515. } else {
  20516. //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法
  20517. if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) &&
  20518. (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) {
  20519. contextItems.push( {
  20520. 'label':item.label || me.getLang( "contextMenu." + item.cmdName ),
  20521. className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')),
  20522. onclick:item.exec ? function () {
  20523. item.exec.call( me );
  20524. } : function () {
  20525. me.execCommand( item.cmdName, item.value );
  20526. }
  20527. } );
  20528. }
  20529. }
  20530. })( ti );
  20531. }
  20532. if ( contextItems[contextItems.length - 1] == '-' ) {
  20533. contextItems.pop();
  20534. }
  20535. menu = new UE.ui.Menu( {
  20536. items:contextItems,
  20537. className:"edui-contextmenu",
  20538. editor:me
  20539. } );
  20540. menu.render();
  20541. menu.showAt( offset );
  20542. me.fireEvent("aftershowcontextmenu",menu);
  20543. domUtils.preventDefault( evt );
  20544. if ( browser.ie ) {
  20545. var ieRange;
  20546. try {
  20547. ieRange = me.selection.getNative().createRange();
  20548. } catch ( e ) {
  20549. return;
  20550. }
  20551. if ( ieRange.item ) {
  20552. var range = new dom.Range( me.document );
  20553. range.selectNode( ieRange.item( 0 ) ).select( true, true );
  20554. }
  20555. }
  20556. });
  20557. // 添加复制的flash按钮
  20558. me.addListener('aftershowcontextmenu', function(type, menu) {
  20559. if (me.zeroclipboard) {
  20560. var items = menu.items;
  20561. for (var key in items) {
  20562. if (items[key].className == 'edui-for-copy') {
  20563. me.zeroclipboard.clip(items[key].getDom());
  20564. }
  20565. }
  20566. }
  20567. });
  20568. };
  20569. // plugins/shortcutmenu.js
  20570. ///import core
  20571. ///commands 弹出菜单
  20572. // commandsName popupmenu
  20573. ///commandsTitle 弹出菜单
  20574. /**
  20575. * 弹出菜单
  20576. * @function
  20577. * @name baidu.editor.plugins.popupmenu
  20578. * @author xuheng
  20579. */
  20580. UE.plugins['shortcutmenu'] = function () {
  20581. var me = this,
  20582. menu,
  20583. items = me.options.shortcutMenu || [];
  20584. if (!items.length) {
  20585. return;
  20586. }
  20587. me.addListener ('contextmenu mouseup' , function (type , e) {
  20588. var me = this,
  20589. customEvt = {
  20590. type : type ,
  20591. target : e.target || e.srcElement ,
  20592. screenX : e.screenX ,
  20593. screenY : e.screenY ,
  20594. clientX : e.clientX ,
  20595. clientY : e.clientY
  20596. };
  20597. setTimeout (function () {
  20598. var rng = me.selection.getRange ();
  20599. if (rng.collapsed === false || type == "contextmenu") {
  20600. if (!menu) {
  20601. menu = new baidu.editor.ui.ShortCutMenu ({
  20602. editor : me ,
  20603. items : items ,
  20604. theme : me.options.theme ,
  20605. className : 'edui-shortcutmenu'
  20606. });
  20607. menu.render ();
  20608. me.fireEvent ("afterrendershortcutmenu" , menu);
  20609. }
  20610. menu.show (customEvt , !!UE.plugins['contextmenu']);
  20611. }
  20612. });
  20613. if (type == 'contextmenu') {
  20614. domUtils.preventDefault (e);
  20615. if (browser.ie9below) {
  20616. var ieRange;
  20617. try {
  20618. ieRange = me.selection.getNative().createRange();
  20619. } catch (e) {
  20620. return;
  20621. }
  20622. if (ieRange.item) {
  20623. var range = new dom.Range (me.document);
  20624. range.selectNode (ieRange.item (0)).select (true , true);
  20625. }
  20626. }
  20627. }
  20628. });
  20629. me.addListener ('keydown' , function (type) {
  20630. if (type == "keydown") {
  20631. menu && !menu.isHidden && menu.hide ();
  20632. }
  20633. });
  20634. };
  20635. // plugins/basestyle.js
  20636. /**
  20637. * B、I、sub、super命令支持
  20638. * @file
  20639. * @since 1.2.6.1
  20640. */
  20641. UE.plugins['basestyle'] = function(){
  20642. /**
  20643. * 字体加粗
  20644. * @command bold
  20645. * @param { String } cmd 命令字符串
  20646. * @remind 对已加粗的文本内容执行该命令, 将取消加粗
  20647. * @method execCommand
  20648. * @example
  20649. * ```javascript
  20650. * //editor是编辑器实例
  20651. * //对当前选中的文本内容执行加粗操作
  20652. * //第一次执行, 文本内容加粗
  20653. * editor.execCommand( 'bold' );
  20654. *
  20655. * //第二次执行, 文本内容取消加粗
  20656. * editor.execCommand( 'bold' );
  20657. * ```
  20658. */
  20659. /**
  20660. * 字体倾斜
  20661. * @command italic
  20662. * @method execCommand
  20663. * @param { String } cmd 命令字符串
  20664. * @remind 对已倾斜的文本内容执行该命令, 将取消倾斜
  20665. * @example
  20666. * ```javascript
  20667. * //editor是编辑器实例
  20668. * //对当前选中的文本内容执行斜体操作
  20669. * //第一次操作, 文本内容将变成斜体
  20670. * editor.execCommand( 'italic' );
  20671. *
  20672. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20673. * editor.execCommand( 'italic' );
  20674. * ```
  20675. */
  20676. /**
  20677. * 下标文本,与“superscript”命令互斥
  20678. * @command subscript
  20679. * @method execCommand
  20680. * @remind 把选中的文本内容切换成下标文本, 如果当前选中的文本已经是下标, 则该操作会把文本内容还原成正常文本
  20681. * @param { String } cmd 命令字符串
  20682. * @example
  20683. * ```javascript
  20684. * //editor是编辑器实例
  20685. * //对当前选中的文本内容执行下标操作
  20686. * //第一次操作, 文本内容将变成下标文本
  20687. * editor.execCommand( 'subscript' );
  20688. *
  20689. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20690. * editor.execCommand( 'subscript' );
  20691. * ```
  20692. */
  20693. /**
  20694. * 上标文本,与“subscript”命令互斥
  20695. * @command superscript
  20696. * @method execCommand
  20697. * @remind 把选中的文本内容切换成上标文本, 如果当前选中的文本已经是上标, 则该操作会把文本内容还原成正常文本
  20698. * @param { String } cmd 命令字符串
  20699. * @example
  20700. * ```javascript
  20701. * //editor是编辑器实例
  20702. * //对当前选中的文本内容执行上标操作
  20703. * //第一次操作, 文本内容将变成上标文本
  20704. * editor.execCommand( 'superscript' );
  20705. *
  20706. * //再次对同一文本内容执行, 则文本内容将恢复正常
  20707. * editor.execCommand( 'superscript' );
  20708. * ```
  20709. */
  20710. var basestyles = {
  20711. 'bold':['strong','b'],
  20712. 'italic':['em','i'],
  20713. 'subscript':['sub'],
  20714. 'superscript':['sup']
  20715. },
  20716. getObj = function(editor,tagNames){
  20717. return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames);
  20718. },
  20719. me = this;
  20720. //添加快捷键
  20721. me.addshortcutkey({
  20722. "Bold" : "ctrl+66",//^B
  20723. "Italic" : "ctrl+73", //^I
  20724. "Underline" : "ctrl+85"//^U
  20725. });
  20726. me.addInputRule(function(root){
  20727. utils.each(root.getNodesByTagName('b i'),function(node){
  20728. switch (node.tagName){
  20729. case 'b':
  20730. node.tagName = 'strong';
  20731. break;
  20732. case 'i':
  20733. node.tagName = 'em';
  20734. }
  20735. });
  20736. });
  20737. for ( var style in basestyles ) {
  20738. (function( cmd, tagNames ) {
  20739. me.commands[cmd] = {
  20740. execCommand : function( cmdName ) {
  20741. var range = me.selection.getRange(),obj = getObj(this,tagNames);
  20742. if ( range.collapsed ) {
  20743. if ( obj ) {
  20744. var tmpText = me.document.createTextNode('');
  20745. range.insertNode( tmpText ).removeInlineStyle( tagNames );
  20746. range.setStartBefore(tmpText);
  20747. domUtils.remove(tmpText);
  20748. } else {
  20749. var tmpNode = range.document.createElement( tagNames[0] );
  20750. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20751. tmpText = me.document.createTextNode('');
  20752. range.insertNode(tmpText)
  20753. .removeInlineStyle(['sub','sup'])
  20754. .setStartBefore(tmpText)
  20755. .collapse(true);
  20756. }
  20757. range.insertNode( tmpNode ).setStart( tmpNode, 0 );
  20758. }
  20759. range.collapse( true );
  20760. } else {
  20761. if(cmdName == 'superscript' || cmdName == 'subscript'){
  20762. if(!obj || obj.tagName.toLowerCase() != cmdName){
  20763. range.removeInlineStyle(['sub','sup']);
  20764. }
  20765. }
  20766. obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] );
  20767. }
  20768. range.select();
  20769. },
  20770. queryCommandState : function() {
  20771. return getObj(this,tagNames) ? 1 : 0;
  20772. }
  20773. };
  20774. })( style, basestyles[style] );
  20775. }
  20776. };
  20777. // plugins/elementpath.js
  20778. /**
  20779. * 选取路径命令
  20780. * @file
  20781. */
  20782. UE.plugins['elementpath'] = function(){
  20783. var currentLevel,
  20784. tagNames,
  20785. me = this;
  20786. me.setOpt('elementPathEnabled',true);
  20787. if(!me.options.elementPathEnabled){
  20788. return;
  20789. }
  20790. me.commands['elementpath'] = {
  20791. execCommand : function( cmdName, level ) {
  20792. var start = tagNames[level],
  20793. range = me.selection.getRange();
  20794. currentLevel = level*1;
  20795. range.selectNode(start).select();
  20796. },
  20797. queryCommandValue : function() {
  20798. //产生一个副本,不能修改原来的startElementPath;
  20799. var parents = [].concat(this.selection.getStartElementPath()).reverse(),
  20800. names = [];
  20801. tagNames = parents;
  20802. for(var i=0,ci;ci=parents[i];i++){
  20803. if(ci.nodeType == 3) {
  20804. continue;
  20805. }
  20806. var name = ci.tagName.toLowerCase();
  20807. if(name == 'img' && ci.getAttribute('anchorname')){
  20808. name = 'anchor';
  20809. }
  20810. names[i] = name;
  20811. if(currentLevel == i){
  20812. currentLevel = -1;
  20813. break;
  20814. }
  20815. }
  20816. return names;
  20817. }
  20818. };
  20819. };
  20820. // plugins/formatmatch.js
  20821. /**
  20822. * 格式刷,只格式inline的
  20823. * @file
  20824. * @since 1.2.6.1
  20825. */
  20826. /**
  20827. * 格式刷
  20828. * @command formatmatch
  20829. * @method execCommand
  20830. * @remind 该操作不能复制段落格式
  20831. * @param { String } cmd 命令字符串
  20832. * @example
  20833. * ```javascript
  20834. * //editor是编辑器实例
  20835. * //获取格式刷
  20836. * editor.execCommand( 'formatmatch' );
  20837. * ```
  20838. */
  20839. UE.plugins['formatmatch'] = function(){
  20840. var me = this,
  20841. list = [],img,
  20842. flag = 0;
  20843. me.addListener('reset',function(){
  20844. list = [];
  20845. flag = 0;
  20846. });
  20847. function addList(type,evt){
  20848. if(browser.webkit){
  20849. var target = evt.target.tagName == 'IMG' ? evt.target : null;
  20850. }
  20851. function addFormat(range){
  20852. if(text){
  20853. range.selectNode(text);
  20854. }
  20855. return range.applyInlineStyle(list[list.length-1].tagName,null,list);
  20856. }
  20857. me.undoManger && me.undoManger.save();
  20858. var range = me.selection.getRange(),
  20859. imgT = target || range.getClosedNode();
  20860. if(img && imgT && imgT.tagName == 'IMG'){
  20861. //trace:964
  20862. imgT.style.cssText += ';float:' + (img.style.cssFloat || img.style.styleFloat ||'none') + ';display:' + (img.style.display||'inline');
  20863. img = null;
  20864. }else{
  20865. if(!img){
  20866. var collapsed = range.collapsed;
  20867. if(collapsed){
  20868. var text = me.document.createTextNode('match');
  20869. range.insertNode(text).select();
  20870. }
  20871. me.__hasEnterExecCommand = true;
  20872. //不能把block上的属性干掉
  20873. //trace:1553
  20874. var removeFormatAttributes = me.options.removeFormatAttributes;
  20875. me.options.removeFormatAttributes = '';
  20876. me.execCommand('removeformat');
  20877. me.options.removeFormatAttributes = removeFormatAttributes;
  20878. me.__hasEnterExecCommand = false;
  20879. //trace:969
  20880. range = me.selection.getRange();
  20881. if(list.length){
  20882. addFormat(range);
  20883. }
  20884. if(text){
  20885. range.setStartBefore(text).collapse(true);
  20886. }
  20887. range.select();
  20888. text && domUtils.remove(text);
  20889. }
  20890. }
  20891. me.undoManger && me.undoManger.save();
  20892. me.removeListener('mouseup',addList);
  20893. flag = 0;
  20894. }
  20895. me.commands['formatmatch'] = {
  20896. execCommand : function( cmdName ) {
  20897. if(flag){
  20898. flag = 0;
  20899. list = [];
  20900. me.removeListener('mouseup',addList);
  20901. return;
  20902. }
  20903. var range = me.selection.getRange();
  20904. img = range.getClosedNode();
  20905. if(!img || img.tagName != 'IMG'){
  20906. range.collapse(true).shrinkBoundary();
  20907. var start = range.startContainer;
  20908. list = domUtils.findParents(start,true,function(node){
  20909. return !domUtils.isBlockElm(node) && node.nodeType == 1;
  20910. });
  20911. //a不能加入格式刷, 并且克隆节点
  20912. for(var i=0,ci;ci=list[i];i++){
  20913. if(ci.tagName == 'A'){
  20914. list.splice(i,1);
  20915. break;
  20916. }
  20917. }
  20918. }
  20919. me.addListener('mouseup',addList);
  20920. flag = 1;
  20921. },
  20922. queryCommandState : function() {
  20923. return flag;
  20924. },
  20925. notNeedUndo : 1
  20926. };
  20927. };
  20928. // plugins/searchreplace.js
  20929. ///import core
  20930. ///commands 查找替换
  20931. ///commandsName SearchReplace
  20932. ///commandsTitle 查询替换
  20933. ///commandsDialog dialogs\searchreplace
  20934. /**
  20935. * @description 查找替换
  20936. * @author zhanyi
  20937. */
  20938. UE.plugin.register('searchreplace',function(){
  20939. var me = this;
  20940. var _blockElm = {'table':1,'tbody':1,'tr':1,'ol':1,'ul':1};
  20941. function findTextInString(textContent,opt,currentIndex){
  20942. var str = opt.searchStr;
  20943. if(opt.dir == -1){
  20944. textContent = textContent.split('').reverse().join('');
  20945. str = str.split('').reverse().join('');
  20946. currentIndex = textContent.length - currentIndex;
  20947. }
  20948. var reg = new RegExp(str,'g' + (opt.casesensitive ? '' : 'i')),match;
  20949. while(match = reg.exec(textContent)){
  20950. if(match.index >= currentIndex){
  20951. return opt.dir == -1 ? textContent.length - match.index - opt.searchStr.length : match.index;
  20952. }
  20953. }
  20954. return -1
  20955. }
  20956. function findTextBlockElm(node,currentIndex,opt){
  20957. var textContent,index,methodName = opt.all || opt.dir == 1 ? 'getNextDomNode' : 'getPreDomNode';
  20958. if(domUtils.isBody(node)){
  20959. node = node.firstChild;
  20960. }
  20961. var first = 1;
  20962. while(node){
  20963. textContent = node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent'];
  20964. index = findTextInString(textContent,opt,currentIndex );
  20965. first = 0;
  20966. if(index!=-1){
  20967. return {
  20968. 'node':node,
  20969. 'index':index
  20970. }
  20971. }
  20972. node = domUtils[methodName](node);
  20973. while(node && _blockElm[node.nodeName.toLowerCase()]){
  20974. node = domUtils[methodName](node,true);
  20975. }
  20976. if(node){
  20977. currentIndex = opt.dir == -1 ? (node.nodeType == 3 ? node.nodeValue : node[browser.ie ? 'innerText' : 'textContent']).length : 0;
  20978. }
  20979. }
  20980. }
  20981. function findNTextInBlockElm(node,index,str){
  20982. var currentIndex = 0,
  20983. currentNode = node.firstChild,
  20984. currentNodeLength = 0,
  20985. result;
  20986. while(currentNode){
  20987. if(currentNode.nodeType == 3){
  20988. currentNodeLength = currentNode.nodeValue.replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length;
  20989. currentIndex += currentNodeLength;
  20990. if(currentIndex >= index){
  20991. return {
  20992. 'node':currentNode,
  20993. 'index': currentNodeLength - (currentIndex - index)
  20994. }
  20995. }
  20996. }else if(!dtd.$empty[currentNode.tagName]){
  20997. currentNodeLength = currentNode[browser.ie ? 'innerText' : 'textContent'].replace(/(^[\t\r\n]+)|([\t\r\n]+$)/,'').length
  20998. currentIndex += currentNodeLength;
  20999. if(currentIndex >= index){
  21000. result = findNTextInBlockElm(currentNode,currentNodeLength - (currentIndex - index),str);
  21001. if(result){
  21002. return result;
  21003. }
  21004. }
  21005. }
  21006. currentNode = domUtils.getNextDomNode(currentNode);
  21007. }
  21008. }
  21009. function searchReplace(me,opt){
  21010. var rng = me.selection.getRange(),
  21011. startBlockNode,
  21012. searchStr = opt.searchStr,
  21013. span = me.document.createElement('span');
  21014. span.innerHTML = '$$ueditor_searchreplace_key$$';
  21015. rng.shrinkBoundary(true);
  21016. //判断是不是第一次选中
  21017. if(!rng.collapsed){
  21018. rng.select();
  21019. var rngText = me.selection.getText();
  21020. if(new RegExp('^' + opt.searchStr + '$',(opt.casesensitive ? '' : 'i')).test(rngText)){
  21021. if(opt.replaceStr != undefined){
  21022. replaceText(rng,opt.replaceStr);
  21023. rng.select();
  21024. return true;
  21025. }else{
  21026. rng.collapse(opt.dir == -1)
  21027. }
  21028. }
  21029. }
  21030. rng.insertNode(span);
  21031. rng.enlargeToBlockElm(true);
  21032. startBlockNode = rng.startContainer;
  21033. var currentIndex = startBlockNode[browser.ie ? 'innerText' : 'textContent'].indexOf('$$ueditor_searchreplace_key$$');
  21034. rng.setStartBefore(span);
  21035. domUtils.remove(span);
  21036. var result = findTextBlockElm(startBlockNode,currentIndex,opt);
  21037. if(result){
  21038. var rngStart = findNTextInBlockElm(result.node,result.index,searchStr);
  21039. var rngEnd = findNTextInBlockElm(result.node,result.index + searchStr.length,searchStr);
  21040. rng.setStart(rngStart.node,rngStart.index).setEnd(rngEnd.node,rngEnd.index);
  21041. if(opt.replaceStr !== undefined){
  21042. replaceText(rng,opt.replaceStr)
  21043. }
  21044. rng.select();
  21045. return true;
  21046. }else{
  21047. rng.setCursor()
  21048. }
  21049. }
  21050. function replaceText(rng,str){
  21051. str = me.document.createTextNode(str);
  21052. rng.deleteContents().insertNode(str);
  21053. }
  21054. return {
  21055. commands:{
  21056. 'searchreplace':{
  21057. execCommand:function(cmdName,opt){
  21058. utils.extend(opt,{
  21059. all : false,
  21060. casesensitive : false,
  21061. dir : 1
  21062. },true);
  21063. var num = 0;
  21064. if(opt.all){
  21065. var rng = me.selection.getRange(),
  21066. first = me.body.firstChild;
  21067. if(first && first.nodeType == 1){
  21068. rng.setStart(first,0);
  21069. rng.shrinkBoundary(true);
  21070. }else if(first.nodeType == 3){
  21071. rng.setStartBefore(first)
  21072. }
  21073. rng.collapse(true).select(true);
  21074. if(opt.replaceStr !== undefined){
  21075. me.fireEvent('saveScene');
  21076. }
  21077. while(searchReplace(this,opt)){
  21078. num++;
  21079. }
  21080. if(num){
  21081. me.fireEvent('saveScene');
  21082. }
  21083. }else{
  21084. if(opt.replaceStr !== undefined){
  21085. me.fireEvent('saveScene');
  21086. }
  21087. if(searchReplace(this,opt)){
  21088. num++
  21089. }
  21090. if(num){
  21091. me.fireEvent('saveScene');
  21092. }
  21093. }
  21094. return num;
  21095. },
  21096. notNeedUndo:1
  21097. }
  21098. }
  21099. }
  21100. });
  21101. // plugins/customstyle.js
  21102. /**
  21103. * 自定义样式
  21104. * @file
  21105. * @since 1.2.6.1
  21106. */
  21107. /**
  21108. * 根据config配置文件里“customstyle”选项的值对匹配的标签执行样式替换。
  21109. * @command customstyle
  21110. * @method execCommand
  21111. * @param { String } cmd 命令字符串
  21112. * @example
  21113. * ```javascript
  21114. * editor.execCommand( 'customstyle' );
  21115. * ```
  21116. */
  21117. UE.plugins['customstyle'] = function() {
  21118. var me = this;
  21119. me.setOpt({ 'customstyle':[
  21120. {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;'},
  21121. {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;'},
  21122. {tag:'span',name:'im', style:'font-size:16px;font-style:italic;font-weight:bold;line-height:18px;'},
  21123. {tag:'span',name:'hi', style:'font-size:16px;font-style:italic;font-weight:bold;color:rgb(51, 153, 204);line-height:18px;'}
  21124. ]});
  21125. me.commands['customstyle'] = {
  21126. execCommand : function(cmdName, obj) {
  21127. var me = this,
  21128. tagName = obj.tag,
  21129. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21130. return node.getAttribute('label');
  21131. }, true),
  21132. range,bk,tmpObj = {};
  21133. for (var p in obj) {
  21134. if(obj[p]!==undefined)
  21135. tmpObj[p] = obj[p];
  21136. }
  21137. delete tmpObj.tag;
  21138. if (node && node.getAttribute('label') == obj.label) {
  21139. range = this.selection.getRange();
  21140. bk = range.createBookmark();
  21141. if (range.collapsed) {
  21142. //trace:1732 删掉自定义标签,要有p来回填站位
  21143. if(dtd.$block[node.tagName]){
  21144. var fillNode = me.document.createElement('p');
  21145. domUtils.moveChild(node, fillNode);
  21146. node.parentNode.insertBefore(fillNode, node);
  21147. domUtils.remove(node);
  21148. }else{
  21149. domUtils.remove(node,true);
  21150. }
  21151. } else {
  21152. var common = domUtils.getCommonAncestor(bk.start, bk.end),
  21153. nodes = domUtils.getElementsByTagName(common, tagName);
  21154. if(new RegExp(tagName,'i').test(common.tagName)){
  21155. nodes.push(common);
  21156. }
  21157. for (var i = 0,ni; ni = nodes[i++];) {
  21158. if (ni.getAttribute('label') == obj.label) {
  21159. var ps = domUtils.getPosition(ni, bk.start),pe = domUtils.getPosition(ni, bk.end);
  21160. if ((ps & domUtils.POSITION_FOLLOWING || ps & domUtils.POSITION_CONTAINS)
  21161. &&
  21162. (pe & domUtils.POSITION_PRECEDING || pe & domUtils.POSITION_CONTAINS)
  21163. )
  21164. if (dtd.$block[tagName]) {
  21165. var fillNode = me.document.createElement('p');
  21166. domUtils.moveChild(ni, fillNode);
  21167. ni.parentNode.insertBefore(fillNode, ni);
  21168. }
  21169. domUtils.remove(ni, true);
  21170. }
  21171. }
  21172. node = domUtils.findParent(common, function(node) {
  21173. return node.getAttribute('label') == obj.label;
  21174. }, true);
  21175. if (node) {
  21176. domUtils.remove(node, true);
  21177. }
  21178. }
  21179. range.moveToBookmark(bk).select();
  21180. } else {
  21181. if (dtd.$block[tagName]) {
  21182. this.execCommand('paragraph', tagName, tmpObj,'customstyle');
  21183. range = me.selection.getRange();
  21184. if (!range.collapsed) {
  21185. range.collapse();
  21186. node = domUtils.findParent(me.selection.getStart(), function(node) {
  21187. return node.getAttribute('label') == obj.label;
  21188. }, true);
  21189. var pNode = me.document.createElement('p');
  21190. domUtils.insertAfter(node, pNode);
  21191. domUtils.fillNode(me.document, pNode);
  21192. range.setStart(pNode, 0).setCursor();
  21193. }
  21194. } else {
  21195. range = me.selection.getRange();
  21196. if (range.collapsed) {
  21197. node = me.document.createElement(tagName);
  21198. domUtils.setAttributes(node, tmpObj);
  21199. range.insertNode(node).setStart(node, 0).setCursor();
  21200. return;
  21201. }
  21202. bk = range.createBookmark();
  21203. range.applyInlineStyle(tagName, tmpObj).moveToBookmark(bk).select();
  21204. }
  21205. }
  21206. },
  21207. queryCommandValue : function() {
  21208. var parent = domUtils.filterNodeList(
  21209. this.selection.getStartElementPath(),
  21210. function(node){return node.getAttribute('label')}
  21211. );
  21212. return parent ? parent.getAttribute('label') : '';
  21213. }
  21214. };
  21215. //当去掉customstyle是,如果是块元素,用p代替
  21216. me.addListener('keyup', function(type, evt) {
  21217. var keyCode = evt.keyCode || evt.which;
  21218. if (keyCode == 32 || keyCode == 13) {
  21219. var range = me.selection.getRange();
  21220. if (range.collapsed) {
  21221. var node = domUtils.findParent(me.selection.getStart(), function(node) {
  21222. return node.getAttribute('label');
  21223. }, true);
  21224. if (node && dtd.$block[node.tagName] && domUtils.isEmptyNode(node)) {
  21225. var p = me.document.createElement('p');
  21226. domUtils.insertAfter(node, p);
  21227. domUtils.fillNode(me.document, p);
  21228. domUtils.remove(node);
  21229. range.setStart(p, 0).setCursor();
  21230. }
  21231. }
  21232. }
  21233. });
  21234. };
  21235. // plugins/catchremoteimage.js
  21236. ///import core
  21237. ///commands 远程图片抓取
  21238. ///commandsName catchRemoteImage,catchremoteimageenable
  21239. ///commandsTitle 远程图片抓取
  21240. /**
  21241. * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片
  21242. */
  21243. UE.plugins['catchremoteimage'] = function () {
  21244. var me = this,
  21245. ajax = UE.ajax;
  21246. /* 设置默认值 */
  21247. if (me.options.catchRemoteImageEnable === false) return;
  21248. me.setOpt({
  21249. catchRemoteImageEnable: false
  21250. });
  21251. me.addListener("afterpaste", function () {
  21252. me.fireEvent("catchRemoteImage");
  21253. });
  21254. me.addListener("catchRemoteImage", function () {
  21255. var catcherLocalDomain = me.getOpt('catcherLocalDomain'),
  21256. catcherActionUrl = me.getActionUrl(me.getOpt('catcherActionName')),
  21257. catcherUrlPrefix = me.getOpt('catcherUrlPrefix'),
  21258. catcherFieldName = me.getOpt('catcherFieldName');
  21259. var remoteImages = [],
  21260. imgs = domUtils.getElementsByTagName(me.document, "img"),
  21261. test = function (src, urls) {
  21262. if (src.indexOf(location.host) != -1 || /(^\.)|(^\/)/.test(src)) {
  21263. return true;
  21264. }
  21265. if (urls) {
  21266. for (var j = 0, url; url = urls[j++];) {
  21267. if (src.indexOf(url) !== -1) {
  21268. return true;
  21269. }
  21270. }
  21271. }
  21272. return false;
  21273. };
  21274. for (var i = 0, ci; ci = imgs[i++];) {
  21275. if (ci.getAttribute("word_img")) {
  21276. continue;
  21277. }
  21278. var src = ci.getAttribute("_src") || ci.src || "";
  21279. if (/^(https?|ftp):/i.test(src) && !test(src, catcherLocalDomain)) {
  21280. remoteImages.push(src);
  21281. }
  21282. }
  21283. if (remoteImages.length) {
  21284. catchremoteimage(remoteImages, {
  21285. //成功抓取
  21286. success: function (r) {
  21287. try {
  21288. var info = r.state !== undefined ? r:eval("(" + r.responseText + ")");
  21289. } catch (e) {
  21290. return;
  21291. }
  21292. /* 获取源路径和新路径 */
  21293. var i, j, ci, cj, oldSrc, newSrc, list = info.list;
  21294. for (i = 0; ci = imgs[i++];) {
  21295. oldSrc = ci.getAttribute("_src") || ci.src || "";
  21296. for (j = 0; cj = list[j++];) {
  21297. if (oldSrc == cj.source && cj.state == "SUCCESS") { //抓取失败时不做替换处理
  21298. newSrc = catcherUrlPrefix + cj.url;
  21299. domUtils.setAttributes(ci, {
  21300. "src": newSrc,
  21301. "_src": newSrc
  21302. });
  21303. break;
  21304. }
  21305. }
  21306. }
  21307. me.fireEvent('catchremotesuccess')
  21308. },
  21309. //回调失败,本次请求超时
  21310. error: function () {
  21311. me.fireEvent("catchremoteerror");
  21312. }
  21313. });
  21314. }
  21315. function catchremoteimage(imgs, callbacks) {
  21316. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21317. url = utils.formatUrl(catcherActionUrl + (catcherActionUrl.indexOf('?') == -1 ? '?':'&') + params),
  21318. isJsonp = utils.isCrossDomainUrl(url),
  21319. opt = {
  21320. 'method': 'POST',
  21321. 'dataType': isJsonp ? 'jsonp':'',
  21322. 'timeout': 60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值
  21323. 'onsuccess': callbacks["success"],
  21324. 'onerror': callbacks["error"]
  21325. };
  21326. opt[catcherFieldName] = imgs;
  21327. ajax.request(url, opt);
  21328. }
  21329. });
  21330. };
  21331. // plugins/snapscreen.js
  21332. /**
  21333. * 截屏插件,为UEditor提供插入支持
  21334. * @file
  21335. * @since 1.4.2
  21336. */
  21337. UE.plugin.register('snapscreen', function (){
  21338. var me = this;
  21339. var snapplugin;
  21340. function getLocation(url){
  21341. var search,
  21342. a = document.createElement('a'),
  21343. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  21344. a.href = url;
  21345. if (browser.ie) {
  21346. a.href = a.href;
  21347. }
  21348. search = a.search;
  21349. if (params) {
  21350. search = search + (search.indexOf('?') == -1 ? '?':'&')+ params;
  21351. search = search.replace(/[&]+/ig, '&');
  21352. }
  21353. return {
  21354. 'port': a.port,
  21355. 'hostname': a.hostname,
  21356. 'path': a.pathname + search || + a.hash
  21357. }
  21358. }
  21359. return {
  21360. commands:{
  21361. /**
  21362. * 字体背景颜色
  21363. * @command snapscreen
  21364. * @method execCommand
  21365. * @param { String } cmd 命令字符串
  21366. * @example
  21367. * ```javascript
  21368. * editor.execCommand('snapscreen');
  21369. * ```
  21370. */
  21371. 'snapscreen':{
  21372. execCommand:function (cmd) {
  21373. var url, local, res;
  21374. var lang = me.getLang("snapScreen_plugin");
  21375. if(!snapplugin){
  21376. var container = me.container;
  21377. var doc = me.container.ownerDocument || me.container.document;
  21378. snapplugin = doc.createElement("object");
  21379. try{snapplugin.type = "application/x-pluginbaidusnap";}catch(e){
  21380. return;
  21381. }
  21382. snapplugin.style.cssText = "position:absolute;left:-9999px;width:0;height:0;";
  21383. snapplugin.setAttribute("width","0");
  21384. snapplugin.setAttribute("height","0");
  21385. container.appendChild(snapplugin);
  21386. }
  21387. function onSuccess(rs){
  21388. try{
  21389. rs = eval("("+ rs +")");
  21390. if(rs.state == 'SUCCESS'){
  21391. var opt = me.options;
  21392. me.execCommand('insertimage', {
  21393. src: opt.snapscreenUrlPrefix + rs.url,
  21394. _src: opt.snapscreenUrlPrefix + rs.url,
  21395. alt: rs.title || '',
  21396. floatStyle: opt.snapscreenImgAlign
  21397. });
  21398. } else {
  21399. alert(rs.state);
  21400. }
  21401. }catch(e){
  21402. alert(lang.callBackErrorMsg);
  21403. }
  21404. }
  21405. url = me.getActionUrl(me.getOpt('snapscreenActionName'));
  21406. local = getLocation(url);
  21407. setTimeout(function () {
  21408. try{
  21409. res =snapplugin.saveSnapshot(local.hostname, local.path, local.port);
  21410. }catch(e){
  21411. me.ui._dialogs['snapscreenDialog'].open();
  21412. return;
  21413. }
  21414. onSuccess(res);
  21415. }, 50);
  21416. },
  21417. queryCommandState: function(){
  21418. return (navigator.userAgent.indexOf("Windows",0) != -1) ? 0:-1;
  21419. }
  21420. }
  21421. }
  21422. }
  21423. });
  21424. // plugins/insertparagraph.js
  21425. /**
  21426. * 插入段落
  21427. * @file
  21428. * @since 1.2.6.1
  21429. */
  21430. /**
  21431. * 插入段落
  21432. * @command insertparagraph
  21433. * @method execCommand
  21434. * @param { String } cmd 命令字符串
  21435. * @example
  21436. * ```javascript
  21437. * //editor是编辑器实例
  21438. * editor.execCommand( 'insertparagraph' );
  21439. * ```
  21440. */
  21441. UE.commands['insertparagraph'] = {
  21442. execCommand : function( cmdName,front) {
  21443. var me = this,
  21444. range = me.selection.getRange(),
  21445. start = range.startContainer,tmpNode;
  21446. while(start ){
  21447. if(domUtils.isBody(start)){
  21448. break;
  21449. }
  21450. tmpNode = start;
  21451. start = start.parentNode;
  21452. }
  21453. if(tmpNode){
  21454. var p = me.document.createElement('p');
  21455. if(front){
  21456. tmpNode.parentNode.insertBefore(p,tmpNode)
  21457. }else{
  21458. tmpNode.parentNode.insertBefore(p,tmpNode.nextSibling)
  21459. }
  21460. domUtils.fillNode(me.document,p);
  21461. range.setStart(p,0).setCursor(false,true);
  21462. }
  21463. }
  21464. };
  21465. // plugins/webapp.js
  21466. /**
  21467. * 百度应用
  21468. * @file
  21469. * @since 1.2.6.1
  21470. */
  21471. /**
  21472. * 插入百度应用
  21473. * @command webapp
  21474. * @method execCommand
  21475. * @remind 需要百度APPKey
  21476. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21477. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21478. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21479. * @example
  21480. * ```javascript
  21481. * //editor是编辑器实例
  21482. * //在编辑器里插入一个“植物大战僵尸”的APP
  21483. * editor.execCommand( 'webapp' , {
  21484. * title: '植物大战僵尸',
  21485. * width: 560,
  21486. * height: 465,
  21487. * logo: '应用展示的图片',
  21488. * url: '百度应用的地址'
  21489. * } );
  21490. * ```
  21491. */
  21492. //UE.plugins['webapp'] = function () {
  21493. // var me = this;
  21494. // function createInsertStr( obj, toIframe, addParagraph ) {
  21495. // return !toIframe ?
  21496. // (addParagraph ? '<p>' : '') + '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21497. // ' 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 + '" />' +
  21498. // (addParagraph ? '</p>' : '')
  21499. // :
  21500. // '<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>';
  21501. // }
  21502. //
  21503. // function switchImgAndIframe( img2frame ) {
  21504. // var tmpdiv,
  21505. // nodes = domUtils.getElementsByTagName( me.document, !img2frame ? "iframe" : "img" );
  21506. // for ( var i = 0, node; node = nodes[i++]; ) {
  21507. // if ( node.className != "edui-faked-webapp" ){
  21508. // continue;
  21509. // }
  21510. // tmpdiv = me.document.createElement( "div" );
  21511. // 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 );
  21512. // node.parentNode.replaceChild( tmpdiv.firstChild, node );
  21513. // }
  21514. // }
  21515. //
  21516. // me.addListener( "beforegetcontent", function () {
  21517. // switchImgAndIframe( true );
  21518. // } );
  21519. // me.addListener( 'aftersetcontent', function () {
  21520. // switchImgAndIframe( false );
  21521. // } );
  21522. // me.addListener( 'aftergetcontent', function ( cmdName ) {
  21523. // if ( cmdName == 'aftergetcontent' && me.queryCommandState( 'source' ) ){
  21524. // return;
  21525. // }
  21526. // switchImgAndIframe( false );
  21527. // } );
  21528. //
  21529. // me.commands['webapp'] = {
  21530. // execCommand:function ( cmd, obj ) {
  21531. // me.execCommand( "inserthtml", createInsertStr( obj, false,true ) );
  21532. // }
  21533. // };
  21534. //};
  21535. UE.plugin.register('webapp', function (){
  21536. var me = this;
  21537. function createInsertStr(obj,toEmbed){
  21538. return !toEmbed ?
  21539. '<img title="'+obj.title+'" width="' + obj.width + '" height="' + obj.height + '"' +
  21540. ' src="' + me.options.UEDITOR_HOME_URL + 'themes/default/images/spacer.gif" _logo_url="'+obj.logo+'" style="background:url(' + obj.logo
  21541. +') no-repeat center center; border:1px solid gray;" class="edui-faked-webapp" _url="' + obj.url + '" ' +
  21542. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21543. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21544. '/>'
  21545. :
  21546. '<iframe class="edui-faked-webapp" title="'+obj.title+'" ' +
  21547. (obj.align && !obj.cssfloat? 'align="' + obj.align + '"' : '') +
  21548. (obj.cssfloat ? 'style="float:' + obj.cssfloat + '"' : '') +
  21549. 'width="' + obj.width + '" height="' + obj.height + '" scrolling="no" frameborder="0" src="' + obj.url + '" logo_url = "'+obj.logo+'"></iframe>'
  21550. }
  21551. return {
  21552. outputRule: function(root){
  21553. utils.each(root.getNodesByTagName('img'),function(node){
  21554. var html;
  21555. if(node.getAttr('class') == 'edui-faked-webapp'){
  21556. html = createInsertStr({
  21557. title:node.getAttr('title'),
  21558. 'width':node.getAttr('width'),
  21559. 'height':node.getAttr('height'),
  21560. 'align':node.getAttr('align'),
  21561. 'cssfloat':node.getStyle('float'),
  21562. 'url':node.getAttr("_url"),
  21563. 'logo':node.getAttr('_logo_url')
  21564. },true);
  21565. var embed = UE.uNode.createElement(html);
  21566. node.parentNode.replaceChild(embed,node);
  21567. }
  21568. })
  21569. },
  21570. inputRule:function(root){
  21571. utils.each(root.getNodesByTagName('iframe'),function(node){
  21572. if(node.getAttr('class') == 'edui-faked-webapp'){
  21573. var img = UE.uNode.createElement(createInsertStr({
  21574. title:node.getAttr('title'),
  21575. 'width':node.getAttr('width'),
  21576. 'height':node.getAttr('height'),
  21577. 'align':node.getAttr('align'),
  21578. 'cssfloat':node.getStyle('float'),
  21579. 'url':node.getAttr("src"),
  21580. 'logo':node.getAttr('logo_url')
  21581. }));
  21582. node.parentNode.replaceChild(img,node);
  21583. }
  21584. })
  21585. },
  21586. commands:{
  21587. /**
  21588. * 插入百度应用
  21589. * @command webapp
  21590. * @method execCommand
  21591. * @remind 需要百度APPKey
  21592. * @remind 百度应用主页: <a href="http://app.baidu.com/" target="_blank">http://app.baidu.com/</a>
  21593. * @param { Object } appOptions 应用所需的参数项, 支持的key有: title=>应用标题, width=>应用容器宽度,
  21594. * height=>应用容器高度,logo=>应用logo,url=>应用地址
  21595. * @example
  21596. * ```javascript
  21597. * //editor是编辑器实例
  21598. * //在编辑器里插入一个“植物大战僵尸”的APP
  21599. * editor.execCommand( 'webapp' , {
  21600. * title: '植物大战僵尸',
  21601. * width: 560,
  21602. * height: 465,
  21603. * logo: '应用展示的图片',
  21604. * url: '百度应用的地址'
  21605. * } );
  21606. * ```
  21607. */
  21608. 'webapp':{
  21609. execCommand:function (cmd, obj) {
  21610. var me = this,
  21611. str = createInsertStr(utils.extend(obj,{
  21612. align:'none'
  21613. }), false);
  21614. me.execCommand("inserthtml",str);
  21615. },
  21616. queryCommandState:function () {
  21617. var me = this,
  21618. img = me.selection.getRange().getClosedNode(),
  21619. flag = img && (img.className == "edui-faked-webapp");
  21620. return flag ? 1 : 0;
  21621. }
  21622. }
  21623. }
  21624. }
  21625. });
  21626. // plugins/template.js
  21627. ///import core
  21628. ///import plugins\inserthtml.js
  21629. ///import plugins\cleardoc.js
  21630. ///commands 模板
  21631. ///commandsName template
  21632. ///commandsTitle 模板
  21633. ///commandsDialog dialogs\template
  21634. UE.plugins['template'] = function () {
  21635. UE.commands['template'] = {
  21636. execCommand:function (cmd, obj) {
  21637. obj.html && this.execCommand("inserthtml", obj.html);
  21638. }
  21639. };
  21640. this.addListener("click", function (type, evt) {
  21641. var el = evt.target || evt.srcElement,
  21642. range = this.selection.getRange();
  21643. var tnode = domUtils.findParent(el, function (node) {
  21644. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21645. return node;
  21646. }
  21647. }, true);
  21648. tnode && range.selectNode(tnode).shrinkBoundary().select();
  21649. });
  21650. this.addListener("keydown", function (type, evt) {
  21651. var range = this.selection.getRange();
  21652. if (!range.collapsed) {
  21653. if (!evt.ctrlKey && !evt.metaKey && !evt.shiftKey && !evt.altKey) {
  21654. var tnode = domUtils.findParent(range.startContainer, function (node) {
  21655. if (node.className && domUtils.hasClass(node, "ue_t")) {
  21656. return node;
  21657. }
  21658. }, true);
  21659. if (tnode) {
  21660. domUtils.removeClasses(tnode, ["ue_t"]);
  21661. }
  21662. }
  21663. }
  21664. });
  21665. };
  21666. // plugins/music.js
  21667. /**
  21668. * 插入音乐命令
  21669. * @file
  21670. */
  21671. UE.plugin.register('music', function (){
  21672. var me = this;
  21673. function creatInsertStr(url,width,height,align,cssfloat,toEmbed){
  21674. return !toEmbed ?
  21675. '<img ' +
  21676. (align && !cssfloat? 'align="' + align + '"' : '') +
  21677. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21678. ' width="'+ width +'" height="' + height + '" _url="'+url+'" class="edui-faked-music"' +
  21679. ' src="'+me.options.langPath+me.options.lang+'/images/music.png" />'
  21680. :
  21681. '<embed type="application/x-shockwave-flash" class="edui-faked-music" pluginspage="http://www.macromedia.com/go/getflashplayer"' +
  21682. ' src="' + url + '" width="' + width + '" height="' + height + '" '+ (align && !cssfloat? 'align="' + align + '"' : '') +
  21683. (cssfloat ? 'style="float:' + cssfloat + '"' : '') +
  21684. ' wmode="transparent" play="true" loop="false" menu="false" allowscriptaccess="never" allowfullscreen="true" >';
  21685. }
  21686. return {
  21687. outputRule: function(root){
  21688. utils.each(root.getNodesByTagName('img'),function(node){
  21689. var html;
  21690. if(node.getAttr('class') == 'edui-faked-music'){
  21691. var cssfloat = node.getStyle('float');
  21692. var align = node.getAttr('align');
  21693. html = creatInsertStr(node.getAttr("_url"), node.getAttr('width'), node.getAttr('height'), align, cssfloat, true);
  21694. var embed = UE.uNode.createElement(html);
  21695. node.parentNode.replaceChild(embed,node);
  21696. }
  21697. })
  21698. },
  21699. inputRule:function(root){
  21700. utils.each(root.getNodesByTagName('embed'),function(node){
  21701. if(node.getAttr('class') == 'edui-faked-music'){
  21702. var cssfloat = node.getStyle('float');
  21703. var align = node.getAttr('align');
  21704. html = creatInsertStr(node.getAttr("src"), node.getAttr('width'), node.getAttr('height'), align, cssfloat,false);
  21705. var img = UE.uNode.createElement(html);
  21706. node.parentNode.replaceChild(img,node);
  21707. }
  21708. })
  21709. },
  21710. commands:{
  21711. /**
  21712. * 插入音乐
  21713. * @command music
  21714. * @method execCommand
  21715. * @param { Object } musicOptions 插入音乐的参数项, 支持的key有: url=>音乐地址;
  21716. * width=>音乐容器宽度;height=>音乐容器高度;align=>音乐文件的对齐方式, 可选值有: left, center, right, none
  21717. * @example
  21718. * ```javascript
  21719. * //editor是编辑器实例
  21720. * //在编辑器里插入一个“植物大战僵尸”的APP
  21721. * editor.execCommand( 'music' , {
  21722. * width: 400,
  21723. * height: 95,
  21724. * align: "center",
  21725. * url: "音乐地址"
  21726. * } );
  21727. * ```
  21728. */
  21729. 'music':{
  21730. execCommand:function (cmd, musicObj) {
  21731. var me = this,
  21732. str = creatInsertStr(musicObj.url, musicObj.width || 400, musicObj.height || 95, "none", false);
  21733. me.execCommand("inserthtml",str);
  21734. },
  21735. queryCommandState:function () {
  21736. var me = this,
  21737. img = me.selection.getRange().getClosedNode(),
  21738. flag = img && (img.className == "edui-faked-music");
  21739. return flag ? 1 : 0;
  21740. }
  21741. }
  21742. }
  21743. }
  21744. });
  21745. // plugins/autoupload.js
  21746. /**
  21747. * @description
  21748. * 1.拖放文件到编辑区域,自动上传并插入到选区
  21749. * 2.插入粘贴板的图片,自动上传并插入到选区
  21750. * @author Jinqn
  21751. * @date 2013-10-14
  21752. */
  21753. UE.plugin.register('autoupload', function (){
  21754. function sendAndInsertFile(file, editor) {
  21755. var me = editor;
  21756. //模拟数据
  21757. var fieldName, urlPrefix, maxSize, allowFiles, actionUrl,
  21758. loadingHtml, errorHandler, successHandler,
  21759. filetype = /image\/\w+/i.test(file.type) ? 'image':'file',
  21760. loadingId = 'loading_' + (+new Date()).toString(36);
  21761. fieldName = me.getOpt(filetype + 'FieldName');
  21762. urlPrefix = me.getOpt(filetype + 'UrlPrefix');
  21763. maxSize = me.getOpt(filetype + 'MaxSize');
  21764. allowFiles = me.getOpt(filetype + 'AllowFiles');
  21765. actionUrl = me.getActionUrl(me.getOpt(filetype + 'ActionName'));
  21766. errorHandler = function(title) {
  21767. var loader = me.document.getElementById(loadingId);
  21768. loader && domUtils.remove(loader);
  21769. me.fireEvent('showmessage', {
  21770. 'id': loadingId,
  21771. 'content': title,
  21772. 'type': 'error',
  21773. 'timeout': 4000
  21774. });
  21775. };
  21776. if (filetype == 'image') {
  21777. loadingHtml = '<img class="loadingclass" id="' + loadingId + '" src="' +
  21778. me.options.themePath + me.options.theme +
  21779. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >';
  21780. successHandler = function(data) {
  21781. var link = urlPrefix + data.url,
  21782. loader = me.document.getElementById(loadingId);
  21783. if (loader) {
  21784. loader.setAttribute('src', link);
  21785. loader.setAttribute('_src', link);
  21786. loader.setAttribute('title', data.title || '');
  21787. loader.setAttribute('alt', data.original || '');
  21788. loader.removeAttribute('id');
  21789. domUtils.removeClasses(loader, 'loadingclass');
  21790. }
  21791. };
  21792. } else {
  21793. loadingHtml = '<p>' +
  21794. '<img class="loadingclass" id="' + loadingId + '" src="' +
  21795. me.options.themePath + me.options.theme +
  21796. '/images/spacer.gif" title="' + (me.getLang('autoupload.loading') || '') + '" >' +
  21797. '</p>';
  21798. successHandler = function(data) {
  21799. var link = urlPrefix + data.url,
  21800. loader = me.document.getElementById(loadingId);
  21801. var rng = me.selection.getRange(),
  21802. bk = rng.createBookmark();
  21803. rng.selectNode(loader).select();
  21804. me.execCommand('insertfile', {'url': link});
  21805. rng.moveToBookmark(bk).select();
  21806. };
  21807. }
  21808. /* 插入loading的占位符 */
  21809. me.execCommand('inserthtml', loadingHtml);
  21810. /* 判断后端配置是否没有加载成功 */
  21811. if (!me.getOpt(filetype + 'ActionName')) {
  21812. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  21813. return;
  21814. }
  21815. /* 判断文件大小是否超出限制 */
  21816. if(file.size > maxSize) {
  21817. errorHandler(me.getLang('autoupload.exceedSizeError'));
  21818. return;
  21819. }
  21820. /* 判断文件格式是否超出允许 */
  21821. var fileext = file.name ? file.name.substr(file.name.lastIndexOf('.')):'';
  21822. if ((fileext && filetype != 'image') || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  21823. errorHandler(me.getLang('autoupload.exceedTypeError'));
  21824. return;
  21825. }
  21826. /* 创建Ajax并提交 */
  21827. var xhr = new XMLHttpRequest(),
  21828. fd = new FormData(),
  21829. params = utils.serializeParam(me.queryCommandValue('serverparam')) || '',
  21830. url = utils.formatUrl(actionUrl + (actionUrl.indexOf('?') == -1 ? '?':'&') + params);
  21831. fd.append(fieldName, file, file.name || ('blob.' + file.type.substr('image/'.length)));
  21832. fd.append('type', 'ajax');
  21833. xhr.open("post", url, true);
  21834. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  21835. xhr.addEventListener('load', function (e) {
  21836. try{
  21837. var json = (new Function("return " + utils.trim(e.target.response)))();
  21838. if (json.state == 'SUCCESS' && json.url) {
  21839. successHandler(json);
  21840. } else {
  21841. errorHandler(json.state);
  21842. }
  21843. }catch(er){
  21844. errorHandler(me.getLang('autoupload.loadError'));
  21845. }
  21846. });
  21847. xhr.send(fd);
  21848. }
  21849. function getPasteImage(e){
  21850. return e.clipboardData && e.clipboardData.items && e.clipboardData.items.length == 1 && /^image\//.test(e.clipboardData.items[0].type) ? e.clipboardData.items:null;
  21851. }
  21852. function getDropImage(e){
  21853. return e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files:null;
  21854. }
  21855. return {
  21856. outputRule: function(root){
  21857. utils.each(root.getNodesByTagName('img'),function(n){
  21858. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  21859. n.parentNode.removeChild(n);
  21860. }
  21861. });
  21862. utils.each(root.getNodesByTagName('p'),function(n){
  21863. if (/\bloadpara\b/.test(n.getAttr('class'))) {
  21864. n.parentNode.removeChild(n);
  21865. }
  21866. });
  21867. },
  21868. bindEvents:{
  21869. //插入粘贴板的图片,拖放插入图片
  21870. 'ready':function(e){
  21871. var me = this;
  21872. if(window.FormData && window.FileReader) {
  21873. domUtils.on(me.body, 'paste drop', function(e){
  21874. var hasImg = false,
  21875. items;
  21876. //获取粘贴板文件列表或者拖放文件列表
  21877. items = e.type == 'paste' ? getPasteImage(e):getDropImage(e);
  21878. if(items){
  21879. var len = items.length,
  21880. file;
  21881. while (len--){
  21882. file = items[len];
  21883. if(file.getAsFile) file = file.getAsFile();
  21884. if(file && file.size > 0) {
  21885. sendAndInsertFile(file, me);
  21886. hasImg = true;
  21887. }
  21888. }
  21889. hasImg && e.preventDefault();
  21890. }
  21891. });
  21892. //取消拖放图片时出现的文字光标位置提示
  21893. domUtils.on(me.body, 'dragover', function (e) {
  21894. if(e.dataTransfer.types[0] == 'Files') {
  21895. e.preventDefault();
  21896. }
  21897. });
  21898. //设置loading的样式
  21899. utils.cssRule('loading',
  21900. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  21901. + this.options.themePath
  21902. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-left:1px;height: 22px;width: 22px;}\n' +
  21903. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  21904. + this.options.themePath
  21905. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  21906. '}',
  21907. this.document);
  21908. }
  21909. }
  21910. }
  21911. }
  21912. });
  21913. // plugins/autosave.js
  21914. UE.plugin.register('autosave', function (){
  21915. var me = this,
  21916. //无限循环保护
  21917. lastSaveTime = new Date(),
  21918. //最小保存间隔时间
  21919. MIN_TIME = 20,
  21920. //auto save key
  21921. saveKey = null;
  21922. function save ( editor ) {
  21923. var saveData;
  21924. if ( new Date() - lastSaveTime < MIN_TIME ) {
  21925. return;
  21926. }
  21927. if ( !editor.hasContents() ) {
  21928. //这里不能调用命令来删除, 会造成事件死循环
  21929. saveKey && me.removePreferences( saveKey );
  21930. return;
  21931. }
  21932. lastSaveTime = new Date();
  21933. editor._saveFlag = null;
  21934. saveData = me.body.innerHTML;
  21935. if ( editor.fireEvent( "beforeautosave", {
  21936. content: saveData
  21937. } ) === false ) {
  21938. return;
  21939. }
  21940. me.setPreferences( saveKey, saveData );
  21941. editor.fireEvent( "afterautosave", {
  21942. content: saveData
  21943. } );
  21944. }
  21945. return {
  21946. defaultOptions: {
  21947. //默认间隔时间
  21948. saveInterval: 500
  21949. },
  21950. bindEvents:{
  21951. 'ready':function(){
  21952. var _suffix = "-drafts-data",
  21953. key = null;
  21954. if ( me.key ) {
  21955. key = me.key + _suffix;
  21956. } else {
  21957. key = ( me.container.parentNode.id || 'ue-common' ) + _suffix;
  21958. }
  21959. //页面地址+编辑器ID 保持唯一
  21960. saveKey = ( location.protocol + location.host + location.pathname ).replace( /[.:\/]/g, '_' ) + key;
  21961. },
  21962. 'contentchange': function () {
  21963. if ( !saveKey ) {
  21964. return;
  21965. }
  21966. if ( me._saveFlag ) {
  21967. window.clearTimeout( me._saveFlag );
  21968. }
  21969. if ( me.options.saveInterval > 0 ) {
  21970. me._saveFlag = window.setTimeout( function () {
  21971. save( me );
  21972. }, me.options.saveInterval );
  21973. } else {
  21974. save(me);
  21975. }
  21976. }
  21977. },
  21978. commands:{
  21979. 'clearlocaldata':{
  21980. execCommand:function (cmd, name) {
  21981. if ( saveKey && me.getPreferences( saveKey ) ) {
  21982. me.removePreferences( saveKey )
  21983. }
  21984. },
  21985. notNeedUndo: true,
  21986. ignoreContentChange:true
  21987. },
  21988. 'getlocaldata':{
  21989. execCommand:function (cmd, name) {
  21990. return saveKey ? me.getPreferences( saveKey ) || '' : '';
  21991. },
  21992. notNeedUndo: true,
  21993. ignoreContentChange:true
  21994. },
  21995. 'drafts':{
  21996. execCommand:function (cmd, name) {
  21997. if ( saveKey ) {
  21998. me.body.innerHTML = me.getPreferences( saveKey ) || '<p>'+domUtils.fillHtml+'</p>';
  21999. me.focus(true);
  22000. }
  22001. },
  22002. queryCommandState: function () {
  22003. return saveKey ? ( me.getPreferences( saveKey ) === null ? -1 : 0 ) : -1;
  22004. },
  22005. notNeedUndo: true,
  22006. ignoreContentChange:true
  22007. }
  22008. }
  22009. }
  22010. });
  22011. // plugins/charts.js
  22012. UE.plugin.register('charts', function (){
  22013. var me = this;
  22014. return {
  22015. bindEvents: {
  22016. 'chartserror': function () {
  22017. }
  22018. },
  22019. commands:{
  22020. 'charts': {
  22021. execCommand: function ( cmd, data ) {
  22022. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true),
  22023. flagText = [],
  22024. config = {};
  22025. if ( !tableNode ) {
  22026. return false;
  22027. }
  22028. if ( !validData( tableNode ) ) {
  22029. me.fireEvent( "chartserror" );
  22030. return false;
  22031. }
  22032. config.title = data.title || '';
  22033. config.subTitle = data.subTitle || '';
  22034. config.xTitle = data.xTitle || '';
  22035. config.yTitle = data.yTitle || '';
  22036. config.suffix = data.suffix || '';
  22037. config.tip = data.tip || '';
  22038. //数据对齐方式
  22039. config.dataFormat = data.tableDataFormat || '';
  22040. //图表类型
  22041. config.chartType = data.chartType || 0;
  22042. for ( var key in config ) {
  22043. if ( !config.hasOwnProperty( key ) ) {
  22044. continue;
  22045. }
  22046. flagText.push( key+":"+config[ key ] );
  22047. }
  22048. tableNode.setAttribute( "data-chart", flagText.join( ";" ) );
  22049. domUtils.addClass( tableNode, "edui-charts-table" );
  22050. },
  22051. queryCommandState: function ( cmd, name ) {
  22052. var tableNode = domUtils.findParentByTagName(this.selection.getRange().startContainer, 'table', true);
  22053. return tableNode && validData( tableNode ) ? 0 : -1;
  22054. }
  22055. }
  22056. },
  22057. inputRule:function(root){
  22058. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22059. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22060. tableNode.setAttr("style");
  22061. }
  22062. })
  22063. },
  22064. outputRule:function(root){
  22065. utils.each(root.getNodesByTagName('table'),function( tableNode ){
  22066. if ( tableNode.getAttr("data-chart") !== undefined ) {
  22067. tableNode.setAttr("style", "display: none;");
  22068. }
  22069. })
  22070. }
  22071. }
  22072. function validData ( table ) {
  22073. var firstRows = null,
  22074. cellCount = 0;
  22075. //行数不够
  22076. if ( table.rows.length < 2 ) {
  22077. return false;
  22078. }
  22079. //列数不够
  22080. if ( table.rows[0].cells.length < 2 ) {
  22081. return false;
  22082. }
  22083. //第一行所有cell必须是th
  22084. firstRows = table.rows[ 0 ].cells;
  22085. cellCount = firstRows.length;
  22086. for ( var i = 0, cell; cell = firstRows[ i ]; i++ ) {
  22087. if ( cell.tagName.toLowerCase() !== 'th' ) {
  22088. return false;
  22089. }
  22090. }
  22091. for ( var i = 1, row; row = table.rows[ i ]; i++ ) {
  22092. //每行单元格数不匹配, 返回false
  22093. if ( row.cells.length != cellCount ) {
  22094. return false;
  22095. }
  22096. //第一列不是th也返回false
  22097. if ( row.cells[0].tagName.toLowerCase() !== 'th' ) {
  22098. return false;
  22099. }
  22100. for ( var j = 1, cell; cell = row.cells[ j ]; j++ ) {
  22101. var value = utils.trim( ( cell.innerText || cell.textContent || '' ) );
  22102. value = value.replace( new RegExp( UE.dom.domUtils.fillChar, 'g' ), '' ).replace( /^\s+|\s+$/g, '' );
  22103. //必须是数字
  22104. if ( !/^\d*\.?\d+$/.test( value ) ) {
  22105. return false;
  22106. }
  22107. }
  22108. }
  22109. return true;
  22110. }
  22111. });
  22112. // plugins/section.js
  22113. /**
  22114. * 目录大纲支持插件
  22115. * @file
  22116. * @since 1.3.0
  22117. */
  22118. UE.plugin.register('section', function (){
  22119. /* 目录节点对象 */
  22120. function Section(option){
  22121. this.tag = '';
  22122. this.level = -1,
  22123. this.dom = null;
  22124. this.nextSection = null;
  22125. this.previousSection = null;
  22126. this.parentSection = null;
  22127. this.startAddress = [];
  22128. this.endAddress = [];
  22129. this.children = [];
  22130. }
  22131. function getSection(option) {
  22132. var section = new Section();
  22133. return utils.extend(section, option);
  22134. }
  22135. function getNodeFromAddress(startAddress, root) {
  22136. var current = root;
  22137. for(var i = 0;i < startAddress.length; i++) {
  22138. if(!current.childNodes) return null;
  22139. current = current.childNodes[startAddress[i]];
  22140. }
  22141. return current;
  22142. }
  22143. var me = this;
  22144. return {
  22145. bindMultiEvents:{
  22146. type: 'aftersetcontent afterscencerestore',
  22147. handler: function(){
  22148. me.fireEvent('updateSections');
  22149. }
  22150. },
  22151. bindEvents:{
  22152. /* 初始化、拖拽、粘贴、执行setcontent之后 */
  22153. 'ready': function (){
  22154. me.fireEvent('updateSections');
  22155. domUtils.on(me.body, 'drop paste', function(){
  22156. me.fireEvent('updateSections');
  22157. });
  22158. },
  22159. /* 执行paragraph命令之后 */
  22160. 'afterexeccommand': function (type, cmd) {
  22161. if(cmd == 'paragraph') {
  22162. me.fireEvent('updateSections');
  22163. }
  22164. },
  22165. /* 部分键盘操作,触发updateSections事件 */
  22166. 'keyup': function (type, e) {
  22167. var me = this,
  22168. range = me.selection.getRange();
  22169. if(range.collapsed != true) {
  22170. me.fireEvent('updateSections');
  22171. } else {
  22172. var keyCode = e.keyCode || e.which;
  22173. if(keyCode == 13 || keyCode == 8 || keyCode == 46) {
  22174. me.fireEvent('updateSections');
  22175. }
  22176. }
  22177. }
  22178. },
  22179. commands:{
  22180. 'getsections': {
  22181. execCommand: function (cmd, levels) {
  22182. var levelFn = levels || ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  22183. for (var i = 0; i < levelFn.length; i++) {
  22184. if (typeof levelFn[i] == 'string') {
  22185. levelFn[i] = function(fn){
  22186. return function(node){
  22187. return node.tagName == fn.toUpperCase()
  22188. };
  22189. }(levelFn[i]);
  22190. } else if (typeof levelFn[i] != 'function') {
  22191. levelFn[i] = function (node) {
  22192. return null;
  22193. }
  22194. }
  22195. }
  22196. function getSectionLevel(node) {
  22197. for (var i = 0; i < levelFn.length; i++) {
  22198. if (levelFn[i](node)) return i;
  22199. }
  22200. return -1;
  22201. }
  22202. var me = this,
  22203. Directory = getSection({'level':-1, 'title':'root'}),
  22204. previous = Directory;
  22205. function traversal(node, Directory) {
  22206. var level,
  22207. tmpSection = null,
  22208. parent,
  22209. child,
  22210. children = node.childNodes;
  22211. for (var i = 0, len = children.length; i < len; i++) {
  22212. child = children[i];
  22213. level = getSectionLevel(child);
  22214. if (level >= 0) {
  22215. var address = me.selection.getRange().selectNode(child).createAddress(true).startAddress,
  22216. current = getSection({
  22217. 'tag': child.tagName,
  22218. 'title': child.innerText || child.textContent || '',
  22219. 'level': level,
  22220. 'dom': child,
  22221. 'startAddress': utils.clone(address, []),
  22222. 'endAddress': utils.clone(address, []),
  22223. 'children': []
  22224. });
  22225. previous.nextSection = current;
  22226. current.previousSection = previous;
  22227. parent = previous;
  22228. while(level <= parent.level){
  22229. parent = parent.parentSection;
  22230. }
  22231. current.parentSection = parent;
  22232. parent.children.push(current);
  22233. tmpSection = previous = current;
  22234. } else {
  22235. child.nodeType === 1 && traversal(child, Directory);
  22236. tmpSection && tmpSection.endAddress[tmpSection.endAddress.length - 1] ++;
  22237. }
  22238. }
  22239. }
  22240. traversal(me.body, Directory);
  22241. return Directory;
  22242. },
  22243. notNeedUndo: true
  22244. },
  22245. 'movesection': {
  22246. execCommand: function (cmd, sourceSection, targetSection, isAfter) {
  22247. var me = this,
  22248. targetAddress,
  22249. target;
  22250. if(!sourceSection || !targetSection || targetSection.level == -1) return;
  22251. targetAddress = isAfter ? targetSection.endAddress:targetSection.startAddress;
  22252. target = getNodeFromAddress(targetAddress, me.body);
  22253. /* 判断目标地址是否被源章节包含 */
  22254. if(!targetAddress || !target || isContainsAddress(sourceSection.startAddress, sourceSection.endAddress, targetAddress)) return;
  22255. var startNode = getNodeFromAddress(sourceSection.startAddress, me.body),
  22256. endNode = getNodeFromAddress(sourceSection.endAddress, me.body),
  22257. current,
  22258. nextNode;
  22259. if(isAfter) {
  22260. current = endNode;
  22261. while ( current && !(domUtils.getPosition( startNode, current ) & domUtils.POSITION_FOLLOWING) ) {
  22262. nextNode = current.previousSibling;
  22263. domUtils.insertAfter(target, current);
  22264. if(current == startNode) break;
  22265. current = nextNode;
  22266. }
  22267. } else {
  22268. current = startNode;
  22269. while ( current && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22270. nextNode = current.nextSibling;
  22271. target.parentNode.insertBefore(current, target);
  22272. if(current == endNode) break;
  22273. current = nextNode;
  22274. }
  22275. }
  22276. me.fireEvent('updateSections');
  22277. /* 获取地址的包含关系 */
  22278. function isContainsAddress(startAddress, endAddress, addressTarget){
  22279. var isAfterStartAddress = false,
  22280. isBeforeEndAddress = false;
  22281. for(var i = 0; i< startAddress.length; i++){
  22282. if(i >= addressTarget.length) break;
  22283. if(addressTarget[i] > startAddress[i]) {
  22284. isAfterStartAddress = true;
  22285. break;
  22286. } else if(addressTarget[i] < startAddress[i]) {
  22287. break;
  22288. }
  22289. }
  22290. for(var i = 0; i< endAddress.length; i++){
  22291. if(i >= addressTarget.length) break;
  22292. if(addressTarget[i] < startAddress[i]) {
  22293. isBeforeEndAddress = true;
  22294. break;
  22295. } else if(addressTarget[i] > startAddress[i]) {
  22296. break;
  22297. }
  22298. }
  22299. return isAfterStartAddress && isBeforeEndAddress;
  22300. }
  22301. }
  22302. },
  22303. 'deletesection': {
  22304. execCommand: function (cmd, section, keepChildren) {
  22305. var me = this;
  22306. if(!section) return;
  22307. function getNodeFromAddress(startAddress) {
  22308. var current = me.body;
  22309. for(var i = 0;i < startAddress.length; i++) {
  22310. if(!current.childNodes) return null;
  22311. current = current.childNodes[startAddress[i]];
  22312. }
  22313. return current;
  22314. }
  22315. var startNode = getNodeFromAddress(section.startAddress),
  22316. endNode = getNodeFromAddress(section.endAddress),
  22317. current = startNode,
  22318. nextNode;
  22319. if(!keepChildren) {
  22320. while ( current && domUtils.inDoc(endNode, me.document) && !(domUtils.getPosition( current, endNode ) & domUtils.POSITION_FOLLOWING) ) {
  22321. nextNode = current.nextSibling;
  22322. domUtils.remove(current);
  22323. current = nextNode;
  22324. }
  22325. } else {
  22326. domUtils.remove(current);
  22327. }
  22328. me.fireEvent('updateSections');
  22329. }
  22330. },
  22331. 'selectsection': {
  22332. execCommand: function (cmd, section) {
  22333. if(!section && !section.dom) return false;
  22334. var me = this,
  22335. range = me.selection.getRange(),
  22336. address = {
  22337. 'startAddress':utils.clone(section.startAddress, []),
  22338. 'endAddress':utils.clone(section.endAddress, [])
  22339. };
  22340. address.endAddress[address.endAddress.length - 1]++;
  22341. range.moveToAddress(address).select().scrollToView();
  22342. return true;
  22343. },
  22344. notNeedUndo: true
  22345. },
  22346. 'scrolltosection': {
  22347. execCommand: function (cmd, section) {
  22348. if(!section && !section.dom) return false;
  22349. var me = this,
  22350. range = me.selection.getRange(),
  22351. address = {
  22352. 'startAddress':section.startAddress,
  22353. 'endAddress':section.endAddress
  22354. };
  22355. address.endAddress[address.endAddress.length - 1]++;
  22356. range.moveToAddress(address).scrollToView();
  22357. return true;
  22358. },
  22359. notNeedUndo: true
  22360. }
  22361. }
  22362. }
  22363. });
  22364. // plugins/simpleupload.js
  22365. /**
  22366. * @description
  22367. * 简单上传:点击按钮,直接选择文件上传
  22368. * @author Jinqn
  22369. * @date 2014-03-31
  22370. */
  22371. UE.plugin.register('simpleupload', function (){
  22372. var me = this,
  22373. isLoaded = false,
  22374. containerBtn;
  22375. function initUploadBtn(){
  22376. var w = containerBtn.offsetWidth || 20,
  22377. h = containerBtn.offsetHeight || 20,
  22378. btnIframe = document.createElement('iframe'),
  22379. btnStyle = 'display:block;width:' + w + 'px;height:' + h + 'px;overflow:hidden;border:0;margin:0;padding:0;position:absolute;top:0;left:0;filter:alpha(opacity=0);-moz-opacity:0;-khtml-opacity: 0;opacity: 0;cursor:pointer;';
  22380. domUtils.on(btnIframe, 'load', function(){
  22381. var timestrap = (+new Date()).toString(36),
  22382. wrapper,
  22383. btnIframeDoc,
  22384. btnIframeBody;
  22385. btnIframeDoc = (btnIframe.contentDocument || btnIframe.contentWindow.document);
  22386. btnIframeBody = btnIframeDoc.body;
  22387. wrapper = btnIframeDoc.createElement('div');
  22388. wrapper.innerHTML = '<form id="edui_form_' + timestrap + '" target="edui_iframe_' + timestrap + '" method="POST" enctype="multipart/form-data" action="' + me.getOpt('serverUrl') + '" ' +
  22389. 'style="' + btnStyle + '">' +
  22390. '<input id="edui_input_' + timestrap + '" type="file" accept="image/*" name="' + me.options.imageFieldName + '" ' +
  22391. 'style="' + btnStyle + '">' +
  22392. '</form>' +
  22393. '<iframe id="edui_iframe_' + timestrap + '" name="edui_iframe_' + timestrap + '" style="display:none;width:0;height:0;border:0;margin:0;padding:0;position:absolute;"></iframe>';
  22394. wrapper.className = 'edui-' + me.options.theme;
  22395. wrapper.id = me.ui.id + '_iframeupload';
  22396. btnIframeBody.style.cssText = btnStyle;
  22397. btnIframeBody.style.width = w + 'px';
  22398. btnIframeBody.style.height = h + 'px';
  22399. btnIframeBody.appendChild(wrapper);
  22400. if (btnIframeBody.parentNode) {
  22401. btnIframeBody.parentNode.style.width = w + 'px';
  22402. btnIframeBody.parentNode.style.height = w + 'px';
  22403. }
  22404. var form = btnIframeDoc.getElementById('edui_form_' + timestrap);
  22405. var input = btnIframeDoc.getElementById('edui_input_' + timestrap);
  22406. var iframe = btnIframeDoc.getElementById('edui_iframe_' + timestrap);
  22407. domUtils.on(input, 'change', function(){
  22408. if(!input.value) return;
  22409. var loadingId = 'loading_' + (+new Date()).toString(36);
  22410. var params = utils.serializeParam(me.queryCommandValue('serverparam')) || '';
  22411. var imageActionUrl = me.getActionUrl(me.getOpt('imageActionName'));
  22412. var allowFiles = me.getOpt('imageAllowFiles');
  22413. me.focus();
  22414. me.execCommand('inserthtml', '<img class="loadingclass" id="' + loadingId + '" src="' + me.options.themePath + me.options.theme +'/images/spacer.gif" title="' + (me.getLang('simpleupload.loading') || '') + '" >');
  22415. function callback(){
  22416. try{
  22417. var link, json, loader,
  22418. body = (iframe.contentDocument || iframe.contentWindow.document).body,
  22419. result = body.innerText || body.textContent || '';
  22420. json = (new Function("return " + result))();
  22421. link = me.options.imageUrlPrefix + json.url;
  22422. if(json.state == 'SUCCESS' && json.url) {
  22423. loader = me.document.getElementById(loadingId);
  22424. loader.setAttribute('src', link);
  22425. loader.setAttribute('_src', link);
  22426. loader.setAttribute('title', json.title || '');
  22427. loader.setAttribute('alt', json.original || '');
  22428. loader.removeAttribute('id');
  22429. domUtils.removeClasses(loader, 'loadingclass');
  22430. } else {
  22431. showErrorLoader && showErrorLoader(json.state);
  22432. }
  22433. }catch(er){
  22434. showErrorLoader && showErrorLoader(me.getLang('simpleupload.loadError'));
  22435. }
  22436. form.reset();
  22437. domUtils.un(iframe, 'load', callback);
  22438. }
  22439. function showErrorLoader(title){
  22440. if(loadingId) {
  22441. var loader = me.document.getElementById(loadingId);
  22442. loader && domUtils.remove(loader);
  22443. me.fireEvent('showmessage', {
  22444. 'id': loadingId,
  22445. 'content': title,
  22446. 'type': 'error',
  22447. 'timeout': 4000
  22448. });
  22449. }
  22450. }
  22451. /* 判断后端配置是否没有加载成功 */
  22452. if (!me.getOpt('imageActionName')) {
  22453. errorHandler(me.getLang('autoupload.errorLoadConfig'));
  22454. return;
  22455. }
  22456. // 判断文件格式是否错误
  22457. var filename = input.value,
  22458. fileext = filename ? filename.substr(filename.lastIndexOf('.')):'';
  22459. if (!fileext || (allowFiles && (allowFiles.join('') + '.').indexOf(fileext.toLowerCase() + '.') == -1)) {
  22460. showErrorLoader(me.getLang('simpleupload.exceedTypeError'));
  22461. return;
  22462. }
  22463. domUtils.on(iframe, 'load', callback);
  22464. form.action = utils.formatUrl(imageActionUrl + (imageActionUrl.indexOf('?') == -1 ? '?':'&') + params);
  22465. form.submit();
  22466. });
  22467. var stateTimer;
  22468. me.addListener('selectionchange', function () {
  22469. clearTimeout(stateTimer);
  22470. stateTimer = setTimeout(function() {
  22471. var state = me.queryCommandState('simpleupload');
  22472. if (state == -1) {
  22473. input.disabled = 'disabled';
  22474. } else {
  22475. input.disabled = false;
  22476. }
  22477. }, 400);
  22478. });
  22479. isLoaded = true;
  22480. });
  22481. btnIframe.style.cssText = btnStyle;
  22482. containerBtn.appendChild(btnIframe);
  22483. }
  22484. return {
  22485. bindEvents:{
  22486. 'ready': function() {
  22487. //设置loading的样式
  22488. utils.cssRule('loading',
  22489. '.loadingclass{display:inline-block;cursor:default;background: url(\''
  22490. + this.options.themePath
  22491. + this.options.theme +'/images/loading.gif\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;}\n' +
  22492. '.loaderrorclass{display:inline-block;cursor:default;background: url(\''
  22493. + this.options.themePath
  22494. + this.options.theme +'/images/loaderror.png\') no-repeat center center transparent;border:1px solid #cccccc;margin-right:1px;height: 22px;width: 22px;' +
  22495. '}',
  22496. this.document);
  22497. },
  22498. /* 初始化简单上传按钮 */
  22499. 'simpleuploadbtnready': function(type, container) {
  22500. containerBtn = container;
  22501. me.afterConfigReady(initUploadBtn);
  22502. }
  22503. },
  22504. outputRule: function(root){
  22505. utils.each(root.getNodesByTagName('img'),function(n){
  22506. if (/\b(loaderrorclass)|(bloaderrorclass)\b/.test(n.getAttr('class'))) {
  22507. n.parentNode.removeChild(n);
  22508. }
  22509. });
  22510. },
  22511. commands: {
  22512. 'simpleupload': {
  22513. queryCommandState: function () {
  22514. return isLoaded ? 0:-1;
  22515. }
  22516. }
  22517. }
  22518. }
  22519. });
  22520. // plugins/serverparam.js
  22521. /**
  22522. * 服务器提交的额外参数列表设置插件
  22523. * @file
  22524. * @since 1.2.6.1
  22525. */
  22526. UE.plugin.register('serverparam', function (){
  22527. var me = this,
  22528. serverParam = {};
  22529. return {
  22530. commands:{
  22531. /**
  22532. * 修改服务器提交的额外参数列表,清除所有项
  22533. * @command serverparam
  22534. * @method execCommand
  22535. * @param { String } cmd 命令字符串
  22536. * @example
  22537. * ```javascript
  22538. * editor.execCommand('serverparam');
  22539. * editor.queryCommandValue('serverparam'); //返回空
  22540. * ```
  22541. */
  22542. /**
  22543. * 修改服务器提交的额外参数列表,删除指定项
  22544. * @command serverparam
  22545. * @method execCommand
  22546. * @param { String } cmd 命令字符串
  22547. * @param { String } key 要清除的属性
  22548. * @example
  22549. * ```javascript
  22550. * editor.execCommand('serverparam', 'name'); //删除属性name
  22551. * ```
  22552. */
  22553. /**
  22554. * 修改服务器提交的额外参数列表,使用键值添加项
  22555. * @command serverparam
  22556. * @method execCommand
  22557. * @param { String } cmd 命令字符串
  22558. * @param { String } key 要添加的属性
  22559. * @param { String } value 要添加属性的值
  22560. * @example
  22561. * ```javascript
  22562. * editor.execCommand('serverparam', 'name', 'hello');
  22563. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22564. * ```
  22565. */
  22566. /**
  22567. * 修改服务器提交的额外参数列表,传入键值对对象添加多项
  22568. * @command serverparam
  22569. * @method execCommand
  22570. * @param { String } cmd 命令字符串
  22571. * @param { Object } key 传入的键值对对象
  22572. * @example
  22573. * ```javascript
  22574. * editor.execCommand('serverparam', {'name': 'hello'});
  22575. * editor.queryCommandValue('serverparam'); //返回对象 {'name': 'hello'}
  22576. * ```
  22577. */
  22578. /**
  22579. * 修改服务器提交的额外参数列表,使用自定义函数添加多项
  22580. * @command serverparam
  22581. * @method execCommand
  22582. * @param { String } cmd 命令字符串
  22583. * @param { Function } key 自定义获取参数的函数
  22584. * @example
  22585. * ```javascript
  22586. * editor.execCommand('serverparam', function(editor){
  22587. * return {'key': 'value'};
  22588. * });
  22589. * editor.queryCommandValue('serverparam'); //返回对象 {'key': 'value'}
  22590. * ```
  22591. */
  22592. /**
  22593. * 获取服务器提交的额外参数列表
  22594. * @command serverparam
  22595. * @method queryCommandValue
  22596. * @param { String } cmd 命令字符串
  22597. * @example
  22598. * ```javascript
  22599. * editor.queryCommandValue( 'serverparam' ); //返回对象 {'key': 'value'}
  22600. * ```
  22601. */
  22602. 'serverparam':{
  22603. execCommand:function (cmd, key, value) {
  22604. if (key === undefined || key === null) { //不传参数,清空列表
  22605. serverParam = {};
  22606. } else if (utils.isString(key)) { //传入键值
  22607. if(value === undefined || value === null) {
  22608. delete serverParam[key];
  22609. } else {
  22610. serverParam[key] = value;
  22611. }
  22612. } else if (utils.isObject(key)) { //传入对象,覆盖列表项
  22613. utils.extend(serverParam, key, true);
  22614. } else if (utils.isFunction(key)){ //传入函数,添加列表项
  22615. utils.extend(serverParam, key(), true);
  22616. }
  22617. },
  22618. queryCommandValue: function(){
  22619. return serverParam || {};
  22620. }
  22621. }
  22622. }
  22623. }
  22624. });
  22625. // plugins/insertfile.js
  22626. /**
  22627. * 插入附件
  22628. */
  22629. UE.plugin.register('insertfile', function (){
  22630. var me = this;
  22631. function getFileIcon(url){
  22632. var ext = url.substr(url.lastIndexOf('.') + 1).toLowerCase(),
  22633. maps = {
  22634. "rar":"icon_rar.gif",
  22635. "zip":"icon_rar.gif",
  22636. "tar":"icon_rar.gif",
  22637. "gz":"icon_rar.gif",
  22638. "bz2":"icon_rar.gif",
  22639. "doc":"icon_doc.gif",
  22640. "docx":"icon_doc.gif",
  22641. "pdf":"icon_pdf.gif",
  22642. "mp3":"icon_mp3.gif",
  22643. "xls":"icon_xls.gif",
  22644. "chm":"icon_chm.gif",
  22645. "ppt":"icon_ppt.gif",
  22646. "pptx":"icon_ppt.gif",
  22647. "avi":"icon_mv.gif",
  22648. "rmvb":"icon_mv.gif",
  22649. "wmv":"icon_mv.gif",
  22650. "flv":"icon_mv.gif",
  22651. "swf":"icon_mv.gif",
  22652. "rm":"icon_mv.gif",
  22653. "exe":"icon_exe.gif",
  22654. "psd":"icon_psd.gif",
  22655. "txt":"icon_txt.gif",
  22656. "jpg":"icon_jpg.gif",
  22657. "png":"icon_jpg.gif",
  22658. "jpeg":"icon_jpg.gif",
  22659. "gif":"icon_jpg.gif",
  22660. "ico":"icon_jpg.gif",
  22661. "bmp":"icon_jpg.gif"
  22662. };
  22663. return maps[ext] ? maps[ext]:maps['txt'];
  22664. }
  22665. return {
  22666. commands:{
  22667. 'insertfile': {
  22668. execCommand: function (command, filelist){
  22669. filelist = utils.isArray(filelist) ? filelist : [filelist];
  22670. var i, item, icon, title,
  22671. html = '',
  22672. URL = me.getOpt('UEDITOR_HOME_URL'),
  22673. iconDir = URL + (URL.substr(URL.length - 1) == '/' ? '':'/') + 'dialogs/attachment/fileTypeImages/';
  22674. for (i = 0; i < filelist.length; i++) {
  22675. item = filelist[i];
  22676. icon = iconDir + getFileIcon(item.url);
  22677. title = item.title || item.url.substr(item.url.lastIndexOf('/') + 1);
  22678. html += '<p style="line-height: 16px;">' +
  22679. '<img style="vertical-align: middle; margin-right: 2px;" src="'+ icon + '" _src="' + icon + '" />' +
  22680. '<a style="font-size:12px; color:#0066cc;" href="' + item.url +'" title="' + title + '">' + title + '</a>' +
  22681. '</p>';
  22682. }
  22683. me.execCommand('insertHtml', html);
  22684. }
  22685. }
  22686. }
  22687. }
  22688. });
  22689. // plugins/xssFilter.js
  22690. /**
  22691. * @file xssFilter.js
  22692. * @desc xss过滤器
  22693. * @author robbenmu
  22694. */
  22695. UE.plugins.xssFilter = function() {
  22696. var config = UEDITOR_CONFIG;
  22697. var whitList = config.whitList;
  22698. function filter(node) {
  22699. var tagName = node.tagName;
  22700. var attrs = node.attrs;
  22701. if (!whitList.hasOwnProperty(tagName)) {
  22702. node.parentNode.removeChild(node);
  22703. return false;
  22704. }
  22705. UE.utils.each(attrs, function (val, key) {
  22706. if (whitList[tagName].indexOf(key) === -1) {
  22707. node.setAttr(key);
  22708. }
  22709. });
  22710. }
  22711. // 添加inserthtml\paste等操作用的过滤规则
  22712. if (whitList && config.xssFilterRules) {
  22713. this.options.filterRules = function () {
  22714. var result = {};
  22715. UE.utils.each(whitList, function(val, key) {
  22716. result[key] = function (node) {
  22717. return filter(node);
  22718. };
  22719. });
  22720. return result;
  22721. }();
  22722. }
  22723. var tagList = [];
  22724. UE.utils.each(whitList, function (val, key) {
  22725. tagList.push(key);
  22726. });
  22727. // 添加input过滤规则
  22728. //
  22729. if (whitList && config.inputXssFilter) {
  22730. this.addInputRule(function (root) {
  22731. root.traversal(function(node) {
  22732. if (node.type !== 'element') {
  22733. return false;
  22734. }
  22735. filter(node);
  22736. });
  22737. });
  22738. }
  22739. // 添加output过滤规则
  22740. //
  22741. if (whitList && config.outputXssFilter) {
  22742. this.addOutputRule(function (root) {
  22743. root.traversal(function(node) {
  22744. if (node.type !== 'element') {
  22745. return false;
  22746. }
  22747. filter(node);
  22748. });
  22749. });
  22750. }
  22751. };
  22752. // ui/ui.js
  22753. var baidu = baidu || {};
  22754. baidu.editor = baidu.editor || {};
  22755. UE.ui = baidu.editor.ui = {};
  22756. // ui/uiutils.js
  22757. (function (){
  22758. var browser = baidu.editor.browser,
  22759. domUtils = baidu.editor.dom.domUtils;
  22760. var magic = '$EDITORUI';
  22761. var root = window[magic] = {};
  22762. var uidMagic = 'ID' + magic;
  22763. var uidCount = 0;
  22764. var uiUtils = baidu.editor.ui.uiUtils = {
  22765. uid: function (obj){
  22766. return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount);
  22767. },
  22768. hook: function ( fn, callback ) {
  22769. var dg;
  22770. if (fn && fn._callbacks) {
  22771. dg = fn;
  22772. } else {
  22773. dg = function (){
  22774. var q;
  22775. if (fn) {
  22776. q = fn.apply(this, arguments);
  22777. }
  22778. var callbacks = dg._callbacks;
  22779. var k = callbacks.length;
  22780. while (k --) {
  22781. var r = callbacks[k].apply(this, arguments);
  22782. if (q === undefined) {
  22783. q = r;
  22784. }
  22785. }
  22786. return q;
  22787. };
  22788. dg._callbacks = [];
  22789. }
  22790. dg._callbacks.push(callback);
  22791. return dg;
  22792. },
  22793. createElementByHtml: function (html){
  22794. var el = document.createElement('div');
  22795. el.innerHTML = html;
  22796. el = el.firstChild;
  22797. el.parentNode.removeChild(el);
  22798. return el;
  22799. },
  22800. getViewportElement: function (){
  22801. return (browser.ie && browser.quirks) ?
  22802. document.body : document.documentElement;
  22803. },
  22804. getClientRect: function (element){
  22805. var bcr;
  22806. //trace IE6下在控制编辑器显隐时可能会报错,catch一下
  22807. try{
  22808. bcr = element.getBoundingClientRect();
  22809. }catch(e){
  22810. bcr={left:0,top:0,height:0,width:0}
  22811. }
  22812. var rect = {
  22813. left: Math.round(bcr.left),
  22814. top: Math.round(bcr.top),
  22815. height: Math.round(bcr.bottom - bcr.top),
  22816. width: Math.round(bcr.right - bcr.left)
  22817. };
  22818. var doc;
  22819. while ((doc = element.ownerDocument) !== document &&
  22820. (element = domUtils.getWindow(doc).frameElement)) {
  22821. bcr = element.getBoundingClientRect();
  22822. rect.left += bcr.left;
  22823. rect.top += bcr.top;
  22824. }
  22825. rect.bottom = rect.top + rect.height;
  22826. rect.right = rect.left + rect.width;
  22827. return rect;
  22828. },
  22829. getViewportRect: function (){
  22830. var viewportEl = uiUtils.getViewportElement();
  22831. var width = (window.innerWidth || viewportEl.clientWidth) | 0;
  22832. var height = (window.innerHeight ||viewportEl.clientHeight) | 0;
  22833. return {
  22834. left: 0,
  22835. top: 0,
  22836. height: height,
  22837. width: width,
  22838. bottom: height,
  22839. right: width
  22840. };
  22841. },
  22842. setViewportOffset: function (element, offset){
  22843. var rect;
  22844. var fixedLayer = uiUtils.getFixedLayer();
  22845. if (element.parentNode === fixedLayer) {
  22846. element.style.left = offset.left + 'px';
  22847. element.style.top = offset.top + 'px';
  22848. } else {
  22849. domUtils.setViewportOffset(element, offset);
  22850. }
  22851. },
  22852. getEventOffset: function (evt){
  22853. var el = evt.target || evt.srcElement;
  22854. var rect = uiUtils.getClientRect(el);
  22855. var offset = uiUtils.getViewportOffsetByEvent(evt);
  22856. return {
  22857. left: offset.left - rect.left,
  22858. top: offset.top - rect.top
  22859. };
  22860. },
  22861. getViewportOffsetByEvent: function (evt){
  22862. var el = evt.target || evt.srcElement;
  22863. var frameEl = domUtils.getWindow(el).frameElement;
  22864. var offset = {
  22865. left: evt.clientX,
  22866. top: evt.clientY
  22867. };
  22868. if (frameEl && el.ownerDocument !== document) {
  22869. var rect = uiUtils.getClientRect(frameEl);
  22870. offset.left += rect.left;
  22871. offset.top += rect.top;
  22872. }
  22873. return offset;
  22874. },
  22875. setGlobal: function (id, obj){
  22876. root[id] = obj;
  22877. return magic + '["' + id + '"]';
  22878. },
  22879. unsetGlobal: function (id){
  22880. delete root[id];
  22881. },
  22882. copyAttributes: function (tgt, src){
  22883. var attributes = src.attributes;
  22884. var k = attributes.length;
  22885. while (k --) {
  22886. var attrNode = attributes[k];
  22887. if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) {
  22888. tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue);
  22889. }
  22890. }
  22891. if (src.className) {
  22892. domUtils.addClass(tgt,src.className);
  22893. }
  22894. if (src.style.cssText) {
  22895. tgt.style.cssText += ';' + src.style.cssText;
  22896. }
  22897. },
  22898. removeStyle: function (el, styleName){
  22899. if (el.style.removeProperty) {
  22900. el.style.removeProperty(styleName);
  22901. } else if (el.style.removeAttribute) {
  22902. el.style.removeAttribute(styleName);
  22903. } else throw '';
  22904. },
  22905. contains: function (elA, elB){
  22906. return elA && elB && (elA === elB ? false : (
  22907. elA.contains ? elA.contains(elB) :
  22908. elA.compareDocumentPosition(elB) & 16
  22909. ));
  22910. },
  22911. startDrag: function (evt, callbacks,doc){
  22912. var doc = doc || document;
  22913. var startX = evt.clientX;
  22914. var startY = evt.clientY;
  22915. function handleMouseMove(evt){
  22916. var x = evt.clientX - startX;
  22917. var y = evt.clientY - startY;
  22918. callbacks.ondragmove(x, y,evt);
  22919. if (evt.stopPropagation) {
  22920. evt.stopPropagation();
  22921. } else {
  22922. evt.cancelBubble = true;
  22923. }
  22924. }
  22925. if (doc.addEventListener) {
  22926. function handleMouseUp(evt){
  22927. doc.removeEventListener('mousemove', handleMouseMove, true);
  22928. doc.removeEventListener('mouseup', handleMouseUp, true);
  22929. window.removeEventListener('mouseup', handleMouseUp, true);
  22930. callbacks.ondragstop();
  22931. }
  22932. doc.addEventListener('mousemove', handleMouseMove, true);
  22933. doc.addEventListener('mouseup', handleMouseUp, true);
  22934. window.addEventListener('mouseup', handleMouseUp, true);
  22935. evt.preventDefault();
  22936. } else {
  22937. var elm = evt.srcElement;
  22938. elm.setCapture();
  22939. function releaseCaptrue(){
  22940. elm.releaseCapture();
  22941. elm.detachEvent('onmousemove', handleMouseMove);
  22942. elm.detachEvent('onmouseup', releaseCaptrue);
  22943. elm.detachEvent('onlosecaptrue', releaseCaptrue);
  22944. callbacks.ondragstop();
  22945. }
  22946. elm.attachEvent('onmousemove', handleMouseMove);
  22947. elm.attachEvent('onmouseup', releaseCaptrue);
  22948. elm.attachEvent('onlosecaptrue', releaseCaptrue);
  22949. evt.returnValue = false;
  22950. }
  22951. callbacks.ondragstart();
  22952. },
  22953. getFixedLayer: function (){
  22954. var layer = document.getElementById('edui_fixedlayer');
  22955. if (layer == null) {
  22956. layer = document.createElement('div');
  22957. layer.id = 'edui_fixedlayer';
  22958. document.body.appendChild(layer);
  22959. if (browser.ie && browser.version <= 8) {
  22960. layer.style.position = 'absolute';
  22961. bindFixedLayer();
  22962. setTimeout(updateFixedOffset);
  22963. } else {
  22964. layer.style.position = 'fixed';
  22965. }
  22966. layer.style.left = '0';
  22967. layer.style.top = '0';
  22968. layer.style.width = '0';
  22969. layer.style.height = '0';
  22970. }
  22971. return layer;
  22972. },
  22973. makeUnselectable: function (element){
  22974. if (browser.opera || (browser.ie && browser.version < 9)) {
  22975. element.unselectable = 'on';
  22976. if (element.hasChildNodes()) {
  22977. for (var i=0; i<element.childNodes.length; i++) {
  22978. if (element.childNodes[i].nodeType == 1) {
  22979. uiUtils.makeUnselectable(element.childNodes[i]);
  22980. }
  22981. }
  22982. }
  22983. } else {
  22984. if (element.style.MozUserSelect !== undefined) {
  22985. element.style.MozUserSelect = 'none';
  22986. } else if (element.style.WebkitUserSelect !== undefined) {
  22987. element.style.WebkitUserSelect = 'none';
  22988. } else if (element.style.KhtmlUserSelect !== undefined) {
  22989. element.style.KhtmlUserSelect = 'none';
  22990. }
  22991. }
  22992. }
  22993. };
  22994. function updateFixedOffset(){
  22995. var layer = document.getElementById('edui_fixedlayer');
  22996. uiUtils.setViewportOffset(layer, {
  22997. left: 0,
  22998. top: 0
  22999. });
  23000. // layer.style.display = 'none';
  23001. // layer.style.display = 'block';
  23002. //#trace: 1354
  23003. // setTimeout(updateFixedOffset);
  23004. }
  23005. function bindFixedLayer(adjOffset){
  23006. domUtils.on(window, 'scroll', updateFixedOffset);
  23007. domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true));
  23008. }
  23009. })();
  23010. // ui/uibase.js
  23011. (function () {
  23012. var utils = baidu.editor.utils,
  23013. uiUtils = baidu.editor.ui.uiUtils,
  23014. EventBase = baidu.editor.EventBase,
  23015. UIBase = baidu.editor.ui.UIBase = function () {
  23016. };
  23017. UIBase.prototype = {
  23018. className:'',
  23019. uiName:'',
  23020. initOptions:function (options) {
  23021. var me = this;
  23022. for (var k in options) {
  23023. me[k] = options[k];
  23024. }
  23025. this.id = this.id || 'edui' + uiUtils.uid();
  23026. },
  23027. initUIBase:function () {
  23028. this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this));
  23029. },
  23030. render:function (holder) {
  23031. var html = this.renderHtml();
  23032. var el = uiUtils.createElementByHtml(html);
  23033. //by xuheng 给每个node添加class
  23034. var list = domUtils.getElementsByTagName(el, "*");
  23035. var theme = "edui-" + (this.theme || this.editor.options.theme);
  23036. var layer = document.getElementById('edui_fixedlayer');
  23037. for (var i = 0, node; node = list[i++];) {
  23038. domUtils.addClass(node, theme);
  23039. }
  23040. domUtils.addClass(el, theme);
  23041. if(layer){
  23042. layer.className="";
  23043. domUtils.addClass(layer,theme);
  23044. }
  23045. var seatEl = this.getDom();
  23046. if (seatEl != null) {
  23047. seatEl.parentNode.replaceChild(el, seatEl);
  23048. uiUtils.copyAttributes(el, seatEl);
  23049. } else {
  23050. if (typeof holder == 'string') {
  23051. holder = document.getElementById(holder);
  23052. }
  23053. holder = holder || uiUtils.getFixedLayer();
  23054. domUtils.addClass(holder, theme);
  23055. holder.appendChild(el);
  23056. }
  23057. this.postRender();
  23058. },
  23059. getDom:function (name) {
  23060. if (!name) {
  23061. return document.getElementById(this.id);
  23062. } else {
  23063. return document.getElementById(this.id + '_' + name);
  23064. }
  23065. },
  23066. postRender:function () {
  23067. this.fireEvent('postrender');
  23068. },
  23069. getHtmlTpl:function () {
  23070. return '';
  23071. },
  23072. formatHtml:function (tpl) {
  23073. var prefix = 'edui-' + this.uiName;
  23074. return (tpl
  23075. .replace(/##/g, this.id)
  23076. .replace(/%%-/g, this.uiName ? prefix + '-' : '')
  23077. .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className)
  23078. .replace(/\$\$/g, this._globalKey));
  23079. },
  23080. renderHtml:function () {
  23081. return this.formatHtml(this.getHtmlTpl());
  23082. },
  23083. dispose:function () {
  23084. var box = this.getDom();
  23085. if (box) baidu.editor.dom.domUtils.remove(box);
  23086. uiUtils.unsetGlobal(this.id);
  23087. }
  23088. };
  23089. utils.inherits(UIBase, EventBase);
  23090. })();
  23091. // ui/separator.js
  23092. (function (){
  23093. var utils = baidu.editor.utils,
  23094. UIBase = baidu.editor.ui.UIBase,
  23095. Separator = baidu.editor.ui.Separator = function (options){
  23096. this.initOptions(options);
  23097. this.initSeparator();
  23098. };
  23099. Separator.prototype = {
  23100. uiName: 'separator',
  23101. initSeparator: function (){
  23102. this.initUIBase();
  23103. },
  23104. getHtmlTpl: function (){
  23105. return '<div id="##" class="edui-box %%"></div>';
  23106. }
  23107. };
  23108. utils.inherits(Separator, UIBase);
  23109. })();
  23110. // ui/mask.js
  23111. ///import core
  23112. ///import uicore
  23113. (function (){
  23114. var utils = baidu.editor.utils,
  23115. domUtils = baidu.editor.dom.domUtils,
  23116. UIBase = baidu.editor.ui.UIBase,
  23117. uiUtils = baidu.editor.ui.uiUtils;
  23118. var Mask = baidu.editor.ui.Mask = function (options){
  23119. this.initOptions(options);
  23120. this.initUIBase();
  23121. };
  23122. Mask.prototype = {
  23123. getHtmlTpl: function (){
  23124. return '<div id="##" class="edui-mask %%" onclick="return $$._onClick(event, this);" onmousedown="return $$._onMouseDown(event, this);"></div>';
  23125. },
  23126. postRender: function (){
  23127. var me = this;
  23128. domUtils.on(window, 'resize', function (){
  23129. setTimeout(function (){
  23130. if (!me.isHidden()) {
  23131. me._fill();
  23132. }
  23133. });
  23134. });
  23135. },
  23136. show: function (zIndex){
  23137. this._fill();
  23138. this.getDom().style.display = '';
  23139. this.getDom().style.zIndex = zIndex;
  23140. },
  23141. hide: function (){
  23142. this.getDom().style.display = 'none';
  23143. this.getDom().style.zIndex = '';
  23144. },
  23145. isHidden: function (){
  23146. return this.getDom().style.display == 'none';
  23147. },
  23148. _onMouseDown: function (){
  23149. return false;
  23150. },
  23151. _onClick: function (e, target){
  23152. this.fireEvent('click', e, target);
  23153. },
  23154. _fill: function (){
  23155. var el = this.getDom();
  23156. var vpRect = uiUtils.getViewportRect();
  23157. el.style.width = vpRect.width + 'px';
  23158. el.style.height = vpRect.height + 'px';
  23159. }
  23160. };
  23161. utils.inherits(Mask, UIBase);
  23162. })();
  23163. // ui/popup.js
  23164. ///import core
  23165. ///import uicore
  23166. (function () {
  23167. var utils = baidu.editor.utils,
  23168. uiUtils = baidu.editor.ui.uiUtils,
  23169. domUtils = baidu.editor.dom.domUtils,
  23170. UIBase = baidu.editor.ui.UIBase,
  23171. Popup = baidu.editor.ui.Popup = function (options){
  23172. this.initOptions(options);
  23173. this.initPopup();
  23174. };
  23175. var allPopups = [];
  23176. function closeAllPopup( evt,el ){
  23177. for ( var i = 0; i < allPopups.length; i++ ) {
  23178. var pop = allPopups[i];
  23179. if (!pop.isHidden()) {
  23180. if (pop.queryAutoHide(el) !== false) {
  23181. if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return;
  23182. pop.hide();
  23183. }
  23184. }
  23185. }
  23186. if(allPopups.length)
  23187. pop.editor.fireEvent("afterhidepop");
  23188. }
  23189. Popup.postHide = closeAllPopup;
  23190. var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright',
  23191. 'edui-anchor-bottomleft','edui-anchor-bottomright'];
  23192. Popup.prototype = {
  23193. SHADOW_RADIUS: 5,
  23194. content: null,
  23195. _hidden: false,
  23196. autoRender: true,
  23197. canSideLeft: true,
  23198. canSideUp: true,
  23199. initPopup: function (){
  23200. this.initUIBase();
  23201. allPopups.push( this );
  23202. },
  23203. getHtmlTpl: function (){
  23204. return '<div id="##" class="edui-popup %%" onmousedown="return false;">' +
  23205. ' <div id="##_body" class="edui-popup-body">' +
  23206. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  23207. ' <div class="edui-shadow"></div>' +
  23208. ' <div id="##_content" class="edui-popup-content">' +
  23209. this.getContentHtmlTpl() +
  23210. ' </div>' +
  23211. ' </div>' +
  23212. '</div>';
  23213. },
  23214. getContentHtmlTpl: function (){
  23215. if(this.content){
  23216. if (typeof this.content == 'string') {
  23217. return this.content;
  23218. }
  23219. return this.content.renderHtml();
  23220. }else{
  23221. return ''
  23222. }
  23223. },
  23224. _UIBase_postRender: UIBase.prototype.postRender,
  23225. postRender: function (){
  23226. if (this.content instanceof UIBase) {
  23227. this.content.postRender();
  23228. }
  23229. //捕获鼠标滚轮
  23230. if( this.captureWheel && !this.captured ) {
  23231. this.captured = true;
  23232. var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80,
  23233. _height = this.getDom().offsetHeight,
  23234. _top = uiUtils.getClientRect( this.combox.getDom() ).top,
  23235. content = this.getDom('content'),
  23236. ifr = this.getDom('body').getElementsByTagName('iframe'),
  23237. me = this;
  23238. ifr.length && ( ifr = ifr[0] );
  23239. while( _top + _height > winHeight ) {
  23240. _height -= 30;
  23241. }
  23242. content.style.height = _height + 'px';
  23243. //同步更改iframe高度
  23244. ifr && ( ifr.style.height = _height + 'px' );
  23245. //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解
  23246. if( window.XMLHttpRequest ) {
  23247. domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){
  23248. if(e.preventDefault) {
  23249. e.preventDefault();
  23250. } else {
  23251. e.returnValue = false;
  23252. }
  23253. if( e.wheelDelta ) {
  23254. content.scrollTop -= ( e.wheelDelta / 120 )*60;
  23255. } else {
  23256. content.scrollTop -= ( e.detail / -3 )*60;
  23257. }
  23258. });
  23259. } else {
  23260. //ie6
  23261. domUtils.on( this.getDom(), 'mousewheel' , function(e){
  23262. e.returnValue = false;
  23263. me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60;
  23264. });
  23265. }
  23266. }
  23267. this.fireEvent('postRenderAfter');
  23268. this.hide(true);
  23269. this._UIBase_postRender();
  23270. },
  23271. _doAutoRender: function (){
  23272. if (!this.getDom() && this.autoRender) {
  23273. this.render();
  23274. }
  23275. },
  23276. mesureSize: function (){
  23277. var box = this.getDom('content');
  23278. return uiUtils.getClientRect(box);
  23279. },
  23280. fitSize: function (){
  23281. if( this.captureWheel && this.sized ) {
  23282. return this.__size;
  23283. }
  23284. this.sized = true;
  23285. var popBodyEl = this.getDom('body');
  23286. popBodyEl.style.width = '';
  23287. popBodyEl.style.height = '';
  23288. var size = this.mesureSize();
  23289. if( this.captureWheel ) {
  23290. popBodyEl.style.width = -(-20 -size.width) + 'px';
  23291. var height = parseInt( this.getDom('content').style.height, 10 );
  23292. !window.isNaN( height ) && ( size.height = height );
  23293. } else {
  23294. popBodyEl.style.width = size.width + 'px';
  23295. }
  23296. popBodyEl.style.height = size.height + 'px';
  23297. this.__size = size;
  23298. this.captureWheel && (this.getDom('content').style.overflow = 'auto');
  23299. return size;
  23300. },
  23301. showAnchor: function ( element, hoz ){
  23302. this.showAnchorRect( uiUtils.getClientRect( element ), hoz );
  23303. },
  23304. showAnchorRect: function ( rect, hoz, adj ){
  23305. this._doAutoRender();
  23306. var vpRect = uiUtils.getViewportRect();
  23307. this.getDom().style.visibility = 'hidden';
  23308. this._show();
  23309. var popSize = this.fitSize();
  23310. var sideLeft, sideUp, left, top;
  23311. if (hoz) {
  23312. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23313. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23314. left = (sideLeft ? rect.left - popSize.width : rect.right);
  23315. top = (sideUp ? rect.bottom - popSize.height : rect.top);
  23316. } else {
  23317. sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width);
  23318. sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height);
  23319. left = (sideLeft ? rect.right - popSize.width : rect.left);
  23320. top = (sideUp ? rect.top - popSize.height : rect.bottom);
  23321. }
  23322. var popEl = this.getDom();
  23323. uiUtils.setViewportOffset(popEl, {
  23324. left: left,
  23325. top: top
  23326. });
  23327. domUtils.removeClasses(popEl, ANCHOR_CLASSES);
  23328. popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)];
  23329. if(this.editor){
  23330. popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10;
  23331. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1;
  23332. }
  23333. this.getDom().style.visibility = 'visible';
  23334. },
  23335. showAt: function (offset) {
  23336. var left = offset.left;
  23337. var top = offset.top;
  23338. var rect = {
  23339. left: left,
  23340. top: top,
  23341. right: left,
  23342. bottom: top,
  23343. height: 0,
  23344. width: 0
  23345. };
  23346. this.showAnchorRect(rect, false, true);
  23347. },
  23348. _show: function (){
  23349. if (this._hidden) {
  23350. var box = this.getDom();
  23351. box.style.display = '';
  23352. this._hidden = false;
  23353. // if (box.setActive) {
  23354. // box.setActive();
  23355. // }
  23356. this.fireEvent('show');
  23357. }
  23358. },
  23359. isHidden: function (){
  23360. return this._hidden;
  23361. },
  23362. show: function (){
  23363. this._doAutoRender();
  23364. this._show();
  23365. },
  23366. hide: function (notNofity){
  23367. if (!this._hidden && this.getDom()) {
  23368. this.getDom().style.display = 'none';
  23369. this._hidden = true;
  23370. if (!notNofity) {
  23371. this.fireEvent('hide');
  23372. }
  23373. }
  23374. },
  23375. queryAutoHide: function (el){
  23376. return !el || !uiUtils.contains(this.getDom(), el);
  23377. }
  23378. };
  23379. utils.inherits(Popup, UIBase);
  23380. domUtils.on( document, 'mousedown', function ( evt ) {
  23381. var el = evt.target || evt.srcElement;
  23382. closeAllPopup( evt,el );
  23383. } );
  23384. domUtils.on( window, 'scroll', function (evt,el) {
  23385. closeAllPopup( evt,el );
  23386. } );
  23387. })();
  23388. // ui/colorpicker.js
  23389. ///import core
  23390. ///import uicore
  23391. (function (){
  23392. var utils = baidu.editor.utils,
  23393. UIBase = baidu.editor.ui.UIBase,
  23394. ColorPicker = baidu.editor.ui.ColorPicker = function (options){
  23395. this.initOptions(options);
  23396. this.noColorText = this.noColorText || this.editor.getLang("clearColor");
  23397. this.initUIBase();
  23398. };
  23399. ColorPicker.prototype = {
  23400. getHtmlTpl: function (){
  23401. return genColorPicker(this.noColorText,this.editor);
  23402. },
  23403. _onTableClick: function (evt){
  23404. var tgt = evt.target || evt.srcElement;
  23405. var color = tgt.getAttribute('data-color');
  23406. if (color) {
  23407. this.fireEvent('pickcolor', color);
  23408. }
  23409. },
  23410. _onTableOver: function (evt){
  23411. var tgt = evt.target || evt.srcElement;
  23412. var color = tgt.getAttribute('data-color');
  23413. if (color) {
  23414. this.getDom('preview').style.backgroundColor = color;
  23415. }
  23416. },
  23417. _onTableOut: function (){
  23418. this.getDom('preview').style.backgroundColor = '';
  23419. },
  23420. _onPickNoColor: function (){
  23421. this.fireEvent('picknocolor');
  23422. }
  23423. };
  23424. utils.inherits(ColorPicker, UIBase);
  23425. var COLORS = (
  23426. 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' +
  23427. 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' +
  23428. 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' +
  23429. 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' +
  23430. 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' +
  23431. '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' +
  23432. 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(',');
  23433. function genColorPicker(noColorText,editor){
  23434. var html = '<div id="##" class="edui-colorpicker %%">' +
  23435. '<div class="edui-colorpicker-topbar edui-clearfix">' +
  23436. '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' +
  23437. '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' +
  23438. '</div>' +
  23439. '<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">' +
  23440. '<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>'+
  23441. '<tr class="edui-colorpicker-tablefirstrow" >';
  23442. for (var i=0; i<COLORS.length; i++) {
  23443. if (i && i%10 === 0) {
  23444. 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"':'')+'>';
  23445. }
  23446. 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"' +
  23447. ' data-color="#'+ COLORS[i] +'"'+
  23448. ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+
  23449. (i<10 || i>=60?'border-width:1px;':
  23450. i>=10&&i<20?'border-width:1px 1px 0 1px;':
  23451. 'border-width:0 1px 0 1px;')+
  23452. '"' +
  23453. '></a></td>':'';
  23454. }
  23455. html += '</tr></table></div>';
  23456. return html;
  23457. }
  23458. })();
  23459. // ui/tablepicker.js
  23460. ///import core
  23461. ///import uicore
  23462. (function (){
  23463. var utils = baidu.editor.utils,
  23464. uiUtils = baidu.editor.ui.uiUtils,
  23465. UIBase = baidu.editor.ui.UIBase;
  23466. var TablePicker = baidu.editor.ui.TablePicker = function (options){
  23467. this.initOptions(options);
  23468. this.initTablePicker();
  23469. };
  23470. TablePicker.prototype = {
  23471. defaultNumRows: 10,
  23472. defaultNumCols: 10,
  23473. maxNumRows: 20,
  23474. maxNumCols: 20,
  23475. numRows: 10,
  23476. numCols: 10,
  23477. lengthOfCellSide: 22,
  23478. initTablePicker: function (){
  23479. this.initUIBase();
  23480. },
  23481. getHtmlTpl: function (){
  23482. var me = this;
  23483. return '<div id="##" class="edui-tablepicker %%">' +
  23484. '<div class="edui-tablepicker-body">' +
  23485. '<div class="edui-infoarea">' +
  23486. '<span id="##_label" class="edui-label"></span>' +
  23487. '</div>' +
  23488. '<div class="edui-pickarea"' +
  23489. ' onmousemove="$$._onMouseMove(event, this);"' +
  23490. ' onmouseover="$$._onMouseOver(event, this);"' +
  23491. ' onmouseout="$$._onMouseOut(event, this);"' +
  23492. ' onclick="$$._onClick(event, this);"' +
  23493. '>' +
  23494. '<div id="##_overlay" class="edui-overlay"></div>' +
  23495. '</div>' +
  23496. '</div>' +
  23497. '</div>';
  23498. },
  23499. _UIBase_render: UIBase.prototype.render,
  23500. render: function (holder){
  23501. this._UIBase_render(holder);
  23502. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col");
  23503. },
  23504. _track: function (numCols, numRows){
  23505. var style = this.getDom('overlay').style;
  23506. var sideLen = this.lengthOfCellSide;
  23507. style.width = numCols * sideLen + 'px';
  23508. style.height = numRows * sideLen + 'px';
  23509. var label = this.getDom('label');
  23510. label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row");
  23511. this.numCols = numCols;
  23512. this.numRows = numRows;
  23513. },
  23514. _onMouseOver: function (evt, el){
  23515. var rel = evt.relatedTarget || evt.fromElement;
  23516. if (!uiUtils.contains(el, rel) && el !== rel) {
  23517. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23518. this.getDom('overlay').style.visibility = '';
  23519. }
  23520. },
  23521. _onMouseOut: function (evt, el){
  23522. var rel = evt.relatedTarget || evt.toElement;
  23523. if (!uiUtils.contains(el, rel) && el !== rel) {
  23524. this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row");
  23525. this.getDom('overlay').style.visibility = 'hidden';
  23526. }
  23527. },
  23528. _onMouseMove: function (evt, el){
  23529. var style = this.getDom('overlay').style;
  23530. var offset = uiUtils.getEventOffset(evt);
  23531. var sideLen = this.lengthOfCellSide;
  23532. var numCols = Math.ceil(offset.left / sideLen);
  23533. var numRows = Math.ceil(offset.top / sideLen);
  23534. this._track(numCols, numRows);
  23535. },
  23536. _onClick: function (){
  23537. this.fireEvent('picktable', this.numCols, this.numRows);
  23538. }
  23539. };
  23540. utils.inherits(TablePicker, UIBase);
  23541. })();
  23542. // ui/stateful.js
  23543. (function (){
  23544. var browser = baidu.editor.browser,
  23545. domUtils = baidu.editor.dom.domUtils,
  23546. uiUtils = baidu.editor.ui.uiUtils;
  23547. var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' +
  23548. ' onmouseup="$$.Stateful_onMouseUp(event, this);"' +
  23549. ( browser.ie ? (
  23550. ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' +
  23551. ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' )
  23552. : (
  23553. ' onmouseover="$$.Stateful_onMouseOver(event, this);"' +
  23554. ' onmouseout="$$.Stateful_onMouseOut(event, this);"' ));
  23555. baidu.editor.ui.Stateful = {
  23556. alwalysHoverable: false,
  23557. target:null,//目标元素和this指向dom不一样
  23558. Stateful_init: function (){
  23559. this._Stateful_dGetHtmlTpl = this.getHtmlTpl;
  23560. this.getHtmlTpl = this.Stateful_getHtmlTpl;
  23561. },
  23562. Stateful_getHtmlTpl: function (){
  23563. var tpl = this._Stateful_dGetHtmlTpl();
  23564. // 使用function避免$转义
  23565. return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; });
  23566. },
  23567. Stateful_onMouseEnter: function (evt, el){
  23568. this.target=el;
  23569. if (!this.isDisabled() || this.alwalysHoverable) {
  23570. this.addState('hover');
  23571. this.fireEvent('over');
  23572. }
  23573. },
  23574. Stateful_onMouseLeave: function (evt, el){
  23575. if (!this.isDisabled() || this.alwalysHoverable) {
  23576. this.removeState('hover');
  23577. this.removeState('active');
  23578. this.fireEvent('out');
  23579. }
  23580. },
  23581. Stateful_onMouseOver: function (evt, el){
  23582. var rel = evt.relatedTarget;
  23583. if (!uiUtils.contains(el, rel) && el !== rel) {
  23584. this.Stateful_onMouseEnter(evt, el);
  23585. }
  23586. },
  23587. Stateful_onMouseOut: function (evt, el){
  23588. var rel = evt.relatedTarget;
  23589. if (!uiUtils.contains(el, rel) && el !== rel) {
  23590. this.Stateful_onMouseLeave(evt, el);
  23591. }
  23592. },
  23593. Stateful_onMouseDown: function (evt, el){
  23594. if (!this.isDisabled()) {
  23595. this.addState('active');
  23596. }
  23597. },
  23598. Stateful_onMouseUp: function (evt, el){
  23599. if (!this.isDisabled()) {
  23600. this.removeState('active');
  23601. }
  23602. },
  23603. Stateful_postRender: function (){
  23604. if (this.disabled && !this.hasState('disabled')) {
  23605. this.addState('disabled');
  23606. }
  23607. },
  23608. hasState: function (state){
  23609. return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state);
  23610. },
  23611. addState: function (state){
  23612. if (!this.hasState(state)) {
  23613. this.getStateDom().className += ' edui-state-' + state;
  23614. }
  23615. },
  23616. removeState: function (state){
  23617. if (this.hasState(state)) {
  23618. domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]);
  23619. }
  23620. },
  23621. getStateDom: function (){
  23622. return this.getDom('state');
  23623. },
  23624. isChecked: function (){
  23625. return this.hasState('checked');
  23626. },
  23627. setChecked: function (checked){
  23628. if (!this.isDisabled() && checked) {
  23629. this.addState('checked');
  23630. } else {
  23631. this.removeState('checked');
  23632. }
  23633. },
  23634. isDisabled: function (){
  23635. return this.hasState('disabled');
  23636. },
  23637. setDisabled: function (disabled){
  23638. if (disabled) {
  23639. this.removeState('hover');
  23640. this.removeState('checked');
  23641. this.removeState('active');
  23642. this.addState('disabled');
  23643. } else {
  23644. this.removeState('disabled');
  23645. }
  23646. }
  23647. };
  23648. })();
  23649. // ui/button.js
  23650. ///import core
  23651. ///import uicore
  23652. ///import ui/stateful.js
  23653. (function (){
  23654. var utils = baidu.editor.utils,
  23655. UIBase = baidu.editor.ui.UIBase,
  23656. Stateful = baidu.editor.ui.Stateful,
  23657. Button = baidu.editor.ui.Button = function (options){
  23658. if(options.name){
  23659. var btnName = options.name;
  23660. var cssRules = options.cssRules;
  23661. if(!options.className){
  23662. options.className = 'edui-for-' + btnName;
  23663. }
  23664. options.cssRules = '.edui-default .edui-for-'+ btnName +' .edui-icon {'+ cssRules +'}'
  23665. }
  23666. this.initOptions(options);
  23667. this.initButton();
  23668. };
  23669. Button.prototype = {
  23670. uiName: 'button',
  23671. label: '',
  23672. title: '',
  23673. showIcon: true,
  23674. showText: true,
  23675. cssRules:'',
  23676. initButton: function (){
  23677. this.initUIBase();
  23678. this.Stateful_init();
  23679. if(this.cssRules){
  23680. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  23681. }
  23682. },
  23683. getHtmlTpl: function (){
  23684. return '<div id="##" class="edui-box %%">' +
  23685. '<div id="##_state" stateful>' +
  23686. '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') +
  23687. ' class="%%-body" onmousedown="return $$._onMouseDown(event, this);" onclick="return $$._onClick(event, this);">' +
  23688. (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') +
  23689. (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') +
  23690. '</div>' +
  23691. '</div>' +
  23692. '</div></div>';
  23693. },
  23694. postRender: function (){
  23695. this.Stateful_postRender();
  23696. this.setDisabled(this.disabled)
  23697. },
  23698. _onMouseDown: function (e){
  23699. var target = e.target || e.srcElement,
  23700. tagName = target && target.tagName && target.tagName.toLowerCase();
  23701. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  23702. return false;
  23703. }
  23704. },
  23705. _onClick: function (){
  23706. if (!this.isDisabled()) {
  23707. this.fireEvent('click');
  23708. }
  23709. },
  23710. setTitle: function(text){
  23711. var label = this.getDom('label');
  23712. label.innerHTML = text;
  23713. }
  23714. };
  23715. utils.inherits(Button, UIBase);
  23716. utils.extend(Button.prototype, Stateful);
  23717. })();
  23718. // ui/splitbutton.js
  23719. ///import core
  23720. ///import uicore
  23721. ///import ui/stateful.js
  23722. (function (){
  23723. var utils = baidu.editor.utils,
  23724. uiUtils = baidu.editor.ui.uiUtils,
  23725. domUtils = baidu.editor.dom.domUtils,
  23726. UIBase = baidu.editor.ui.UIBase,
  23727. Stateful = baidu.editor.ui.Stateful,
  23728. SplitButton = baidu.editor.ui.SplitButton = function (options){
  23729. this.initOptions(options);
  23730. this.initSplitButton();
  23731. };
  23732. SplitButton.prototype = {
  23733. popup: null,
  23734. uiName: 'splitbutton',
  23735. title: '',
  23736. initSplitButton: function (){
  23737. this.initUIBase();
  23738. this.Stateful_init();
  23739. var me = this;
  23740. if (this.popup != null) {
  23741. var popup = this.popup;
  23742. this.popup = null;
  23743. this.setPopup(popup);
  23744. }
  23745. },
  23746. _UIBase_postRender: UIBase.prototype.postRender,
  23747. postRender: function (){
  23748. this.Stateful_postRender();
  23749. this._UIBase_postRender();
  23750. },
  23751. setPopup: function (popup){
  23752. if (this.popup === popup) return;
  23753. if (this.popup != null) {
  23754. this.popup.dispose();
  23755. }
  23756. popup.addListener('show', utils.bind(this._onPopupShow, this));
  23757. popup.addListener('hide', utils.bind(this._onPopupHide, this));
  23758. popup.addListener('postrender', utils.bind(function (){
  23759. popup.getDom('body').appendChild(
  23760. uiUtils.createElementByHtml('<div id="' +
  23761. this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' +
  23762. (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>')
  23763. );
  23764. popup.getDom().className += ' ' + this.className;
  23765. }, this));
  23766. this.popup = popup;
  23767. },
  23768. _onPopupShow: function (){
  23769. this.addState('opened');
  23770. },
  23771. _onPopupHide: function (){
  23772. this.removeState('opened');
  23773. },
  23774. getHtmlTpl: function (){
  23775. return '<div id="##" class="edui-box %%">' +
  23776. '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' +
  23777. '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' +
  23778. '<div class="edui-box edui-icon"></div>' +
  23779. '</div>' +
  23780. '<div class="edui-box edui-splitborder"></div>' +
  23781. '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' +
  23782. '</div></div></div>';
  23783. },
  23784. showPopup: function (){
  23785. // 当popup往上弹出的时候,做特殊处理
  23786. var rect = uiUtils.getClientRect(this.getDom());
  23787. rect.top -= this.popup.SHADOW_RADIUS;
  23788. rect.height += this.popup.SHADOW_RADIUS;
  23789. this.popup.showAnchorRect(rect);
  23790. },
  23791. _onArrowClick: function (event, el){
  23792. if (!this.isDisabled()) {
  23793. this.showPopup();
  23794. }
  23795. },
  23796. _onButtonClick: function (){
  23797. if (!this.isDisabled()) {
  23798. this.fireEvent('buttonclick');
  23799. }
  23800. }
  23801. };
  23802. utils.inherits(SplitButton, UIBase);
  23803. utils.extend(SplitButton.prototype, Stateful, true);
  23804. })();
  23805. // ui/colorbutton.js
  23806. ///import core
  23807. ///import uicore
  23808. ///import ui/colorpicker.js
  23809. ///import ui/popup.js
  23810. ///import ui/splitbutton.js
  23811. (function (){
  23812. var utils = baidu.editor.utils,
  23813. uiUtils = baidu.editor.ui.uiUtils,
  23814. ColorPicker = baidu.editor.ui.ColorPicker,
  23815. Popup = baidu.editor.ui.Popup,
  23816. SplitButton = baidu.editor.ui.SplitButton,
  23817. ColorButton = baidu.editor.ui.ColorButton = function (options){
  23818. this.initOptions(options);
  23819. this.initColorButton();
  23820. };
  23821. ColorButton.prototype = {
  23822. initColorButton: function (){
  23823. var me = this;
  23824. this.popup = new Popup({
  23825. content: new ColorPicker({
  23826. noColorText: me.editor.getLang("clearColor"),
  23827. editor:me.editor,
  23828. onpickcolor: function (t, color){
  23829. me._onPickColor(color);
  23830. },
  23831. onpicknocolor: function (t, color){
  23832. me._onPickNoColor(color);
  23833. }
  23834. }),
  23835. editor:me.editor
  23836. });
  23837. this.initSplitButton();
  23838. },
  23839. _SplitButton_postRender: SplitButton.prototype.postRender,
  23840. postRender: function (){
  23841. this._SplitButton_postRender();
  23842. this.getDom('button_body').appendChild(
  23843. uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>')
  23844. );
  23845. this.getDom().className += ' edui-colorbutton';
  23846. },
  23847. setColor: function (color){
  23848. this.getDom('colorlump').style.backgroundColor = color;
  23849. this.color = color;
  23850. },
  23851. _onPickColor: function (color){
  23852. if (this.fireEvent('pickcolor', color) !== false) {
  23853. this.setColor(color);
  23854. this.popup.hide();
  23855. }
  23856. },
  23857. _onPickNoColor: function (color){
  23858. if (this.fireEvent('picknocolor') !== false) {
  23859. this.popup.hide();
  23860. }
  23861. }
  23862. };
  23863. utils.inherits(ColorButton, SplitButton);
  23864. })();
  23865. // ui/tablebutton.js
  23866. ///import core
  23867. ///import uicore
  23868. ///import ui/popup.js
  23869. ///import ui/tablepicker.js
  23870. ///import ui/splitbutton.js
  23871. (function (){
  23872. var utils = baidu.editor.utils,
  23873. Popup = baidu.editor.ui.Popup,
  23874. TablePicker = baidu.editor.ui.TablePicker,
  23875. SplitButton = baidu.editor.ui.SplitButton,
  23876. TableButton = baidu.editor.ui.TableButton = function (options){
  23877. this.initOptions(options);
  23878. this.initTableButton();
  23879. };
  23880. TableButton.prototype = {
  23881. initTableButton: function (){
  23882. var me = this;
  23883. this.popup = new Popup({
  23884. content: new TablePicker({
  23885. editor:me.editor,
  23886. onpicktable: function (t, numCols, numRows){
  23887. me._onPickTable(numCols, numRows);
  23888. }
  23889. }),
  23890. 'editor':me.editor
  23891. });
  23892. this.initSplitButton();
  23893. },
  23894. _onPickTable: function (numCols, numRows){
  23895. if (this.fireEvent('picktable', numCols, numRows) !== false) {
  23896. this.popup.hide();
  23897. }
  23898. }
  23899. };
  23900. utils.inherits(TableButton, SplitButton);
  23901. })();
  23902. // ui/autotypesetpicker.js
  23903. ///import core
  23904. ///import uicore
  23905. (function () {
  23906. var utils = baidu.editor.utils,
  23907. UIBase = baidu.editor.ui.UIBase;
  23908. var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) {
  23909. this.initOptions(options);
  23910. this.initAutoTypeSetPicker();
  23911. };
  23912. AutoTypeSetPicker.prototype = {
  23913. initAutoTypeSetPicker:function () {
  23914. this.initUIBase();
  23915. },
  23916. getHtmlTpl:function () {
  23917. var me = this.editor,
  23918. opt = me.options.autotypeset,
  23919. lang = me.getLang("autoTypeSet");
  23920. var textAlignInputName = 'textAlignValue' + me.uid,
  23921. imageBlockInputName = 'imageBlockLineValue' + me.uid,
  23922. symbolConverInputName = 'symbolConverValue' + me.uid;
  23923. return '<div id="##" class="edui-autotypesetpicker %%">' +
  23924. '<div class="edui-autotypesetpicker-body">' +
  23925. '<table >' +
  23926. '<tr><td nowrap><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>' +
  23927. '<tr><td nowrap><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>' +
  23928. '<tr>' +
  23929. '<td nowrap><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td>' +
  23930. '<td colspan="2" id="' + textAlignInputName + '">' +
  23931. '<input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23932. '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23933. '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23934. '</td>' +
  23935. '</tr>' +
  23936. '<tr>' +
  23937. '<td nowrap><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' +
  23938. '<td nowrap id="'+ imageBlockInputName +'">' +
  23939. '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") +
  23940. '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") +
  23941. '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") +
  23942. '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") +
  23943. '</td>' +
  23944. '</tr>' +
  23945. '<tr><td nowrap><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>' +
  23946. '<tr><td nowrap colspan="3"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' +
  23947. '<tr><td nowrap colspan="3"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' +
  23948. '<tr>' +
  23949. '<td nowrap><input type="checkbox" name="symbolConver" ' + (opt["bdc2sb"] || opt["tobdc"] ? "checked" : "" ) + '>' + lang.symbol + '</td>' +
  23950. '<td id="' + symbolConverInputName + '">' +
  23951. '<input type="radio" name="bdc" value="bdc2sb" ' + (opt["bdc2sb"] ? "checked" : "" ) + '>' + lang.bdc2sb +
  23952. '<input type="radio" name="bdc" value="tobdc" ' + (opt["tobdc"] ? "checked" : "" ) + '>' + lang.tobdc + '' +
  23953. '</td>' +
  23954. '<td nowrap align="right"><button >' + lang.run + '</button></td>' +
  23955. '</tr>' +
  23956. '</table>' +
  23957. '</div>' +
  23958. '</div>';
  23959. },
  23960. _UIBase_render:UIBase.prototype.render
  23961. };
  23962. utils.inherits(AutoTypeSetPicker, UIBase);
  23963. })();
  23964. // ui/autotypesetbutton.js
  23965. ///import core
  23966. ///import uicore
  23967. ///import ui/popup.js
  23968. ///import ui/autotypesetpicker.js
  23969. ///import ui/splitbutton.js
  23970. (function (){
  23971. var utils = baidu.editor.utils,
  23972. Popup = baidu.editor.ui.Popup,
  23973. AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker,
  23974. SplitButton = baidu.editor.ui.SplitButton,
  23975. AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){
  23976. this.initOptions(options);
  23977. this.initAutoTypeSetButton();
  23978. };
  23979. function getPara(me){
  23980. var opt = {},
  23981. cont = me.getDom(),
  23982. editorId = me.editor.uid,
  23983. inputType = null,
  23984. attrName = null,
  23985. ipts = domUtils.getElementsByTagName(cont,"input");
  23986. for(var i=ipts.length-1,ipt;ipt=ipts[i--];){
  23987. inputType = ipt.getAttribute("type");
  23988. if(inputType=="checkbox"){
  23989. attrName = ipt.getAttribute("name");
  23990. opt[attrName] && delete opt[attrName];
  23991. if(ipt.checked){
  23992. var attrValue = document.getElementById( attrName + "Value" + editorId );
  23993. if(attrValue){
  23994. if(/input/ig.test(attrValue.tagName)){
  23995. opt[attrName] = attrValue.value;
  23996. } else {
  23997. var iptChilds = attrValue.getElementsByTagName("input");
  23998. for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){
  23999. if(iptchild.checked){
  24000. opt[attrName] = iptchild.value;
  24001. break;
  24002. }
  24003. }
  24004. }
  24005. } else {
  24006. opt[attrName] = true;
  24007. }
  24008. } else {
  24009. opt[attrName] = false;
  24010. }
  24011. } else {
  24012. opt[ipt.getAttribute("value")] = ipt.checked;
  24013. }
  24014. }
  24015. var selects = domUtils.getElementsByTagName(cont,"select");
  24016. for(var i=0,si;si=selects[i++];){
  24017. var attr = si.getAttribute('name');
  24018. opt[attr] = opt[attr] ? si.value : '';
  24019. }
  24020. utils.extend(me.editor.options.autotypeset,opt);
  24021. me.editor.setPreferences('autotypeset', opt);
  24022. }
  24023. AutoTypeSetButton.prototype = {
  24024. initAutoTypeSetButton: function (){
  24025. var me = this;
  24026. this.popup = new Popup({
  24027. //传入配置参数
  24028. content: new AutoTypeSetPicker({editor:me.editor}),
  24029. 'editor':me.editor,
  24030. hide : function(){
  24031. if (!this._hidden && this.getDom()) {
  24032. getPara(this);
  24033. this.getDom().style.display = 'none';
  24034. this._hidden = true;
  24035. this.fireEvent('hide');
  24036. }
  24037. }
  24038. });
  24039. var flag = 0;
  24040. this.popup.addListener('postRenderAfter',function(){
  24041. var popupUI = this;
  24042. if(flag)return;
  24043. var cont = this.getDom(),
  24044. btn = cont.getElementsByTagName('button')[0];
  24045. btn.onclick = function(){
  24046. getPara(popupUI);
  24047. me.editor.execCommand('autotypeset');
  24048. popupUI.hide()
  24049. };
  24050. domUtils.on(cont, 'click', function(e) {
  24051. var target = e.target || e.srcElement,
  24052. editorId = me.editor.uid;
  24053. if (target && target.tagName == 'INPUT') {
  24054. // 点击图片浮动的checkbox,去除对应的radio
  24055. if (target.name == 'imageBlockLine' || target.name == 'textAlign' || target.name == 'symbolConver') {
  24056. var checked = target.checked,
  24057. radioTd = document.getElementById( target.name + 'Value' + editorId),
  24058. radios = radioTd.getElementsByTagName('input'),
  24059. defalutSelect = {
  24060. 'imageBlockLine': 'none',
  24061. 'textAlign': 'left',
  24062. 'symbolConver': 'tobdc'
  24063. };
  24064. for (var i = 0; i < radios.length; i++) {
  24065. if (checked) {
  24066. if (radios[i].value == defalutSelect[target.name]) {
  24067. radios[i].checked = 'checked';
  24068. }
  24069. } else {
  24070. radios[i].checked = false;
  24071. }
  24072. }
  24073. }
  24074. // 点击radio,选中对应的checkbox
  24075. if (target.name == ('imageBlockLineValue' + editorId) || target.name == ('textAlignValue' + editorId) || target.name == 'bdc') {
  24076. var checkboxs = target.parentNode.previousSibling.getElementsByTagName('input');
  24077. checkboxs && (checkboxs[0].checked = true);
  24078. }
  24079. getPara(popupUI);
  24080. }
  24081. });
  24082. flag = 1;
  24083. });
  24084. this.initSplitButton();
  24085. }
  24086. };
  24087. utils.inherits(AutoTypeSetButton, SplitButton);
  24088. })();
  24089. // ui/cellalignpicker.js
  24090. ///import core
  24091. ///import uicore
  24092. (function () {
  24093. var utils = baidu.editor.utils,
  24094. Popup = baidu.editor.ui.Popup,
  24095. Stateful = baidu.editor.ui.Stateful,
  24096. UIBase = baidu.editor.ui.UIBase;
  24097. /**
  24098. * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始
  24099. * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom'
  24100. * @update 2013/4/2 hancong03@baidu.com
  24101. */
  24102. var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) {
  24103. this.initOptions(options);
  24104. this.initSelected();
  24105. this.initCellAlignPicker();
  24106. };
  24107. CellAlignPicker.prototype = {
  24108. //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引
  24109. initSelected: function(){
  24110. var status = {
  24111. valign: {
  24112. top: 0,
  24113. middle: 1,
  24114. bottom: 2
  24115. },
  24116. align: {
  24117. left: 0,
  24118. center: 1,
  24119. right: 2
  24120. },
  24121. count: 3
  24122. },
  24123. result = -1;
  24124. if( this.selected ) {
  24125. this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ];
  24126. }
  24127. },
  24128. initCellAlignPicker:function () {
  24129. this.initUIBase();
  24130. this.Stateful_init();
  24131. },
  24132. getHtmlTpl:function () {
  24133. var alignType = [ 'left', 'center', 'right' ],
  24134. COUNT = 9,
  24135. tempClassName = null,
  24136. tempIndex = -1,
  24137. tmpl = [];
  24138. for( var i= 0; i<COUNT; i++ ) {
  24139. tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : '';
  24140. tempIndex = i % 3;
  24141. tempIndex === 0 && tmpl.push('<tr>');
  24142. tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' );
  24143. tempIndex === 2 && tmpl.push('</tr>');
  24144. }
  24145. return '<div id="##" class="edui-cellalignpicker %%">' +
  24146. '<div class="edui-cellalignpicker-body">' +
  24147. '<table onclick="$$._onClick(event);">' +
  24148. tmpl.join('') +
  24149. '</table>' +
  24150. '</div>' +
  24151. '</div>';
  24152. },
  24153. getStateDom: function (){
  24154. return this.target;
  24155. },
  24156. _onClick: function (evt){
  24157. var target= evt.target || evt.srcElement;
  24158. if(/icon/.test(target.className)){
  24159. this.items[target.parentNode.getAttribute("index")].onclick();
  24160. Popup.postHide(evt);
  24161. }
  24162. },
  24163. _UIBase_render:UIBase.prototype.render
  24164. };
  24165. utils.inherits(CellAlignPicker, UIBase);
  24166. utils.extend(CellAlignPicker.prototype, Stateful,true);
  24167. })();
  24168. // ui/pastepicker.js
  24169. ///import core
  24170. ///import uicore
  24171. (function () {
  24172. var utils = baidu.editor.utils,
  24173. Stateful = baidu.editor.ui.Stateful,
  24174. uiUtils = baidu.editor.ui.uiUtils,
  24175. UIBase = baidu.editor.ui.UIBase;
  24176. var PastePicker = baidu.editor.ui.PastePicker = function (options) {
  24177. this.initOptions(options);
  24178. this.initPastePicker();
  24179. };
  24180. PastePicker.prototype = {
  24181. initPastePicker:function () {
  24182. this.initUIBase();
  24183. this.Stateful_init();
  24184. },
  24185. getHtmlTpl:function () {
  24186. return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' +
  24187. '<div class="edui-pastecontainer">' +
  24188. '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' +
  24189. '<div class="edui-button">' +
  24190. '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' +
  24191. '<div class="edui-richtxticon"></div></div>' +
  24192. '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' +
  24193. '<div class="edui-tagicon"></div></div>' +
  24194. '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' +
  24195. '<div class="edui-plaintxticon"></div></div>' +
  24196. '</div>' +
  24197. '</div>' +
  24198. '</div>'
  24199. },
  24200. getStateDom:function () {
  24201. return this.target;
  24202. },
  24203. format:function (param) {
  24204. this.editor.ui._isTransfer = true;
  24205. this.editor.fireEvent('pasteTransfer', param);
  24206. },
  24207. _onClick:function (cur) {
  24208. var node = domUtils.getNextDomNode(cur),
  24209. screenHt = uiUtils.getViewportRect().height,
  24210. subPop = uiUtils.getClientRect(node);
  24211. if ((subPop.top + subPop.height) > screenHt)
  24212. node.style.top = (-subPop.height - cur.offsetHeight) + "px";
  24213. else
  24214. node.style.top = "";
  24215. if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) {
  24216. node.style.visibility = "visible";
  24217. domUtils.addClass(cur, "edui-state-opened");
  24218. } else {
  24219. node.style.visibility = "hidden";
  24220. domUtils.removeClasses(cur, "edui-state-opened")
  24221. }
  24222. },
  24223. _UIBase_render:UIBase.prototype.render
  24224. };
  24225. utils.inherits(PastePicker, UIBase);
  24226. utils.extend(PastePicker.prototype, Stateful, true);
  24227. })();
  24228. // ui/toolbar.js
  24229. (function (){
  24230. var utils = baidu.editor.utils,
  24231. uiUtils = baidu.editor.ui.uiUtils,
  24232. UIBase = baidu.editor.ui.UIBase,
  24233. Toolbar = baidu.editor.ui.Toolbar = function (options){
  24234. this.initOptions(options);
  24235. this.initToolbar();
  24236. };
  24237. Toolbar.prototype = {
  24238. items: null,
  24239. initToolbar: function (){
  24240. this.items = this.items || [];
  24241. this.initUIBase();
  24242. },
  24243. add: function (item,index){
  24244. if(index === undefined){
  24245. this.items.push(item);
  24246. }else{
  24247. this.items.splice(index,0,item)
  24248. }
  24249. },
  24250. getHtmlTpl: function (){
  24251. var buff = [];
  24252. for (var i=0; i<this.items.length; i++) {
  24253. buff[i] = this.items[i].renderHtml();
  24254. }
  24255. return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' +
  24256. buff.join('') +
  24257. '</div>'
  24258. },
  24259. postRender: function (){
  24260. var box = this.getDom();
  24261. for (var i=0; i<this.items.length; i++) {
  24262. this.items[i].postRender();
  24263. }
  24264. uiUtils.makeUnselectable(box);
  24265. },
  24266. _onMouseDown: function (e){
  24267. var target = e.target || e.srcElement,
  24268. tagName = target && target.tagName && target.tagName.toLowerCase();
  24269. if (tagName == 'input' || tagName == 'object' || tagName == 'object') {
  24270. return false;
  24271. }
  24272. }
  24273. };
  24274. utils.inherits(Toolbar, UIBase);
  24275. })();
  24276. // ui/menu.js
  24277. ///import core
  24278. ///import uicore
  24279. ///import ui\popup.js
  24280. ///import ui\stateful.js
  24281. (function () {
  24282. var utils = baidu.editor.utils,
  24283. domUtils = baidu.editor.dom.domUtils,
  24284. uiUtils = baidu.editor.ui.uiUtils,
  24285. UIBase = baidu.editor.ui.UIBase,
  24286. Popup = baidu.editor.ui.Popup,
  24287. Stateful = baidu.editor.ui.Stateful,
  24288. CellAlignPicker = baidu.editor.ui.CellAlignPicker,
  24289. Menu = baidu.editor.ui.Menu = function (options) {
  24290. this.initOptions(options);
  24291. this.initMenu();
  24292. };
  24293. var menuSeparator = {
  24294. renderHtml:function () {
  24295. return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>';
  24296. },
  24297. postRender:function () {
  24298. },
  24299. queryAutoHide:function () {
  24300. return true;
  24301. }
  24302. };
  24303. Menu.prototype = {
  24304. items:null,
  24305. uiName:'menu',
  24306. initMenu:function () {
  24307. this.items = this.items || [];
  24308. this.initPopup();
  24309. this.initItems();
  24310. },
  24311. initItems:function () {
  24312. for (var i = 0; i < this.items.length; i++) {
  24313. var item = this.items[i];
  24314. if (item == '-') {
  24315. this.items[i] = this.getSeparator();
  24316. } else if (!(item instanceof MenuItem)) {
  24317. item.editor = this.editor;
  24318. item.theme = this.editor.options.theme;
  24319. this.items[i] = this.createItem(item);
  24320. }
  24321. }
  24322. },
  24323. getSeparator:function () {
  24324. return menuSeparator;
  24325. },
  24326. createItem:function (item) {
  24327. //新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24328. item.menu = this;
  24329. return new MenuItem(item);
  24330. },
  24331. _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl,
  24332. getContentHtmlTpl:function () {
  24333. if (this.items.length == 0) {
  24334. return this._Popup_getContentHtmlTpl();
  24335. }
  24336. var buff = [];
  24337. for (var i = 0; i < this.items.length; i++) {
  24338. var item = this.items[i];
  24339. buff[i] = item.renderHtml();
  24340. }
  24341. return ('<div class="%%-body">' + buff.join('') + '</div>');
  24342. },
  24343. _Popup_postRender:Popup.prototype.postRender,
  24344. postRender:function () {
  24345. var me = this;
  24346. for (var i = 0; i < this.items.length; i++) {
  24347. var item = this.items[i];
  24348. item.ownerMenu = this;
  24349. item.postRender();
  24350. }
  24351. domUtils.on(this.getDom(), 'mouseover', function (evt) {
  24352. evt = evt || event;
  24353. var rel = evt.relatedTarget || evt.fromElement;
  24354. var el = me.getDom();
  24355. if (!uiUtils.contains(el, rel) && el !== rel) {
  24356. me.fireEvent('over');
  24357. }
  24358. });
  24359. this._Popup_postRender();
  24360. },
  24361. queryAutoHide:function (el) {
  24362. if (el) {
  24363. if (uiUtils.contains(this.getDom(), el)) {
  24364. return false;
  24365. }
  24366. for (var i = 0; i < this.items.length; i++) {
  24367. var item = this.items[i];
  24368. if (item.queryAutoHide(el) === false) {
  24369. return false;
  24370. }
  24371. }
  24372. }
  24373. },
  24374. clearItems:function () {
  24375. for (var i = 0; i < this.items.length; i++) {
  24376. var item = this.items[i];
  24377. clearTimeout(item._showingTimer);
  24378. clearTimeout(item._closingTimer);
  24379. if (item.subMenu) {
  24380. item.subMenu.destroy();
  24381. }
  24382. }
  24383. this.items = [];
  24384. },
  24385. destroy:function () {
  24386. if (this.getDom()) {
  24387. domUtils.remove(this.getDom());
  24388. }
  24389. this.clearItems();
  24390. },
  24391. dispose:function () {
  24392. this.destroy();
  24393. }
  24394. };
  24395. utils.inherits(Menu, Popup);
  24396. /**
  24397. * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用
  24398. * @type {Function}
  24399. */
  24400. var MenuItem = baidu.editor.ui.MenuItem = function (options) {
  24401. this.initOptions(options);
  24402. this.initUIBase();
  24403. this.Stateful_init();
  24404. if (this.subMenu && !(this.subMenu instanceof Menu)) {
  24405. if (options.className && options.className.indexOf("aligntd") != -1) {
  24406. var me = this;
  24407. //获取单元格对齐初始状态
  24408. this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' );
  24409. this.subMenu = new Popup({
  24410. content:new CellAlignPicker(this.subMenu),
  24411. parentMenu:me,
  24412. editor:me.editor,
  24413. destroy:function () {
  24414. if (this.getDom()) {
  24415. domUtils.remove(this.getDom());
  24416. }
  24417. }
  24418. });
  24419. this.subMenu.addListener("postRenderAfter", function () {
  24420. domUtils.on(this.getDom(), "mouseover", function () {
  24421. me.addState('opened');
  24422. });
  24423. });
  24424. } else {
  24425. this.subMenu = new Menu(this.subMenu);
  24426. }
  24427. }
  24428. };
  24429. MenuItem.prototype = {
  24430. label:'',
  24431. subMenu:null,
  24432. ownerMenu:null,
  24433. uiName:'menuitem',
  24434. alwalysHoverable:true,
  24435. getHtmlTpl:function () {
  24436. return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' +
  24437. '<div class="%%-body">' +
  24438. this.renderLabelHtml() +
  24439. '</div>' +
  24440. '</div>';
  24441. },
  24442. postRender:function () {
  24443. var me = this;
  24444. this.addListener('over', function () {
  24445. me.ownerMenu.fireEvent('submenuover', me);
  24446. if (me.subMenu) {
  24447. me.delayShowSubMenu();
  24448. }
  24449. });
  24450. if (this.subMenu) {
  24451. this.getDom().className += ' edui-hassubmenu';
  24452. this.subMenu.render();
  24453. this.addListener('out', function () {
  24454. me.delayHideSubMenu();
  24455. });
  24456. this.subMenu.addListener('over', function () {
  24457. clearTimeout(me._closingTimer);
  24458. me._closingTimer = null;
  24459. me.addState('opened');
  24460. });
  24461. this.ownerMenu.addListener('hide', function () {
  24462. me.hideSubMenu();
  24463. });
  24464. this.ownerMenu.addListener('submenuover', function (t, subMenu) {
  24465. if (subMenu !== me) {
  24466. me.delayHideSubMenu();
  24467. }
  24468. });
  24469. this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide;
  24470. this.subMenu.queryAutoHide = function (el) {
  24471. if (el && uiUtils.contains(me.getDom(), el)) {
  24472. return false;
  24473. }
  24474. return this._bakQueryAutoHide(el);
  24475. };
  24476. }
  24477. this.getDom().style.tabIndex = '-1';
  24478. uiUtils.makeUnselectable(this.getDom());
  24479. this.Stateful_postRender();
  24480. },
  24481. delayShowSubMenu:function () {
  24482. var me = this;
  24483. if (!me.isDisabled()) {
  24484. me.addState('opened');
  24485. clearTimeout(me._showingTimer);
  24486. clearTimeout(me._closingTimer);
  24487. me._closingTimer = null;
  24488. me._showingTimer = setTimeout(function () {
  24489. me.showSubMenu();
  24490. }, 250);
  24491. }
  24492. },
  24493. delayHideSubMenu:function () {
  24494. var me = this;
  24495. if (!me.isDisabled()) {
  24496. me.removeState('opened');
  24497. clearTimeout(me._showingTimer);
  24498. if (!me._closingTimer) {
  24499. me._closingTimer = setTimeout(function () {
  24500. if (!me.hasState('opened')) {
  24501. me.hideSubMenu();
  24502. }
  24503. me._closingTimer = null;
  24504. }, 400);
  24505. }
  24506. }
  24507. },
  24508. renderLabelHtml:function () {
  24509. return '<div class="edui-arrow"></div>' +
  24510. '<div class="edui-box edui-icon"></div>' +
  24511. '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>';
  24512. },
  24513. getStateDom:function () {
  24514. return this.getDom();
  24515. },
  24516. queryAutoHide:function (el) {
  24517. if (this.subMenu && this.hasState('opened')) {
  24518. return this.subMenu.queryAutoHide(el);
  24519. }
  24520. },
  24521. _onClick:function (event, this_) {
  24522. if (this.hasState('disabled')) return;
  24523. if (this.fireEvent('click', event, this_) !== false) {
  24524. if (this.subMenu) {
  24525. this.showSubMenu();
  24526. } else {
  24527. Popup.postHide(event);
  24528. }
  24529. }
  24530. },
  24531. showSubMenu:function () {
  24532. var rect = uiUtils.getClientRect(this.getDom());
  24533. rect.right -= 5;
  24534. rect.left += 2;
  24535. rect.width -= 7;
  24536. rect.top -= 4;
  24537. rect.bottom += 4;
  24538. rect.height += 8;
  24539. this.subMenu.showAnchorRect(rect, true, true);
  24540. },
  24541. hideSubMenu:function () {
  24542. this.subMenu.hide();
  24543. }
  24544. };
  24545. utils.inherits(MenuItem, UIBase);
  24546. utils.extend(MenuItem.prototype, Stateful, true);
  24547. })();
  24548. // ui/combox.js
  24549. ///import core
  24550. ///import uicore
  24551. ///import ui/menu.js
  24552. ///import ui/splitbutton.js
  24553. (function (){
  24554. // todo: menu和item提成通用list
  24555. var utils = baidu.editor.utils,
  24556. uiUtils = baidu.editor.ui.uiUtils,
  24557. Menu = baidu.editor.ui.Menu,
  24558. SplitButton = baidu.editor.ui.SplitButton,
  24559. Combox = baidu.editor.ui.Combox = function (options){
  24560. this.initOptions(options);
  24561. this.initCombox();
  24562. };
  24563. Combox.prototype = {
  24564. uiName: 'combox',
  24565. onbuttonclick:function () {
  24566. this.showPopup();
  24567. },
  24568. initCombox: function (){
  24569. var me = this;
  24570. this.items = this.items || [];
  24571. for (var i=0; i<this.items.length; i++) {
  24572. var item = this.items[i];
  24573. item.uiName = 'listitem';
  24574. item.index = i;
  24575. item.onclick = function (){
  24576. me.selectByIndex(this.index);
  24577. };
  24578. }
  24579. this.popup = new Menu({
  24580. items: this.items,
  24581. uiName: 'list',
  24582. editor:this.editor,
  24583. captureWheel: true,
  24584. combox: this
  24585. });
  24586. this.initSplitButton();
  24587. },
  24588. _SplitButton_postRender: SplitButton.prototype.postRender,
  24589. postRender: function (){
  24590. this._SplitButton_postRender();
  24591. this.setLabel(this.label || '');
  24592. this.setValue(this.initValue || '');
  24593. },
  24594. showPopup: function (){
  24595. var rect = uiUtils.getClientRect(this.getDom());
  24596. rect.top += 1;
  24597. rect.bottom -= 1;
  24598. rect.height -= 2;
  24599. this.popup.showAnchorRect(rect);
  24600. },
  24601. getValue: function (){
  24602. return this.value;
  24603. },
  24604. setValue: function (value){
  24605. var index = this.indexByValue(value);
  24606. if (index != -1) {
  24607. this.selectedIndex = index;
  24608. this.setLabel(this.items[index].label);
  24609. this.value = this.items[index].value;
  24610. } else {
  24611. this.selectedIndex = -1;
  24612. this.setLabel(this.getLabelForUnknowValue(value));
  24613. this.value = value;
  24614. }
  24615. },
  24616. setLabel: function (label){
  24617. this.getDom('button_body').innerHTML = label;
  24618. this.label = label;
  24619. },
  24620. getLabelForUnknowValue: function (value){
  24621. return value;
  24622. },
  24623. indexByValue: function (value){
  24624. for (var i=0; i<this.items.length; i++) {
  24625. if (value == this.items[i].value) {
  24626. return i;
  24627. }
  24628. }
  24629. return -1;
  24630. },
  24631. getItem: function (index){
  24632. return this.items[index];
  24633. },
  24634. selectByIndex: function (index){
  24635. if (index < this.items.length && this.fireEvent('select', index) !== false) {
  24636. this.selectedIndex = index;
  24637. this.value = this.items[index].value;
  24638. this.setLabel(this.items[index].label);
  24639. }
  24640. }
  24641. };
  24642. utils.inherits(Combox, SplitButton);
  24643. })();
  24644. // ui/dialog.js
  24645. ///import core
  24646. ///import uicore
  24647. ///import ui/mask.js
  24648. ///import ui/button.js
  24649. (function (){
  24650. var utils = baidu.editor.utils,
  24651. domUtils = baidu.editor.dom.domUtils,
  24652. uiUtils = baidu.editor.ui.uiUtils,
  24653. Mask = baidu.editor.ui.Mask,
  24654. UIBase = baidu.editor.ui.UIBase,
  24655. Button = baidu.editor.ui.Button,
  24656. Dialog = baidu.editor.ui.Dialog = function (options){
  24657. if(options.name){
  24658. var name = options.name;
  24659. var cssRules = options.cssRules;
  24660. if(!options.className){
  24661. options.className = 'edui-for-' + name;
  24662. }
  24663. if(cssRules){
  24664. options.cssRules = '.edui-default .edui-for-'+ name +' .edui-dialog-content {'+ cssRules +'}'
  24665. }
  24666. }
  24667. this.initOptions(utils.extend({
  24668. autoReset: true,
  24669. draggable: true,
  24670. onok: function (){},
  24671. oncancel: function (){},
  24672. onclose: function (t, ok){
  24673. return ok ? this.onok() : this.oncancel();
  24674. },
  24675. //是否控制dialog中的scroll事件, 默认为不阻止
  24676. holdScroll: false
  24677. },options));
  24678. this.initDialog();
  24679. };
  24680. var modalMask;
  24681. var dragMask;
  24682. var activeDialog;
  24683. Dialog.prototype = {
  24684. draggable: false,
  24685. uiName: 'dialog',
  24686. initDialog: function (){
  24687. var me = this,
  24688. theme=this.editor.options.theme;
  24689. if(this.cssRules){
  24690. utils.cssRule('edui-customize-'+this.name+'-style',this.cssRules);
  24691. }
  24692. this.initUIBase();
  24693. this.modalMask = (modalMask || (modalMask = new Mask({
  24694. className: 'edui-dialog-modalmask',
  24695. theme:theme,
  24696. onclick: function (){
  24697. activeDialog && activeDialog.close(false);
  24698. }
  24699. })));
  24700. this.dragMask = (dragMask || (dragMask = new Mask({
  24701. className: 'edui-dialog-dragmask',
  24702. theme:theme
  24703. })));
  24704. this.closeButton = new Button({
  24705. className: 'edui-dialog-closebutton',
  24706. title: me.closeDialog,
  24707. theme:theme,
  24708. onclick: function (){
  24709. me.close(false);
  24710. }
  24711. });
  24712. this.fullscreen && this.initResizeEvent();
  24713. if (this.buttons) {
  24714. for (var i=0; i<this.buttons.length; i++) {
  24715. if (!(this.buttons[i] instanceof Button)) {
  24716. this.buttons[i] = new Button(utils.extend(this.buttons[i],{
  24717. editor : this.editor
  24718. },true));
  24719. }
  24720. }
  24721. }
  24722. },
  24723. initResizeEvent: function () {
  24724. var me = this;
  24725. domUtils.on( window, "resize", function () {
  24726. if ( me._hidden || me._hidden === undefined ) {
  24727. return;
  24728. }
  24729. if ( me.__resizeTimer ) {
  24730. window.clearTimeout( me.__resizeTimer );
  24731. }
  24732. me.__resizeTimer = window.setTimeout( function () {
  24733. me.__resizeTimer = null;
  24734. var dialogWrapNode = me.getDom(),
  24735. contentNode = me.getDom('content'),
  24736. wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24737. contentRect = UE.ui.uiUtils.getClientRect( contentNode ),
  24738. vpRect = uiUtils.getViewportRect();
  24739. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24740. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24741. dialogWrapNode.style.width = vpRect.width + "px";
  24742. dialogWrapNode.style.height = vpRect.height + "px";
  24743. me.fireEvent( "resize" );
  24744. }, 100 );
  24745. } );
  24746. },
  24747. fitSize: function (){
  24748. var popBodyEl = this.getDom('body');
  24749. // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) {
  24750. // uiUtils.removeStyle(popBodyEl, 'width');
  24751. // uiUtils.removeStyle(popBodyEl, 'height');
  24752. // }
  24753. var size = this.mesureSize();
  24754. popBodyEl.style.width = size.width + 'px';
  24755. popBodyEl.style.height = size.height + 'px';
  24756. return size;
  24757. },
  24758. safeSetOffset: function (offset){
  24759. var me = this;
  24760. var el = me.getDom();
  24761. var vpRect = uiUtils.getViewportRect();
  24762. var rect = uiUtils.getClientRect(el);
  24763. var left = offset.left;
  24764. if (left + rect.width > vpRect.right) {
  24765. left = vpRect.right - rect.width;
  24766. }
  24767. var top = offset.top;
  24768. if (top + rect.height > vpRect.bottom) {
  24769. top = vpRect.bottom - rect.height;
  24770. }
  24771. el.style.left = Math.max(left, 0) + 'px';
  24772. el.style.top = Math.max(top, 0) + 'px';
  24773. },
  24774. showAtCenter: function (){
  24775. var vpRect = uiUtils.getViewportRect();
  24776. if ( !this.fullscreen ) {
  24777. this.getDom().style.display = '';
  24778. var popSize = this.fitSize();
  24779. var titleHeight = this.getDom('titlebar').offsetHeight | 0;
  24780. var left = vpRect.width / 2 - popSize.width / 2;
  24781. var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight;
  24782. var popEl = this.getDom();
  24783. this.safeSetOffset({
  24784. left: Math.max(left | 0, 0),
  24785. top: Math.max(top | 0, 0)
  24786. });
  24787. if (!domUtils.hasClass(popEl, 'edui-state-centered')) {
  24788. popEl.className += ' edui-state-centered';
  24789. }
  24790. } else {
  24791. var dialogWrapNode = this.getDom(),
  24792. contentNode = this.getDom('content');
  24793. dialogWrapNode.style.display = "block";
  24794. var wrapRect = UE.ui.uiUtils.getClientRect( dialogWrapNode ),
  24795. contentRect = UE.ui.uiUtils.getClientRect( contentNode );
  24796. dialogWrapNode.style.left = "-100000px";
  24797. contentNode.style.width = ( vpRect.width - wrapRect.width + contentRect.width ) + "px";
  24798. contentNode.style.height = ( vpRect.height - wrapRect.height + contentRect.height ) + "px";
  24799. dialogWrapNode.style.width = vpRect.width + "px";
  24800. dialogWrapNode.style.height = vpRect.height + "px";
  24801. dialogWrapNode.style.left = 0;
  24802. //保存环境的overflow值
  24803. this._originalContext = {
  24804. html: {
  24805. overflowX: document.documentElement.style.overflowX,
  24806. overflowY: document.documentElement.style.overflowY
  24807. },
  24808. body: {
  24809. overflowX: document.body.style.overflowX,
  24810. overflowY: document.body.style.overflowY
  24811. }
  24812. };
  24813. document.documentElement.style.overflowX = 'hidden';
  24814. document.documentElement.style.overflowY = 'hidden';
  24815. document.body.style.overflowX = 'hidden';
  24816. document.body.style.overflowY = 'hidden';
  24817. }
  24818. this._show();
  24819. },
  24820. getContentHtml: function (){
  24821. var contentHtml = '';
  24822. if (typeof this.content == 'string') {
  24823. contentHtml = this.content;
  24824. } else if (this.iframeUrl) {
  24825. contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id +
  24826. '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>';
  24827. }
  24828. return contentHtml;
  24829. },
  24830. getHtmlTpl: function (){
  24831. var footHtml = '';
  24832. if (this.buttons) {
  24833. var buff = [];
  24834. for (var i=0; i<this.buttons.length; i++) {
  24835. buff[i] = this.buttons[i].renderHtml();
  24836. }
  24837. footHtml = '<div class="%%-foot">' +
  24838. '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' +
  24839. '</div>';
  24840. }
  24841. return '<div id="##" class="%%"><div '+ ( !this.fullscreen ? 'class="%%"' : 'class="%%-wrap edui-dialog-fullscreen-flag"' ) +'><div id="##_body" class="%%-body">' +
  24842. '<div class="%%-shadow"></div>' +
  24843. '<div id="##_titlebar" class="%%-titlebar">' +
  24844. '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' +
  24845. '<span class="%%-caption">' + (this.title || '') + '</span>' +
  24846. '</div>' +
  24847. this.closeButton.renderHtml() +
  24848. '</div>' +
  24849. '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' +
  24850. footHtml +
  24851. '</div></div></div>';
  24852. },
  24853. postRender: function (){
  24854. // todo: 保持居中/记住上次关闭位置选项
  24855. if (!this.modalMask.getDom()) {
  24856. this.modalMask.render();
  24857. this.modalMask.hide();
  24858. }
  24859. if (!this.dragMask.getDom()) {
  24860. this.dragMask.render();
  24861. this.dragMask.hide();
  24862. }
  24863. var me = this;
  24864. this.addListener('show', function (){
  24865. me.modalMask.show(this.getDom().style.zIndex - 2);
  24866. });
  24867. this.addListener('hide', function (){
  24868. me.modalMask.hide();
  24869. });
  24870. if (this.buttons) {
  24871. for (var i=0; i<this.buttons.length; i++) {
  24872. this.buttons[i].postRender();
  24873. }
  24874. }
  24875. domUtils.on(window, 'resize', function (){
  24876. setTimeout(function (){
  24877. if (!me.isHidden()) {
  24878. me.safeSetOffset(uiUtils.getClientRect(me.getDom()));
  24879. }
  24880. });
  24881. });
  24882. //hold住scroll事件,防止dialog的滚动影响页面
  24883. // if( this.holdScroll ) {
  24884. //
  24885. // if( !me.iframeUrl ) {
  24886. // domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24887. // domUtils.preventDefault(e);
  24888. // } );
  24889. // } else {
  24890. // me.addListener('dialogafterreset', function(){
  24891. // window.setTimeout(function(){
  24892. // var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow;
  24893. //
  24894. // if( browser.ie ) {
  24895. //
  24896. // var timer = window.setInterval(function(){
  24897. //
  24898. // if( iframeWindow.document && iframeWindow.document.body ) {
  24899. // window.clearInterval( timer );
  24900. // timer = null;
  24901. // domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24902. // domUtils.preventDefault(e);
  24903. // } );
  24904. // }
  24905. //
  24906. // }, 100);
  24907. //
  24908. // } else {
  24909. // domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){
  24910. // domUtils.preventDefault(e);
  24911. // } );
  24912. // }
  24913. //
  24914. // }, 1);
  24915. // });
  24916. // }
  24917. //
  24918. // }
  24919. this._hide();
  24920. },
  24921. mesureSize: function (){
  24922. var body = this.getDom('body');
  24923. var width = uiUtils.getClientRect(this.getDom('content')).width;
  24924. var dialogBodyStyle = body.style;
  24925. dialogBodyStyle.width = width;
  24926. return uiUtils.getClientRect(body);
  24927. },
  24928. _onTitlebarMouseDown: function (evt, el){
  24929. if (this.draggable) {
  24930. var rect;
  24931. var vpRect = uiUtils.getViewportRect();
  24932. var me = this;
  24933. uiUtils.startDrag(evt, {
  24934. ondragstart: function (){
  24935. rect = uiUtils.getClientRect(me.getDom());
  24936. me.getDom('contmask').style.visibility = 'visible';
  24937. me.dragMask.show(me.getDom().style.zIndex - 1);
  24938. },
  24939. ondragmove: function (x, y){
  24940. var left = rect.left + x;
  24941. var top = rect.top + y;
  24942. me.safeSetOffset({
  24943. left: left,
  24944. top: top
  24945. });
  24946. },
  24947. ondragstop: function (){
  24948. me.getDom('contmask').style.visibility = 'hidden';
  24949. domUtils.removeClasses(me.getDom(), ['edui-state-centered']);
  24950. me.dragMask.hide();
  24951. }
  24952. });
  24953. }
  24954. },
  24955. reset: function (){
  24956. this.getDom('content').innerHTML = this.getContentHtml();
  24957. this.fireEvent('dialogafterreset');
  24958. },
  24959. _show: function (){
  24960. if (this._hidden) {
  24961. this.getDom().style.display = '';
  24962. //要高过编辑器的zindxe
  24963. this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10);
  24964. this._hidden = false;
  24965. this.fireEvent('show');
  24966. baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4;
  24967. }
  24968. },
  24969. isHidden: function (){
  24970. return this._hidden;
  24971. },
  24972. _hide: function (){
  24973. if (!this._hidden) {
  24974. var wrapNode = this.getDom();
  24975. wrapNode.style.display = 'none';
  24976. wrapNode.style.zIndex = '';
  24977. wrapNode.style.width = '';
  24978. wrapNode.style.height = '';
  24979. this._hidden = true;
  24980. this.fireEvent('hide');
  24981. }
  24982. },
  24983. open: function (){
  24984. if (this.autoReset) {
  24985. //有可能还没有渲染
  24986. try{
  24987. this.reset();
  24988. }catch(e){
  24989. this.render();
  24990. this.open()
  24991. }
  24992. }
  24993. this.showAtCenter();
  24994. if (this.iframeUrl) {
  24995. try {
  24996. this.getDom('iframe').focus();
  24997. } catch(ex){}
  24998. }
  24999. activeDialog = this;
  25000. },
  25001. _onCloseButtonClick: function (evt, el){
  25002. this.close(false);
  25003. },
  25004. close: function (ok){
  25005. if (this.fireEvent('close', ok) !== false) {
  25006. //还原环境
  25007. if ( this.fullscreen ) {
  25008. document.documentElement.style.overflowX = this._originalContext.html.overflowX;
  25009. document.documentElement.style.overflowY = this._originalContext.html.overflowY;
  25010. document.body.style.overflowX = this._originalContext.body.overflowX;
  25011. document.body.style.overflowY = this._originalContext.body.overflowY;
  25012. delete this._originalContext;
  25013. }
  25014. this._hide();
  25015. //销毁content
  25016. var content = this.getDom('content');
  25017. var iframe = this.getDom('iframe');
  25018. if (content && iframe) {
  25019. var doc = iframe.contentDocument || iframe.contentWindow.document;
  25020. doc && (doc.body.innerHTML = '');
  25021. domUtils.remove(content);
  25022. }
  25023. }
  25024. }
  25025. };
  25026. utils.inherits(Dialog, UIBase);
  25027. })();
  25028. // ui/menubutton.js
  25029. ///import core
  25030. ///import uicore
  25031. ///import ui/menu.js
  25032. ///import ui/splitbutton.js
  25033. (function (){
  25034. var utils = baidu.editor.utils,
  25035. Menu = baidu.editor.ui.Menu,
  25036. SplitButton = baidu.editor.ui.SplitButton,
  25037. MenuButton = baidu.editor.ui.MenuButton = function (options){
  25038. this.initOptions(options);
  25039. this.initMenuButton();
  25040. };
  25041. MenuButton.prototype = {
  25042. initMenuButton: function (){
  25043. var me = this;
  25044. this.uiName = "menubutton";
  25045. this.popup = new Menu({
  25046. items: me.items,
  25047. className: me.className,
  25048. editor:me.editor
  25049. });
  25050. this.popup.addListener('show', function (){
  25051. var list = this;
  25052. for (var i=0; i<list.items.length; i++) {
  25053. list.items[i].removeState('checked');
  25054. if (list.items[i].value == me._value) {
  25055. list.items[i].addState('checked');
  25056. this.value = me._value;
  25057. }
  25058. }
  25059. });
  25060. this.initSplitButton();
  25061. },
  25062. setValue : function(value){
  25063. this._value = value;
  25064. }
  25065. };
  25066. utils.inherits(MenuButton, SplitButton);
  25067. })();
  25068. // ui/multiMenu.js
  25069. ///import core
  25070. ///import uicore
  25071. ///commands 表情
  25072. (function(){
  25073. var utils = baidu.editor.utils,
  25074. Popup = baidu.editor.ui.Popup,
  25075. SplitButton = baidu.editor.ui.SplitButton,
  25076. MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){
  25077. this.initOptions(options);
  25078. this.initMultiMenu();
  25079. };
  25080. MultiMenuPop.prototype = {
  25081. initMultiMenu: function (){
  25082. var me = this;
  25083. this.popup = new Popup({
  25084. content: '',
  25085. editor : me.editor,
  25086. iframe_rendered: false,
  25087. onshow: function (){
  25088. if (!this.iframe_rendered) {
  25089. this.iframe_rendered = true;
  25090. this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>';
  25091. me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1);
  25092. }
  25093. }
  25094. // canSideUp:false,
  25095. // canSideLeft:false
  25096. });
  25097. this.onbuttonclick = function(){
  25098. this.showPopup();
  25099. };
  25100. this.initSplitButton();
  25101. }
  25102. };
  25103. utils.inherits(MultiMenuPop, SplitButton);
  25104. })();
  25105. // ui/shortcutmenu.js
  25106. (function () {
  25107. var UI = baidu.editor.ui,
  25108. UIBase = UI.UIBase,
  25109. uiUtils = UI.uiUtils,
  25110. utils = baidu.editor.utils,
  25111. domUtils = baidu.editor.dom.domUtils;
  25112. var allMenus = [],//存储所有快捷菜单
  25113. timeID,
  25114. isSubMenuShow = false;//是否有子pop显示
  25115. var ShortCutMenu = UI.ShortCutMenu = function (options) {
  25116. this.initOptions (options);
  25117. this.initShortCutMenu ();
  25118. };
  25119. ShortCutMenu.postHide = hideAllMenu;
  25120. ShortCutMenu.prototype = {
  25121. isHidden : true ,
  25122. SPACE : 5 ,
  25123. initShortCutMenu : function () {
  25124. this.items = this.items || [];
  25125. this.initUIBase ();
  25126. this.initItems ();
  25127. this.initEvent ();
  25128. allMenus.push (this);
  25129. } ,
  25130. initEvent : function () {
  25131. var me = this,
  25132. doc = me.editor.document;
  25133. domUtils.on (doc , "mousemove" , function (e) {
  25134. if (me.isHidden === false) {
  25135. //有pop显示就不隐藏快捷菜单
  25136. if (me.getSubMenuMark () || me.eventType == "contextmenu") return;
  25137. var flag = true,
  25138. el = me.getDom (),
  25139. wt = el.offsetWidth,
  25140. ht = el.offsetHeight,
  25141. distanceX = wt / 2 + me.SPACE,//距离中心X标准
  25142. distanceY = ht / 2,//距离中心Y标准
  25143. x = Math.abs (e.screenX - me.left),//离中心距离横坐标
  25144. y = Math.abs (e.screenY - me.top);//离中心距离纵坐标
  25145. clearTimeout (timeID);
  25146. timeID = setTimeout (function () {
  25147. if (y > 0 && y < distanceY) {
  25148. me.setOpacity (el , "1");
  25149. } else if (y > distanceY && y < distanceY + 70) {
  25150. me.setOpacity (el , "0.5");
  25151. flag = false;
  25152. } else if (y > distanceY + 70 && y < distanceY + 140) {
  25153. me.hide ();
  25154. }
  25155. if (flag && x > 0 && x < distanceX) {
  25156. me.setOpacity (el , "1")
  25157. } else if (x > distanceX && x < distanceX + 70) {
  25158. me.setOpacity (el , "0.5")
  25159. } else if (x > distanceX + 70 && x < distanceX + 140) {
  25160. me.hide ();
  25161. }
  25162. });
  25163. }
  25164. });
  25165. //ie\ff下 mouseout不准
  25166. if (browser.chrome) {
  25167. domUtils.on (doc , "mouseout" , function (e) {
  25168. var relatedTgt = e.relatedTarget || e.toElement;
  25169. if (relatedTgt == null || relatedTgt.tagName == "HTML") {
  25170. me.hide ();
  25171. }
  25172. });
  25173. }
  25174. me.editor.addListener ("afterhidepop" , function () {
  25175. if (!me.isHidden) {
  25176. isSubMenuShow = true;
  25177. }
  25178. });
  25179. } ,
  25180. initItems : function () {
  25181. if (utils.isArray (this.items)) {
  25182. for (var i = 0, len = this.items.length ; i < len ; i++) {
  25183. var item = this.items[i].toLowerCase ();
  25184. if (UI[item]) {
  25185. this.items[i] = new UI[item] (this.editor);
  25186. this.items[i].className += " edui-shortcutsubmenu ";
  25187. }
  25188. }
  25189. }
  25190. } ,
  25191. setOpacity : function (el , value) {
  25192. if (browser.ie && browser.version < 9) {
  25193. el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");"
  25194. } else {
  25195. el.style.opacity = value;
  25196. }
  25197. } ,
  25198. getSubMenuMark : function () {
  25199. isSubMenuShow = false;
  25200. var layerEle = uiUtils.getFixedLayer ();
  25201. var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) {
  25202. return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup")
  25203. });
  25204. for (var i = 0, node ; node = list[i++] ;) {
  25205. if (node.style.display != "none") {
  25206. isSubMenuShow = true;
  25207. }
  25208. }
  25209. return isSubMenuShow;
  25210. } ,
  25211. show : function (e , hasContextmenu) {
  25212. var me = this,
  25213. offset = {},
  25214. el = this.getDom (),
  25215. fixedlayer = uiUtils.getFixedLayer ();
  25216. function setPos (offset) {
  25217. if (offset.left < 0) {
  25218. offset.left = 0;
  25219. }
  25220. if (offset.top < 0) {
  25221. offset.top = 0;
  25222. }
  25223. el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;";
  25224. }
  25225. function setPosByCxtMenu (menu) {
  25226. if (!menu.tagName) {
  25227. menu = menu.getDom ();
  25228. }
  25229. offset.left = parseInt (menu.style.left);
  25230. offset.top = parseInt (menu.style.top);
  25231. offset.top -= el.offsetHeight + 15;
  25232. setPos (offset);
  25233. }
  25234. me.eventType = e.type;
  25235. el.style.cssText = "display:block;left:-9999px";
  25236. if (e.type == "contextmenu" && hasContextmenu) {
  25237. var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0];
  25238. if (menu) {
  25239. setPosByCxtMenu (menu)
  25240. } else {
  25241. me.editor.addListener ("aftershowcontextmenu" , function (type , menu) {
  25242. setPosByCxtMenu (menu);
  25243. });
  25244. }
  25245. } else {
  25246. offset = uiUtils.getViewportOffsetByEvent (e);
  25247. offset.top -= el.offsetHeight + me.SPACE;
  25248. offset.left += me.SPACE + 20;
  25249. setPos (offset);
  25250. me.setOpacity (el , 0.2);
  25251. }
  25252. me.isHidden = false;
  25253. me.left = e.screenX + el.offsetWidth / 2 - me.SPACE;
  25254. me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE;
  25255. if (me.editor) {
  25256. el.style.zIndex = me.editor.container.style.zIndex * 1 + 10;
  25257. fixedlayer.style.zIndex = el.style.zIndex - 1;
  25258. }
  25259. } ,
  25260. hide : function () {
  25261. if (this.getDom ()) {
  25262. this.getDom ().style.display = "none";
  25263. }
  25264. this.isHidden = true;
  25265. } ,
  25266. postRender : function () {
  25267. if (utils.isArray (this.items)) {
  25268. for (var i = 0, item ; item = this.items[i++] ;) {
  25269. item.postRender ();
  25270. }
  25271. }
  25272. } ,
  25273. getHtmlTpl : function () {
  25274. var buff;
  25275. if (utils.isArray (this.items)) {
  25276. buff = [];
  25277. for (var i = 0 ; i < this.items.length ; i++) {
  25278. buff[i] = this.items[i].renderHtml ();
  25279. }
  25280. buff = buff.join ("");
  25281. } else {
  25282. buff = this.items;
  25283. }
  25284. return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' +
  25285. buff +
  25286. '</div>';
  25287. }
  25288. };
  25289. utils.inherits (ShortCutMenu , UIBase);
  25290. function hideAllMenu (e) {
  25291. var tgt = e.target || e.srcElement,
  25292. cur = domUtils.findParent (tgt , function (node) {
  25293. return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup");
  25294. } , true);
  25295. if (!cur) {
  25296. for (var i = 0, menu ; menu = allMenus[i++] ;) {
  25297. menu.hide ()
  25298. }
  25299. }
  25300. }
  25301. domUtils.on (document , 'mousedown' , function (e) {
  25302. hideAllMenu (e);
  25303. });
  25304. domUtils.on (window , 'scroll' , function (e) {
  25305. hideAllMenu (e);
  25306. });
  25307. }) ();
  25308. // ui/breakline.js
  25309. (function (){
  25310. var utils = baidu.editor.utils,
  25311. UIBase = baidu.editor.ui.UIBase,
  25312. Breakline = baidu.editor.ui.Breakline = function (options){
  25313. this.initOptions(options);
  25314. this.initSeparator();
  25315. };
  25316. Breakline.prototype = {
  25317. uiName: 'Breakline',
  25318. initSeparator: function (){
  25319. this.initUIBase();
  25320. },
  25321. getHtmlTpl: function (){
  25322. return '<br/>';
  25323. }
  25324. };
  25325. utils.inherits(Breakline, UIBase);
  25326. })();
  25327. // ui/message.js
  25328. ///import core
  25329. ///import uicore
  25330. (function () {
  25331. var utils = baidu.editor.utils,
  25332. domUtils = baidu.editor.dom.domUtils,
  25333. UIBase = baidu.editor.ui.UIBase,
  25334. Message = baidu.editor.ui.Message = function (options){
  25335. this.initOptions(options);
  25336. this.initMessage();
  25337. };
  25338. Message.prototype = {
  25339. initMessage: function (){
  25340. this.initUIBase();
  25341. },
  25342. getHtmlTpl: function (){
  25343. return '<div id="##" class="edui-message %%">' +
  25344. ' <div id="##_closer" class="edui-message-closer">×</div>' +
  25345. ' <div id="##_body" class="edui-message-body edui-message-type-info">' +
  25346. ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="about:blank"></iframe>' +
  25347. ' <div class="edui-shadow"></div>' +
  25348. ' <div id="##_content" class="edui-message-content">' +
  25349. ' </div>' +
  25350. ' </div>' +
  25351. '</div>';
  25352. },
  25353. reset: function(opt){
  25354. var me = this;
  25355. if (!opt.keepshow) {
  25356. clearTimeout(this.timer);
  25357. me.timer = setTimeout(function(){
  25358. me.hide();
  25359. }, opt.timeout || 4000);
  25360. }
  25361. opt.content !== undefined && me.setContent(opt.content);
  25362. opt.type !== undefined && me.setType(opt.type);
  25363. me.show();
  25364. },
  25365. postRender: function(){
  25366. var me = this,
  25367. closer = this.getDom('closer');
  25368. closer && domUtils.on(closer, 'click', function(){
  25369. me.hide();
  25370. });
  25371. },
  25372. setContent: function(content){
  25373. this.getDom('content').innerHTML = content;
  25374. },
  25375. setType: function(type){
  25376. type = type || 'info';
  25377. var body = this.getDom('body');
  25378. body.className = body.className.replace(/edui-message-type-[\w-]+/, 'edui-message-type-' + type);
  25379. },
  25380. getContent: function(){
  25381. return this.getDom('content').innerHTML;
  25382. },
  25383. getType: function(){
  25384. var arr = this.getDom('body').match(/edui-message-type-([\w-]+)/);
  25385. return arr ? arr[1]:'';
  25386. },
  25387. show: function (){
  25388. this.getDom().style.display = 'block';
  25389. },
  25390. hide: function (){
  25391. var dom = this.getDom();
  25392. if (dom) {
  25393. dom.style.display = 'none';
  25394. dom.parentNode && dom.parentNode.removeChild(dom);
  25395. }
  25396. }
  25397. };
  25398. utils.inherits(Message, UIBase);
  25399. })();
  25400. // adapter/editorui.js
  25401. //ui跟编辑器的适配層
  25402. //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置
  25403. //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化
  25404. (function () {
  25405. var utils = baidu.editor.utils;
  25406. var editorui = baidu.editor.ui;
  25407. var _Dialog = editorui.Dialog;
  25408. editorui.buttons = {};
  25409. editorui.Dialog = function (options) {
  25410. var dialog = new _Dialog(options);
  25411. dialog.addListener('hide', function () {
  25412. if (dialog.editor) {
  25413. var editor = dialog.editor;
  25414. try {
  25415. if (browser.gecko) {
  25416. var y = editor.window.scrollY,
  25417. x = editor.window.scrollX;
  25418. editor.body.focus();
  25419. editor.window.scrollTo(x, y);
  25420. } else {
  25421. editor.focus();
  25422. }
  25423. } catch (ex) {
  25424. }
  25425. }
  25426. });
  25427. return dialog;
  25428. };
  25429. var iframeUrlMap = {
  25430. 'anchor':'~/dialogs/anchor/anchor.html',
  25431. 'insertimage':'~/dialogs/image/image.html',
  25432. 'link':'~/dialogs/link/link.html',
  25433. 'spechars':'~/dialogs/spechars/spechars.html',
  25434. 'searchreplace':'~/dialogs/searchreplace/searchreplace.html',
  25435. 'map':'~/dialogs/map/map.html',
  25436. 'gmap':'~/dialogs/gmap/gmap.html',
  25437. 'insertvideo':'~/dialogs/video/video.html',
  25438. 'help':'~/dialogs/help/help.html',
  25439. 'preview':'~/dialogs/preview/preview.html',
  25440. 'emotion':'~/dialogs/emotion/emotion.html',
  25441. 'wordimage':'~/dialogs/wordimage/wordimage.html',
  25442. 'attachment':'~/dialogs/attachment/attachment.html',
  25443. 'insertframe':'~/dialogs/insertframe/insertframe.html',
  25444. 'edittip':'~/dialogs/table/edittip.html',
  25445. 'edittable':'~/dialogs/table/edittable.html',
  25446. 'edittd':'~/dialogs/table/edittd.html',
  25447. 'webapp':'~/dialogs/webapp/webapp.html',
  25448. 'snapscreen':'~/dialogs/snapscreen/snapscreen.html',
  25449. 'scrawl':'~/dialogs/scrawl/scrawl.html',
  25450. 'music':'~/dialogs/music/music.html',
  25451. 'template':'~/dialogs/template/template.html',
  25452. 'background':'~/dialogs/background/background.html',
  25453. 'charts': '~/dialogs/charts/charts.html'
  25454. };
  25455. //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起
  25456. var btnCmds = ['undo', 'redo', 'formatmatch',
  25457. 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase',
  25458. 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent',
  25459. 'blockquote', 'pasteplain', 'pagebreak',
  25460. 'selectall', 'print','horizontal', 'removeformat', 'time', 'date', 'unlink',
  25461. 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow',
  25462. 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable', 'drafts'];
  25463. for (var i = 0, ci; ci = btnCmds[i++];) {
  25464. ci = ci.toLowerCase();
  25465. editorui[ci] = function (cmd) {
  25466. return function (editor) {
  25467. var ui = new editorui.Button({
  25468. className:'edui-for-' + cmd,
  25469. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25470. onclick:function () {
  25471. editor.execCommand(cmd);
  25472. },
  25473. theme:editor.options.theme,
  25474. showText:false
  25475. });
  25476. editorui.buttons[cmd] = ui;
  25477. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25478. var state = editor.queryCommandState(cmd);
  25479. if (state == -1) {
  25480. ui.setDisabled(true);
  25481. ui.setChecked(false);
  25482. } else {
  25483. if (!uiReady) {
  25484. ui.setDisabled(false);
  25485. ui.setChecked(state);
  25486. }
  25487. }
  25488. });
  25489. return ui;
  25490. };
  25491. }(ci);
  25492. }
  25493. //清除文档
  25494. editorui.cleardoc = function (editor) {
  25495. var ui = new editorui.Button({
  25496. className:'edui-for-cleardoc',
  25497. title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '',
  25498. theme:editor.options.theme,
  25499. onclick:function () {
  25500. if (confirm(editor.getLang("confirmClear"))) {
  25501. editor.execCommand('cleardoc');
  25502. }
  25503. }
  25504. });
  25505. editorui.buttons["cleardoc"] = ui;
  25506. editor.addListener('selectionchange', function () {
  25507. ui.setDisabled(editor.queryCommandState('cleardoc') == -1);
  25508. });
  25509. return ui;
  25510. };
  25511. //排版,图片排版,文字方向
  25512. var typeset = {
  25513. 'justify':['left', 'right', 'center', 'justify'],
  25514. 'imagefloat':['none', 'left', 'center', 'right'],
  25515. 'directionality':['ltr', 'rtl']
  25516. };
  25517. for (var p in typeset) {
  25518. (function (cmd, val) {
  25519. for (var i = 0, ci; ci = val[i++];) {
  25520. (function (cmd2) {
  25521. editorui[cmd.replace('float', '') + cmd2] = function (editor) {
  25522. var ui = new editorui.Button({
  25523. className:'edui-for-' + cmd.replace('float', '') + cmd2,
  25524. title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '',
  25525. theme:editor.options.theme,
  25526. onclick:function () {
  25527. editor.execCommand(cmd, cmd2);
  25528. }
  25529. });
  25530. editorui.buttons[cmd] = ui;
  25531. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25532. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25533. ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady);
  25534. });
  25535. return ui;
  25536. };
  25537. })(ci)
  25538. }
  25539. })(p, typeset[p])
  25540. }
  25541. //字体颜色和背景颜色
  25542. for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) {
  25543. editorui[ci] = function (cmd) {
  25544. return function (editor) {
  25545. var ui = new editorui.ColorButton({
  25546. className:'edui-for-' + cmd,
  25547. color:'default',
  25548. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '',
  25549. editor:editor,
  25550. onpickcolor:function (t, color) {
  25551. editor.execCommand(cmd, color);
  25552. },
  25553. onpicknocolor:function () {
  25554. editor.execCommand(cmd, 'default');
  25555. this.setColor('transparent');
  25556. this.color = 'default';
  25557. },
  25558. onbuttonclick:function () {
  25559. editor.execCommand(cmd, this.color);
  25560. }
  25561. });
  25562. editorui.buttons[cmd] = ui;
  25563. editor.addListener('selectionchange', function () {
  25564. ui.setDisabled(editor.queryCommandState(cmd) == -1);
  25565. });
  25566. return ui;
  25567. };
  25568. }(ci);
  25569. }
  25570. var dialogBtns = {
  25571. noOk:['searchreplace', 'help', 'spechars', 'webapp','preview'],
  25572. ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage',
  25573. 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background', 'charts']
  25574. };
  25575. for (var p in dialogBtns) {
  25576. (function (type, vals) {
  25577. for (var i = 0, ci; ci = vals[i++];) {
  25578. //todo opera下存在问题
  25579. if (browser.opera && ci === "searchreplace") {
  25580. continue;
  25581. }
  25582. (function (cmd) {
  25583. editorui[cmd] = function (editor, iframeUrl, title) {
  25584. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd];
  25585. title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '';
  25586. var dialog;
  25587. //没有iframeUrl不创建dialog
  25588. if (iframeUrl) {
  25589. dialog = new editorui.Dialog(utils.extend({
  25590. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25591. editor:editor,
  25592. className:'edui-for-' + cmd,
  25593. title:title,
  25594. holdScroll: cmd === 'insertimage',
  25595. fullscreen: /charts|preview/.test(cmd),
  25596. closeDialog:editor.getLang("closeDialog")
  25597. }, type == 'ok' ? {
  25598. buttons:[
  25599. {
  25600. className:'edui-okbutton',
  25601. label:editor.getLang("ok"),
  25602. editor:editor,
  25603. onclick:function () {
  25604. dialog.close(true);
  25605. }
  25606. },
  25607. {
  25608. className:'edui-cancelbutton',
  25609. label:editor.getLang("cancel"),
  25610. editor:editor,
  25611. onclick:function () {
  25612. dialog.close(false);
  25613. }
  25614. }
  25615. ]
  25616. } : {}));
  25617. editor.ui._dialogs[cmd + "Dialog"] = dialog;
  25618. }
  25619. var ui = new editorui.Button({
  25620. className:'edui-for-' + cmd,
  25621. title:title,
  25622. onclick:function () {
  25623. if (dialog) {
  25624. switch (cmd) {
  25625. case "wordimage":
  25626. var images = editor.execCommand("wordimage");
  25627. if (images && images.length) {
  25628. dialog.render();
  25629. dialog.open();
  25630. }
  25631. break;
  25632. case "scrawl":
  25633. if (editor.queryCommandState("scrawl") != -1) {
  25634. dialog.render();
  25635. dialog.open();
  25636. }
  25637. break;
  25638. default:
  25639. dialog.render();
  25640. dialog.open();
  25641. }
  25642. }
  25643. },
  25644. theme:editor.options.theme,
  25645. disabled:(cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1) || ( cmd == 'charts' )
  25646. });
  25647. editorui.buttons[cmd] = ui;
  25648. editor.addListener('selectionchange', function () {
  25649. //只存在于右键菜单而无工具栏按钮的ui不需要检测状态
  25650. var unNeedCheckState = {'edittable':1};
  25651. if (cmd in unNeedCheckState)return;
  25652. var state = editor.queryCommandState(cmd);
  25653. if (ui.getDom()) {
  25654. ui.setDisabled(state == -1);
  25655. ui.setChecked(state);
  25656. }
  25657. });
  25658. return ui;
  25659. };
  25660. })(ci.toLowerCase())
  25661. }
  25662. })(p, dialogBtns[p]);
  25663. }
  25664. editorui.snapscreen = function (editor, iframeUrl, title) {
  25665. title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || '';
  25666. var ui = new editorui.Button({
  25667. className:'edui-for-snapscreen',
  25668. title:title,
  25669. onclick:function () {
  25670. editor.execCommand("snapscreen");
  25671. },
  25672. theme:editor.options.theme
  25673. });
  25674. editorui.buttons['snapscreen'] = ui;
  25675. iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"];
  25676. if (iframeUrl) {
  25677. var dialog = new editorui.Dialog({
  25678. iframeUrl:editor.ui.mapUrl(iframeUrl),
  25679. editor:editor,
  25680. className:'edui-for-snapscreen',
  25681. title:title,
  25682. buttons:[
  25683. {
  25684. className:'edui-okbutton',
  25685. label:editor.getLang("ok"),
  25686. editor:editor,
  25687. onclick:function () {
  25688. dialog.close(true);
  25689. }
  25690. },
  25691. {
  25692. className:'edui-cancelbutton',
  25693. label:editor.getLang("cancel"),
  25694. editor:editor,
  25695. onclick:function () {
  25696. dialog.close(false);
  25697. }
  25698. }
  25699. ]
  25700. });
  25701. dialog.render();
  25702. editor.ui._dialogs["snapscreenDialog"] = dialog;
  25703. }
  25704. editor.addListener('selectionchange', function () {
  25705. ui.setDisabled(editor.queryCommandState('snapscreen') == -1);
  25706. });
  25707. return ui;
  25708. };
  25709. editorui.insertcode = function (editor, list, title) {
  25710. list = editor.options['insertcode'] || [];
  25711. title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || '';
  25712. // if (!list.length) return;
  25713. var items = [];
  25714. utils.each(list,function(key,val){
  25715. items.push({
  25716. label:key,
  25717. value:val,
  25718. theme:editor.options.theme,
  25719. renderLabelHtml:function () {
  25720. return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>';
  25721. }
  25722. });
  25723. });
  25724. var ui = new editorui.Combox({
  25725. editor:editor,
  25726. items:items,
  25727. onselect:function (t, index) {
  25728. editor.execCommand('insertcode', this.items[index].value);
  25729. },
  25730. onbuttonclick:function () {
  25731. this.showPopup();
  25732. },
  25733. title:title,
  25734. initValue:title,
  25735. className:'edui-for-insertcode',
  25736. indexByValue:function (value) {
  25737. if (value) {
  25738. for (var i = 0, ci; ci = this.items[i]; i++) {
  25739. if (ci.value.indexOf(value) != -1)
  25740. return i;
  25741. }
  25742. }
  25743. return -1;
  25744. }
  25745. });
  25746. editorui.buttons['insertcode'] = ui;
  25747. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25748. if (!uiReady) {
  25749. var state = editor.queryCommandState('insertcode');
  25750. if (state == -1) {
  25751. ui.setDisabled(true);
  25752. } else {
  25753. ui.setDisabled(false);
  25754. var value = editor.queryCommandValue('insertcode');
  25755. if(!value){
  25756. ui.setValue(title);
  25757. return;
  25758. }
  25759. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25760. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25761. ui.setValue(value);
  25762. }
  25763. }
  25764. });
  25765. return ui;
  25766. };
  25767. editorui.fontfamily = function (editor, list, title) {
  25768. list = editor.options['fontfamily'] || [];
  25769. title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || '';
  25770. if (!list.length) return;
  25771. for (var i = 0, ci, items = []; ci = list[i]; i++) {
  25772. var langLabel = editor.getLang('fontfamily')[ci.name] || "";
  25773. (function (key, val) {
  25774. items.push({
  25775. label:key,
  25776. value:val,
  25777. theme:editor.options.theme,
  25778. renderLabelHtml:function () {
  25779. return '<div class="edui-label %%-label" style="font-family:' +
  25780. utils.unhtml(this.value) + '">' + (this.label || '') + '</div>';
  25781. }
  25782. });
  25783. })(ci.label || langLabel, ci.val)
  25784. }
  25785. var ui = new editorui.Combox({
  25786. editor:editor,
  25787. items:items,
  25788. onselect:function (t, index) {
  25789. editor.execCommand('FontFamily', this.items[index].value);
  25790. },
  25791. onbuttonclick:function () {
  25792. this.showPopup();
  25793. },
  25794. title:title,
  25795. initValue:title,
  25796. className:'edui-for-fontfamily',
  25797. indexByValue:function (value) {
  25798. if (value) {
  25799. for (var i = 0, ci; ci = this.items[i]; i++) {
  25800. if (ci.value.indexOf(value) != -1)
  25801. return i;
  25802. }
  25803. }
  25804. return -1;
  25805. }
  25806. });
  25807. editorui.buttons['fontfamily'] = ui;
  25808. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25809. if (!uiReady) {
  25810. var state = editor.queryCommandState('FontFamily');
  25811. if (state == -1) {
  25812. ui.setDisabled(true);
  25813. } else {
  25814. ui.setDisabled(false);
  25815. var value = editor.queryCommandValue('FontFamily');
  25816. //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号
  25817. value && (value = value.replace(/['"]/g, '').split(',')[0]);
  25818. ui.setValue(value);
  25819. }
  25820. }
  25821. });
  25822. return ui;
  25823. };
  25824. editorui.fontsize = function (editor, list, title) {
  25825. title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || '';
  25826. list = list || editor.options['fontsize'] || [];
  25827. if (!list.length) return;
  25828. var items = [];
  25829. for (var i = 0; i < list.length; i++) {
  25830. var size = list[i] + 'px';
  25831. items.push({
  25832. label:size,
  25833. value:size,
  25834. theme:editor.options.theme,
  25835. renderLabelHtml:function () {
  25836. return '<div class="edui-label %%-label" style="line-height:1;font-size:' +
  25837. this.value + '">' + (this.label || '') + '</div>';
  25838. }
  25839. });
  25840. }
  25841. var ui = new editorui.Combox({
  25842. editor:editor,
  25843. items:items,
  25844. title:title,
  25845. initValue:title,
  25846. onselect:function (t, index) {
  25847. editor.execCommand('FontSize', this.items[index].value);
  25848. },
  25849. onbuttonclick:function () {
  25850. this.showPopup();
  25851. },
  25852. className:'edui-for-fontsize'
  25853. });
  25854. editorui.buttons['fontsize'] = ui;
  25855. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25856. if (!uiReady) {
  25857. var state = editor.queryCommandState('FontSize');
  25858. if (state == -1) {
  25859. ui.setDisabled(true);
  25860. } else {
  25861. ui.setDisabled(false);
  25862. ui.setValue(editor.queryCommandValue('FontSize'));
  25863. }
  25864. }
  25865. });
  25866. return ui;
  25867. };
  25868. editorui.paragraph = function (editor, list, title) {
  25869. title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || '';
  25870. list = editor.options['paragraph'] || [];
  25871. if (utils.isEmptyObject(list)) return;
  25872. var items = [];
  25873. for (var i in list) {
  25874. items.push({
  25875. value:i,
  25876. label:list[i] || editor.getLang("paragraph")[i],
  25877. theme:editor.options.theme,
  25878. renderLabelHtml:function () {
  25879. return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>';
  25880. }
  25881. })
  25882. }
  25883. var ui = new editorui.Combox({
  25884. editor:editor,
  25885. items:items,
  25886. title:title,
  25887. initValue:title,
  25888. className:'edui-for-paragraph',
  25889. onselect:function (t, index) {
  25890. editor.execCommand('Paragraph', this.items[index].value);
  25891. },
  25892. onbuttonclick:function () {
  25893. this.showPopup();
  25894. }
  25895. });
  25896. editorui.buttons['paragraph'] = ui;
  25897. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25898. if (!uiReady) {
  25899. var state = editor.queryCommandState('Paragraph');
  25900. if (state == -1) {
  25901. ui.setDisabled(true);
  25902. } else {
  25903. ui.setDisabled(false);
  25904. var value = editor.queryCommandValue('Paragraph');
  25905. var index = ui.indexByValue(value);
  25906. if (index != -1) {
  25907. ui.setValue(value);
  25908. } else {
  25909. ui.setValue(ui.initValue);
  25910. }
  25911. }
  25912. }
  25913. });
  25914. return ui;
  25915. };
  25916. //自定义标题
  25917. editorui.customstyle = function (editor) {
  25918. var list = editor.options['customstyle'] || [],
  25919. title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || '';
  25920. if (!list.length)return;
  25921. var langCs = editor.getLang('customstyle');
  25922. for (var i = 0, items = [], t; t = list[i++];) {
  25923. (function (t) {
  25924. var ck = {};
  25925. ck.label = t.label ? t.label : langCs[t.name];
  25926. ck.style = t.style;
  25927. ck.className = t.className;
  25928. ck.tag = t.tag;
  25929. items.push({
  25930. label:ck.label,
  25931. value:ck,
  25932. theme:editor.options.theme,
  25933. renderLabelHtml:function () {
  25934. return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "")
  25935. + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">"
  25936. + '</div>';
  25937. }
  25938. });
  25939. })(t);
  25940. }
  25941. var ui = new editorui.Combox({
  25942. editor:editor,
  25943. items:items,
  25944. title:title,
  25945. initValue:title,
  25946. className:'edui-for-customstyle',
  25947. onselect:function (t, index) {
  25948. editor.execCommand('customstyle', this.items[index].value);
  25949. },
  25950. onbuttonclick:function () {
  25951. this.showPopup();
  25952. },
  25953. indexByValue:function (value) {
  25954. for (var i = 0, ti; ti = this.items[i++];) {
  25955. if (ti.label == value) {
  25956. return i - 1
  25957. }
  25958. }
  25959. return -1;
  25960. }
  25961. });
  25962. editorui.buttons['customstyle'] = ui;
  25963. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  25964. if (!uiReady) {
  25965. var state = editor.queryCommandState('customstyle');
  25966. if (state == -1) {
  25967. ui.setDisabled(true);
  25968. } else {
  25969. ui.setDisabled(false);
  25970. var value = editor.queryCommandValue('customstyle');
  25971. var index = ui.indexByValue(value);
  25972. if (index != -1) {
  25973. ui.setValue(value);
  25974. } else {
  25975. ui.setValue(ui.initValue);
  25976. }
  25977. }
  25978. }
  25979. });
  25980. return ui;
  25981. };
  25982. editorui.inserttable = function (editor, iframeUrl, title) {
  25983. title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || '';
  25984. var ui = new editorui.TableButton({
  25985. editor:editor,
  25986. title:title,
  25987. className:'edui-for-inserttable',
  25988. onpicktable:function (t, numCols, numRows) {
  25989. editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1});
  25990. },
  25991. onbuttonclick:function () {
  25992. this.showPopup();
  25993. }
  25994. });
  25995. editorui.buttons['inserttable'] = ui;
  25996. editor.addListener('selectionchange', function () {
  25997. ui.setDisabled(editor.queryCommandState('inserttable') == -1);
  25998. });
  25999. return ui;
  26000. };
  26001. editorui.lineheight = function (editor) {
  26002. var val = editor.options.lineheight || [];
  26003. if (!val.length)return;
  26004. for (var i = 0, ci, items = []; ci = val[i++];) {
  26005. items.push({
  26006. //todo:写死了
  26007. label:ci,
  26008. value:ci,
  26009. theme:editor.options.theme,
  26010. onclick:function () {
  26011. editor.execCommand("lineheight", this.value);
  26012. }
  26013. })
  26014. }
  26015. var ui = new editorui.MenuButton({
  26016. editor:editor,
  26017. className:'edui-for-lineheight',
  26018. title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '',
  26019. items:items,
  26020. onbuttonclick:function () {
  26021. var value = editor.queryCommandValue('LineHeight') || this.value;
  26022. editor.execCommand("LineHeight", value);
  26023. }
  26024. });
  26025. editorui.buttons['lineheight'] = ui;
  26026. editor.addListener('selectionchange', function () {
  26027. var state = editor.queryCommandState('LineHeight');
  26028. if (state == -1) {
  26029. ui.setDisabled(true);
  26030. } else {
  26031. ui.setDisabled(false);
  26032. var value = editor.queryCommandValue('LineHeight');
  26033. value && ui.setValue((value + '').replace(/cm/, ''));
  26034. ui.setChecked(state)
  26035. }
  26036. });
  26037. return ui;
  26038. };
  26039. var rowspacings = ['top', 'bottom'];
  26040. for (var r = 0, ri; ri = rowspacings[r++];) {
  26041. (function (cmd) {
  26042. editorui['rowspacing' + cmd] = function (editor) {
  26043. var val = editor.options['rowspacing' + cmd] || [];
  26044. if (!val.length) return null;
  26045. for (var i = 0, ci, items = []; ci = val[i++];) {
  26046. items.push({
  26047. label:ci,
  26048. value:ci,
  26049. theme:editor.options.theme,
  26050. onclick:function () {
  26051. editor.execCommand("rowspacing", this.value, cmd);
  26052. }
  26053. })
  26054. }
  26055. var ui = new editorui.MenuButton({
  26056. editor:editor,
  26057. className:'edui-for-rowspacing' + cmd,
  26058. title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '',
  26059. items:items,
  26060. onbuttonclick:function () {
  26061. var value = editor.queryCommandValue('rowspacing', cmd) || this.value;
  26062. editor.execCommand("rowspacing", value, cmd);
  26063. }
  26064. });
  26065. editorui.buttons[cmd] = ui;
  26066. editor.addListener('selectionchange', function () {
  26067. var state = editor.queryCommandState('rowspacing', cmd);
  26068. if (state == -1) {
  26069. ui.setDisabled(true);
  26070. } else {
  26071. ui.setDisabled(false);
  26072. var value = editor.queryCommandValue('rowspacing', cmd);
  26073. value && ui.setValue((value + '').replace(/%/, ''));
  26074. ui.setChecked(state)
  26075. }
  26076. });
  26077. return ui;
  26078. }
  26079. })(ri)
  26080. }
  26081. //有序,无序列表
  26082. var lists = ['insertorderedlist', 'insertunorderedlist'];
  26083. for (var l = 0, cl; cl = lists[l++];) {
  26084. (function (cmd) {
  26085. editorui[cmd] = function (editor) {
  26086. var vals = editor.options[cmd],
  26087. _onMenuClick = function () {
  26088. editor.execCommand(cmd, this.value);
  26089. }, items = [];
  26090. for (var i in vals) {
  26091. items.push({
  26092. label:vals[i] || editor.getLang()[cmd][i] || "",
  26093. value:i,
  26094. theme:editor.options.theme,
  26095. onclick:_onMenuClick
  26096. })
  26097. }
  26098. var ui = new editorui.MenuButton({
  26099. editor:editor,
  26100. className:'edui-for-' + cmd,
  26101. title:editor.getLang("labelMap." + cmd) || '',
  26102. 'items':items,
  26103. onbuttonclick:function () {
  26104. var value = editor.queryCommandValue(cmd) || this.value;
  26105. editor.execCommand(cmd, value);
  26106. }
  26107. });
  26108. editorui.buttons[cmd] = ui;
  26109. editor.addListener('selectionchange', function () {
  26110. var state = editor.queryCommandState(cmd);
  26111. if (state == -1) {
  26112. ui.setDisabled(true);
  26113. } else {
  26114. ui.setDisabled(false);
  26115. var value = editor.queryCommandValue(cmd);
  26116. ui.setValue(value);
  26117. ui.setChecked(state)
  26118. }
  26119. });
  26120. return ui;
  26121. };
  26122. })(cl)
  26123. }
  26124. editorui.fullscreen = function (editor, title) {
  26125. title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || '';
  26126. var ui = new editorui.Button({
  26127. className:'edui-for-fullscreen',
  26128. title:title,
  26129. theme:editor.options.theme,
  26130. onclick:function () {
  26131. if (editor.ui) {
  26132. editor.ui.setFullScreen(!editor.ui.isFullScreen());
  26133. }
  26134. this.setChecked(editor.ui.isFullScreen());
  26135. }
  26136. });
  26137. editorui.buttons['fullscreen'] = ui;
  26138. editor.addListener('selectionchange', function () {
  26139. var state = editor.queryCommandState('fullscreen');
  26140. ui.setDisabled(state == -1);
  26141. ui.setChecked(editor.ui.isFullScreen());
  26142. });
  26143. return ui;
  26144. };
  26145. // 表情
  26146. editorui["emotion"] = function (editor, iframeUrl) {
  26147. var cmd = "emotion";
  26148. var ui = new editorui.MultiMenuPop({
  26149. title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '',
  26150. editor:editor,
  26151. className:'edui-for-' + cmd,
  26152. iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd])
  26153. });
  26154. editorui.buttons[cmd] = ui;
  26155. editor.addListener('selectionchange', function () {
  26156. ui.setDisabled(editor.queryCommandState(cmd) == -1)
  26157. });
  26158. return ui;
  26159. };
  26160. editorui.autotypeset = function (editor) {
  26161. var ui = new editorui.AutoTypeSetButton({
  26162. editor:editor,
  26163. title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '',
  26164. className:'edui-for-autotypeset',
  26165. onbuttonclick:function () {
  26166. editor.execCommand('autotypeset')
  26167. }
  26168. });
  26169. editorui.buttons['autotypeset'] = ui;
  26170. editor.addListener('selectionchange', function () {
  26171. ui.setDisabled(editor.queryCommandState('autotypeset') == -1);
  26172. });
  26173. return ui;
  26174. };
  26175. /* 简单上传插件 */
  26176. editorui["simpleupload"] = function (editor) {
  26177. var name = 'simpleupload',
  26178. ui = new editorui.Button({
  26179. className:'edui-for-' + name,
  26180. title:editor.options.labelMap[name] || editor.getLang("labelMap." + name) || '',
  26181. onclick:function () {},
  26182. theme:editor.options.theme,
  26183. showText:false
  26184. });
  26185. editorui.buttons[name] = ui;
  26186. editor.addListener('ready', function() {
  26187. var b = ui.getDom('body'),
  26188. iconSpan = b.children[0];
  26189. editor.fireEvent('simpleuploadbtnready', iconSpan);
  26190. });
  26191. editor.addListener('selectionchange', function (type, causeByUi, uiReady) {
  26192. var state = editor.queryCommandState(name);
  26193. if (state == -1) {
  26194. ui.setDisabled(true);
  26195. ui.setChecked(false);
  26196. } else {
  26197. if (!uiReady) {
  26198. ui.setDisabled(false);
  26199. ui.setChecked(state);
  26200. }
  26201. }
  26202. });
  26203. return ui;
  26204. };
  26205. })();
  26206. // adapter/editor.js
  26207. ///import core
  26208. ///commands 全屏
  26209. ///commandsName FullScreen
  26210. ///commandsTitle 全屏
  26211. (function () {
  26212. var utils = baidu.editor.utils,
  26213. uiUtils = baidu.editor.ui.uiUtils,
  26214. UIBase = baidu.editor.ui.UIBase,
  26215. domUtils = baidu.editor.dom.domUtils;
  26216. var nodeStack = [];
  26217. function EditorUI(options) {
  26218. this.initOptions(options);
  26219. this.initEditorUI();
  26220. }
  26221. EditorUI.prototype = {
  26222. uiName:'editor',
  26223. initEditorUI:function () {
  26224. this.editor.ui = this;
  26225. this._dialogs = {};
  26226. this.initUIBase();
  26227. this._initToolbars();
  26228. var editor = this.editor,
  26229. me = this;
  26230. editor.addListener('ready', function () {
  26231. //提供getDialog方法
  26232. editor.getDialog = function (name) {
  26233. return editor.ui._dialogs[name + "Dialog"];
  26234. };
  26235. domUtils.on(editor.window, 'scroll', function (evt) {
  26236. baidu.editor.ui.Popup.postHide(evt);
  26237. });
  26238. //提供编辑器实时宽高(全屏时宽高不变化)
  26239. editor.ui._actualFrameWidth = editor.options.initialFrameWidth;
  26240. UE.browser.ie && UE.browser.version === 6 && editor.container.ownerDocument.execCommand("BackgroundImageCache", false, true);
  26241. //display bottom-bar label based on config
  26242. if (editor.options.elementPathEnabled) {
  26243. editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>';
  26244. }
  26245. if (editor.options.wordCount) {
  26246. function countFn() {
  26247. setCount(editor,me);
  26248. domUtils.un(editor.document, "click", arguments.callee);
  26249. }
  26250. domUtils.on(editor.document, "click", countFn);
  26251. editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip");
  26252. }
  26253. editor.ui._scale();
  26254. if (editor.options.scaleEnabled) {
  26255. if (editor.autoHeightEnabled) {
  26256. editor.disableAutoHeight();
  26257. }
  26258. me.enableScale();
  26259. } else {
  26260. me.disableScale();
  26261. }
  26262. if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) {
  26263. editor.ui.getDom('elementpath').style.display = "none";
  26264. editor.ui.getDom('wordcount').style.display = "none";
  26265. editor.ui.getDom('scale').style.display = "none";
  26266. }
  26267. if (!editor.selection.isFocus())return;
  26268. editor.fireEvent('selectionchange', false, true);
  26269. });
  26270. editor.addListener('mousedown', function (t, evt) {
  26271. var el = evt.target || evt.srcElement;
  26272. baidu.editor.ui.Popup.postHide(evt, el);
  26273. baidu.editor.ui.ShortCutMenu.postHide(evt);
  26274. });
  26275. editor.addListener("delcells", function () {
  26276. if (UE.ui['edittip']) {
  26277. new UE.ui['edittip'](editor);
  26278. }
  26279. editor.getDialog('edittip').open();
  26280. });
  26281. var pastePop, isPaste = false, timer;
  26282. editor.addListener("afterpaste", function () {
  26283. if(editor.queryCommandState('pasteplain'))
  26284. return;
  26285. if(baidu.editor.ui.PastePicker){
  26286. pastePop = new baidu.editor.ui.Popup({
  26287. content:new baidu.editor.ui.PastePicker({editor:editor}),
  26288. editor:editor,
  26289. className:'edui-wordpastepop'
  26290. });
  26291. pastePop.render();
  26292. }
  26293. isPaste = true;
  26294. });
  26295. editor.addListener("afterinserthtml", function () {
  26296. clearTimeout(timer);
  26297. timer = setTimeout(function () {
  26298. if (pastePop && (isPaste || editor.ui._isTransfer)) {
  26299. if(pastePop.isHidden()){
  26300. var span = domUtils.createElement(editor.document, 'span', {
  26301. 'style':"line-height:0px;",
  26302. 'innerHTML':'\ufeff'
  26303. }),
  26304. range = editor.selection.getRange();
  26305. range.insertNode(span);
  26306. var tmp= getDomNode(span, 'firstChild', 'previousSibling');
  26307. tmp && pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp);
  26308. domUtils.remove(span);
  26309. }else{
  26310. pastePop.show();
  26311. }
  26312. delete editor.ui._isTransfer;
  26313. isPaste = false;
  26314. }
  26315. }, 200)
  26316. });
  26317. editor.addListener('contextmenu', function (t, evt) {
  26318. baidu.editor.ui.Popup.postHide(evt);
  26319. });
  26320. editor.addListener('keydown', function (t, evt) {
  26321. if (pastePop) pastePop.dispose(evt);
  26322. var keyCode = evt.keyCode || evt.which;
  26323. if(evt.altKey&&keyCode==90){
  26324. UE.ui.buttons['fullscreen'].onclick();
  26325. }
  26326. });
  26327. editor.addListener('wordcount', function (type) {
  26328. setCount(this,me);
  26329. });
  26330. function setCount(editor,ui) {
  26331. editor.setOpt({
  26332. wordCount:true,
  26333. maximumWords:10000,
  26334. wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"),
  26335. wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg")
  26336. });
  26337. var opt = editor.options,
  26338. max = opt.maximumWords,
  26339. msg = opt.wordCountMsg ,
  26340. errMsg = opt.wordOverFlowMsg,
  26341. countDom = ui.getDom('wordcount');
  26342. if (!opt.wordCount) {
  26343. return;
  26344. }
  26345. var count = editor.getContentLength(true);
  26346. if (count > max) {
  26347. countDom.innerHTML = errMsg;
  26348. editor.fireEvent("wordcountoverflow");
  26349. } else {
  26350. countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count);
  26351. }
  26352. }
  26353. editor.addListener('selectionchange', function () {
  26354. if (editor.options.elementPathEnabled) {
  26355. me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']()
  26356. }
  26357. if (editor.options.scaleEnabled) {
  26358. me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale']();
  26359. }
  26360. });
  26361. var popup = new baidu.editor.ui.Popup({
  26362. editor:editor,
  26363. content:'',
  26364. className:'edui-bubble',
  26365. _onEditButtonClick:function () {
  26366. this.hide();
  26367. editor.ui._dialogs.linkDialog.open();
  26368. },
  26369. _onImgEditButtonClick:function (name) {
  26370. this.hide();
  26371. editor.ui._dialogs[name] && editor.ui._dialogs[name].open();
  26372. },
  26373. _onImgSetFloat:function (value) {
  26374. this.hide();
  26375. editor.execCommand("imagefloat", value);
  26376. },
  26377. _setIframeAlign:function (value) {
  26378. var frame = popup.anchorEl;
  26379. var newFrame = frame.cloneNode(true);
  26380. switch (value) {
  26381. case -2:
  26382. newFrame.setAttribute("align", "");
  26383. break;
  26384. case -1:
  26385. newFrame.setAttribute("align", "left");
  26386. break;
  26387. case 1:
  26388. newFrame.setAttribute("align", "right");
  26389. break;
  26390. }
  26391. frame.parentNode.insertBefore(newFrame, frame);
  26392. domUtils.remove(frame);
  26393. popup.anchorEl = newFrame;
  26394. popup.showAnchor(popup.anchorEl);
  26395. },
  26396. _updateIframe:function () {
  26397. var frame = editor._iframe = popup.anchorEl;
  26398. if(domUtils.hasClass(frame, 'ueditor_baidumap')) {
  26399. editor.selection.getRange().selectNode(frame).select();
  26400. editor.ui._dialogs.mapDialog.open();
  26401. popup.hide();
  26402. } else {
  26403. editor.ui._dialogs.insertframeDialog.open();
  26404. popup.hide();
  26405. }
  26406. },
  26407. _onRemoveButtonClick:function (cmdName) {
  26408. editor.execCommand(cmdName);
  26409. this.hide();
  26410. },
  26411. queryAutoHide:function (el) {
  26412. if (el && el.ownerDocument == editor.document) {
  26413. if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) {
  26414. return el !== popup.anchorEl;
  26415. }
  26416. }
  26417. return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el);
  26418. }
  26419. });
  26420. popup.render();
  26421. if (editor.options.imagePopup) {
  26422. editor.addListener('mouseover', function (t, evt) {
  26423. evt = evt || window.event;
  26424. var el = evt.target || evt.srcElement;
  26425. if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) {
  26426. var html = popup.formatHtml(
  26427. '<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;' +
  26428. ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>');
  26429. if (html) {
  26430. popup.getDom('content').innerHTML = html;
  26431. popup.anchorEl = el;
  26432. popup.showAnchor(popup.anchorEl);
  26433. } else {
  26434. popup.hide();
  26435. }
  26436. }
  26437. });
  26438. editor.addListener('selectionchange', function (t, causeByUi) {
  26439. if (!causeByUi) return;
  26440. var html = '', str = "",
  26441. img = editor.selection.getRange().getClosedNode(),
  26442. dialogs = editor.ui._dialogs;
  26443. if (img && img.tagName == 'IMG') {
  26444. var dialogName = 'insertimageDialog';
  26445. if (img.className.indexOf("edui-faked-video") != -1 || img.className.indexOf("edui-upload-video") != -1) {
  26446. dialogName = "insertvideoDialog"
  26447. }
  26448. if (img.className.indexOf("edui-faked-webapp") != -1) {
  26449. dialogName = "webappDialog"
  26450. }
  26451. if (img.src.indexOf("http://api.map.baidu.com") != -1) {
  26452. dialogName = "mapDialog"
  26453. }
  26454. if (img.className.indexOf("edui-faked-music") != -1) {
  26455. dialogName = "musicDialog"
  26456. }
  26457. if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) {
  26458. dialogName = "gmapDialog"
  26459. }
  26460. if (img.getAttribute("anchorname")) {
  26461. dialogName = "anchorDialog";
  26462. html = popup.formatHtml(
  26463. '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' +
  26464. '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>');
  26465. }
  26466. if (img.getAttribute("word_img")) {
  26467. //todo 放到dialog去做查询
  26468. editor.word_img = [img.getAttribute("word_img")];
  26469. dialogName = "wordimageDialog"
  26470. }
  26471. if(domUtils.hasClass(img, 'loadingclass') || domUtils.hasClass(img, 'loaderrorclass')) {
  26472. dialogName = "";
  26473. }
  26474. if (!dialogs[dialogName]) {
  26475. return;
  26476. }
  26477. str = '<nobr>' + editor.getLang("property") + ': '+
  26478. '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' +
  26479. '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' +
  26480. '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' +
  26481. '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+
  26482. '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>';
  26483. !html && (html = popup.formatHtml(str))
  26484. }
  26485. if (editor.ui._dialogs.linkDialog) {
  26486. var link = editor.queryCommandValue('link');
  26487. var url;
  26488. if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) {
  26489. var txt = url;
  26490. if (url.length > 30) {
  26491. txt = url.substring(0, 20) + "...";
  26492. }
  26493. if (html) {
  26494. html += '<div style="height:5px;"></div>'
  26495. }
  26496. html += popup.formatHtml(
  26497. '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' +
  26498. ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' +
  26499. ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>');
  26500. popup.showAnchor(link);
  26501. }
  26502. }
  26503. if (html) {
  26504. popup.getDom('content').innerHTML = html;
  26505. popup.anchorEl = img || link;
  26506. popup.showAnchor(popup.anchorEl);
  26507. } else {
  26508. popup.hide();
  26509. }
  26510. });
  26511. }
  26512. },
  26513. _initToolbars:function () {
  26514. var editor = this.editor;
  26515. var toolbars = this.toolbars || [];
  26516. var toolbarUis = [];
  26517. for (var i = 0; i < toolbars.length; i++) {
  26518. var toolbar = toolbars[i];
  26519. var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme});
  26520. for (var j = 0; j < toolbar.length; j++) {
  26521. var toolbarItem = toolbar[j];
  26522. var toolbarItemUi = null;
  26523. if (typeof toolbarItem == 'string') {
  26524. toolbarItem = toolbarItem.toLowerCase();
  26525. if (toolbarItem == '|') {
  26526. toolbarItem = 'Separator';
  26527. }
  26528. if(toolbarItem == '||'){
  26529. toolbarItem = 'Breakline';
  26530. }
  26531. if (baidu.editor.ui[toolbarItem]) {
  26532. toolbarItemUi = new baidu.editor.ui[toolbarItem](editor);
  26533. }
  26534. //fullscreen这里单独处理一下,放到首行去
  26535. if (toolbarItem == 'fullscreen') {
  26536. if (toolbarUis && toolbarUis[0]) {
  26537. toolbarUis[0].items.splice(0, 0, toolbarItemUi);
  26538. } else {
  26539. toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi);
  26540. }
  26541. continue;
  26542. }
  26543. } else {
  26544. toolbarItemUi = toolbarItem;
  26545. }
  26546. if (toolbarItemUi && toolbarItemUi.id) {
  26547. toolbarUi.add(toolbarItemUi);
  26548. }
  26549. }
  26550. toolbarUis[i] = toolbarUi;
  26551. }
  26552. //接受外部定制的UI
  26553. utils.each(UE._customizeUI,function(obj,key){
  26554. var itemUI,index;
  26555. if(obj.id && obj.id != editor.key){
  26556. return false;
  26557. }
  26558. itemUI = obj.execFn.call(editor,editor,key);
  26559. if(itemUI){
  26560. index = obj.index;
  26561. if(index === undefined){
  26562. index = toolbarUi.items.length;
  26563. }
  26564. toolbarUi.add(itemUI,index)
  26565. }
  26566. });
  26567. this.toolbars = toolbarUis;
  26568. },
  26569. getHtmlTpl:function () {
  26570. return '<div id="##" class="%%">' +
  26571. '<div id="##_toolbarbox" class="%%-toolbarbox">' +
  26572. (this.toolbars.length ?
  26573. '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' +
  26574. this.renderToolbarBoxHtml() +
  26575. '</div></div>' : '') +
  26576. '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' +
  26577. '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' +
  26578. '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' +
  26579. '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' +
  26580. '<div style="height:0;overflow:hidden;clear:both;"></div>' +
  26581. '</div>' +
  26582. '<div id="##_message_holder" class="%%-messageholder"></div>' +
  26583. '</div>' +
  26584. '<div id="##_iframeholder" class="%%-iframeholder">' +
  26585. '</div>' +
  26586. //modify wdcount by matao
  26587. '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' +
  26588. '<td id="##_elementpath" class="%%-bottombar"></td>' +
  26589. '<td id="##_wordcount" class="%%-wordcount"></td>' +
  26590. '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' +
  26591. '</tr></table></div>' +
  26592. '<div id="##_scalelayer"></div>' +
  26593. '</div>';
  26594. },
  26595. showWordImageDialog:function () {
  26596. this._dialogs['wordimageDialog'].open();
  26597. },
  26598. renderToolbarBoxHtml:function () {
  26599. var buff = [];
  26600. for (var i = 0; i < this.toolbars.length; i++) {
  26601. buff.push(this.toolbars[i].renderHtml());
  26602. }
  26603. return buff.join('');
  26604. },
  26605. setFullScreen:function (fullscreen) {
  26606. var editor = this.editor,
  26607. container = editor.container.parentNode.parentNode;
  26608. if (this._fullscreen != fullscreen) {
  26609. this._fullscreen = fullscreen;
  26610. this.editor.fireEvent('beforefullscreenchange', fullscreen);
  26611. if (baidu.editor.browser.gecko) {
  26612. var bk = editor.selection.getRange().createBookmark();
  26613. }
  26614. if (fullscreen) {
  26615. while (container.tagName != "BODY") {
  26616. var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position");
  26617. nodeStack.push(position);
  26618. container.style.position = "static";
  26619. container = container.parentNode;
  26620. }
  26621. this._bakHtmlOverflow = document.documentElement.style.overflow;
  26622. this._bakBodyOverflow = document.body.style.overflow;
  26623. this._bakAutoHeight = this.editor.autoHeightEnabled;
  26624. this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
  26625. this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth;
  26626. if (this._bakAutoHeight) {
  26627. //当全屏时不能执行自动长高
  26628. editor.autoHeightEnabled = false;
  26629. this.editor.disableAutoHeight();
  26630. }
  26631. document.documentElement.style.overflow = 'hidden';
  26632. //修复,滚动条不收起的问题
  26633. window.scrollTo(0,window.scrollY);
  26634. this._bakCssText = this.getDom().style.cssText;
  26635. this._bakCssText1 = this.getDom('iframeholder').style.cssText;
  26636. editor.iframe.parentNode.style.width = '';
  26637. this._updateFullScreen();
  26638. } else {
  26639. while (container.tagName != "BODY") {
  26640. container.style.position = nodeStack.shift();
  26641. container = container.parentNode;
  26642. }
  26643. this.getDom().style.cssText = this._bakCssText;
  26644. this.getDom('iframeholder').style.cssText = this._bakCssText1;
  26645. if (this._bakAutoHeight) {
  26646. editor.autoHeightEnabled = true;
  26647. this.editor.enableAutoHeight();
  26648. }
  26649. document.documentElement.style.overflow = this._bakHtmlOverflow;
  26650. document.body.style.overflow = this._bakBodyOverflow;
  26651. editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px';
  26652. window.scrollTo(0, this._bakScrollTop);
  26653. }
  26654. if (browser.gecko && editor.body.contentEditable === 'true') {
  26655. var input = document.createElement('input');
  26656. document.body.appendChild(input);
  26657. editor.body.contentEditable = false;
  26658. setTimeout(function () {
  26659. input.focus();
  26660. setTimeout(function () {
  26661. editor.body.contentEditable = true;
  26662. editor.fireEvent('fullscreenchanged', fullscreen);
  26663. editor.selection.getRange().moveToBookmark(bk).select(true);
  26664. baidu.editor.dom.domUtils.remove(input);
  26665. fullscreen && window.scroll(0, 0);
  26666. }, 0)
  26667. }, 0)
  26668. }
  26669. if(editor.body.contentEditable === 'true'){
  26670. this.editor.fireEvent('fullscreenchanged', fullscreen);
  26671. this.triggerLayout();
  26672. }
  26673. }
  26674. },
  26675. _updateFullScreen:function () {
  26676. if (this._fullscreen) {
  26677. var vpRect = uiUtils.getViewportRect();
  26678. 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);
  26679. uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 });
  26680. this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0),true);
  26681. //不手动调一下,会导致全屏失效
  26682. if(browser.gecko){
  26683. try{
  26684. window.onresize();
  26685. }catch(e){
  26686. }
  26687. }
  26688. }
  26689. },
  26690. _updateElementPath:function () {
  26691. var bottom = this.getDom('elementpath'), list;
  26692. if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) {
  26693. var buff = [];
  26694. for (var i = 0, ci; ci = list[i]; i++) {
  26695. buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>');
  26696. }
  26697. bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>';
  26698. } else {
  26699. bottom.style.display = 'none'
  26700. }
  26701. },
  26702. disableElementPath:function () {
  26703. var bottom = this.getDom('elementpath');
  26704. bottom.innerHTML = '';
  26705. bottom.style.display = 'none';
  26706. this.elementPathEnabled = false;
  26707. },
  26708. enableElementPath:function () {
  26709. var bottom = this.getDom('elementpath');
  26710. bottom.style.display = '';
  26711. this.elementPathEnabled = true;
  26712. this._updateElementPath();
  26713. },
  26714. _scale:function () {
  26715. var doc = document,
  26716. editor = this.editor,
  26717. editorHolder = editor.container,
  26718. editorDocument = editor.document,
  26719. toolbarBox = this.getDom("toolbarbox"),
  26720. bottombar = this.getDom("bottombar"),
  26721. scale = this.getDom("scale"),
  26722. scalelayer = this.getDom("scalelayer");
  26723. var isMouseMove = false,
  26724. position = null,
  26725. minEditorHeight = 0,
  26726. minEditorWidth = editor.options.minFrameWidth,
  26727. pageX = 0,
  26728. pageY = 0,
  26729. scaleWidth = 0,
  26730. scaleHeight = 0;
  26731. function down() {
  26732. position = domUtils.getXY(editorHolder);
  26733. if (!minEditorHeight) {
  26734. minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight;
  26735. }
  26736. 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:"
  26737. + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1);
  26738. domUtils.on(doc, "mousemove", move);
  26739. domUtils.on(editorDocument, "mouseup", up);
  26740. domUtils.on(doc, "mouseup", up);
  26741. }
  26742. var me = this;
  26743. //by xuheng 全屏时关掉缩放
  26744. this.editor.addListener('fullscreenchanged', function (e, fullScreen) {
  26745. if (fullScreen) {
  26746. me.disableScale();
  26747. } else {
  26748. if (me.editor.options.scaleEnabled) {
  26749. me.enableScale();
  26750. var tmpNode = me.editor.document.createElement('span');
  26751. me.editor.body.appendChild(tmpNode);
  26752. me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px';
  26753. domUtils.remove(tmpNode)
  26754. }
  26755. }
  26756. });
  26757. function move(event) {
  26758. clearSelection();
  26759. var e = event || window.event;
  26760. pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX);
  26761. pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY);
  26762. scaleWidth = pageX - position.x;
  26763. scaleHeight = pageY - position.y;
  26764. if (scaleWidth >= minEditorWidth) {
  26765. isMouseMove = true;
  26766. scalelayer.style.width = scaleWidth + 'px';
  26767. }
  26768. if (scaleHeight >= minEditorHeight) {
  26769. isMouseMove = true;
  26770. scalelayer.style.height = scaleHeight + "px";
  26771. }
  26772. }
  26773. function up() {
  26774. if (isMouseMove) {
  26775. isMouseMove = false;
  26776. editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2;
  26777. editorHolder.style.width = editor.ui._actualFrameWidth + 'px';
  26778. editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2,true);
  26779. }
  26780. if (scalelayer) {
  26781. scalelayer.style.display = "none";
  26782. }
  26783. clearSelection();
  26784. domUtils.un(doc, "mousemove", move);
  26785. domUtils.un(editorDocument, "mouseup", up);
  26786. domUtils.un(doc, "mouseup", up);
  26787. }
  26788. function clearSelection() {
  26789. if (browser.ie)
  26790. doc.selection.clear();
  26791. else
  26792. window.getSelection().removeAllRanges();
  26793. }
  26794. this.enableScale = function () {
  26795. //trace:2868
  26796. if (editor.queryCommandState("source") == 1) return;
  26797. scale.style.display = "";
  26798. this.scaleEnabled = true;
  26799. domUtils.on(scale, "mousedown", down);
  26800. };
  26801. this.disableScale = function () {
  26802. scale.style.display = "none";
  26803. this.scaleEnabled = false;
  26804. domUtils.un(scale, "mousedown", down);
  26805. };
  26806. },
  26807. isFullScreen:function () {
  26808. return this._fullscreen;
  26809. },
  26810. postRender:function () {
  26811. UIBase.prototype.postRender.call(this);
  26812. for (var i = 0; i < this.toolbars.length; i++) {
  26813. this.toolbars[i].postRender();
  26814. }
  26815. var me = this;
  26816. var timerId,
  26817. domUtils = baidu.editor.dom.domUtils,
  26818. updateFullScreenTime = function () {
  26819. clearTimeout(timerId);
  26820. timerId = setTimeout(function () {
  26821. me._updateFullScreen();
  26822. });
  26823. };
  26824. domUtils.on(window, 'resize', updateFullScreenTime);
  26825. me.addListener('destroy', function () {
  26826. domUtils.un(window, 'resize', updateFullScreenTime);
  26827. clearTimeout(timerId);
  26828. })
  26829. },
  26830. showToolbarMsg:function (msg, flag) {
  26831. this.getDom('toolbarmsg_label').innerHTML = msg;
  26832. this.getDom('toolbarmsg').style.display = '';
  26833. //
  26834. if (!flag) {
  26835. var w = this.getDom('upload_dialog');
  26836. w.style.display = 'none';
  26837. }
  26838. },
  26839. hideToolbarMsg:function () {
  26840. this.getDom('toolbarmsg').style.display = 'none';
  26841. },
  26842. mapUrl:function (url) {
  26843. return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : ''
  26844. },
  26845. triggerLayout:function () {
  26846. var dom = this.getDom();
  26847. if (dom.style.zoom == '1') {
  26848. dom.style.zoom = '100%';
  26849. } else {
  26850. dom.style.zoom = '1';
  26851. }
  26852. }
  26853. };
  26854. utils.inherits(EditorUI, baidu.editor.ui.UIBase);
  26855. var instances = {};
  26856. UE.ui.Editor = function (options) {
  26857. var editor = new UE.Editor(options);
  26858. editor.options.editor = editor;
  26859. utils.loadFile(document, {
  26860. href:editor.options.themePath + editor.options.theme + "/css/ueditor.css",
  26861. tag:"link",
  26862. type:"text/css",
  26863. rel:"stylesheet"
  26864. });
  26865. var oldRender = editor.render;
  26866. editor.render = function (holder) {
  26867. if (holder.constructor === String) {
  26868. editor.key = holder;
  26869. instances[holder] = editor;
  26870. }
  26871. utils.domReady(function () {
  26872. editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI);
  26873. function renderUI() {
  26874. editor.setOpt({
  26875. labelMap:editor.options.labelMap || editor.getLang('labelMap')
  26876. });
  26877. new EditorUI(editor.options);
  26878. if (holder) {
  26879. if (holder.constructor === String) {
  26880. holder = document.getElementById(holder);
  26881. }
  26882. holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name'));
  26883. if (holder && /script|textarea/ig.test(holder.tagName)) {
  26884. var newDiv = document.createElement('div');
  26885. holder.parentNode.insertBefore(newDiv, holder);
  26886. var cont = holder.value || holder.innerHTML;
  26887. editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent :
  26888. cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>')
  26889. .replace(/[\n\r\t]+([ ]{4})+</g, '<')
  26890. .replace(/>[\n\r\t]+</g, '><');
  26891. holder.className && (newDiv.className = holder.className);
  26892. holder.style.cssText && (newDiv.style.cssText = holder.style.cssText);
  26893. if (/textarea/i.test(holder.tagName)) {
  26894. editor.textarea = holder;
  26895. editor.textarea.style.display = 'none';
  26896. } else {
  26897. holder.parentNode.removeChild(holder);
  26898. }
  26899. if(holder.id){
  26900. newDiv.id = holder.id;
  26901. domUtils.removeAttributes(holder,'id');
  26902. }
  26903. holder = newDiv;
  26904. holder.innerHTML = '';
  26905. }
  26906. }
  26907. domUtils.addClass(holder, "edui-" + editor.options.theme);
  26908. editor.ui.render(holder);
  26909. var opt = editor.options;
  26910. //给实例添加一个编辑器的容器引用
  26911. editor.container = editor.ui.getDom();
  26912. var parents = domUtils.findParents(holder,true);
  26913. var displays = [];
  26914. for(var i = 0 ,ci;ci=parents[i];i++){
  26915. displays[i] = ci.style.display;
  26916. ci.style.display = 'block'
  26917. }
  26918. if (opt.initialFrameWidth) {
  26919. opt.minFrameWidth = opt.initialFrameWidth;
  26920. } else {
  26921. opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth;
  26922. var styleWidth = holder.style.width;
  26923. if(/%$/.test(styleWidth)) {
  26924. opt.initialFrameWidth = styleWidth;
  26925. }
  26926. }
  26927. if (opt.initialFrameHeight) {
  26928. opt.minFrameHeight = opt.initialFrameHeight;
  26929. } else {
  26930. opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight;
  26931. }
  26932. for(var i = 0 ,ci;ci=parents[i];i++){
  26933. ci.style.display = displays[i]
  26934. }
  26935. //编辑器最外容器设置了高度,会导致,编辑器不占位
  26936. //todo 先去掉,没有找到原因
  26937. if(holder.style.height){
  26938. holder.style.height = ''
  26939. }
  26940. editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px');
  26941. editor.container.style.zIndex = opt.zIndex;
  26942. oldRender.call(editor, editor.ui.getDom('iframeholder'));
  26943. editor.fireEvent("afteruiready");
  26944. }
  26945. })
  26946. };
  26947. return editor;
  26948. };
  26949. /**
  26950. * @file
  26951. * @name UE
  26952. * @short UE
  26953. * @desc UEditor的顶部命名空间
  26954. */
  26955. /**
  26956. * @name getEditor
  26957. * @since 1.2.4+
  26958. * @grammar UE.getEditor(id,[opt]) => Editor实例
  26959. * @desc 提供一个全局的方法得到编辑器实例
  26960. *
  26961. * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回
  26962. * * ''opt'' 编辑器的可选参数
  26963. * @example
  26964. * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例
  26965. * this.setContent('hello')
  26966. * }});
  26967. * UE.getEditor('containerId'); //返回刚创建的实例
  26968. *
  26969. */
  26970. UE.getEditor = function (id, opt) {
  26971. var editor = instances[id];
  26972. if (!editor) {
  26973. editor = instances[id] = new UE.ui.Editor(opt);
  26974. editor.render(id);
  26975. }
  26976. return editor;
  26977. };
  26978. UE.delEditor = function (id) {
  26979. var editor;
  26980. if (editor = instances[id]) {
  26981. editor.key && editor.destroy();
  26982. delete instances[id]
  26983. }
  26984. };
  26985. UE.registerUI = function(uiName,fn,index,editorId){
  26986. utils.each(uiName.split(/\s+/), function (name) {
  26987. UE._customizeUI[name] = {
  26988. id : editorId,
  26989. execFn:fn,
  26990. index:index
  26991. };
  26992. })
  26993. }
  26994. })();
  26995. // adapter/message.js
  26996. UE.registerUI('message', function(editor) {
  26997. var editorui = baidu.editor.ui;
  26998. var Message = editorui.Message;
  26999. var holder;
  27000. var _messageItems = [];
  27001. var me = editor;
  27002. me.addListener('ready', function(){
  27003. holder = document.getElementById(me.ui.id + '_message_holder');
  27004. updateHolderPos();
  27005. setTimeout(function(){
  27006. updateHolderPos();
  27007. }, 500);
  27008. });
  27009. me.addListener('showmessage', function(type, opt){
  27010. opt = utils.isString(opt) ? {
  27011. 'content': opt
  27012. } : opt;
  27013. var message = new Message({
  27014. 'timeout': opt.timeout,
  27015. 'type': opt.type,
  27016. 'content': opt.content,
  27017. 'keepshow': opt.keepshow,
  27018. 'editor': me
  27019. }),
  27020. mid = opt.id || ('msg_' + (+new Date()).toString(36));
  27021. message.render(holder);
  27022. _messageItems[mid] = message;
  27023. message.reset(opt);
  27024. updateHolderPos();
  27025. return mid;
  27026. });
  27027. me.addListener('updatemessage',function(type, id, opt){
  27028. opt = utils.isString(opt) ? {
  27029. 'content': opt
  27030. } : opt;
  27031. var message = _messageItems[id];
  27032. message.render(holder);
  27033. message && message.reset(opt);
  27034. });
  27035. me.addListener('hidemessage',function(type, id){
  27036. var message = _messageItems[id];
  27037. message && message.hide();
  27038. });
  27039. function updateHolderPos(){
  27040. var toolbarbox = me.ui.getDom('toolbarbox');
  27041. if (toolbarbox) {
  27042. holder.style.top = toolbarbox.offsetHeight + 3 + 'px';
  27043. }
  27044. holder.style.zIndex = Math.max(me.options.zIndex, me.iframe.style.zIndex) + 1;
  27045. }
  27046. });
  27047. // adapter/autosave.js
  27048. UE.registerUI('autosave', function(editor) {
  27049. var timer = null,uid = null;
  27050. editor.on('afterautosave',function(){
  27051. clearTimeout(timer);
  27052. timer = setTimeout(function(){
  27053. if(uid){
  27054. editor.trigger('hidemessage',uid);
  27055. }
  27056. uid = editor.trigger('showmessage',{
  27057. content : editor.getLang('autosave.success'),
  27058. timeout : 2000
  27059. });
  27060. },2000)
  27061. })
  27062. });
  27063. })();