kindeditor.js 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962
  1. /*******************************************************************************
  2. * KindEditor - WYSIWYG HTML Editor for Internet
  3. * Copyright (C) 2006-2013 kindsoft.net
  4. *
  5. * @author Roddy <luolonghao@gmail.com>
  6. * @website http://www.kindsoft.net/
  7. * @licence http://www.kindsoft.net/license.php
  8. * @version 4.1.10 (2013-11-23)
  9. *******************************************************************************/
  10. (function (window, undefined) {
  11. if (window.KindEditor) {
  12. return;
  13. }
  14. if (!window.console) {
  15. window.console = {};
  16. }
  17. if (!console.log) {
  18. console.log = function () {};
  19. }
  20. var _VERSION = '4.1.10 (2013-11-23)',
  21. _ua = navigator.userAgent.toLowerCase(),
  22. _IE = _ua.indexOf('msie') > -1 && _ua.indexOf('opera') == -1,
  23. _NEWIE = _ua.indexOf('msie') == -1 && _ua.indexOf('trident') > -1,
  24. _GECKO = _ua.indexOf('gecko') > -1 && _ua.indexOf('khtml') == -1,
  25. _WEBKIT = _ua.indexOf('applewebkit') > -1,
  26. _OPERA = _ua.indexOf('opera') > -1,
  27. _MOBILE = _ua.indexOf('mobile') > -1,
  28. _IOS = /ipad|iphone|ipod/.test(_ua),
  29. _QUIRKS = document.compatMode != 'CSS1Compat',
  30. _IERANGE = !window.getSelection,
  31. _matches = /(?:msie|firefox|webkit|opera)[\/:\s](\d+)/.exec(_ua),
  32. _V = _matches ? _matches[1] : '0',
  33. _TIME = new Date().getTime();
  34. function _isArray(val) {
  35. if (!val) {
  36. return false;
  37. }
  38. return Object.prototype.toString.call(val) === '[object Array]';
  39. }
  40. function _isFunction(val) {
  41. if (!val) {
  42. return false;
  43. }
  44. return Object.prototype.toString.call(val) === '[object Function]';
  45. }
  46. function _inArray(val, arr) {
  47. for (var i = 0, len = arr.length; i < len; i++) {
  48. if (val === arr[i]) {
  49. return i;
  50. }
  51. }
  52. return -1;
  53. }
  54. function _each(obj, fn) {
  55. if (_isArray(obj)) {
  56. for (var i = 0, len = obj.length; i < len; i++) {
  57. if (fn.call(obj[i], i, obj[i]) === false) {
  58. break;
  59. }
  60. }
  61. } else {
  62. for (var key in obj) {
  63. if (obj.hasOwnProperty(key)) {
  64. if (fn.call(obj[key], key, obj[key]) === false) {
  65. break;
  66. }
  67. }
  68. }
  69. }
  70. }
  71. function _trim(str) {
  72. return str.replace(/(?:^[ \t\n\r]+)|(?:[ \t\n\r]+$)/g, '');
  73. }
  74. function _inString(val, str, delimiter) {
  75. delimiter = delimiter === undefined ? ',' : delimiter;
  76. return (delimiter + str + delimiter).indexOf(delimiter + val + delimiter) >= 0;
  77. }
  78. function _addUnit(val, unit) {
  79. unit = unit || 'px';
  80. return val && /^\d+$/.test(val) ? val + unit : val;
  81. }
  82. function _removeUnit(val) {
  83. var match;
  84. return val && (match = /(\d+)/.exec(val)) ? parseInt(match[1], 10) : 0;
  85. }
  86. function _escape(val) {
  87. return val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  88. }
  89. function _unescape(val) {
  90. return val.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
  91. }
  92. function _toCamel(str) {
  93. var arr = str.split('-');
  94. str = '';
  95. _each(arr, function(key, val) {
  96. str += (key > 0) ? val.charAt(0).toUpperCase() + val.substr(1) : val;
  97. });
  98. return str;
  99. }
  100. function _toHex(val) {
  101. function hex(d) {
  102. var s = parseInt(d, 10).toString(16).toUpperCase();
  103. return s.length > 1 ? s : '0' + s;
  104. }
  105. return val.replace(/rgb\s*\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/ig,
  106. function($0, $1, $2, $3) {
  107. return '#' + hex($1) + hex($2) + hex($3);
  108. }
  109. );
  110. }
  111. function _toMap(val, delimiter) {
  112. delimiter = delimiter === undefined ? ',' : delimiter;
  113. var map = {}, arr = _isArray(val) ? val : val.split(delimiter), match;
  114. _each(arr, function(key, val) {
  115. if ((match = /^(\d+)\.\.(\d+)$/.exec(val))) {
  116. for (var i = parseInt(match[1], 10); i <= parseInt(match[2], 10); i++) {
  117. map[i.toString()] = true;
  118. }
  119. } else {
  120. map[val] = true;
  121. }
  122. });
  123. return map;
  124. }
  125. function _toArray(obj, offset) {
  126. return Array.prototype.slice.call(obj, offset || 0);
  127. }
  128. function _undef(val, defaultVal) {
  129. return val === undefined ? defaultVal : val;
  130. }
  131. function _invalidUrl(url) {
  132. return !url || /[<>"]/.test(url);
  133. }
  134. function _addParam(url, param) {
  135. return url.indexOf('?') >= 0 ? url + '&' + param : url + '?' + param;
  136. }
  137. function _extend(child, parent, proto) {
  138. if (!proto) {
  139. proto = parent;
  140. parent = null;
  141. }
  142. var childProto;
  143. if (parent) {
  144. var fn = function () {};
  145. fn.prototype = parent.prototype;
  146. childProto = new fn();
  147. _each(proto, function(key, val) {
  148. childProto[key] = val;
  149. });
  150. } else {
  151. childProto = proto;
  152. }
  153. childProto.constructor = child;
  154. child.prototype = childProto;
  155. child.parent = parent ? parent.prototype : null;
  156. }
  157. function _json(text) {
  158. var match;
  159. if ((match = /\{[\s\S]*\}|\[[\s\S]*\]/.exec(text))) {
  160. text = match[0];
  161. }
  162. var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
  163. cx.lastIndex = 0;
  164. if (cx.test(text)) {
  165. text = text.replace(cx, function (a) {
  166. return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  167. });
  168. }
  169. if (/^[\],:{}\s]*$/.
  170. test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
  171. replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
  172. replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  173. return eval('(' + text + ')');
  174. }
  175. throw 'JSON parse error';
  176. }
  177. var _round = Math.round;
  178. var K = {
  179. DEBUG : false,
  180. VERSION : _VERSION,
  181. IE : _IE,
  182. GECKO : _GECKO,
  183. WEBKIT : _WEBKIT,
  184. OPERA : _OPERA,
  185. V : _V,
  186. TIME : _TIME,
  187. each : _each,
  188. isArray : _isArray,
  189. isFunction : _isFunction,
  190. inArray : _inArray,
  191. inString : _inString,
  192. trim : _trim,
  193. addUnit : _addUnit,
  194. removeUnit : _removeUnit,
  195. escape : _escape,
  196. unescape : _unescape,
  197. toCamel : _toCamel,
  198. toHex : _toHex,
  199. toMap : _toMap,
  200. toArray : _toArray,
  201. undef : _undef,
  202. invalidUrl : _invalidUrl,
  203. addParam : _addParam,
  204. extend : _extend,
  205. json : _json
  206. };
  207. var _INLINE_TAG_MAP = _toMap('a,abbr,acronym,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,img,input,ins,kbd,label,map,q,s,samp,select,small,span,strike,strong,sub,sup,textarea,tt,u,var'),
  208. _BLOCK_TAG_MAP = _toMap('address,applet,blockquote,body,center,dd,dir,div,dl,dt,fieldset,form,frameset,h1,h2,h3,h4,h5,h6,head,hr,html,iframe,ins,isindex,li,map,menu,meta,noframes,noscript,object,ol,p,pre,script,style,table,tbody,td,tfoot,th,thead,title,tr,ul'),
  209. _SINGLE_TAG_MAP = _toMap('area,base,basefont,br,col,frame,hr,img,input,isindex,link,meta,param,embed'),
  210. _STYLE_TAG_MAP = _toMap('b,basefont,big,del,em,font,i,s,small,span,strike,strong,sub,sup,u'),
  211. _CONTROL_TAG_MAP = _toMap('img,table,input,textarea,button'),
  212. _PRE_TAG_MAP = _toMap('pre,style,script'),
  213. _NOSPLIT_TAG_MAP = _toMap('html,head,body,td,tr,table,ol,ul,li'),
  214. _AUTOCLOSE_TAG_MAP = _toMap('colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr'),
  215. _FILL_ATTR_MAP = _toMap('checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected'),
  216. _VALUE_TAG_MAP = _toMap('input,button,textarea,select');
  217. function _getBasePath() {
  218. var els = document.getElementsByTagName('script'), src;
  219. for (var i = 0, len = els.length; i < len; i++) {
  220. src = els[i].src || '';
  221. if (/kindeditor[\w\-\.]*\.js/.test(src)) {
  222. return src.substring(0, src.lastIndexOf('/') + 1);
  223. }
  224. }
  225. return '';
  226. }
  227. K.basePath = _getBasePath();
  228. K.options = {
  229. designMode : true,
  230. fullscreenMode : false,
  231. filterMode : true,
  232. wellFormatMode : true,
  233. shadowMode : true,
  234. loadStyleMode : true,
  235. basePath : K.basePath,
  236. themesPath : K.basePath + 'themes/',
  237. langPath : K.basePath + 'lang/',
  238. pluginsPath : K.basePath + 'plugins/',
  239. themeType : 'default',
  240. langType : 'zh_CN',
  241. urlType : '',
  242. newlineTag : 'p',
  243. resizeType : 2,
  244. syncType : 'form',
  245. pasteType : 2,
  246. dialogAlignType : 'page',
  247. useContextmenu : true,
  248. fullscreenShortcut : false,
  249. bodyClass : 'ke-content',
  250. indentChar : '\t',
  251. cssPath : '',
  252. cssData : '',
  253. minWidth : 650,
  254. minHeight : 100,
  255. minChangeSize : 50,
  256. zIndex : 811213,
  257. items : [
  258. 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
  259. 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
  260. 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
  261. 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
  262. 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
  263. 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
  264. 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
  265. 'anchor', 'link', 'unlink', '|', 'about'
  266. ],
  267. noDisableItems : ['source', 'fullscreen'],
  268. colorTable : [
  269. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  270. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  271. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  272. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  273. ],
  274. fontSizeTable : ['9px', '10px', '12px', '14px', '16px', '18px', '24px', '32px'],
  275. htmlTags : {
  276. font : ['id', 'class', 'color', 'size', 'face', '.background-color'],
  277. span : [
  278. 'id', 'class', '.color', '.background-color', '.font-size', '.font-family', '.background',
  279. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.line-height'
  280. ],
  281. div : [
  282. 'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color',
  283. '.background-color', '.font-size', '.font-family', '.font-weight', '.background',
  284. '.font-style', '.text-decoration', '.vertical-align', '.margin-left'
  285. ],
  286. table: [
  287. 'id', 'class', 'border', 'cellspacing', 'cellpadding', 'width', 'height', 'align', 'bordercolor',
  288. '.padding', '.margin', '.border', 'bgcolor', '.text-align', '.color', '.background-color',
  289. '.font-size', '.font-family', '.font-weight', '.font-style', '.text-decoration', '.background',
  290. '.width', '.height', '.border-collapse'
  291. ],
  292. 'td,th': [
  293. 'id', 'class', 'align', 'valign', 'width', 'height', 'colspan', 'rowspan', 'bgcolor',
  294. '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight',
  295. '.font-style', '.text-decoration', '.vertical-align', '.background', '.border'
  296. ],
  297. a : ['id', 'class', 'href', 'target', 'name'],
  298. embed : ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'],
  299. img : ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'],
  300. 'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [
  301. 'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background',
  302. '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left'
  303. ],
  304. pre : ['id', 'class'],
  305. hr : ['id', 'class', '.page-break-after'],
  306. 'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : ['id', 'class'],
  307. iframe : ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height']
  308. },
  309. layout : '<div class="container"><div class="toolbar"></div><div class="edit"></div><div class="statusbar"></div></div>'
  310. };
  311. var _useCapture = false;
  312. var _INPUT_KEY_MAP = _toMap('8,9,13,32,46,48..57,59,61,65..90,106,109..111,188,190..192,219..222');
  313. var _CURSORMOVE_KEY_MAP = _toMap('33..40');
  314. var _CHANGE_KEY_MAP = {};
  315. _each(_INPUT_KEY_MAP, function(key, val) {
  316. _CHANGE_KEY_MAP[key] = val;
  317. });
  318. _each(_CURSORMOVE_KEY_MAP, function(key, val) {
  319. _CHANGE_KEY_MAP[key] = val;
  320. });
  321. function _bindEvent(el, type, fn) {
  322. if (el.addEventListener){
  323. el.addEventListener(type, fn, _useCapture);
  324. } else if (el.attachEvent){
  325. el.attachEvent('on' + type, fn);
  326. }
  327. }
  328. function _unbindEvent(el, type, fn) {
  329. if (el.removeEventListener){
  330. el.removeEventListener(type, fn, _useCapture);
  331. } else if (el.detachEvent){
  332. el.detachEvent('on' + type, fn);
  333. }
  334. }
  335. var _EVENT_PROPS = ('altKey,attrChange,attrName,bubbles,button,cancelable,charCode,clientX,clientY,ctrlKey,currentTarget,' +
  336. 'data,detail,eventPhase,fromElement,handler,keyCode,metaKey,newValue,offsetX,offsetY,originalTarget,pageX,' +
  337. 'pageY,prevValue,relatedNode,relatedTarget,screenX,screenY,shiftKey,srcElement,target,toElement,view,wheelDelta,which').split(',');
  338. function KEvent(el, event) {
  339. this.init(el, event);
  340. }
  341. _extend(KEvent, {
  342. init : function(el, event) {
  343. var self = this, doc = el.ownerDocument || el.document || el;
  344. self.event = event;
  345. _each(_EVENT_PROPS, function(key, val) {
  346. self[val] = event[val];
  347. });
  348. if (!self.target) {
  349. self.target = self.srcElement || doc;
  350. }
  351. if (self.target.nodeType === 3) {
  352. self.target = self.target.parentNode;
  353. }
  354. if (!self.relatedTarget && self.fromElement) {
  355. self.relatedTarget = self.fromElement === self.target ? self.toElement : self.fromElement;
  356. }
  357. if (self.pageX == null && self.clientX != null) {
  358. var d = doc.documentElement, body = doc.body;
  359. self.pageX = self.clientX + (d && d.scrollLeft || body && body.scrollLeft || 0) - (d && d.clientLeft || body && body.clientLeft || 0);
  360. self.pageY = self.clientY + (d && d.scrollTop || body && body.scrollTop || 0) - (d && d.clientTop || body && body.clientTop || 0);
  361. }
  362. if (!self.which && ((self.charCode || self.charCode === 0) ? self.charCode : self.keyCode)) {
  363. self.which = self.charCode || self.keyCode;
  364. }
  365. if (!self.metaKey && self.ctrlKey) {
  366. self.metaKey = self.ctrlKey;
  367. }
  368. if (!self.which && self.button !== undefined) {
  369. self.which = (self.button & 1 ? 1 : (self.button & 2 ? 3 : (self.button & 4 ? 2 : 0)));
  370. }
  371. console.log(self.width);
  372. switch (self.which) {
  373. case 186 :
  374. self.which = 59;
  375. break;
  376. case 187 :
  377. case 107 :
  378. case 43 :
  379. self.which = 61;
  380. break;
  381. case 189 :
  382. case 45 :
  383. self.which = 109;
  384. break;
  385. case 42 :
  386. self.which = 106;
  387. break;
  388. case 47 :
  389. self.which = 111;
  390. break;
  391. case 78 :
  392. self.which = 110;
  393. break;
  394. }
  395. if (self.which >= 96 && self.which <= 105) {
  396. self.which -= 48;
  397. }
  398. },
  399. preventDefault : function() {
  400. var ev = this.event;
  401. if (ev.preventDefault) {
  402. ev.preventDefault();
  403. } else {
  404. ev.returnValue = false;
  405. }
  406. },
  407. stopPropagation : function() {
  408. var ev = this.event;
  409. if (ev.stopPropagation) {
  410. ev.stopPropagation();
  411. } else {
  412. ev.cancelBubble = true;
  413. }
  414. },
  415. stop : function() {
  416. this.preventDefault();
  417. this.stopPropagation();
  418. }
  419. });
  420. var _eventExpendo = 'kindeditor_' + _TIME, _eventId = 0, _eventData = {};
  421. function _getId(el) {
  422. return el[_eventExpendo] || null;
  423. }
  424. function _setId(el) {
  425. el[_eventExpendo] = ++_eventId;
  426. return _eventId;
  427. }
  428. function _removeId(el) {
  429. try {
  430. delete el[_eventExpendo];
  431. } catch(e) {
  432. if (el.removeAttribute) {
  433. el.removeAttribute(_eventExpendo);
  434. }
  435. }
  436. }
  437. function _bind(el, type, fn) {
  438. if (type.indexOf(',') >= 0) {
  439. _each(type.split(','), function() {
  440. _bind(el, this, fn);
  441. });
  442. return;
  443. }
  444. var id = _getId(el);
  445. if (!id) {
  446. id = _setId(el);
  447. }
  448. if (_eventData[id] === undefined) {
  449. _eventData[id] = {};
  450. }
  451. var events = _eventData[id][type];
  452. if (events && events.length > 0) {
  453. _unbindEvent(el, type, events[0]);
  454. } else {
  455. _eventData[id][type] = [];
  456. _eventData[id].el = el;
  457. }
  458. events = _eventData[id][type];
  459. if (events.length === 0) {
  460. events[0] = function(e) {
  461. var kevent = e ? new KEvent(el, e) : undefined;
  462. _each(events, function(i, event) {
  463. if (i > 0 && event) {
  464. event.call(el, kevent);
  465. }
  466. });
  467. };
  468. }
  469. if (_inArray(fn, events) < 0) {
  470. events.push(fn);
  471. }
  472. _bindEvent(el, type, events[0]);
  473. }
  474. function _unbind(el, type, fn) {
  475. if (type && type.indexOf(',') >= 0) {
  476. _each(type.split(','), function() {
  477. _unbind(el, this, fn);
  478. });
  479. return;
  480. }
  481. var id = _getId(el);
  482. if (!id) {
  483. return;
  484. }
  485. if (type === undefined) {
  486. if (id in _eventData) {
  487. _each(_eventData[id], function(key, events) {
  488. if (key != 'el' && events.length > 0) {
  489. _unbindEvent(el, key, events[0]);
  490. }
  491. });
  492. delete _eventData[id];
  493. _removeId(el);
  494. }
  495. return;
  496. }
  497. if (!_eventData[id]) {
  498. return;
  499. }
  500. var events = _eventData[id][type];
  501. if (events && events.length > 0) {
  502. if (fn === undefined) {
  503. _unbindEvent(el, type, events[0]);
  504. delete _eventData[id][type];
  505. } else {
  506. _each(events, function(i, event) {
  507. if (i > 0 && event === fn) {
  508. events.splice(i, 1);
  509. }
  510. });
  511. if (events.length == 1) {
  512. _unbindEvent(el, type, events[0]);
  513. delete _eventData[id][type];
  514. }
  515. }
  516. var count = 0;
  517. _each(_eventData[id], function() {
  518. count++;
  519. });
  520. if (count < 2) {
  521. delete _eventData[id];
  522. _removeId(el);
  523. }
  524. }
  525. }
  526. function _fire(el, type) {
  527. if (type.indexOf(',') >= 0) {
  528. _each(type.split(','), function() {
  529. _fire(el, this);
  530. });
  531. return;
  532. }
  533. var id = _getId(el);
  534. if (!id) {
  535. return;
  536. }
  537. var events = _eventData[id][type];
  538. if (_eventData[id] && events && events.length > 0) {
  539. events[0]();
  540. }
  541. }
  542. function _ctrl(el, key, fn) {
  543. var self = this;
  544. key = /^\d{2,}$/.test(key) ? key : key.toUpperCase().charCodeAt(0);
  545. _bind(el, 'keydown', function(e) {
  546. if (e.ctrlKey && e.which == key && !e.shiftKey && !e.altKey) {
  547. fn.call(el);
  548. e.stop();
  549. }
  550. });
  551. }
  552. var _readyFinished = false;
  553. function _ready(fn) {
  554. if (_readyFinished) {
  555. fn(KindEditor);
  556. return;
  557. }
  558. var loaded = false;
  559. function readyFunc() {
  560. if (!loaded) {
  561. loaded = true;
  562. fn(KindEditor);
  563. _readyFinished = true;
  564. }
  565. }
  566. function ieReadyFunc() {
  567. if (!loaded) {
  568. try {
  569. document.documentElement.doScroll('left');
  570. } catch(e) {
  571. setTimeout(ieReadyFunc, 100);
  572. return;
  573. }
  574. readyFunc();
  575. }
  576. }
  577. function ieReadyStateFunc() {
  578. if (document.readyState === 'complete') {
  579. readyFunc();
  580. }
  581. }
  582. if (document.addEventListener) {
  583. _bind(document, 'DOMContentLoaded', readyFunc);
  584. } else if (document.attachEvent) {
  585. _bind(document, 'readystatechange', ieReadyStateFunc);
  586. var toplevel = false;
  587. try {
  588. toplevel = window.frameElement == null;
  589. } catch(e) {}
  590. if (document.documentElement.doScroll && toplevel) {
  591. ieReadyFunc();
  592. }
  593. }
  594. _bind(window, 'load', readyFunc);
  595. }
  596. if (_IE) {
  597. window.attachEvent('onunload', function() {
  598. _each(_eventData, function(key, events) {
  599. if (events.el) {
  600. _unbind(events.el);
  601. }
  602. });
  603. });
  604. }
  605. K.ctrl = _ctrl;
  606. K.ready = _ready;
  607. function _getCssList(css) {
  608. var list = {},
  609. reg = /\s*([\w\-]+)\s*:([^;]*)(;|$)/g,
  610. match;
  611. while ((match = reg.exec(css))) {
  612. var key = _trim(match[1].toLowerCase()),
  613. val = _trim(_toHex(match[2]));
  614. list[key] = val;
  615. }
  616. return list;
  617. }
  618. function _getAttrList(tag) {
  619. var list = {},
  620. reg = /\s+(?:([\w\-:]+)|(?:([\w\-:]+)=([^\s"'<>]+))|(?:([\w\-:"]+)="([^"]*)")|(?:([\w\-:"]+)='([^']*)'))(?=(?:\s|\/|>)+)/g,
  621. match;
  622. while ((match = reg.exec(tag))) {
  623. var key = (match[1] || match[2] || match[4] || match[6]).toLowerCase(),
  624. val = (match[2] ? match[3] : (match[4] ? match[5] : match[7])) || '';
  625. list[key] = val;
  626. }
  627. return list;
  628. }
  629. function _addClassToTag(tag, className) {
  630. if (/\s+class\s*=/.test(tag)) {
  631. tag = tag.replace(/(\s+class=["']?)([^"']*)(["']?[\s>])/, function($0, $1, $2, $3) {
  632. if ((' ' + $2 + ' ').indexOf(' ' + className + ' ') < 0) {
  633. return $2 === '' ? $1 + className + $3 : $1 + $2 + ' ' + className + $3;
  634. } else {
  635. return $0;
  636. }
  637. });
  638. } else {
  639. tag = tag.substr(0, tag.length - 1) + ' class="' + className + '">';
  640. }
  641. return tag;
  642. }
  643. function _formatCss(css) {
  644. var str = '';
  645. _each(_getCssList(css), function(key, val) {
  646. str += key + ':' + val + ';';
  647. });
  648. return str;
  649. }
  650. function _formatUrl(url, mode, host, pathname) {
  651. mode = _undef(mode, '').toLowerCase();
  652. if (url.substr(0, 5) != 'data:') {
  653. url = url.replace(/([^:])\/\//g, '$1/');
  654. }
  655. if (_inArray(mode, ['absolute', 'relative', 'domain']) < 0) {
  656. return url;
  657. }
  658. host = host || location.protocol + '//' + location.host;
  659. if (pathname === undefined) {
  660. var m = location.pathname.match(/^(\/.*)\//);
  661. pathname = m ? m[1] : '';
  662. }
  663. var match;
  664. if ((match = /^(\w+:\/\/[^\/]*)/.exec(url))) {
  665. if (match[1] !== host) {
  666. return url;
  667. }
  668. } else if (/^\w+:/.test(url)) {
  669. return url;
  670. }
  671. function getRealPath(path) {
  672. var parts = path.split('/'), paths = [];
  673. for (var i = 0, len = parts.length; i < len; i++) {
  674. var part = parts[i];
  675. if (part == '..') {
  676. if (paths.length > 0) {
  677. paths.pop();
  678. }
  679. } else if (part !== '' && part != '.') {
  680. paths.push(part);
  681. }
  682. }
  683. return '/' + paths.join('/');
  684. }
  685. if (/^\//.test(url)) {
  686. url = host + getRealPath(url.substr(1));
  687. } else if (!/^\w+:\/\//.test(url)) {
  688. url = host + getRealPath(pathname + '/' + url);
  689. }
  690. function getRelativePath(path, depth) {
  691. if (url.substr(0, path.length) === path) {
  692. var arr = [];
  693. for (var i = 0; i < depth; i++) {
  694. arr.push('..');
  695. }
  696. var prefix = '.';
  697. if (arr.length > 0) {
  698. prefix += '/' + arr.join('/');
  699. }
  700. if (pathname == '/') {
  701. prefix += '/';
  702. }
  703. return prefix + url.substr(path.length);
  704. } else {
  705. if ((match = /^(.*)\//.exec(path))) {
  706. return getRelativePath(match[1], ++depth);
  707. }
  708. }
  709. }
  710. if (mode === 'relative') {
  711. url = getRelativePath(host + pathname, 0).substr(2);
  712. } else if (mode === 'absolute') {
  713. if (url.substr(0, host.length) === host) {
  714. url = url.substr(host.length);
  715. }
  716. }
  717. return url;
  718. }
  719. function _formatHtml(html, htmlTags, urlType, wellFormatted, indentChar) {
  720. if (html == null) {
  721. html = '';
  722. }
  723. urlType = urlType || '';
  724. wellFormatted = _undef(wellFormatted, false);
  725. indentChar = _undef(indentChar, '\t');
  726. var fontSizeList = 'xx-small,x-small,small,medium,large,x-large,xx-large'.split(',');
  727. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  728. return $1 + $2.replace(/<(?:br|br\s[^>]*)>/ig, '\n') + $3;
  729. });
  730. html = html.replace(/<(?:br|br\s[^>]*)\s*\/?>\s*<\/p>/ig, '</p>');
  731. html = html.replace(/(<(?:p|p\s[^>]*)>)\s*(<\/p>)/ig, '$1<br />$2');
  732. html = html.replace(/\u200B/g, '');
  733. html = html.replace(/\u00A9/g, '&copy;');
  734. html = html.replace(/\u00AE/g, '&reg;');
  735. html = html.replace(/<[^>]+/g, function($0) {
  736. return $0.replace(/\s+/g, ' ');
  737. });
  738. var htmlTagMap = {};
  739. if (htmlTags) {
  740. _each(htmlTags, function(key, val) {
  741. var arr = key.split(',');
  742. for (var i = 0, len = arr.length; i < len; i++) {
  743. htmlTagMap[arr[i]] = _toMap(val);
  744. }
  745. });
  746. if (!htmlTagMap.script) {
  747. html = html.replace(/(<(?:script|script\s[^>]*)>)([\s\S]*?)(<\/script>)/ig, '');
  748. }
  749. if (!htmlTagMap.style) {
  750. html = html.replace(/(<(?:style|style\s[^>]*)>)([\s\S]*?)(<\/style>)/ig, '');
  751. }
  752. }
  753. var re = /(\s*)<(\/)?([\w\-:]+)((?:\s+|(?:\s+[\w\-:]+)|(?:\s+[\w\-:]+=[^\s"'<>]+)|(?:\s+[\w\-:"]+="[^"]*")|(?:\s+[\w\-:"]+='[^']*'))*)(\/)?>(\s*)/g;
  754. var tagStack = [];
  755. html = html.replace(re, function($0, $1, $2, $3, $4, $5, $6) {
  756. var full = $0,
  757. startNewline = $1 || '',
  758. startSlash = $2 || '',
  759. tagName = $3.toLowerCase(),
  760. attr = $4 || '',
  761. endSlash = $5 ? ' ' + $5 : '',
  762. endNewline = $6 || '';
  763. if (htmlTags && !htmlTagMap[tagName]) {
  764. return '';
  765. }
  766. if (endSlash === '' && _SINGLE_TAG_MAP[tagName]) {
  767. endSlash = ' /';
  768. }
  769. if (_INLINE_TAG_MAP[tagName]) {
  770. if (startNewline) {
  771. startNewline = ' ';
  772. }
  773. if (endNewline) {
  774. endNewline = ' ';
  775. }
  776. }
  777. if (_PRE_TAG_MAP[tagName]) {
  778. if (startSlash) {
  779. endNewline = '\n';
  780. } else {
  781. startNewline = '\n';
  782. }
  783. }
  784. if (wellFormatted && tagName == 'br') {
  785. endNewline = '\n';
  786. }
  787. if (_BLOCK_TAG_MAP[tagName] && !_PRE_TAG_MAP[tagName]) {
  788. if (wellFormatted) {
  789. if (startSlash && tagStack.length > 0 && tagStack[tagStack.length - 1] === tagName) {
  790. tagStack.pop();
  791. } else {
  792. tagStack.push(tagName);
  793. }
  794. startNewline = '\n';
  795. endNewline = '\n';
  796. for (var i = 0, len = startSlash ? tagStack.length : tagStack.length - 1; i < len; i++) {
  797. startNewline += indentChar;
  798. if (!startSlash) {
  799. endNewline += indentChar;
  800. }
  801. }
  802. if (endSlash) {
  803. tagStack.pop();
  804. } else if (!startSlash) {
  805. endNewline += indentChar;
  806. }
  807. } else {
  808. startNewline = endNewline = '';
  809. }
  810. }
  811. if (attr !== '') {
  812. var attrMap = _getAttrList(full);
  813. if (tagName === 'font') {
  814. var fontStyleMap = {}, fontStyle = '';
  815. _each(attrMap, function(key, val) {
  816. if (key === 'color') {
  817. fontStyleMap.color = val;
  818. delete attrMap[key];
  819. }
  820. if (key === 'size') {
  821. fontStyleMap['font-size'] = fontSizeList[parseInt(val, 10) - 1] || '';
  822. delete attrMap[key];
  823. }
  824. if (key === 'face') {
  825. fontStyleMap['font-family'] = val;
  826. delete attrMap[key];
  827. }
  828. if (key === 'style') {
  829. fontStyle = val;
  830. }
  831. });
  832. if (fontStyle && !/;$/.test(fontStyle)) {
  833. fontStyle += ';';
  834. }
  835. _each(fontStyleMap, function(key, val) {
  836. if (val === '') {
  837. return;
  838. }
  839. if (/\s/.test(val)) {
  840. val = "'" + val + "'";
  841. }
  842. fontStyle += key + ':' + val + ';';
  843. });
  844. attrMap.style = fontStyle;
  845. }
  846. _each(attrMap, function(key, val) {
  847. if (_FILL_ATTR_MAP[key]) {
  848. attrMap[key] = key;
  849. }
  850. if (_inArray(key, ['src', 'href']) >= 0) {
  851. attrMap[key] = _formatUrl(val, urlType);
  852. }
  853. if (htmlTags && key !== 'style' && !htmlTagMap[tagName]['*'] && !htmlTagMap[tagName][key] ||
  854. tagName === 'body' && key === 'contenteditable' ||
  855. /^kindeditor_\d+$/.test(key)) {
  856. delete attrMap[key];
  857. }
  858. if (key === 'style' && val !== '') {
  859. var styleMap = _getCssList(val);
  860. _each(styleMap, function(k, v) {
  861. if (htmlTags && !htmlTagMap[tagName].style && !htmlTagMap[tagName]['.' + k]) {
  862. delete styleMap[k];
  863. }
  864. });
  865. var style = '';
  866. _each(styleMap, function(k, v) {
  867. style += k + ':' + v + ';';
  868. });
  869. attrMap.style = style;
  870. }
  871. });
  872. attr = '';
  873. _each(attrMap, function(key, val) {
  874. if (key === 'style' && val === '') {
  875. return;
  876. }
  877. val = val.replace(/"/g, '&quot;');
  878. attr += ' ' + key + '="' + val + '"';
  879. });
  880. }
  881. if (tagName === 'font') {
  882. tagName = 'span';
  883. }
  884. return startNewline + '<' + startSlash + tagName + attr + endSlash + '>' + endNewline;
  885. });
  886. html = html.replace(/(<(?:pre|pre\s[^>]*)>)([\s\S]*?)(<\/pre>)/ig, function($0, $1, $2, $3) {
  887. return $1 + $2.replace(/\n/g, '<span id="__kindeditor_pre_newline__">\n') + $3;
  888. });
  889. html = html.replace(/\n\s*\n/g, '\n');
  890. html = html.replace(/<span id="__kindeditor_pre_newline__">\n/g, '\n');
  891. return _trim(html);
  892. }
  893. function _clearMsWord(html, htmlTags) {
  894. html = html.replace(/<meta[\s\S]*?>/ig, '')
  895. .replace(/<![\s\S]*?>/ig, '')
  896. .replace(/<style[^>]*>[\s\S]*?<\/style>/ig, '')
  897. .replace(/<script[^>]*>[\s\S]*?<\/script>/ig, '')
  898. .replace(/<w:[^>]+>[\s\S]*?<\/w:[^>]+>/ig, '')
  899. .replace(/<o:[^>]+>[\s\S]*?<\/o:[^>]+>/ig, '')
  900. .replace(/<xml>[\s\S]*?<\/xml>/ig, '')
  901. .replace(/<(?:table|td)[^>]*>/ig, function(full) {
  902. return full.replace(/border-bottom:([#\w\s]+)/ig, 'border:$1');
  903. });
  904. return _formatHtml(html, htmlTags);
  905. }
  906. function _mediaType(src) {
  907. if (/\.(rm|rmvb)(\?|$)/i.test(src)) {
  908. return 'audio/x-pn-realaudio-plugin';
  909. }
  910. if (/\.(swf|flv)(\?|$)/i.test(src)) {
  911. return 'application/x-shockwave-flash';
  912. }
  913. return 'video/x-ms-asf-plugin';
  914. }
  915. function _mediaClass(type) {
  916. if (/realaudio/i.test(type)) {
  917. return 'ke-rm';
  918. }
  919. if (/flash/i.test(type)) {
  920. return 'ke-flash';
  921. }
  922. return 'ke-media';
  923. }
  924. function _mediaAttrs(srcTag) {
  925. return _getAttrList(unescape(srcTag));
  926. }
  927. function _mediaEmbed(attrs) {
  928. var html = '<embed ';
  929. _each(attrs, function(key, val) {
  930. html += key + '="' + val + '" ';
  931. });
  932. html += '/>';
  933. return html;
  934. }
  935. function _mediaImg(blankPath, attrs) {
  936. var width = attrs.width,
  937. height = attrs.height,
  938. type = attrs.type || _mediaType(attrs.src),
  939. srcTag = _mediaEmbed(attrs),
  940. style = '';
  941. if (/\D/.test(width)) {
  942. style += 'width:' + width + ';';
  943. } else if (width > 0) {
  944. style += 'width:' + width + 'px;';
  945. }
  946. if (/\D/.test(height)) {
  947. style += 'height:' + height + ';';
  948. } else if (height > 0) {
  949. style += 'height:' + height + 'px;';
  950. }
  951. var html = '<img class="' + _mediaClass(type) + '" src="' + blankPath + '" ';
  952. if (style !== '') {
  953. html += 'style="' + style + '" ';
  954. }
  955. html += 'data-ke-tag="' + escape(srcTag) + '" alt="" />';
  956. return html;
  957. }
  958. function _tmpl(str, data) {
  959. var fn = new Function("obj",
  960. "var p=[],print=function(){p.push.apply(p,arguments);};" +
  961. "with(obj){p.push('" +
  962. str.replace(/[\r\t\n]/g, " ")
  963. .split("<%").join("\t")
  964. .replace(/((^|%>)[^\t]*)'/g, "$1\r")
  965. .replace(/\t=(.*?)%>/g, "',$1,'")
  966. .split("\t").join("');")
  967. .split("%>").join("p.push('")
  968. .split("\r").join("\\'") + "');}return p.join('');");
  969. return data ? fn(data) : fn;
  970. }
  971. K.formatUrl = _formatUrl;
  972. K.formatHtml = _formatHtml;
  973. K.getCssList = _getCssList;
  974. K.getAttrList = _getAttrList;
  975. K.mediaType = _mediaType;
  976. K.mediaAttrs = _mediaAttrs;
  977. K.mediaEmbed = _mediaEmbed;
  978. K.mediaImg = _mediaImg;
  979. K.clearMsWord = _clearMsWord;
  980. K.tmpl = _tmpl;
  981. function _contains(nodeA, nodeB) {
  982. if (nodeA.nodeType == 9 && nodeB.nodeType != 9) {
  983. return true;
  984. }
  985. while ((nodeB = nodeB.parentNode)) {
  986. if (nodeB == nodeA) {
  987. return true;
  988. }
  989. }
  990. return false;
  991. }
  992. var _getSetAttrDiv = document.createElement('div');
  993. _getSetAttrDiv.setAttribute('className', 't');
  994. var _GET_SET_ATTRIBUTE = _getSetAttrDiv.className !== 't';
  995. function _getAttr(el, key) {
  996. key = key.toLowerCase();
  997. var val = null;
  998. if (!_GET_SET_ATTRIBUTE && el.nodeName.toLowerCase() != 'script') {
  999. var div = el.ownerDocument.createElement('div');
  1000. div.appendChild(el.cloneNode(false));
  1001. var list = _getAttrList(_unescape(div.innerHTML));
  1002. if (key in list) {
  1003. val = list[key];
  1004. }
  1005. } else {
  1006. try {
  1007. val = el.getAttribute(key, 2);
  1008. } catch(e) {
  1009. val = el.getAttribute(key, 1);
  1010. }
  1011. }
  1012. if (key === 'style' && val !== null) {
  1013. val = _formatCss(val);
  1014. }
  1015. return val;
  1016. }
  1017. function _queryAll(expr, root) {
  1018. var exprList = expr.split(',');
  1019. if (exprList.length > 1) {
  1020. var mergedResults = [];
  1021. _each(exprList, function() {
  1022. _each(_queryAll(this, root), function() {
  1023. if (_inArray(this, mergedResults) < 0) {
  1024. mergedResults.push(this);
  1025. }
  1026. });
  1027. });
  1028. return mergedResults;
  1029. }
  1030. root = root || document;
  1031. function escape(str) {
  1032. if (typeof str != 'string') {
  1033. return str;
  1034. }
  1035. return str.replace(/([^\w\-])/g, '\\$1');
  1036. }
  1037. function stripslashes(str) {
  1038. return str.replace(/\\/g, '');
  1039. }
  1040. function cmpTag(tagA, tagB) {
  1041. return tagA === '*' || tagA.toLowerCase() === escape(tagB.toLowerCase());
  1042. }
  1043. function byId(id, tag, root) {
  1044. var arr = [],
  1045. doc = root.ownerDocument || root,
  1046. el = doc.getElementById(stripslashes(id));
  1047. if (el) {
  1048. if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1049. arr.push(el);
  1050. }
  1051. }
  1052. return arr;
  1053. }
  1054. function byClass(className, tag, root) {
  1055. var doc = root.ownerDocument || root, arr = [], els, i, len, el;
  1056. if (root.getElementsByClassName) {
  1057. els = root.getElementsByClassName(stripslashes(className));
  1058. for (i = 0, len = els.length; i < len; i++) {
  1059. el = els[i];
  1060. if (cmpTag(tag, el.nodeName)) {
  1061. arr.push(el);
  1062. }
  1063. }
  1064. } else if (doc.querySelectorAll) {
  1065. els = doc.querySelectorAll((root.nodeName !== '#document' ? root.nodeName + ' ' : '') + tag + '.' + className);
  1066. for (i = 0, len = els.length; i < len; i++) {
  1067. el = els[i];
  1068. if (_contains(root, el)) {
  1069. arr.push(el);
  1070. }
  1071. }
  1072. } else {
  1073. els = root.getElementsByTagName(tag);
  1074. className = ' ' + className + ' ';
  1075. for (i = 0, len = els.length; i < len; i++) {
  1076. el = els[i];
  1077. if (el.nodeType == 1) {
  1078. var cls = el.className;
  1079. if (cls && (' ' + cls + ' ').indexOf(className) > -1) {
  1080. arr.push(el);
  1081. }
  1082. }
  1083. }
  1084. }
  1085. return arr;
  1086. }
  1087. function byName(name, tag, root) {
  1088. var arr = [], doc = root.ownerDocument || root,
  1089. els = doc.getElementsByName(stripslashes(name)), el;
  1090. for (var i = 0, len = els.length; i < len; i++) {
  1091. el = els[i];
  1092. if (cmpTag(tag, el.nodeName) && _contains(root, el)) {
  1093. if (el.getAttribute('name') !== null) {
  1094. arr.push(el);
  1095. }
  1096. }
  1097. }
  1098. return arr;
  1099. }
  1100. function byAttr(key, val, tag, root) {
  1101. var arr = [], els = root.getElementsByTagName(tag), el;
  1102. for (var i = 0, len = els.length; i < len; i++) {
  1103. el = els[i];
  1104. if (el.nodeType == 1) {
  1105. if (val === null) {
  1106. if (_getAttr(el, key) !== null) {
  1107. arr.push(el);
  1108. }
  1109. } else {
  1110. if (val === escape(_getAttr(el, key))) {
  1111. arr.push(el);
  1112. }
  1113. }
  1114. }
  1115. }
  1116. return arr;
  1117. }
  1118. function select(expr, root) {
  1119. var arr = [], matches;
  1120. matches = /^((?:\\.|[^.#\s\[<>])+)/.exec(expr);
  1121. var tag = matches ? matches[1] : '*';
  1122. if ((matches = /#((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1123. arr = byId(matches[1], tag, root);
  1124. } else if ((matches = /\.((?:[\w\-]|\\.)+)$/.exec(expr))) {
  1125. arr = byClass(matches[1], tag, root);
  1126. } else if ((matches = /\[((?:[\w\-]|\\.)+)\]/.exec(expr))) {
  1127. arr = byAttr(matches[1].toLowerCase(), null, tag, root);
  1128. } else if ((matches = /\[((?:[\w\-]|\\.)+)\s*=\s*['"]?((?:\\.|[^'"]+)+)['"]?\]/.exec(expr))) {
  1129. var key = matches[1].toLowerCase(), val = matches[2];
  1130. if (key === 'id') {
  1131. arr = byId(val, tag, root);
  1132. } else if (key === 'class') {
  1133. arr = byClass(val, tag, root);
  1134. } else if (key === 'name') {
  1135. arr = byName(val, tag, root);
  1136. } else {
  1137. arr = byAttr(key, val, tag, root);
  1138. }
  1139. } else {
  1140. var els = root.getElementsByTagName(tag), el;
  1141. for (var i = 0, len = els.length; i < len; i++) {
  1142. el = els[i];
  1143. if (el.nodeType == 1) {
  1144. arr.push(el);
  1145. }
  1146. }
  1147. }
  1148. return arr;
  1149. }
  1150. var parts = [], arr, re = /((?:\\.|[^\s>])+|[\s>])/g;
  1151. while ((arr = re.exec(expr))) {
  1152. if (arr[1] !== ' ') {
  1153. parts.push(arr[1]);
  1154. }
  1155. }
  1156. var results = [];
  1157. if (parts.length == 1) {
  1158. return select(parts[0], root);
  1159. }
  1160. var isChild = false, part, els, subResults, val, v, i, j, k, length, len, l;
  1161. for (i = 0, lenth = parts.length; i < lenth; i++) {
  1162. part = parts[i];
  1163. if (part === '>') {
  1164. isChild = true;
  1165. continue;
  1166. }
  1167. if (i > 0) {
  1168. els = [];
  1169. for (j = 0, len = results.length; j < len; j++) {
  1170. val = results[j];
  1171. subResults = select(part, val);
  1172. for (k = 0, l = subResults.length; k < l; k++) {
  1173. v = subResults[k];
  1174. if (isChild) {
  1175. if (val === v.parentNode) {
  1176. els.push(v);
  1177. }
  1178. } else {
  1179. els.push(v);
  1180. }
  1181. }
  1182. }
  1183. results = els;
  1184. } else {
  1185. results = select(part, root);
  1186. }
  1187. if (results.length === 0) {
  1188. return [];
  1189. }
  1190. }
  1191. return results;
  1192. }
  1193. function _query(expr, root) {
  1194. var arr = _queryAll(expr, root);
  1195. return arr.length > 0 ? arr[0] : null;
  1196. }
  1197. K.query = _query;
  1198. K.queryAll = _queryAll;
  1199. function _get(val) {
  1200. return K(val)[0];
  1201. }
  1202. function _getDoc(node) {
  1203. if (!node) {
  1204. return document;
  1205. }
  1206. return node.ownerDocument || node.document || node;
  1207. }
  1208. function _getWin(node) {
  1209. if (!node) {
  1210. return window;
  1211. }
  1212. var doc = _getDoc(node);
  1213. return doc.parentWindow || doc.defaultView;
  1214. }
  1215. function _setHtml(el, html) {
  1216. if (el.nodeType != 1) {
  1217. return;
  1218. }
  1219. var doc = _getDoc(el);
  1220. try {
  1221. el.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + html;
  1222. var temp = doc.getElementById('__kindeditor_temp_tag__');
  1223. temp.parentNode.removeChild(temp);
  1224. } catch(e) {
  1225. K(el).empty();
  1226. K('@' + html, doc).each(function() {
  1227. el.appendChild(this);
  1228. });
  1229. }
  1230. }
  1231. function _hasClass(el, cls) {
  1232. return _inString(cls, el.className, ' ');
  1233. }
  1234. function _setAttr(el, key, val) {
  1235. if (_IE && _V < 8 && key.toLowerCase() == 'class') {
  1236. key = 'className';
  1237. }
  1238. el.setAttribute(key, '' + val);
  1239. }
  1240. function _removeAttr(el, key) {
  1241. if (_IE && _V < 8 && key.toLowerCase() == 'class') {
  1242. key = 'className';
  1243. }
  1244. _setAttr(el, key, '');
  1245. el.removeAttribute(key);
  1246. }
  1247. function _getNodeName(node) {
  1248. if (!node || !node.nodeName) {
  1249. return '';
  1250. }
  1251. return node.nodeName.toLowerCase();
  1252. }
  1253. function _computedCss(el, key) {
  1254. var self = this, win = _getWin(el), camelKey = _toCamel(key), val = '';
  1255. if (win.getComputedStyle) {
  1256. var style = win.getComputedStyle(el, null);
  1257. val = style[camelKey] || style.getPropertyValue(key) || el.style[camelKey];
  1258. } else if (el.currentStyle) {
  1259. val = el.currentStyle[camelKey] || el.style[camelKey];
  1260. }
  1261. return val;
  1262. }
  1263. function _hasVal(node) {
  1264. return !!_VALUE_TAG_MAP[_getNodeName(node)];
  1265. }
  1266. function _docElement(doc) {
  1267. doc = doc || document;
  1268. return _QUIRKS ? doc.body : doc.documentElement;
  1269. }
  1270. function _docHeight(doc) {
  1271. var el = _docElement(doc);
  1272. return Math.max(el.scrollHeight, el.clientHeight);
  1273. }
  1274. function _docWidth(doc) {
  1275. var el = _docElement(doc);
  1276. return Math.max(el.scrollWidth, el.clientWidth);
  1277. }
  1278. function _getScrollPos(doc) {
  1279. doc = doc || document;
  1280. var x, y;
  1281. if (_IE || _NEWIE || _OPERA) {
  1282. x = _docElement(doc).scrollLeft;
  1283. y = _docElement(doc).scrollTop;
  1284. } else {
  1285. x = _getWin(doc).scrollX;
  1286. y = _getWin(doc).scrollY;
  1287. }
  1288. return {x : x, y : y};
  1289. }
  1290. function KNode(node) {
  1291. this.init(node);
  1292. }
  1293. _extend(KNode, {
  1294. init : function(node) {
  1295. var self = this;
  1296. node = _isArray(node) ? node : [node];
  1297. var length = 0;
  1298. for (var i = 0, len = node.length; i < len; i++) {
  1299. if (node[i]) {
  1300. self[i] = node[i].constructor === KNode ? node[i][0] : node[i];
  1301. length++;
  1302. }
  1303. }
  1304. self.length = length;
  1305. self.doc = _getDoc(self[0]);
  1306. self.name = _getNodeName(self[0]);
  1307. self.type = self.length > 0 ? self[0].nodeType : null;
  1308. self.win = _getWin(self[0]);
  1309. },
  1310. each : function(fn) {
  1311. var self = this;
  1312. for (var i = 0; i < self.length; i++) {
  1313. if (fn.call(self[i], i, self[i]) === false) {
  1314. return self;
  1315. }
  1316. }
  1317. return self;
  1318. },
  1319. bind : function(type, fn) {
  1320. this.each(function() {
  1321. _bind(this, type, fn);
  1322. });
  1323. return this;
  1324. },
  1325. unbind : function(type, fn) {
  1326. this.each(function() {
  1327. _unbind(this, type, fn);
  1328. });
  1329. return this;
  1330. },
  1331. fire : function(type) {
  1332. if (this.length < 1) {
  1333. return this;
  1334. }
  1335. _fire(this[0], type);
  1336. return this;
  1337. },
  1338. hasAttr : function(key) {
  1339. if (this.length < 1) {
  1340. return false;
  1341. }
  1342. return !!_getAttr(this[0], key);
  1343. },
  1344. attr : function(key, val) {
  1345. var self = this;
  1346. if (key === undefined) {
  1347. return _getAttrList(self.outer());
  1348. }
  1349. if (typeof key === 'object') {
  1350. _each(key, function(k, v) {
  1351. self.attr(k, v);
  1352. });
  1353. return self;
  1354. }
  1355. if (val === undefined) {
  1356. val = self.length < 1 ? null : _getAttr(self[0], key);
  1357. return val === null ? '' : val;
  1358. }
  1359. self.each(function() {
  1360. _setAttr(this, key, val);
  1361. });
  1362. return self;
  1363. },
  1364. removeAttr : function(key) {
  1365. this.each(function() {
  1366. _removeAttr(this, key);
  1367. });
  1368. return this;
  1369. },
  1370. get : function(i) {
  1371. if (this.length < 1) {
  1372. return null;
  1373. }
  1374. return this[i || 0];
  1375. },
  1376. eq : function(i) {
  1377. if (this.length < 1) {
  1378. return null;
  1379. }
  1380. return this[i] ? new KNode(this[i]) : null;
  1381. },
  1382. hasClass : function(cls) {
  1383. if (this.length < 1) {
  1384. return false;
  1385. }
  1386. return _hasClass(this[0], cls);
  1387. },
  1388. addClass : function(cls) {
  1389. this.each(function() {
  1390. if (!_hasClass(this, cls)) {
  1391. this.className = _trim(this.className + ' ' + cls);
  1392. }
  1393. });
  1394. return this;
  1395. },
  1396. removeClass : function(cls) {
  1397. this.each(function() {
  1398. if (_hasClass(this, cls)) {
  1399. this.className = _trim(this.className.replace(new RegExp('(^|\\s)' + cls + '(\\s|$)'), ' '));
  1400. }
  1401. });
  1402. return this;
  1403. },
  1404. html : function(val) {
  1405. var self = this;
  1406. if (val === undefined) {
  1407. if (self.length < 1 || self.type != 1) {
  1408. return '';
  1409. }
  1410. return _formatHtml(self[0].innerHTML);
  1411. }
  1412. self.each(function() {
  1413. _setHtml(this, val);
  1414. });
  1415. return self;
  1416. },
  1417. text : function() {
  1418. var self = this;
  1419. if (self.length < 1) {
  1420. return '';
  1421. }
  1422. return _IE ? self[0].innerText : self[0].textContent;
  1423. },
  1424. hasVal : function() {
  1425. if (this.length < 1) {
  1426. return false;
  1427. }
  1428. return _hasVal(this[0]);
  1429. },
  1430. val : function(val) {
  1431. var self = this;
  1432. if (val === undefined) {
  1433. if (self.length < 1) {
  1434. return '';
  1435. }
  1436. return self.hasVal() ? self[0].value : self.attr('value');
  1437. } else {
  1438. self.each(function() {
  1439. if (_hasVal(this)) {
  1440. this.value = val;
  1441. } else {
  1442. _setAttr(this, 'value' , val);
  1443. }
  1444. });
  1445. return self;
  1446. }
  1447. },
  1448. css : function(key, val) {
  1449. var self = this;
  1450. if (key === undefined) {
  1451. return _getCssList(self.attr('style'));
  1452. }
  1453. if (typeof key === 'object') {
  1454. _each(key, function(k, v) {
  1455. self.css(k, v);
  1456. });
  1457. return self;
  1458. }
  1459. if (val === undefined) {
  1460. if (self.length < 1) {
  1461. return '';
  1462. }
  1463. return self[0].style[_toCamel(key)] || _computedCss(self[0], key) || '';
  1464. }
  1465. self.each(function() {
  1466. this.style[_toCamel(key)] = val;
  1467. });
  1468. return self;
  1469. },
  1470. width : function(val) {
  1471. var self = this;
  1472. if (val === undefined) {
  1473. if (self.length < 1) {
  1474. return 0;
  1475. }
  1476. return self[0].offsetWidth;
  1477. }
  1478. return self.css('width', _addUnit(val));
  1479. },
  1480. height : function(val) {
  1481. var self = this;
  1482. if (val === undefined) {
  1483. if (self.length < 1) {
  1484. return 0;
  1485. }
  1486. return self[0].offsetHeight;
  1487. }
  1488. return self.css('height', _addUnit(val));
  1489. },
  1490. opacity : function(val) {
  1491. this.each(function() {
  1492. if (this.style.opacity === undefined) {
  1493. this.style.filter = val == 1 ? '' : 'alpha(opacity=' + (val * 100) + ')';
  1494. } else {
  1495. this.style.opacity = val == 1 ? '' : val;
  1496. }
  1497. });
  1498. return this;
  1499. },
  1500. data : function(key, val) {
  1501. var self = this;
  1502. key = 'kindeditor_data_' + key;
  1503. if (val === undefined) {
  1504. if (self.length < 1) {
  1505. return null;
  1506. }
  1507. return self[0][key];
  1508. }
  1509. this.each(function() {
  1510. this[key] = val;
  1511. });
  1512. return self;
  1513. },
  1514. pos : function() {
  1515. var self = this, node = self[0], x = 0, y = 0;
  1516. if (node) {
  1517. if (node.getBoundingClientRect) {
  1518. var box = node.getBoundingClientRect(),
  1519. pos = _getScrollPos(self.doc);
  1520. x = box.left + pos.x;
  1521. y = box.top + pos.y;
  1522. } else {
  1523. while (node) {
  1524. x += node.offsetLeft;
  1525. y += node.offsetTop;
  1526. node = node.offsetParent;
  1527. }
  1528. }
  1529. }
  1530. return {x : _round(x), y : _round(y)};
  1531. },
  1532. clone : function(bool) {
  1533. if (this.length < 1) {
  1534. return new KNode([]);
  1535. }
  1536. return new KNode(this[0].cloneNode(bool));
  1537. },
  1538. append : function(expr) {
  1539. this.each(function() {
  1540. if (this.appendChild) {
  1541. this.appendChild(_get(expr));
  1542. }
  1543. });
  1544. return this;
  1545. },
  1546. appendTo : function(expr) {
  1547. this.each(function() {
  1548. _get(expr).appendChild(this);
  1549. });
  1550. return this;
  1551. },
  1552. before : function(expr) {
  1553. this.each(function() {
  1554. this.parentNode.insertBefore(_get(expr), this);
  1555. });
  1556. return this;
  1557. },
  1558. after : function(expr) {
  1559. this.each(function() {
  1560. if (this.nextSibling) {
  1561. this.parentNode.insertBefore(_get(expr), this.nextSibling);
  1562. } else {
  1563. this.parentNode.appendChild(_get(expr));
  1564. }
  1565. });
  1566. return this;
  1567. },
  1568. replaceWith : function(expr) {
  1569. var nodes = [];
  1570. this.each(function(i, node) {
  1571. _unbind(node);
  1572. var newNode = _get(expr);
  1573. node.parentNode.replaceChild(newNode, node);
  1574. nodes.push(newNode);
  1575. });
  1576. return K(nodes);
  1577. },
  1578. empty : function() {
  1579. var self = this;
  1580. self.each(function(i, node) {
  1581. var child = node.firstChild;
  1582. while (child) {
  1583. if (!node.parentNode) {
  1584. return;
  1585. }
  1586. var next = child.nextSibling;
  1587. child.parentNode.removeChild(child);
  1588. child = next;
  1589. }
  1590. });
  1591. return self;
  1592. },
  1593. remove : function(keepChilds) {
  1594. var self = this;
  1595. self.each(function(i, node) {
  1596. if (!node.parentNode) {
  1597. return;
  1598. }
  1599. _unbind(node);
  1600. if (keepChilds) {
  1601. var child = node.firstChild;
  1602. while (child) {
  1603. var next = child.nextSibling;
  1604. node.parentNode.insertBefore(child, node);
  1605. child = next;
  1606. }
  1607. }
  1608. node.parentNode.removeChild(node);
  1609. delete self[i];
  1610. });
  1611. self.length = 0;
  1612. return self;
  1613. },
  1614. show : function(val) {
  1615. var self = this;
  1616. if (val === undefined) {
  1617. val = self._originDisplay || '';
  1618. }
  1619. if (self.css('display') != 'none') {
  1620. return self;
  1621. }
  1622. return self.css('display', val);
  1623. },
  1624. hide : function() {
  1625. var self = this;
  1626. if (self.length < 1) {
  1627. return self;
  1628. }
  1629. self._originDisplay = self[0].style.display;
  1630. return self.css('display', 'none');
  1631. },
  1632. outer : function() {
  1633. var self = this;
  1634. if (self.length < 1) {
  1635. return '';
  1636. }
  1637. var div = self.doc.createElement('div'), html;
  1638. div.appendChild(self[0].cloneNode(true));
  1639. html = _formatHtml(div.innerHTML);
  1640. div = null;
  1641. return html;
  1642. },
  1643. isSingle : function() {
  1644. return !!_SINGLE_TAG_MAP[this.name];
  1645. },
  1646. isInline : function() {
  1647. return !!_INLINE_TAG_MAP[this.name];
  1648. },
  1649. isBlock : function() {
  1650. return !!_BLOCK_TAG_MAP[this.name];
  1651. },
  1652. isStyle : function() {
  1653. return !!_STYLE_TAG_MAP[this.name];
  1654. },
  1655. isControl : function() {
  1656. return !!_CONTROL_TAG_MAP[this.name];
  1657. },
  1658. contains : function(otherNode) {
  1659. if (this.length < 1) {
  1660. return false;
  1661. }
  1662. return _contains(this[0], _get(otherNode));
  1663. },
  1664. parent : function() {
  1665. if (this.length < 1) {
  1666. return null;
  1667. }
  1668. var node = this[0].parentNode;
  1669. return node ? new KNode(node) : null;
  1670. },
  1671. children : function() {
  1672. if (this.length < 1) {
  1673. return new KNode([]);
  1674. }
  1675. var list = [], child = this[0].firstChild;
  1676. while (child) {
  1677. if (child.nodeType != 3 || _trim(child.nodeValue) !== '') {
  1678. list.push(child);
  1679. }
  1680. child = child.nextSibling;
  1681. }
  1682. return new KNode(list);
  1683. },
  1684. first : function() {
  1685. var list = this.children();
  1686. return list.length > 0 ? list.eq(0) : null;
  1687. },
  1688. last : function() {
  1689. var list = this.children();
  1690. return list.length > 0 ? list.eq(list.length - 1) : null;
  1691. },
  1692. index : function() {
  1693. if (this.length < 1) {
  1694. return -1;
  1695. }
  1696. var i = -1, sibling = this[0];
  1697. while (sibling) {
  1698. i++;
  1699. sibling = sibling.previousSibling;
  1700. }
  1701. return i;
  1702. },
  1703. prev : function() {
  1704. if (this.length < 1) {
  1705. return null;
  1706. }
  1707. var node = this[0].previousSibling;
  1708. return node ? new KNode(node) : null;
  1709. },
  1710. next : function() {
  1711. if (this.length < 1) {
  1712. return null;
  1713. }
  1714. var node = this[0].nextSibling;
  1715. return node ? new KNode(node) : null;
  1716. },
  1717. scan : function(fn, order) {
  1718. if (this.length < 1) {
  1719. return;
  1720. }
  1721. order = (order === undefined) ? true : order;
  1722. function walk(node) {
  1723. var n = order ? node.firstChild : node.lastChild;
  1724. while (n) {
  1725. var next = order ? n.nextSibling : n.previousSibling;
  1726. if (fn(n) === false) {
  1727. return false;
  1728. }
  1729. if (walk(n) === false) {
  1730. return false;
  1731. }
  1732. n = next;
  1733. }
  1734. }
  1735. walk(this[0]);
  1736. return this;
  1737. }
  1738. });
  1739. _each(('blur,focus,focusin,focusout,load,resize,scroll,unload,click,dblclick,' +
  1740. 'mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,' +
  1741. 'change,select,submit,keydown,keypress,keyup,error,contextmenu').split(','), function(i, type) {
  1742. KNode.prototype[type] = function(fn) {
  1743. return fn ? this.bind(type, fn) : this.fire(type);
  1744. };
  1745. });
  1746. var _K = K;
  1747. K = function(expr, root) {
  1748. if (expr === undefined || expr === null) {
  1749. return;
  1750. }
  1751. function newNode(node) {
  1752. if (!node[0]) {
  1753. node = [];
  1754. }
  1755. return new KNode(node);
  1756. }
  1757. if (typeof expr === 'string') {
  1758. if (root) {
  1759. root = _get(root);
  1760. }
  1761. var length = expr.length;
  1762. if (expr.charAt(0) === '@') {
  1763. expr = expr.substr(1);
  1764. }
  1765. if (expr.length !== length || /<.+>/.test(expr)) {
  1766. var doc = root ? root.ownerDocument || root : document,
  1767. div = doc.createElement('div'), list = [];
  1768. div.innerHTML = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + expr;
  1769. for (var i = 0, len = div.childNodes.length; i < len; i++) {
  1770. var child = div.childNodes[i];
  1771. if (child.id == '__kindeditor_temp_tag__') {
  1772. continue;
  1773. }
  1774. list.push(child);
  1775. }
  1776. return newNode(list);
  1777. }
  1778. return newNode(_queryAll(expr, root));
  1779. }
  1780. if (expr && expr.constructor === KNode) {
  1781. return expr;
  1782. }
  1783. if (expr.toArray) {
  1784. expr = expr.toArray();
  1785. }
  1786. if (_isArray(expr)) {
  1787. return newNode(expr);
  1788. }
  1789. return newNode(_toArray(arguments));
  1790. };
  1791. _each(_K, function(key, val) {
  1792. K[key] = val;
  1793. });
  1794. K.NodeClass = KNode;
  1795. window.KindEditor = K;
  1796. var _START_TO_START = 0,
  1797. _START_TO_END = 1,
  1798. _END_TO_END = 2,
  1799. _END_TO_START = 3,
  1800. _BOOKMARK_ID = 0;
  1801. function _updateCollapsed(range) {
  1802. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset);
  1803. return range;
  1804. }
  1805. function _copyAndDelete(range, isCopy, isDelete) {
  1806. var doc = range.doc, nodeList = [];
  1807. function splitTextNode(node, startOffset, endOffset) {
  1808. var length = node.nodeValue.length, centerNode;
  1809. if (isCopy) {
  1810. var cloneNode = node.cloneNode(true);
  1811. if (startOffset > 0) {
  1812. centerNode = cloneNode.splitText(startOffset);
  1813. } else {
  1814. centerNode = cloneNode;
  1815. }
  1816. if (endOffset < length) {
  1817. centerNode.splitText(endOffset - startOffset);
  1818. }
  1819. }
  1820. if (isDelete) {
  1821. var center = node;
  1822. if (startOffset > 0) {
  1823. center = node.splitText(startOffset);
  1824. range.setStart(node, startOffset);
  1825. }
  1826. if (endOffset < length) {
  1827. var right = center.splitText(endOffset - startOffset);
  1828. range.setEnd(right, 0);
  1829. }
  1830. nodeList.push(center);
  1831. }
  1832. return centerNode;
  1833. }
  1834. function removeNodes() {
  1835. if (isDelete) {
  1836. range.up().collapse(true);
  1837. }
  1838. for (var i = 0, len = nodeList.length; i < len; i++) {
  1839. var node = nodeList[i];
  1840. if (node.parentNode) {
  1841. node.parentNode.removeChild(node);
  1842. }
  1843. }
  1844. }
  1845. var copyRange = range.cloneRange().down();
  1846. var start = -1, incStart = -1, incEnd = -1, end = -1,
  1847. ancestor = range.commonAncestor(), frag = doc.createDocumentFragment();
  1848. if (ancestor.nodeType == 3) {
  1849. var textNode = splitTextNode(ancestor, range.startOffset, range.endOffset);
  1850. if (isCopy) {
  1851. frag.appendChild(textNode);
  1852. }
  1853. removeNodes();
  1854. return isCopy ? frag : range;
  1855. }
  1856. function extractNodes(parent, frag) {
  1857. var node = parent.firstChild, nextNode;
  1858. while (node) {
  1859. var testRange = new KRange(doc).selectNode(node);
  1860. start = testRange.compareBoundaryPoints(_START_TO_END, range);
  1861. if (start >= 0 && incStart <= 0) {
  1862. incStart = testRange.compareBoundaryPoints(_START_TO_START, range);
  1863. }
  1864. if (incStart >= 0 && incEnd <= 0) {
  1865. incEnd = testRange.compareBoundaryPoints(_END_TO_END, range);
  1866. }
  1867. if (incEnd >= 0 && end <= 0) {
  1868. end = testRange.compareBoundaryPoints(_END_TO_START, range);
  1869. }
  1870. if (end >= 0) {
  1871. return false;
  1872. }
  1873. nextNode = node.nextSibling;
  1874. if (start > 0) {
  1875. if (node.nodeType == 1) {
  1876. if (incStart >= 0 && incEnd <= 0) {
  1877. if (isCopy) {
  1878. frag.appendChild(node.cloneNode(true));
  1879. }
  1880. if (isDelete) {
  1881. nodeList.push(node);
  1882. }
  1883. } else {
  1884. var childFlag;
  1885. if (isCopy) {
  1886. childFlag = node.cloneNode(false);
  1887. frag.appendChild(childFlag);
  1888. }
  1889. if (extractNodes(node, childFlag) === false) {
  1890. return false;
  1891. }
  1892. }
  1893. } else if (node.nodeType == 3) {
  1894. var textNode;
  1895. if (node == copyRange.startContainer) {
  1896. textNode = splitTextNode(node, copyRange.startOffset, node.nodeValue.length);
  1897. } else if (node == copyRange.endContainer) {
  1898. textNode = splitTextNode(node, 0, copyRange.endOffset);
  1899. } else {
  1900. textNode = splitTextNode(node, 0, node.nodeValue.length);
  1901. }
  1902. if (isCopy) {
  1903. try {
  1904. frag.appendChild(textNode);
  1905. } catch(e) {}
  1906. }
  1907. }
  1908. }
  1909. node = nextNode;
  1910. }
  1911. }
  1912. extractNodes(ancestor, frag);
  1913. if (isDelete) {
  1914. range.up().collapse(true);
  1915. }
  1916. for (var i = 0, len = nodeList.length; i < len; i++) {
  1917. var node = nodeList[i];
  1918. if (node.parentNode) {
  1919. node.parentNode.removeChild(node);
  1920. }
  1921. }
  1922. return isCopy ? frag : range;
  1923. }
  1924. function _moveToElementText(range, el) {
  1925. var node = el;
  1926. while (node) {
  1927. var knode = K(node);
  1928. if (knode.name == 'marquee' || knode.name == 'select') {
  1929. return;
  1930. }
  1931. node = node.parentNode;
  1932. }
  1933. try {
  1934. range.moveToElementText(el);
  1935. } catch(e) {}
  1936. }
  1937. function _getStartEnd(rng, isStart) {
  1938. var doc = rng.parentElement().ownerDocument,
  1939. pointRange = rng.duplicate();
  1940. pointRange.collapse(isStart);
  1941. var parent = pointRange.parentElement(),
  1942. nodes = parent.childNodes;
  1943. if (nodes.length === 0) {
  1944. return {node: parent.parentNode, offset: K(parent).index()};
  1945. }
  1946. var startNode = doc, startPos = 0, cmp = -1;
  1947. var testRange = rng.duplicate();
  1948. _moveToElementText(testRange, parent);
  1949. for (var i = 0, len = nodes.length; i < len; i++) {
  1950. var node = nodes[i];
  1951. cmp = testRange.compareEndPoints('StartToStart', pointRange);
  1952. if (cmp === 0) {
  1953. return {node: node.parentNode, offset: i};
  1954. }
  1955. if (node.nodeType == 1) {
  1956. var nodeRange = rng.duplicate(), dummy, knode = K(node), newNode = node;
  1957. if (knode.isControl()) {
  1958. dummy = doc.createElement('span');
  1959. knode.after(dummy);
  1960. newNode = dummy;
  1961. startPos += knode.text().replace(/\r\n|\n|\r/g, '').length;
  1962. }
  1963. _moveToElementText(nodeRange, newNode);
  1964. testRange.setEndPoint('StartToEnd', nodeRange);
  1965. if (cmp > 0) {
  1966. startPos += nodeRange.text.replace(/\r\n|\n|\r/g, '').length;
  1967. } else {
  1968. startPos = 0;
  1969. }
  1970. if (dummy) {
  1971. K(dummy).remove();
  1972. }
  1973. } else if (node.nodeType == 3) {
  1974. testRange.moveStart('character', node.nodeValue.length);
  1975. startPos += node.nodeValue.length;
  1976. }
  1977. if (cmp < 0) {
  1978. startNode = node;
  1979. }
  1980. }
  1981. if (cmp < 0 && startNode.nodeType == 1) {
  1982. return {node: parent, offset: K(parent.lastChild).index() + 1};
  1983. }
  1984. if (cmp > 0) {
  1985. while (startNode.nextSibling && startNode.nodeType == 1) {
  1986. startNode = startNode.nextSibling;
  1987. }
  1988. }
  1989. testRange = rng.duplicate();
  1990. _moveToElementText(testRange, parent);
  1991. testRange.setEndPoint('StartToEnd', pointRange);
  1992. startPos -= testRange.text.replace(/\r\n|\n|\r/g, '').length;
  1993. if (cmp > 0 && startNode.nodeType == 3) {
  1994. var prevNode = startNode.previousSibling;
  1995. while (prevNode && prevNode.nodeType == 3) {
  1996. startPos -= prevNode.nodeValue.length;
  1997. prevNode = prevNode.previousSibling;
  1998. }
  1999. }
  2000. return {node: startNode, offset: startPos};
  2001. }
  2002. function _getEndRange(node, offset) {
  2003. var doc = node.ownerDocument || node,
  2004. range = doc.body.createTextRange();
  2005. if (doc == node) {
  2006. range.collapse(true);
  2007. return range;
  2008. }
  2009. if (node.nodeType == 1 && node.childNodes.length > 0) {
  2010. var children = node.childNodes, isStart, child;
  2011. if (offset === 0) {
  2012. child = children[0];
  2013. isStart = true;
  2014. } else {
  2015. child = children[offset - 1];
  2016. isStart = false;
  2017. }
  2018. if (!child) {
  2019. return range;
  2020. }
  2021. if (K(child).name === 'head') {
  2022. if (offset === 1) {
  2023. isStart = true;
  2024. }
  2025. if (offset === 2) {
  2026. isStart = false;
  2027. }
  2028. range.collapse(isStart);
  2029. return range;
  2030. }
  2031. if (child.nodeType == 1) {
  2032. var kchild = K(child), span;
  2033. if (kchild.isControl()) {
  2034. span = doc.createElement('span');
  2035. if (isStart) {
  2036. kchild.before(span);
  2037. } else {
  2038. kchild.after(span);
  2039. }
  2040. child = span;
  2041. }
  2042. _moveToElementText(range, child);
  2043. range.collapse(isStart);
  2044. if (span) {
  2045. K(span).remove();
  2046. }
  2047. return range;
  2048. }
  2049. node = child;
  2050. offset = isStart ? 0 : child.nodeValue.length;
  2051. }
  2052. var dummy = doc.createElement('span');
  2053. K(node).before(dummy);
  2054. _moveToElementText(range, dummy);
  2055. range.moveStart('character', offset);
  2056. K(dummy).remove();
  2057. return range;
  2058. }
  2059. function _toRange(rng) {
  2060. var doc, range;
  2061. function tr2td(start) {
  2062. if (K(start.node).name == 'tr') {
  2063. start.node = start.node.cells[start.offset];
  2064. start.offset = 0;
  2065. }
  2066. }
  2067. if (_IERANGE) {
  2068. if (rng.item) {
  2069. doc = _getDoc(rng.item(0));
  2070. range = new KRange(doc);
  2071. range.selectNode(rng.item(0));
  2072. return range;
  2073. }
  2074. doc = rng.parentElement().ownerDocument;
  2075. var start = _getStartEnd(rng, true),
  2076. end = _getStartEnd(rng, false);
  2077. tr2td(start);
  2078. tr2td(end);
  2079. range = new KRange(doc);
  2080. range.setStart(start.node, start.offset);
  2081. range.setEnd(end.node, end.offset);
  2082. return range;
  2083. }
  2084. var startContainer = rng.startContainer;
  2085. doc = startContainer.ownerDocument || startContainer;
  2086. range = new KRange(doc);
  2087. range.setStart(startContainer, rng.startOffset);
  2088. range.setEnd(rng.endContainer, rng.endOffset);
  2089. return range;
  2090. }
  2091. function KRange(doc) {
  2092. this.init(doc);
  2093. }
  2094. _extend(KRange, {
  2095. init : function(doc) {
  2096. var self = this;
  2097. self.startContainer = doc;
  2098. self.startOffset = 0;
  2099. self.endContainer = doc;
  2100. self.endOffset = 0;
  2101. self.collapsed = true;
  2102. self.doc = doc;
  2103. },
  2104. commonAncestor : function() {
  2105. function getParents(node) {
  2106. var parents = [];
  2107. while (node) {
  2108. parents.push(node);
  2109. node = node.parentNode;
  2110. }
  2111. return parents;
  2112. }
  2113. var parentsA = getParents(this.startContainer),
  2114. parentsB = getParents(this.endContainer),
  2115. i = 0, lenA = parentsA.length, lenB = parentsB.length, parentA, parentB;
  2116. while (++i) {
  2117. parentA = parentsA[lenA - i];
  2118. parentB = parentsB[lenB - i];
  2119. if (!parentA || !parentB || parentA !== parentB) {
  2120. break;
  2121. }
  2122. }
  2123. return parentsA[lenA - i + 1];
  2124. },
  2125. setStart : function(node, offset) {
  2126. var self = this, doc = self.doc;
  2127. self.startContainer = node;
  2128. self.startOffset = offset;
  2129. if (self.endContainer === doc) {
  2130. self.endContainer = node;
  2131. self.endOffset = offset;
  2132. }
  2133. return _updateCollapsed(this);
  2134. },
  2135. setEnd : function(node, offset) {
  2136. var self = this, doc = self.doc;
  2137. self.endContainer = node;
  2138. self.endOffset = offset;
  2139. if (self.startContainer === doc) {
  2140. self.startContainer = node;
  2141. self.startOffset = offset;
  2142. }
  2143. return _updateCollapsed(this);
  2144. },
  2145. setStartBefore : function(node) {
  2146. return this.setStart(node.parentNode || this.doc, K(node).index());
  2147. },
  2148. setStartAfter : function(node) {
  2149. return this.setStart(node.parentNode || this.doc, K(node).index() + 1);
  2150. },
  2151. setEndBefore : function(node) {
  2152. return this.setEnd(node.parentNode || this.doc, K(node).index());
  2153. },
  2154. setEndAfter : function(node) {
  2155. return this.setEnd(node.parentNode || this.doc, K(node).index() + 1);
  2156. },
  2157. selectNode : function(node) {
  2158. return this.setStartBefore(node).setEndAfter(node);
  2159. },
  2160. selectNodeContents : function(node) {
  2161. var knode = K(node);
  2162. if (knode.type == 3 || knode.isSingle()) {
  2163. return this.selectNode(node);
  2164. }
  2165. var children = knode.children();
  2166. if (children.length > 0) {
  2167. return this.setStartBefore(children[0]).setEndAfter(children[children.length - 1]);
  2168. }
  2169. return this.setStart(node, 0).setEnd(node, 0);
  2170. },
  2171. collapse : function(toStart) {
  2172. if (toStart) {
  2173. return this.setEnd(this.startContainer, this.startOffset);
  2174. }
  2175. return this.setStart(this.endContainer, this.endOffset);
  2176. },
  2177. compareBoundaryPoints : function(how, range) {
  2178. var rangeA = this.get(), rangeB = range.get();
  2179. if (_IERANGE) {
  2180. var arr = {};
  2181. arr[_START_TO_START] = 'StartToStart';
  2182. arr[_START_TO_END] = 'EndToStart';
  2183. arr[_END_TO_END] = 'EndToEnd';
  2184. arr[_END_TO_START] = 'StartToEnd';
  2185. var cmp = rangeA.compareEndPoints(arr[how], rangeB);
  2186. if (cmp !== 0) {
  2187. return cmp;
  2188. }
  2189. var nodeA, nodeB, nodeC, posA, posB;
  2190. if (how === _START_TO_START || how === _END_TO_START) {
  2191. nodeA = this.startContainer;
  2192. posA = this.startOffset;
  2193. }
  2194. if (how === _START_TO_END || how === _END_TO_END) {
  2195. nodeA = this.endContainer;
  2196. posA = this.endOffset;
  2197. }
  2198. if (how === _START_TO_START || how === _START_TO_END) {
  2199. nodeB = range.startContainer;
  2200. posB = range.startOffset;
  2201. }
  2202. if (how === _END_TO_END || how === _END_TO_START) {
  2203. nodeB = range.endContainer;
  2204. posB = range.endOffset;
  2205. }
  2206. if (nodeA === nodeB) {
  2207. var diff = posA - posB;
  2208. return diff > 0 ? 1 : (diff < 0 ? -1 : 0);
  2209. }
  2210. nodeC = nodeB;
  2211. while (nodeC && nodeC.parentNode !== nodeA) {
  2212. nodeC = nodeC.parentNode;
  2213. }
  2214. if (nodeC) {
  2215. return K(nodeC).index() >= posA ? -1 : 1;
  2216. }
  2217. nodeC = nodeA;
  2218. while (nodeC && nodeC.parentNode !== nodeB) {
  2219. nodeC = nodeC.parentNode;
  2220. }
  2221. if (nodeC) {
  2222. return K(nodeC).index() >= posB ? 1 : -1;
  2223. }
  2224. nodeC = K(nodeB).next();
  2225. if (nodeC && nodeC.contains(nodeA)) {
  2226. return 1;
  2227. }
  2228. nodeC = K(nodeA).next();
  2229. if (nodeC && nodeC.contains(nodeB)) {
  2230. return -1;
  2231. }
  2232. } else {
  2233. return rangeA.compareBoundaryPoints(how, rangeB);
  2234. }
  2235. },
  2236. cloneRange : function() {
  2237. return new KRange(this.doc).setStart(this.startContainer, this.startOffset).setEnd(this.endContainer, this.endOffset);
  2238. },
  2239. toString : function() {
  2240. var rng = this.get(), str = _IERANGE ? rng.text : rng.toString();
  2241. return str.replace(/\r\n|\n|\r/g, '');
  2242. },
  2243. cloneContents : function() {
  2244. return _copyAndDelete(this, true, false);
  2245. },
  2246. deleteContents : function() {
  2247. return _copyAndDelete(this, false, true);
  2248. },
  2249. extractContents : function() {
  2250. return _copyAndDelete(this, true, true);
  2251. },
  2252. insertNode : function(node) {
  2253. var self = this,
  2254. sc = self.startContainer, so = self.startOffset,
  2255. ec = self.endContainer, eo = self.endOffset,
  2256. firstChild, lastChild, c, nodeCount = 1;
  2257. if (node.nodeName.toLowerCase() === '#document-fragment') {
  2258. firstChild = node.firstChild;
  2259. lastChild = node.lastChild;
  2260. nodeCount = node.childNodes.length;
  2261. }
  2262. if (sc.nodeType == 1) {
  2263. c = sc.childNodes[so];
  2264. if (c) {
  2265. sc.insertBefore(node, c);
  2266. if (sc === ec) {
  2267. eo += nodeCount;
  2268. }
  2269. } else {
  2270. sc.appendChild(node);
  2271. }
  2272. } else if (sc.nodeType == 3) {
  2273. if (so === 0) {
  2274. sc.parentNode.insertBefore(node, sc);
  2275. if (sc.parentNode === ec) {
  2276. eo += nodeCount;
  2277. }
  2278. } else if (so >= sc.nodeValue.length) {
  2279. if (sc.nextSibling) {
  2280. sc.parentNode.insertBefore(node, sc.nextSibling);
  2281. } else {
  2282. sc.parentNode.appendChild(node);
  2283. }
  2284. } else {
  2285. if (so > 0) {
  2286. c = sc.splitText(so);
  2287. } else {
  2288. c = sc;
  2289. }
  2290. sc.parentNode.insertBefore(node, c);
  2291. if (sc === ec) {
  2292. ec = c;
  2293. eo -= so;
  2294. }
  2295. }
  2296. }
  2297. if (firstChild) {
  2298. self.setStartBefore(firstChild).setEndAfter(lastChild);
  2299. } else {
  2300. self.selectNode(node);
  2301. }
  2302. if (self.compareBoundaryPoints(_END_TO_END, self.cloneRange().setEnd(ec, eo)) >= 1) {
  2303. return self;
  2304. }
  2305. return self.setEnd(ec, eo);
  2306. },
  2307. surroundContents : function(node) {
  2308. node.appendChild(this.extractContents());
  2309. return this.insertNode(node).selectNode(node);
  2310. },
  2311. isControl : function() {
  2312. var self = this,
  2313. sc = self.startContainer, so = self.startOffset,
  2314. ec = self.endContainer, eo = self.endOffset, rng;
  2315. return sc.nodeType == 1 && sc === ec && so + 1 === eo && K(sc.childNodes[so]).isControl();
  2316. },
  2317. get : function(hasControlRange) {
  2318. var self = this, doc = self.doc, node, rng;
  2319. if (!_IERANGE) {
  2320. rng = doc.createRange();
  2321. try {
  2322. rng.setStart(self.startContainer, self.startOffset);
  2323. rng.setEnd(self.endContainer, self.endOffset);
  2324. } catch (e) {}
  2325. return rng;
  2326. }
  2327. if (hasControlRange && self.isControl()) {
  2328. rng = doc.body.createControlRange();
  2329. rng.addElement(self.startContainer.childNodes[self.startOffset]);
  2330. return rng;
  2331. }
  2332. var range = self.cloneRange().down();
  2333. rng = doc.body.createTextRange();
  2334. rng.setEndPoint('StartToStart', _getEndRange(range.startContainer, range.startOffset));
  2335. rng.setEndPoint('EndToStart', _getEndRange(range.endContainer, range.endOffset));
  2336. return rng;
  2337. },
  2338. html : function() {
  2339. return K(this.cloneContents()).outer();
  2340. },
  2341. down : function() {
  2342. var self = this;
  2343. function downPos(node, pos, isStart) {
  2344. if (node.nodeType != 1) {
  2345. return;
  2346. }
  2347. var children = K(node).children();
  2348. if (children.length === 0) {
  2349. return;
  2350. }
  2351. var left, right, child, offset;
  2352. if (pos > 0) {
  2353. left = children.eq(pos - 1);
  2354. }
  2355. if (pos < children.length) {
  2356. right = children.eq(pos);
  2357. }
  2358. if (left && left.type == 3) {
  2359. child = left[0];
  2360. offset = child.nodeValue.length;
  2361. }
  2362. if (right && right.type == 3) {
  2363. child = right[0];
  2364. offset = 0;
  2365. }
  2366. if (!child) {
  2367. return;
  2368. }
  2369. if (isStart) {
  2370. self.setStart(child, offset);
  2371. } else {
  2372. self.setEnd(child, offset);
  2373. }
  2374. }
  2375. downPos(self.startContainer, self.startOffset, true);
  2376. downPos(self.endContainer, self.endOffset, false);
  2377. return self;
  2378. },
  2379. up : function() {
  2380. var self = this;
  2381. function upPos(node, pos, isStart) {
  2382. if (node.nodeType != 3) {
  2383. return;
  2384. }
  2385. if (pos === 0) {
  2386. if (isStart) {
  2387. self.setStartBefore(node);
  2388. } else {
  2389. self.setEndBefore(node);
  2390. }
  2391. } else if (pos == node.nodeValue.length) {
  2392. if (isStart) {
  2393. self.setStartAfter(node);
  2394. } else {
  2395. self.setEndAfter(node);
  2396. }
  2397. }
  2398. }
  2399. upPos(self.startContainer, self.startOffset, true);
  2400. upPos(self.endContainer, self.endOffset, false);
  2401. return self;
  2402. },
  2403. enlarge : function(toBlock) {
  2404. var self = this;
  2405. self.up();
  2406. function enlargePos(node, pos, isStart) {
  2407. var knode = K(node), parent;
  2408. if (knode.type == 3 || _NOSPLIT_TAG_MAP[knode.name] || !toBlock && knode.isBlock()) {
  2409. return;
  2410. }
  2411. if (pos === 0) {
  2412. while (!knode.prev()) {
  2413. parent = knode.parent();
  2414. if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2415. break;
  2416. }
  2417. knode = parent;
  2418. }
  2419. if (isStart) {
  2420. self.setStartBefore(knode[0]);
  2421. } else {
  2422. self.setEndBefore(knode[0]);
  2423. }
  2424. } else if (pos == knode.children().length) {
  2425. while (!knode.next()) {
  2426. parent = knode.parent();
  2427. if (!parent || _NOSPLIT_TAG_MAP[parent.name] || !toBlock && parent.isBlock()) {
  2428. break;
  2429. }
  2430. knode = parent;
  2431. }
  2432. if (isStart) {
  2433. self.setStartAfter(knode[0]);
  2434. } else {
  2435. self.setEndAfter(knode[0]);
  2436. }
  2437. }
  2438. }
  2439. enlargePos(self.startContainer, self.startOffset, true);
  2440. enlargePos(self.endContainer, self.endOffset, false);
  2441. return self;
  2442. },
  2443. shrink : function() {
  2444. var self = this, child, collapsed = self.collapsed;
  2445. while (self.startContainer.nodeType == 1 && (child = self.startContainer.childNodes[self.startOffset]) && child.nodeType == 1 && !K(child).isSingle()) {
  2446. self.setStart(child, 0);
  2447. }
  2448. if (collapsed) {
  2449. return self.collapse(collapsed);
  2450. }
  2451. while (self.endContainer.nodeType == 1 && self.endOffset > 0 && (child = self.endContainer.childNodes[self.endOffset - 1]) && child.nodeType == 1 && !K(child).isSingle()) {
  2452. self.setEnd(child, child.childNodes.length);
  2453. }
  2454. return self;
  2455. },
  2456. createBookmark : function(serialize) {
  2457. var self = this, doc = self.doc, endNode,
  2458. startNode = K('<span style="display:none;"></span>', doc)[0];
  2459. startNode.id = '__kindeditor_bookmark_start_' + (_BOOKMARK_ID++) + '__';
  2460. if (!self.collapsed) {
  2461. endNode = startNode.cloneNode(true);
  2462. endNode.id = '__kindeditor_bookmark_end_' + (_BOOKMARK_ID++) + '__';
  2463. }
  2464. if (endNode) {
  2465. self.cloneRange().collapse(false).insertNode(endNode).setEndBefore(endNode);
  2466. }
  2467. self.insertNode(startNode).setStartAfter(startNode);
  2468. return {
  2469. start : serialize ? '#' + startNode.id : startNode,
  2470. end : endNode ? (serialize ? '#' + endNode.id : endNode) : null
  2471. };
  2472. },
  2473. moveToBookmark : function(bookmark) {
  2474. var self = this, doc = self.doc,
  2475. start = K(bookmark.start, doc), end = bookmark.end ? K(bookmark.end, doc) : null;
  2476. if (!start || start.length < 1) {
  2477. return self;
  2478. }
  2479. self.setStartBefore(start[0]);
  2480. start.remove();
  2481. if (end && end.length > 0) {
  2482. self.setEndBefore(end[0]);
  2483. end.remove();
  2484. } else {
  2485. self.collapse(true);
  2486. }
  2487. return self;
  2488. },
  2489. dump : function() {
  2490. console.log('--------------------');
  2491. console.log(this.startContainer.nodeType == 3 ? this.startContainer.nodeValue : this.startContainer, this.startOffset);
  2492. console.log(this.endContainer.nodeType == 3 ? this.endContainer.nodeValue : this.endContainer, this.endOffset);
  2493. }
  2494. });
  2495. function _range(mixed) {
  2496. if (!mixed.nodeName) {
  2497. return mixed.constructor === KRange ? mixed : _toRange(mixed);
  2498. }
  2499. return new KRange(mixed);
  2500. }
  2501. K.RangeClass = KRange;
  2502. K.range = _range;
  2503. K.START_TO_START = _START_TO_START;
  2504. K.START_TO_END = _START_TO_END;
  2505. K.END_TO_END = _END_TO_END;
  2506. K.END_TO_START = _END_TO_START;
  2507. function _nativeCommand(doc, key, val) {
  2508. try {
  2509. doc.execCommand(key, false, val);
  2510. } catch(e) {}
  2511. }
  2512. function _nativeCommandValue(doc, key) {
  2513. var val = '';
  2514. try {
  2515. val = doc.queryCommandValue(key);
  2516. } catch (e) {}
  2517. if (typeof val !== 'string') {
  2518. val = '';
  2519. }
  2520. return val;
  2521. }
  2522. function _getSel(doc) {
  2523. var win = _getWin(doc);
  2524. return _IERANGE ? doc.selection : win.getSelection();
  2525. }
  2526. function _getRng(doc) {
  2527. var sel = _getSel(doc), rng;
  2528. try {
  2529. if (sel.rangeCount > 0) {
  2530. rng = sel.getRangeAt(0);
  2531. } else {
  2532. rng = sel.createRange();
  2533. }
  2534. } catch(e) {}
  2535. if (_IERANGE && (!rng || (!rng.item && rng.parentElement().ownerDocument !== doc))) {
  2536. return null;
  2537. }
  2538. return rng;
  2539. }
  2540. function _singleKeyMap(map) {
  2541. var newMap = {}, arr, v;
  2542. _each(map, function(key, val) {
  2543. arr = key.split(',');
  2544. for (var i = 0, len = arr.length; i < len; i++) {
  2545. v = arr[i];
  2546. newMap[v] = val;
  2547. }
  2548. });
  2549. return newMap;
  2550. }
  2551. function _hasAttrOrCss(knode, map) {
  2552. return _hasAttrOrCssByKey(knode, map, '*') || _hasAttrOrCssByKey(knode, map);
  2553. }
  2554. function _hasAttrOrCssByKey(knode, map, mapKey) {
  2555. mapKey = mapKey || knode.name;
  2556. if (knode.type !== 1) {
  2557. return false;
  2558. }
  2559. var newMap = _singleKeyMap(map);
  2560. if (!newMap[mapKey]) {
  2561. return false;
  2562. }
  2563. var arr = newMap[mapKey].split(',');
  2564. for (var i = 0, len = arr.length; i < len; i++) {
  2565. var key = arr[i];
  2566. if (key === '*') {
  2567. return true;
  2568. }
  2569. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2570. var method = match[1] ? 'css' : 'attr';
  2571. key = match[2];
  2572. var val = match[3] || '';
  2573. if (val === '' && knode[method](key) !== '') {
  2574. return true;
  2575. }
  2576. if (val !== '' && knode[method](key) === val) {
  2577. return true;
  2578. }
  2579. }
  2580. return false;
  2581. }
  2582. function _removeAttrOrCss(knode, map) {
  2583. if (knode.type != 1) {
  2584. return;
  2585. }
  2586. _removeAttrOrCssByKey(knode, map, '*');
  2587. _removeAttrOrCssByKey(knode, map);
  2588. }
  2589. function _removeAttrOrCssByKey(knode, map, mapKey) {
  2590. mapKey = mapKey || knode.name;
  2591. if (knode.type !== 1) {
  2592. return;
  2593. }
  2594. var newMap = _singleKeyMap(map);
  2595. if (!newMap[mapKey]) {
  2596. return;
  2597. }
  2598. var arr = newMap[mapKey].split(','), allFlag = false;
  2599. for (var i = 0, len = arr.length; i < len; i++) {
  2600. var key = arr[i];
  2601. if (key === '*') {
  2602. allFlag = true;
  2603. break;
  2604. }
  2605. var match = /^(\.?)([^=]+)(?:=([^=]*))?$/.exec(key);
  2606. key = match[2];
  2607. if (match[1]) {
  2608. key = _toCamel(key);
  2609. if (knode[0].style[key]) {
  2610. knode[0].style[key] = '';
  2611. }
  2612. } else {
  2613. knode.removeAttr(key);
  2614. }
  2615. }
  2616. if (allFlag) {
  2617. knode.remove(true);
  2618. }
  2619. }
  2620. function _getInnerNode(knode) {
  2621. var inner = knode;
  2622. while (inner.first()) {
  2623. inner = inner.first();
  2624. }
  2625. return inner;
  2626. }
  2627. function _isEmptyNode(knode) {
  2628. if (knode.type != 1 || knode.isSingle()) {
  2629. return false;
  2630. }
  2631. return knode.html().replace(/<[^>]+>/g, '') === '';
  2632. }
  2633. function _mergeWrapper(a, b) {
  2634. a = a.clone(true);
  2635. var lastA = _getInnerNode(a), childA = a, merged = false;
  2636. while (b) {
  2637. while (childA) {
  2638. if (childA.name === b.name) {
  2639. _mergeAttrs(childA, b.attr(), b.css());
  2640. merged = true;
  2641. }
  2642. childA = childA.first();
  2643. }
  2644. if (!merged) {
  2645. lastA.append(b.clone(false));
  2646. }
  2647. merged = false;
  2648. b = b.first();
  2649. }
  2650. return a;
  2651. }
  2652. function _wrapNode(knode, wrapper) {
  2653. wrapper = wrapper.clone(true);
  2654. if (knode.type == 3) {
  2655. _getInnerNode(wrapper).append(knode.clone(false));
  2656. knode.replaceWith(wrapper);
  2657. return wrapper;
  2658. }
  2659. var nodeWrapper = knode, child;
  2660. while ((child = knode.first()) && child.children().length == 1) {
  2661. knode = child;
  2662. }
  2663. child = knode.first();
  2664. var frag = knode.doc.createDocumentFragment();
  2665. while (child) {
  2666. frag.appendChild(child[0]);
  2667. child = child.next();
  2668. }
  2669. wrapper = _mergeWrapper(nodeWrapper, wrapper);
  2670. if (frag.firstChild) {
  2671. _getInnerNode(wrapper).append(frag);
  2672. }
  2673. nodeWrapper.replaceWith(wrapper);
  2674. return wrapper;
  2675. }
  2676. function _mergeAttrs(knode, attrs, styles) {
  2677. _each(attrs, function(key, val) {
  2678. if (key !== 'style') {
  2679. knode.attr(key, val);
  2680. }
  2681. });
  2682. _each(styles, function(key, val) {
  2683. knode.css(key, val);
  2684. });
  2685. }
  2686. function _inPreElement(knode) {
  2687. while (knode && knode.name != 'body') {
  2688. if (_PRE_TAG_MAP[knode.name] || knode.name == 'div' && knode.hasClass('ke-script')) {
  2689. return true;
  2690. }
  2691. knode = knode.parent();
  2692. }
  2693. return false;
  2694. }
  2695. function KCmd(range) {
  2696. this.init(range);
  2697. }
  2698. _extend(KCmd, {
  2699. init : function(range) {
  2700. var self = this, doc = range.doc;
  2701. self.doc = doc;
  2702. self.win = _getWin(doc);
  2703. self.sel = _getSel(doc);
  2704. self.range = range;
  2705. },
  2706. selection : function(forceReset) {
  2707. var self = this, doc = self.doc, rng = _getRng(doc);
  2708. self.sel = _getSel(doc);
  2709. if (rng) {
  2710. self.range = _range(rng);
  2711. if (K(self.range.startContainer).name == 'html') {
  2712. self.range.selectNodeContents(doc.body).collapse(false);
  2713. }
  2714. return self;
  2715. }
  2716. if (forceReset) {
  2717. self.range.selectNodeContents(doc.body).collapse(false);
  2718. }
  2719. return self;
  2720. },
  2721. select : function(hasDummy) {
  2722. hasDummy = _undef(hasDummy, true);
  2723. var self = this, sel = self.sel, range = self.range.cloneRange().shrink(),
  2724. sc = range.startContainer, so = range.startOffset,
  2725. ec = range.endContainer, eo = range.endOffset,
  2726. doc = _getDoc(sc), win = self.win, rng, hasU200b = false;
  2727. if (hasDummy && sc.nodeType == 1 && range.collapsed) {
  2728. if (_IERANGE) {
  2729. var dummy = K('<span>&nbsp;</span>', doc);
  2730. range.insertNode(dummy[0]);
  2731. rng = doc.body.createTextRange();
  2732. try {
  2733. rng.moveToElementText(dummy[0]);
  2734. } catch(ex) {}
  2735. rng.collapse(false);
  2736. rng.select();
  2737. dummy.remove();
  2738. win.focus();
  2739. return self;
  2740. }
  2741. if (_WEBKIT) {
  2742. var children = sc.childNodes;
  2743. if (K(sc).isInline() || so > 0 && K(children[so - 1]).isInline() || children[so] && K(children[so]).isInline()) {
  2744. range.insertNode(doc.createTextNode('\u200B'));
  2745. hasU200b = true;
  2746. }
  2747. }
  2748. }
  2749. if (_IERANGE) {
  2750. try {
  2751. rng = range.get(true);
  2752. rng.select();
  2753. } catch(e) {}
  2754. } else {
  2755. if (hasU200b) {
  2756. range.collapse(false);
  2757. }
  2758. rng = range.get(true);
  2759. sel.removeAllRanges();
  2760. sel.addRange(rng);
  2761. if (doc !== document) {
  2762. var pos = K(rng.endContainer).pos();
  2763. win.scrollTo(pos.x, pos.y);
  2764. }
  2765. }
  2766. win.focus();
  2767. return self;
  2768. },
  2769. wrap : function(val) {
  2770. var self = this, doc = self.doc, range = self.range, wrapper;
  2771. wrapper = K(val, doc);
  2772. if (range.collapsed) {
  2773. range.shrink();
  2774. range.insertNode(wrapper[0]).selectNodeContents(wrapper[0]);
  2775. return self;
  2776. }
  2777. if (wrapper.isBlock()) {
  2778. var copyWrapper = wrapper.clone(true), child = copyWrapper;
  2779. while (child.first()) {
  2780. child = child.first();
  2781. }
  2782. child.append(range.extractContents());
  2783. range.insertNode(copyWrapper[0]).selectNode(copyWrapper[0]);
  2784. return self;
  2785. }
  2786. range.enlarge();
  2787. var bookmark = range.createBookmark(), ancestor = range.commonAncestor(), isStart = false;
  2788. K(ancestor).scan(function(node) {
  2789. if (!isStart && node == bookmark.start) {
  2790. isStart = true;
  2791. return;
  2792. }
  2793. if (isStart) {
  2794. if (node == bookmark.end) {
  2795. return false;
  2796. }
  2797. var knode = K(node);
  2798. if (_inPreElement(knode)) {
  2799. return;
  2800. }
  2801. if (knode.type == 3 && _trim(node.nodeValue).length > 0) {
  2802. var parent;
  2803. while ((parent = knode.parent()) && parent.isStyle() && parent.children().length == 1) {
  2804. knode = parent;
  2805. }
  2806. _wrapNode(knode, wrapper);
  2807. }
  2808. }
  2809. });
  2810. range.moveToBookmark(bookmark);
  2811. return self;
  2812. },
  2813. split : function(isStart, map) {
  2814. var range = this.range, doc = range.doc;
  2815. var tempRange = range.cloneRange().collapse(isStart);
  2816. var node = tempRange.startContainer, pos = tempRange.startOffset,
  2817. parent = node.nodeType == 3 ? node.parentNode : node,
  2818. needSplit = false, knode;
  2819. while (parent && parent.parentNode) {
  2820. knode = K(parent);
  2821. if (map) {
  2822. if (!knode.isStyle()) {
  2823. break;
  2824. }
  2825. if (!_hasAttrOrCss(knode, map)) {
  2826. break;
  2827. }
  2828. } else {
  2829. if (_NOSPLIT_TAG_MAP[knode.name]) {
  2830. break;
  2831. }
  2832. }
  2833. needSplit = true;
  2834. parent = parent.parentNode;
  2835. }
  2836. if (needSplit) {
  2837. var dummy = doc.createElement('span');
  2838. range.cloneRange().collapse(!isStart).insertNode(dummy);
  2839. if (isStart) {
  2840. tempRange.setStartBefore(parent.firstChild).setEnd(node, pos);
  2841. } else {
  2842. tempRange.setStart(node, pos).setEndAfter(parent.lastChild);
  2843. }
  2844. var frag = tempRange.extractContents(),
  2845. first = frag.firstChild, last = frag.lastChild;
  2846. if (isStart) {
  2847. tempRange.insertNode(frag);
  2848. range.setStartAfter(last).setEndBefore(dummy);
  2849. } else {
  2850. parent.appendChild(frag);
  2851. range.setStartBefore(dummy).setEndBefore(first);
  2852. }
  2853. var dummyParent = dummy.parentNode;
  2854. if (dummyParent == range.endContainer) {
  2855. var prev = K(dummy).prev(), next = K(dummy).next();
  2856. if (prev && next && prev.type == 3 && next.type == 3) {
  2857. range.setEnd(prev[0], prev[0].nodeValue.length);
  2858. } else if (!isStart) {
  2859. range.setEnd(range.endContainer, range.endOffset - 1);
  2860. }
  2861. }
  2862. dummyParent.removeChild(dummy);
  2863. }
  2864. return this;
  2865. },
  2866. remove : function(map) {
  2867. var self = this, doc = self.doc, range = self.range;
  2868. range.enlarge();
  2869. if (range.startOffset === 0) {
  2870. var ksc = K(range.startContainer), parent;
  2871. while ((parent = ksc.parent()) && parent.isStyle() && parent.children().length == 1) {
  2872. ksc = parent;
  2873. }
  2874. range.setStart(ksc[0], 0);
  2875. ksc = K(range.startContainer);
  2876. if (ksc.isBlock()) {
  2877. _removeAttrOrCss(ksc, map);
  2878. }
  2879. var kscp = ksc.parent();
  2880. if (kscp && kscp.isBlock()) {
  2881. _removeAttrOrCss(kscp, map);
  2882. }
  2883. }
  2884. var sc, so;
  2885. if (range.collapsed) {
  2886. self.split(true, map);
  2887. sc = range.startContainer;
  2888. so = range.startOffset;
  2889. if (so > 0) {
  2890. var sb = K(sc.childNodes[so - 1]);
  2891. if (sb && _isEmptyNode(sb)) {
  2892. sb.remove();
  2893. range.setStart(sc, so - 1);
  2894. }
  2895. }
  2896. var sa = K(sc.childNodes[so]);
  2897. if (sa && _isEmptyNode(sa)) {
  2898. sa.remove();
  2899. }
  2900. if (_isEmptyNode(sc)) {
  2901. range.startBefore(sc);
  2902. sc.remove();
  2903. }
  2904. range.collapse(true);
  2905. return self;
  2906. }
  2907. self.split(true, map);
  2908. self.split(false, map);
  2909. var startDummy = doc.createElement('span'), endDummy = doc.createElement('span');
  2910. range.cloneRange().collapse(false).insertNode(endDummy);
  2911. range.cloneRange().collapse(true).insertNode(startDummy);
  2912. var nodeList = [], cmpStart = false;
  2913. K(range.commonAncestor()).scan(function(node) {
  2914. if (!cmpStart && node == startDummy) {
  2915. cmpStart = true;
  2916. return;
  2917. }
  2918. if (node == endDummy) {
  2919. return false;
  2920. }
  2921. if (cmpStart) {
  2922. nodeList.push(node);
  2923. }
  2924. });
  2925. K(startDummy).remove();
  2926. K(endDummy).remove();
  2927. sc = range.startContainer;
  2928. so = range.startOffset;
  2929. var ec = range.endContainer, eo = range.endOffset;
  2930. if (so > 0) {
  2931. var startBefore = K(sc.childNodes[so - 1]);
  2932. if (startBefore && _isEmptyNode(startBefore)) {
  2933. startBefore.remove();
  2934. range.setStart(sc, so - 1);
  2935. if (sc == ec) {
  2936. range.setEnd(ec, eo - 1);
  2937. }
  2938. }
  2939. var startAfter = K(sc.childNodes[so]);
  2940. if (startAfter && _isEmptyNode(startAfter)) {
  2941. startAfter.remove();
  2942. if (sc == ec) {
  2943. range.setEnd(ec, eo - 1);
  2944. }
  2945. }
  2946. }
  2947. var endAfter = K(ec.childNodes[range.endOffset]);
  2948. if (endAfter && _isEmptyNode(endAfter)) {
  2949. endAfter.remove();
  2950. }
  2951. var bookmark = range.createBookmark(true);
  2952. _each(nodeList, function(i, node) {
  2953. _removeAttrOrCss(K(node), map);
  2954. });
  2955. range.moveToBookmark(bookmark);
  2956. return self;
  2957. },
  2958. commonNode : function(map) {
  2959. var range = this.range;
  2960. var ec = range.endContainer, eo = range.endOffset,
  2961. node = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  2962. function find(node) {
  2963. var child = node, parent = node;
  2964. while (parent) {
  2965. if (_hasAttrOrCss(K(parent), map)) {
  2966. return K(parent);
  2967. }
  2968. parent = parent.parentNode;
  2969. }
  2970. while (child && (child = child.lastChild)) {
  2971. if (_hasAttrOrCss(K(child), map)) {
  2972. return K(child);
  2973. }
  2974. }
  2975. return null;
  2976. }
  2977. var cNode = find(node);
  2978. if (cNode) {
  2979. return cNode;
  2980. }
  2981. if (node.nodeType == 1 || (ec.nodeType == 3 && eo === 0)) {
  2982. var prev = K(node).prev();
  2983. if (prev) {
  2984. return find(prev);
  2985. }
  2986. }
  2987. return null;
  2988. },
  2989. commonAncestor : function(tagName) {
  2990. var range = this.range,
  2991. sc = range.startContainer, so = range.startOffset,
  2992. ec = range.endContainer, eo = range.endOffset,
  2993. startNode = (sc.nodeType == 3 || so === 0) ? sc : sc.childNodes[so - 1],
  2994. endNode = (ec.nodeType == 3 || eo === 0) ? ec : ec.childNodes[eo - 1];
  2995. function find(node) {
  2996. while (node) {
  2997. if (node.nodeType == 1) {
  2998. if (node.tagName.toLowerCase() === tagName) {
  2999. return node;
  3000. }
  3001. }
  3002. node = node.parentNode;
  3003. }
  3004. return null;
  3005. }
  3006. var start = find(startNode), end = find(endNode);
  3007. if (start && end && start === end) {
  3008. return K(start);
  3009. }
  3010. return null;
  3011. },
  3012. state : function(key) {
  3013. var self = this, doc = self.doc, bool = false;
  3014. try {
  3015. bool = doc.queryCommandState(key);
  3016. } catch (e) {}
  3017. return bool;
  3018. },
  3019. val : function(key) {
  3020. var self = this, doc = self.doc, range = self.range;
  3021. function lc(val) {
  3022. return val.toLowerCase();
  3023. }
  3024. key = lc(key);
  3025. var val = '', knode;
  3026. if (key === 'fontfamily' || key === 'fontname') {
  3027. val = _nativeCommandValue(doc, 'fontname');
  3028. val = val.replace(/['"]/g, '');
  3029. return lc(val);
  3030. }
  3031. if (key === 'formatblock') {
  3032. val = _nativeCommandValue(doc, key);
  3033. if (val === '') {
  3034. knode = self.commonNode({'h1,h2,h3,h4,h5,h6,p,div,pre,address' : '*'});
  3035. if (knode) {
  3036. val = knode.name;
  3037. }
  3038. }
  3039. if (val === 'Normal') {
  3040. val = 'p';
  3041. }
  3042. return lc(val);
  3043. }
  3044. if (key === 'fontsize') {
  3045. knode = self.commonNode({'*' : '.font-size'});
  3046. if (knode) {
  3047. val = knode.css('font-size');
  3048. }
  3049. return lc(val);
  3050. }
  3051. if (key === 'forecolor') {
  3052. knode = self.commonNode({'*' : '.color'});
  3053. if (knode) {
  3054. val = knode.css('color');
  3055. }
  3056. val = _toHex(val);
  3057. if (val === '') {
  3058. val = 'default';
  3059. }
  3060. return lc(val);
  3061. }
  3062. if (key === 'hilitecolor') {
  3063. knode = self.commonNode({'*' : '.background-color'});
  3064. if (knode) {
  3065. val = knode.css('background-color');
  3066. }
  3067. val = _toHex(val);
  3068. if (val === '') {
  3069. val = 'default';
  3070. }
  3071. return lc(val);
  3072. }
  3073. return val;
  3074. },
  3075. toggle : function(wrapper, map) {
  3076. var self = this;
  3077. if (self.commonNode(map)) {
  3078. self.remove(map);
  3079. } else {
  3080. self.wrap(wrapper);
  3081. }
  3082. return self.select();
  3083. },
  3084. bold : function() {
  3085. return this.toggle('<strong></strong>', {
  3086. span : '.font-weight=bold',
  3087. strong : '*',
  3088. b : '*'
  3089. });
  3090. },
  3091. italic : function() {
  3092. return this.toggle('<em></em>', {
  3093. span : '.font-style=italic',
  3094. em : '*',
  3095. i : '*'
  3096. });
  3097. },
  3098. underline : function() {
  3099. return this.toggle('<u></u>', {
  3100. span : '.text-decoration=underline',
  3101. u : '*'
  3102. });
  3103. },
  3104. strikethrough : function() {
  3105. return this.toggle('<s></s>', {
  3106. span : '.text-decoration=line-through',
  3107. s : '*'
  3108. });
  3109. },
  3110. forecolor : function(val) {
  3111. return this.wrap('<span style="color:' + val + ';"></span>').select();
  3112. },
  3113. hilitecolor : function(val) {
  3114. return this.wrap('<span style="background-color:' + val + ';"></span>').select();
  3115. },
  3116. fontsize : function(val) {
  3117. return this.wrap('<span style="font-size:' + val + ';"></span>').select();
  3118. },
  3119. fontname : function(val) {
  3120. return this.fontfamily(val);
  3121. },
  3122. fontfamily : function(val) {
  3123. return this.wrap('<span style="font-family:' + val + ';"></span>').select();
  3124. },
  3125. removeformat : function() {
  3126. var map = {
  3127. '*' : '.font-weight,.font-style,.text-decoration,.color,.background-color,.font-size,.font-family,.text-indent'
  3128. },
  3129. tags = _STYLE_TAG_MAP;
  3130. _each(tags, function(key, val) {
  3131. map[key] = '*';
  3132. });
  3133. this.remove(map);
  3134. return this.select();
  3135. },
  3136. inserthtml : function(val, quickMode) {
  3137. var self = this, range = self.range;
  3138. if (val === '') {
  3139. return self;
  3140. }
  3141. function pasteHtml(range, val) {
  3142. val = '<img id="__kindeditor_temp_tag__" width="0" height="0" style="display:none;" />' + val;
  3143. var rng = range.get();
  3144. if (rng.item) {
  3145. rng.item(0).outerHTML = val;
  3146. } else {
  3147. rng.pasteHTML(val);
  3148. }
  3149. var temp = range.doc.getElementById('__kindeditor_temp_tag__');
  3150. temp.parentNode.removeChild(temp);
  3151. var newRange = _toRange(rng);
  3152. range.setEnd(newRange.endContainer, newRange.endOffset);
  3153. range.collapse(false);
  3154. self.select(false);
  3155. }
  3156. function insertHtml(range, val) {
  3157. var doc = range.doc,
  3158. frag = doc.createDocumentFragment();
  3159. K('@' + val, doc).each(function() {
  3160. frag.appendChild(this);
  3161. });
  3162. range.deleteContents();
  3163. range.insertNode(frag);
  3164. range.collapse(false);
  3165. self.select(false);
  3166. }
  3167. if (_IERANGE && quickMode) {
  3168. try {
  3169. pasteHtml(range, val);
  3170. } catch(e) {
  3171. insertHtml(range, val);
  3172. }
  3173. return self;
  3174. }
  3175. insertHtml(range, val);
  3176. return self;
  3177. },
  3178. hr : function() {
  3179. return this.inserthtml('<hr />');
  3180. },
  3181. print : function() {
  3182. this.win.print();
  3183. return this;
  3184. },
  3185. insertimage : function(url, title, width, height, border, align) {
  3186. title = _undef(title, '');
  3187. border = _undef(border, 0);
  3188. var html = '<img src="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3189. if (width) {
  3190. html += 'width="' + _escape(width) + '" ';
  3191. }
  3192. if (height) {
  3193. html += 'height="' + _escape(height) + '" ';
  3194. }
  3195. if (title) {
  3196. html += 'title="' + _escape(title) + '" ';
  3197. }
  3198. if (align) {
  3199. html += 'align="' + _escape(align) + '" ';
  3200. }
  3201. html += 'alt="' + _escape(title) + '" ';
  3202. html += '/>';
  3203. return this.inserthtml(html);
  3204. },
  3205. createlink : function(url, type) {
  3206. var self = this, doc = self.doc, range = self.range;
  3207. self.select();
  3208. var a = self.commonNode({ a : '*' });
  3209. if (a && !range.isControl()) {
  3210. range.selectNode(a.get());
  3211. self.select();
  3212. }
  3213. var html = '<a href="' + _escape(url) + '" data-ke-src="' + _escape(url) + '" ';
  3214. if (type) {
  3215. html += ' target="' + _escape(type) + '"';
  3216. }
  3217. if (range.collapsed) {
  3218. html += '>' + _escape(url) + '</a>';
  3219. return self.inserthtml(html);
  3220. }
  3221. if (range.isControl()) {
  3222. var node = K(range.startContainer.childNodes[range.startOffset]);
  3223. html += '></a>';
  3224. node.after(K(html, doc));
  3225. node.next().append(node);
  3226. range.selectNode(node[0]);
  3227. return self.select();
  3228. }
  3229. function setAttr(node, url, type) {
  3230. K(node).attr('href', url).attr('data-ke-src', url);
  3231. if (type) {
  3232. K(node).attr('target', type);
  3233. } else {
  3234. K(node).removeAttr('target');
  3235. }
  3236. }
  3237. var sc = range.startContainer, so = range.startOffset,
  3238. ec = range.endContainer, eo = range.endOffset;
  3239. if (sc.nodeType == 1 && sc === ec && so + 1 === eo) {
  3240. var child = sc.childNodes[so];
  3241. if (child.nodeName.toLowerCase() == 'a') {
  3242. setAttr(child, url, type);
  3243. return self;
  3244. }
  3245. }
  3246. _nativeCommand(doc, 'createlink', '__kindeditor_temp_url__');
  3247. K('a[href="__kindeditor_temp_url__"]', doc).each(function() {
  3248. setAttr(this, url, type);
  3249. });
  3250. return self;
  3251. },
  3252. unlink : function() {
  3253. var self = this, doc = self.doc, range = self.range;
  3254. self.select();
  3255. if (range.collapsed) {
  3256. var a = self.commonNode({ a : '*' });
  3257. if (a) {
  3258. range.selectNode(a.get());
  3259. self.select();
  3260. }
  3261. _nativeCommand(doc, 'unlink', null);
  3262. if (_WEBKIT && K(range.startContainer).name === 'img') {
  3263. var parent = K(range.startContainer).parent();
  3264. if (parent.name === 'a') {
  3265. parent.remove(true);
  3266. }
  3267. }
  3268. } else {
  3269. _nativeCommand(doc, 'unlink', null);
  3270. }
  3271. return self;
  3272. }
  3273. });
  3274. _each(('formatblock,selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  3275. 'insertunorderedlist,indent,outdent,subscript,superscript').split(','), function(i, name) {
  3276. KCmd.prototype[name] = function(val) {
  3277. var self = this;
  3278. self.select();
  3279. _nativeCommand(self.doc, name, val);
  3280. if (_IERANGE && _inArray(name, 'justifyleft,justifycenter,justifyright,justifyfull'.split(',')) >= 0) {
  3281. self.selection();
  3282. }
  3283. if (!_IERANGE || _inArray(name, 'formatblock,selectall,insertorderedlist,insertunorderedlist'.split(',')) >= 0) {
  3284. self.selection();
  3285. }
  3286. return self;
  3287. };
  3288. });
  3289. _each('cut,copy,paste'.split(','), function(i, name) {
  3290. KCmd.prototype[name] = function() {
  3291. var self = this;
  3292. if (!self.doc.queryCommandSupported(name)) {
  3293. throw 'not supported';
  3294. }
  3295. self.select();
  3296. _nativeCommand(self.doc, name, null);
  3297. return self;
  3298. };
  3299. });
  3300. function _cmd(mixed) {
  3301. if (mixed.nodeName) {
  3302. var doc = _getDoc(mixed);
  3303. mixed = _range(doc).selectNodeContents(doc.body).collapse(false);
  3304. }
  3305. return new KCmd(mixed);
  3306. }
  3307. K.CmdClass = KCmd;
  3308. K.cmd = _cmd;
  3309. function _drag(options) {
  3310. var moveEl = options.moveEl,
  3311. moveFn = options.moveFn,
  3312. clickEl = options.clickEl || moveEl,
  3313. beforeDrag = options.beforeDrag,
  3314. iframeFix = options.iframeFix === undefined ? true : options.iframeFix;
  3315. var docs = [document];
  3316. if (iframeFix) {
  3317. K('iframe').each(function() {
  3318. var src = _formatUrl(this.src || '', 'absolute');
  3319. if (/^https?:\/\//.test(src)) {
  3320. return;
  3321. }
  3322. var doc;
  3323. try {
  3324. doc = _iframeDoc(this);
  3325. } catch(e) {}
  3326. if (doc) {
  3327. var pos = K(this).pos();
  3328. K(doc).data('pos-x', pos.x);
  3329. K(doc).data('pos-y', pos.y);
  3330. docs.push(doc);
  3331. }
  3332. });
  3333. }
  3334. clickEl.mousedown(function(e) {
  3335. e.stopPropagation();
  3336. var self = clickEl.get(),
  3337. x = _removeUnit(moveEl.css('left')),
  3338. y = _removeUnit(moveEl.css('top')),
  3339. width = moveEl.width(),
  3340. height = moveEl.height(),
  3341. pageX = e.pageX,
  3342. pageY = e.pageY;
  3343. if (beforeDrag) {
  3344. beforeDrag();
  3345. }
  3346. function moveListener(e) {
  3347. e.preventDefault();
  3348. var kdoc = K(_getDoc(e.target));
  3349. var diffX = _round((kdoc.data('pos-x') || 0) + e.pageX - pageX);
  3350. var diffY = _round((kdoc.data('pos-y') || 0) + e.pageY - pageY);
  3351. moveFn.call(clickEl, x, y, width, height, diffX, diffY);
  3352. }
  3353. function selectListener(e) {
  3354. e.preventDefault();
  3355. }
  3356. function upListener(e) {
  3357. e.preventDefault();
  3358. K(docs).unbind('mousemove', moveListener)
  3359. .unbind('mouseup', upListener)
  3360. .unbind('selectstart', selectListener);
  3361. if (self.releaseCapture) {
  3362. self.releaseCapture();
  3363. }
  3364. }
  3365. K(docs).mousemove(moveListener)
  3366. .mouseup(upListener)
  3367. .bind('selectstart', selectListener);
  3368. if (self.setCapture) {
  3369. self.setCapture();
  3370. }
  3371. });
  3372. }
  3373. function KWidget(options) {
  3374. this.init(options);
  3375. }
  3376. _extend(KWidget, {
  3377. init : function(options) {
  3378. var self = this;
  3379. self.name = options.name || '';
  3380. self.doc = options.doc || document;
  3381. self.win = _getWin(self.doc);
  3382. self.x = _addUnit(options.x);
  3383. self.y = _addUnit(options.y);
  3384. self.z = options.z;
  3385. self.width = _addUnit(options.width);
  3386. self.height = _addUnit(options.height);
  3387. self.div = K('<div style="display:block;"></div>');
  3388. self.options = options;
  3389. self._alignEl = options.alignEl;
  3390. if (self.width) {
  3391. self.div.css('width', self.width);
  3392. }
  3393. if (self.height) {
  3394. self.div.css('height', self.height);
  3395. }
  3396. if (self.z) {
  3397. self.div.css({
  3398. position : 'absolute',
  3399. left : self.x,
  3400. top : self.y,
  3401. 'z-index' : self.z
  3402. });
  3403. }
  3404. if (self.z && (self.x === undefined || self.y === undefined)) {
  3405. self.autoPos(self.width, self.height);
  3406. }
  3407. if (options.cls) {
  3408. self.div.addClass(options.cls);
  3409. }
  3410. if (options.shadowMode) {
  3411. self.div.addClass('ke-shadow');
  3412. }
  3413. if (options.css) {
  3414. self.div.css(options.css);
  3415. }
  3416. if (options.src) {
  3417. K(options.src).replaceWith(self.div);
  3418. } else {
  3419. K(self.doc.body).append(self.div);
  3420. }
  3421. if (options.html) {
  3422. self.div.html(options.html);
  3423. }
  3424. if (options.autoScroll) {
  3425. if (_IE && _V < 7 || _QUIRKS) {
  3426. var scrollPos = _getScrollPos();
  3427. K(self.win).bind('scroll', function(e) {
  3428. var pos = _getScrollPos(),
  3429. diffX = pos.x - scrollPos.x,
  3430. diffY = pos.y - scrollPos.y;
  3431. self.pos(_removeUnit(self.x) + diffX, _removeUnit(self.y) + diffY, false);
  3432. });
  3433. } else {
  3434. self.div.css('position', 'fixed');
  3435. }
  3436. }
  3437. },
  3438. pos : function(x, y, updateProp) {
  3439. var self = this;
  3440. updateProp = _undef(updateProp, true);
  3441. if (x !== null) {
  3442. x = x < 0 ? 0 : _addUnit(x);
  3443. self.div.css('left', x);
  3444. if (updateProp) {
  3445. self.x = x;
  3446. }
  3447. }
  3448. if (y !== null) {
  3449. y = y < 0 ? 0 : _addUnit(y);
  3450. self.div.css('top', y);
  3451. if (updateProp) {
  3452. self.y = y;
  3453. }
  3454. }
  3455. return self;
  3456. },
  3457. autoPos : function(width, height) {
  3458. var self = this,
  3459. w = _removeUnit(width) || 0,
  3460. h = _removeUnit(height) || 0,
  3461. scrollPos = _getScrollPos();
  3462. if (self._alignEl) {
  3463. var knode = K(self._alignEl),
  3464. pos = knode.pos(),
  3465. diffX = _round(knode[0].clientWidth / 2 - w / 2),
  3466. diffY = _round(knode[0].clientHeight / 2 - h / 2);
  3467. x = diffX < 0 ? pos.x : pos.x + diffX;
  3468. y = diffY < 0 ? pos.y : pos.y + diffY;
  3469. } else {
  3470. var docEl = _docElement(self.doc);
  3471. x = _round(scrollPos.x + (docEl.clientWidth - w) / 2);
  3472. y = _round(scrollPos.y + (docEl.clientHeight - h) / 2);
  3473. }
  3474. if (!(_IE && _V < 7 || _QUIRKS)) {
  3475. x -= scrollPos.x;
  3476. y -= scrollPos.y;
  3477. }
  3478. return self.pos(x, y);
  3479. },
  3480. remove : function() {
  3481. var self = this;
  3482. if (_IE && _V < 7 || _QUIRKS) {
  3483. K(self.win).unbind('scroll');
  3484. }
  3485. self.div.remove();
  3486. _each(self, function(i) {
  3487. self[i] = null;
  3488. });
  3489. return this;
  3490. },
  3491. show : function() {
  3492. this.div.show();
  3493. return this;
  3494. },
  3495. hide : function() {
  3496. this.div.hide();
  3497. return this;
  3498. },
  3499. draggable : function(options) {
  3500. var self = this;
  3501. options = options || {};
  3502. options.moveEl = self.div;
  3503. options.moveFn = function(x, y, width, height, diffX, diffY) {
  3504. if ((x = x + diffX) < 0) {
  3505. x = 0;
  3506. }
  3507. if ((y = y + diffY) < 0) {
  3508. y = 0;
  3509. }
  3510. self.pos(x, y);
  3511. };
  3512. _drag(options);
  3513. return self;
  3514. }
  3515. });
  3516. function _widget(options) {
  3517. return new KWidget(options);
  3518. }
  3519. K.WidgetClass = KWidget;
  3520. K.widget = _widget;
  3521. function _iframeDoc(iframe) {
  3522. iframe = _get(iframe);
  3523. return iframe.contentDocument || iframe.contentWindow.document;
  3524. }
  3525. var html, _direction = '';
  3526. if ((html = document.getElementsByTagName('html'))) {
  3527. _direction = html[0].dir;
  3528. }
  3529. function _getInitHtml(themesPath, bodyClass, cssPath, cssData) {
  3530. var arr = [
  3531. (_direction === '' ? '<html>' : '<html dir="' + _direction + '">'),
  3532. '<head><meta charset="utf-8" /><title></title>',
  3533. '<style>',
  3534. 'html {margin:0;padding:0;}',
  3535. 'body {margin:0;padding:5px;}',
  3536. 'body, td {font:12px/1.5 "sans serif",tahoma,verdana,helvetica;}',
  3537. 'body, p, div {word-wrap: break-word;}',
  3538. 'p {margin:5px 0;}',
  3539. 'table {border-collapse:collapse;}',
  3540. 'img {border:0;}',
  3541. 'noscript {display:none;}',
  3542. 'table.ke-zeroborder td {border:1px dotted #AAA;}',
  3543. 'img.ke-flash {',
  3544. ' border:1px solid #AAA;',
  3545. ' background-image:url(' + themesPath + 'common/flash.gif);',
  3546. ' background-position:center center;',
  3547. ' background-repeat:no-repeat;',
  3548. ' width:100px;',
  3549. ' height:100px;',
  3550. '}',
  3551. 'img.ke-rm {',
  3552. ' border:1px solid #AAA;',
  3553. ' background-image:url(' + themesPath + 'common/rm.gif);',
  3554. ' background-position:center center;',
  3555. ' background-repeat:no-repeat;',
  3556. ' width:100px;',
  3557. ' height:100px;',
  3558. '}',
  3559. 'img.ke-media {',
  3560. ' border:1px solid #AAA;',
  3561. ' background-image:url(' + themesPath + 'common/media.gif);',
  3562. ' background-position:center center;',
  3563. ' background-repeat:no-repeat;',
  3564. ' width:100px;',
  3565. ' height:100px;',
  3566. '}',
  3567. 'img.ke-anchor {',
  3568. ' border:1px dashed #666;',
  3569. ' width:16px;',
  3570. ' height:16px;',
  3571. '}',
  3572. '.ke-script, .ke-noscript, .ke-display-none {',
  3573. ' display:none;',
  3574. ' font-size:0;',
  3575. ' width:0;',
  3576. ' height:0;',
  3577. '}',
  3578. '.ke-pagebreak {',
  3579. ' border:1px dotted #AAA;',
  3580. ' font-size:0;',
  3581. ' height:2px;',
  3582. '}',
  3583. '</style>'
  3584. ];
  3585. if (!_isArray(cssPath)) {
  3586. cssPath = [cssPath];
  3587. }
  3588. _each(cssPath, function(i, path) {
  3589. if (path) {
  3590. arr.push('<link href="' + path + '" rel="stylesheet" />');
  3591. }
  3592. });
  3593. if (cssData) {
  3594. arr.push('<style>' + cssData + '</style>');
  3595. }
  3596. arr.push('</head><body ' + (bodyClass ? 'class="' + bodyClass + '"' : '') + '></body></html>');
  3597. return arr.join('\n');
  3598. }
  3599. function _elementVal(knode, val) {
  3600. if (knode.hasVal()) {
  3601. if (val === undefined) {
  3602. var html = knode.val();
  3603. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  3604. return html;
  3605. }
  3606. return knode.val(val);
  3607. }
  3608. return knode.html(val);
  3609. }
  3610. function KEdit(options) {
  3611. this.init(options);
  3612. }
  3613. _extend(KEdit, KWidget, {
  3614. init : function(options) {
  3615. var self = this;
  3616. KEdit.parent.init.call(self, options);
  3617. self.srcElement = K(options.srcElement);
  3618. self.div.addClass('ke-edit');
  3619. self.designMode = _undef(options.designMode, true);
  3620. self.beforeGetHtml = options.beforeGetHtml;
  3621. self.beforeSetHtml = options.beforeSetHtml;
  3622. self.afterSetHtml = options.afterSetHtml;
  3623. var themesPath = _undef(options.themesPath, ''),
  3624. bodyClass = options.bodyClass,
  3625. cssPath = options.cssPath,
  3626. cssData = options.cssData,
  3627. isDocumentDomain = location.protocol != 'res:' && location.host.replace(/:\d+/, '') !== document.domain,
  3628. srcScript = ('document.open();' +
  3629. (isDocumentDomain ? 'document.domain="' + document.domain + '";' : '') +
  3630. 'document.close();'),
  3631. iframeSrc = _IE ? ' src="javascript:void(function(){' + encodeURIComponent(srcScript) + '}())"' : '';
  3632. self.iframe = K('<iframe class="ke-edit-iframe" hidefocus="true" frameborder="0"' + iframeSrc + '></iframe>').css('width', '100%');
  3633. self.textarea = K('<textarea class="ke-edit-textarea" hidefocus="true"></textarea>').css('width', '100%');
  3634. self.tabIndex = isNaN(parseInt(options.tabIndex, 10)) ? self.srcElement.attr('tabindex') : parseInt(options.tabIndex, 10);
  3635. self.iframe.attr('tabindex', self.tabIndex);
  3636. self.textarea.attr('tabindex', self.tabIndex);
  3637. if (self.width) {
  3638. self.setWidth(self.width);
  3639. }
  3640. if (self.height) {
  3641. self.setHeight(self.height);
  3642. }
  3643. if (self.designMode) {
  3644. self.textarea.hide();
  3645. } else {
  3646. self.iframe.hide();
  3647. }
  3648. function ready() {
  3649. var doc = _iframeDoc(self.iframe);
  3650. doc.open();
  3651. if (isDocumentDomain) {
  3652. doc.domain = document.domain;
  3653. }
  3654. doc.write(_getInitHtml(themesPath, bodyClass, cssPath, cssData));
  3655. doc.close();
  3656. self.win = self.iframe[0].contentWindow;
  3657. self.doc = doc;
  3658. var cmd = _cmd(doc);
  3659. self.afterChange(function(e) {
  3660. cmd.selection();
  3661. });
  3662. if (_WEBKIT) {
  3663. K(doc).click(function(e) {
  3664. if (K(e.target).name === 'img') {
  3665. cmd.selection(true);
  3666. cmd.range.selectNode(e.target);
  3667. cmd.select();
  3668. }
  3669. });
  3670. }
  3671. if (_IE) {
  3672. self._mousedownHandler = function() {
  3673. var newRange = cmd.range.cloneRange();
  3674. newRange.shrink();
  3675. if (newRange.isControl()) {
  3676. self.blur();
  3677. }
  3678. };
  3679. K(document).mousedown(self._mousedownHandler);
  3680. K(doc).keydown(function(e) {
  3681. if (e.which == 8) {
  3682. cmd.selection();
  3683. var rng = cmd.range;
  3684. if (rng.isControl()) {
  3685. rng.collapse(true);
  3686. K(rng.startContainer.childNodes[rng.startOffset]).remove();
  3687. e.preventDefault();
  3688. }
  3689. }
  3690. });
  3691. }
  3692. self.cmd = cmd;
  3693. self.html(_elementVal(self.srcElement));
  3694. if (_IE) {
  3695. doc.body.disabled = true;
  3696. doc.body.contentEditable = true;
  3697. doc.body.removeAttribute('disabled');
  3698. } else {
  3699. doc.designMode = 'on';
  3700. }
  3701. if (options.afterCreate) {
  3702. options.afterCreate.call(self);
  3703. }
  3704. }
  3705. if (isDocumentDomain) {
  3706. self.iframe.bind('load', function(e) {
  3707. self.iframe.unbind('load');
  3708. if (_IE) {
  3709. ready();
  3710. } else {
  3711. setTimeout(ready, 0);
  3712. }
  3713. });
  3714. }
  3715. self.div.append(self.iframe);
  3716. self.div.append(self.textarea);
  3717. self.srcElement.hide();
  3718. !isDocumentDomain && ready();
  3719. },
  3720. setWidth : function(val) {
  3721. var self = this;
  3722. val = _addUnit(val);
  3723. self.width = val;
  3724. self.div.css('width', val);
  3725. return self;
  3726. },
  3727. setHeight : function(val) {
  3728. var self = this;
  3729. val = _addUnit(val);
  3730. self.height = val;
  3731. self.div.css('height', val);
  3732. self.iframe.css('height', val);
  3733. if ((_IE && _V < 8) || _QUIRKS) {
  3734. val = _addUnit(_removeUnit(val) - 2);
  3735. }
  3736. self.textarea.css('height', val);
  3737. return self;
  3738. },
  3739. remove : function() {
  3740. var self = this, doc = self.doc;
  3741. K(doc.body).unbind();
  3742. K(doc).unbind();
  3743. K(self.win).unbind();
  3744. if (self._mousedownHandler) {
  3745. K(document).unbind('mousedown', self._mousedownHandler);
  3746. }
  3747. _elementVal(self.srcElement, self.html());
  3748. self.srcElement.show();
  3749. doc.write('');
  3750. self.iframe.unbind();
  3751. self.textarea.unbind();
  3752. KEdit.parent.remove.call(self);
  3753. },
  3754. html : function(val, isFull) {
  3755. var self = this, doc = self.doc;
  3756. if (self.designMode) {
  3757. var body = doc.body;
  3758. if (val === undefined) {
  3759. if (isFull) {
  3760. val = '<!doctype html><html>' + body.parentNode.innerHTML + '</html>';
  3761. } else {
  3762. val = body.innerHTML;
  3763. }
  3764. if (self.beforeGetHtml) {
  3765. val = self.beforeGetHtml(val);
  3766. }
  3767. if (_GECKO && val == '<br />') {
  3768. val = '';
  3769. }
  3770. return val;
  3771. }
  3772. if (self.beforeSetHtml) {
  3773. val = self.beforeSetHtml(val);
  3774. }
  3775. if (_IE && _V >= 9) {
  3776. val = val.replace(/(<.*?checked=")checked(".*>)/ig, '$1$2');
  3777. }
  3778. K(body).html(val);
  3779. if (self.afterSetHtml) {
  3780. self.afterSetHtml();
  3781. }
  3782. return self;
  3783. }
  3784. if (val === undefined) {
  3785. return self.textarea.val();
  3786. }
  3787. self.textarea.val(val);
  3788. return self;
  3789. },
  3790. design : function(bool) {
  3791. var self = this, val;
  3792. if (bool === undefined ? !self.designMode : bool) {
  3793. if (!self.designMode) {
  3794. val = self.html();
  3795. self.designMode = true;
  3796. self.html(val);
  3797. self.textarea.hide();
  3798. self.iframe.show();
  3799. }
  3800. } else {
  3801. if (self.designMode) {
  3802. val = self.html();
  3803. self.designMode = false;
  3804. self.html(val);
  3805. self.iframe.hide();
  3806. self.textarea.show();
  3807. }
  3808. }
  3809. return self.focus();
  3810. },
  3811. focus : function() {
  3812. var self = this;
  3813. self.designMode ? self.win.focus() : self.textarea[0].focus();
  3814. return self;
  3815. },
  3816. blur : function() {
  3817. var self = this;
  3818. if (_IE) {
  3819. var input = K('<input type="text" style="float:left;width:0;height:0;padding:0;margin:0;border:0;" value="" />', self.div);
  3820. self.div.append(input);
  3821. input[0].focus();
  3822. input.remove();
  3823. } else {
  3824. self.designMode ? self.win.blur() : self.textarea[0].blur();
  3825. }
  3826. return self;
  3827. },
  3828. afterChange : function(fn) {
  3829. var self = this, doc = self.doc, body = doc.body;
  3830. K(doc).keyup(function(e) {
  3831. if (!e.ctrlKey && !e.altKey && _CHANGE_KEY_MAP[e.which]) {
  3832. fn(e);
  3833. }
  3834. });
  3835. K(doc).mouseup(fn).contextmenu(fn);
  3836. K(self.win).blur(fn);
  3837. function timeoutHandler(e) {
  3838. setTimeout(function() {
  3839. fn(e);
  3840. }, 1);
  3841. }
  3842. K(body).bind('paste', timeoutHandler);
  3843. K(body).bind('cut', timeoutHandler);
  3844. return self;
  3845. }
  3846. });
  3847. function _edit(options) {
  3848. return new KEdit(options);
  3849. }
  3850. K.EditClass = KEdit;
  3851. K.edit = _edit;
  3852. K.iframeDoc = _iframeDoc;
  3853. function _selectToolbar(name, fn) {
  3854. var self = this,
  3855. knode = self.get(name);
  3856. if (knode) {
  3857. if (knode.hasClass('ke-disabled')) {
  3858. return;
  3859. }
  3860. fn(knode);
  3861. }
  3862. }
  3863. function KToolbar(options) {
  3864. this.init(options);
  3865. }
  3866. _extend(KToolbar, KWidget, {
  3867. init : function(options) {
  3868. var self = this;
  3869. KToolbar.parent.init.call(self, options);
  3870. self.disableMode = _undef(options.disableMode, false);
  3871. self.noDisableItemMap = _toMap(_undef(options.noDisableItems, []));
  3872. self._itemMap = {};
  3873. self.div.addClass('ke-toolbar').bind('contextmenu,mousedown,mousemove', function(e) {
  3874. e.preventDefault();
  3875. }).attr('unselectable', 'on');
  3876. function find(target) {
  3877. var knode = K(target);
  3878. if (knode.hasClass('ke-outline')) {
  3879. return knode;
  3880. }
  3881. if (knode.hasClass('ke-toolbar-icon')) {
  3882. return knode.parent();
  3883. }
  3884. }
  3885. function hover(e, method) {
  3886. var knode = find(e.target);
  3887. if (knode) {
  3888. if (knode.hasClass('ke-disabled')) {
  3889. return;
  3890. }
  3891. if (knode.hasClass('ke-selected')) {
  3892. return;
  3893. }
  3894. knode[method]('ke-on');
  3895. }
  3896. }
  3897. self.div.mouseover(function(e) {
  3898. hover(e, 'addClass');
  3899. })
  3900. .mouseout(function(e) {
  3901. hover(e, 'removeClass');
  3902. })
  3903. .click(function(e) {
  3904. var knode = find(e.target);
  3905. if (knode) {
  3906. if (knode.hasClass('ke-disabled')) {
  3907. return;
  3908. }
  3909. self.options.click.call(this, e, knode.attr('data-name'));
  3910. }
  3911. });
  3912. },
  3913. get : function(name) {
  3914. if (this._itemMap[name]) {
  3915. return this._itemMap[name];
  3916. }
  3917. return (this._itemMap[name] = K('span.ke-icon-' + name, this.div).parent());
  3918. },
  3919. select : function(name) {
  3920. _selectToolbar.call(this, name, function(knode) {
  3921. knode.addClass('ke-selected');
  3922. });
  3923. return self;
  3924. },
  3925. unselect : function(name) {
  3926. _selectToolbar.call(this, name, function(knode) {
  3927. knode.removeClass('ke-selected').removeClass('ke-on');
  3928. });
  3929. return self;
  3930. },
  3931. enable : function(name) {
  3932. var self = this,
  3933. knode = name.get ? name : self.get(name);
  3934. if (knode) {
  3935. knode.removeClass('ke-disabled');
  3936. knode.opacity(1);
  3937. }
  3938. return self;
  3939. },
  3940. disable : function(name) {
  3941. var self = this,
  3942. knode = name.get ? name : self.get(name);
  3943. if (knode) {
  3944. knode.removeClass('ke-selected').addClass('ke-disabled');
  3945. knode.opacity(0.5);
  3946. }
  3947. return self;
  3948. },
  3949. disableAll : function(bool, noDisableItems) {
  3950. var self = this, map = self.noDisableItemMap, item;
  3951. if (noDisableItems) {
  3952. map = _toMap(noDisableItems);
  3953. }
  3954. if (bool === undefined ? !self.disableMode : bool) {
  3955. K('span.ke-outline', self.div).each(function() {
  3956. var knode = K(this),
  3957. name = knode[0].getAttribute('data-name', 2);
  3958. if (!map[name]) {
  3959. self.disable(knode);
  3960. }
  3961. });
  3962. self.disableMode = true;
  3963. } else {
  3964. K('span.ke-outline', self.div).each(function() {
  3965. var knode = K(this),
  3966. name = knode[0].getAttribute('data-name', 2);
  3967. if (!map[name]) {
  3968. self.enable(knode);
  3969. }
  3970. });
  3971. self.disableMode = false;
  3972. }
  3973. return self;
  3974. }
  3975. });
  3976. function _toolbar(options) {
  3977. return new KToolbar(options);
  3978. }
  3979. K.ToolbarClass = KToolbar;
  3980. K.toolbar = _toolbar;
  3981. function KMenu(options) {
  3982. this.init(options);
  3983. }
  3984. _extend(KMenu, KWidget, {
  3985. init : function(options) {
  3986. var self = this;
  3987. options.z = options.z || 811213;
  3988. KMenu.parent.init.call(self, options);
  3989. self.centerLineMode = _undef(options.centerLineMode, true);
  3990. self.div.addClass('ke-menu').bind('click,mousedown', function(e){
  3991. e.stopPropagation();
  3992. }).attr('unselectable', 'on');
  3993. },
  3994. addItem : function(item) {
  3995. var self = this;
  3996. if (item.title === '-') {
  3997. self.div.append(K('<div class="ke-menu-separator"></div>'));
  3998. return;
  3999. }
  4000. var itemDiv = K('<div class="ke-menu-item" unselectable="on"></div>'),
  4001. leftDiv = K('<div class="ke-inline-block ke-menu-item-left"></div>'),
  4002. rightDiv = K('<div class="ke-inline-block ke-menu-item-right"></div>'),
  4003. height = _addUnit(item.height),
  4004. iconClass = _undef(item.iconClass, '');
  4005. self.div.append(itemDiv);
  4006. if (height) {
  4007. itemDiv.css('height', height);
  4008. rightDiv.css('line-height', height);
  4009. }
  4010. var centerDiv;
  4011. if (self.centerLineMode) {
  4012. centerDiv = K('<div class="ke-inline-block ke-menu-item-center"></div>');
  4013. if (height) {
  4014. centerDiv.css('height', height);
  4015. }
  4016. }
  4017. itemDiv.mouseover(function(e) {
  4018. K(this).addClass('ke-menu-item-on');
  4019. if (centerDiv) {
  4020. centerDiv.addClass('ke-menu-item-center-on');
  4021. }
  4022. })
  4023. .mouseout(function(e) {
  4024. K(this).removeClass('ke-menu-item-on');
  4025. if (centerDiv) {
  4026. centerDiv.removeClass('ke-menu-item-center-on');
  4027. }
  4028. })
  4029. .click(function(e) {
  4030. item.click.call(K(this));
  4031. e.stopPropagation();
  4032. })
  4033. .append(leftDiv);
  4034. if (centerDiv) {
  4035. itemDiv.append(centerDiv);
  4036. }
  4037. itemDiv.append(rightDiv);
  4038. if (item.checked) {
  4039. iconClass = 'ke-icon-checked';
  4040. }
  4041. if (iconClass !== '') {
  4042. leftDiv.html('<span class="ke-inline-block ke-toolbar-icon ke-toolbar-icon-url ' + iconClass + '"></span>');
  4043. }
  4044. rightDiv.html(item.title);
  4045. return self;
  4046. },
  4047. remove : function() {
  4048. var self = this;
  4049. if (self.options.beforeRemove) {
  4050. self.options.beforeRemove.call(self);
  4051. }
  4052. K('.ke-menu-item', self.div[0]).unbind();
  4053. KMenu.parent.remove.call(self);
  4054. return self;
  4055. }
  4056. });
  4057. function _menu(options) {
  4058. return new KMenu(options);
  4059. }
  4060. K.MenuClass = KMenu;
  4061. K.menu = _menu;
  4062. function KColorPicker(options) {
  4063. this.init(options);
  4064. }
  4065. _extend(KColorPicker, KWidget, {
  4066. init : function(options) {
  4067. var self = this;
  4068. options.z = options.z || 811213;
  4069. KColorPicker.parent.init.call(self, options);
  4070. var colors = options.colors || [
  4071. ['#E53333', '#E56600', '#FF9900', '#64451D', '#DFC5A4', '#FFE500'],
  4072. ['#009900', '#006600', '#99BB00', '#B8D100', '#60D978', '#00D5FF'],
  4073. ['#337FE5', '#003399', '#4C33E5', '#9933E5', '#CC33E5', '#EE33EE'],
  4074. ['#FFFFFF', '#CCCCCC', '#999999', '#666666', '#333333', '#000000']
  4075. ];
  4076. self.selectedColor = (options.selectedColor || '').toLowerCase();
  4077. self._cells = [];
  4078. self.div.addClass('ke-colorpicker').bind('click,mousedown', function(e){
  4079. e.stopPropagation();
  4080. }).attr('unselectable', 'on');
  4081. var table = self.doc.createElement('table');
  4082. self.div.append(table);
  4083. table.className = 'ke-colorpicker-table';
  4084. table.cellPadding = 0;
  4085. table.cellSpacing = 0;
  4086. table.border = 0;
  4087. var row = table.insertRow(0), cell = row.insertCell(0);
  4088. cell.colSpan = colors[0].length;
  4089. self._addAttr(cell, '', 'ke-colorpicker-cell-top');
  4090. for (var i = 0; i < colors.length; i++) {
  4091. row = table.insertRow(i + 1);
  4092. for (var j = 0; j < colors[i].length; j++) {
  4093. cell = row.insertCell(j);
  4094. self._addAttr(cell, colors[i][j], 'ke-colorpicker-cell');
  4095. }
  4096. }
  4097. },
  4098. _addAttr : function(cell, color, cls) {
  4099. var self = this;
  4100. cell = K(cell).addClass(cls);
  4101. if (self.selectedColor === color.toLowerCase()) {
  4102. cell.addClass('ke-colorpicker-cell-selected');
  4103. }
  4104. cell.attr('title', color || self.options.noColor);
  4105. cell.mouseover(function(e) {
  4106. K(this).addClass('ke-colorpicker-cell-on');
  4107. });
  4108. cell.mouseout(function(e) {
  4109. K(this).removeClass('ke-colorpicker-cell-on');
  4110. });
  4111. cell.click(function(e) {
  4112. e.stop();
  4113. self.options.click.call(K(this), color);
  4114. });
  4115. if (color) {
  4116. cell.append(K('<div class="ke-colorpicker-cell-color" unselectable="on"></div>').css('background-color', color));
  4117. } else {
  4118. cell.html(self.options.noColor);
  4119. }
  4120. K(cell).attr('unselectable', 'on');
  4121. self._cells.push(cell);
  4122. },
  4123. remove : function() {
  4124. var self = this;
  4125. _each(self._cells, function() {
  4126. this.unbind();
  4127. });
  4128. KColorPicker.parent.remove.call(self);
  4129. return self;
  4130. }
  4131. });
  4132. function _colorpicker(options) {
  4133. return new KColorPicker(options);
  4134. }
  4135. K.ColorPickerClass = KColorPicker;
  4136. K.colorpicker = _colorpicker;
  4137. function KUploadButton(options) {
  4138. this.init(options);
  4139. }
  4140. _extend(KUploadButton, {
  4141. init : function(options) {
  4142. var self = this,
  4143. button = K(options.button),
  4144. fieldName = options.fieldName || 'file',
  4145. url = options.url || '',
  4146. title = button.val(),
  4147. extraParams = options.extraParams || {},
  4148. cls = button[0].className || '',
  4149. target = options.target || 'kindeditor_upload_iframe_' + new Date().getTime();
  4150. options.afterError = options.afterError || function(str) {
  4151. alert(str);
  4152. };
  4153. var hiddenElements = [];
  4154. for(var k in extraParams){
  4155. hiddenElements.push('<input type="hidden" name="' + k + '" value="' + extraParams[k] + '" />');
  4156. }
  4157. var html = [
  4158. '<div class="ke-inline-block ' + cls + '">',
  4159. (options.target ? '' : '<iframe name="' + target + '" style="display:none;"></iframe>'),
  4160. (options.form ? '<div class="ke-upload-area">' : '<form class="ke-upload-area ke-form" method="post" enctype="multipart/form-data" target="' + target + '" action="' + url + '">'),
  4161. '<span class="ke-button-common">',
  4162. hiddenElements.join(''),
  4163. '<input type="button" class="ke-button-common ke-button" value="' + title + '" />',
  4164. '</span>',
  4165. '<input type="file" class="ke-upload-file" name="' + fieldName + '" tabindex="-1" />',
  4166. (options.form ? '</div>' : '</form>'),
  4167. '</div>'].join('');
  4168. var div = K(html, button.doc);
  4169. button.hide();
  4170. button.before(div);
  4171. self.div = div;
  4172. self.button = button;
  4173. self.iframe = options.target ? K('iframe[name="' + target + '"]') : K('iframe', div);
  4174. self.form = options.form ? K(options.form) : K('form', div);
  4175. self.fileBox = K('.ke-upload-file', div);
  4176. var width = options.width || K('.ke-button-common', div).width();
  4177. K('.ke-upload-area', div).width(width);
  4178. self.options = options;
  4179. },
  4180. submit : function() {
  4181. var self = this,
  4182. iframe = self.iframe;
  4183. iframe.bind('load', function() {
  4184. iframe.unbind();
  4185. var tempForm = document.createElement('form');
  4186. self.fileBox.before(tempForm);
  4187. K(tempForm).append(self.fileBox);
  4188. tempForm.reset();
  4189. K(tempForm).remove(true);
  4190. var doc = K.iframeDoc(iframe),
  4191. pre = doc.getElementsByTagName('pre')[0],
  4192. str = '', data;
  4193. if (pre) {
  4194. str = pre.innerHTML;
  4195. } else {
  4196. str = doc.body.innerHTML;
  4197. }
  4198. str = _unescape(str);
  4199. iframe[0].src = 'javascript:false';
  4200. try {
  4201. data = K.json(str);
  4202. } catch (e) {
  4203. self.options.afterError.call(self, '<!doctype html><html>' + doc.body.parentNode.innerHTML + '</html>');
  4204. }
  4205. if (data) {
  4206. self.options.afterUpload.call(self, data);
  4207. }
  4208. });
  4209. self.form[0].submit();
  4210. return self;
  4211. },
  4212. remove : function() {
  4213. var self = this;
  4214. if (self.fileBox) {
  4215. self.fileBox.unbind();
  4216. }
  4217. self.iframe.remove();
  4218. self.div.remove();
  4219. self.button.show();
  4220. return self;
  4221. }
  4222. });
  4223. function _uploadbutton(options) {
  4224. return new KUploadButton(options);
  4225. }
  4226. K.UploadButtonClass = KUploadButton;
  4227. K.uploadbutton = _uploadbutton;
  4228. function _createButton(arg) {
  4229. arg = arg || {};
  4230. var name = arg.name || '',
  4231. span = K('<span class="ke-button-common ke-button-outer" title="' + name + '"></span>'),
  4232. btn = K('<input class="ke-button-common ke-button" type="button" value="' + name + '" />');
  4233. if (arg.click) {
  4234. btn.click(arg.click);
  4235. }
  4236. span.append(btn);
  4237. return span;
  4238. }
  4239. function KDialog(options) {
  4240. this.init(options);
  4241. }
  4242. _extend(KDialog, KWidget, {
  4243. init : function(options) {
  4244. var self = this;
  4245. var shadowMode = _undef(options.shadowMode, true);
  4246. options.z = options.z || 811213;
  4247. options.shadowMode = false;
  4248. options.autoScroll = _undef(options.autoScroll, true);
  4249. KDialog.parent.init.call(self, options);
  4250. var title = options.title,
  4251. body = K(options.body, self.doc),
  4252. previewBtn = options.previewBtn,
  4253. yesBtn = options.yesBtn,
  4254. noBtn = options.noBtn,
  4255. closeBtn = options.closeBtn,
  4256. showMask = _undef(options.showMask, true);
  4257. self.div.addClass('ke-dialog').bind('click,mousedown', function(e){
  4258. e.stopPropagation();
  4259. });
  4260. var contentDiv = K('<div class="ke-dialog-content"></div>').appendTo(self.div);
  4261. if (_IE && _V < 7) {
  4262. self.iframeMask = K('<iframe src="about:blank" class="ke-dialog-shadow"></iframe>').appendTo(self.div);
  4263. } else if (shadowMode) {
  4264. K('<div class="ke-dialog-shadow"></div>').appendTo(self.div);
  4265. }
  4266. var headerDiv = K('<div class="ke-dialog-header"></div>');
  4267. contentDiv.append(headerDiv);
  4268. headerDiv.html(title);
  4269. self.closeIcon = K('<span class="ke-dialog-icon-close" title="' + closeBtn.name + '"></span>').click(closeBtn.click);
  4270. headerDiv.append(self.closeIcon);
  4271. self.draggable({
  4272. clickEl : headerDiv,
  4273. beforeDrag : options.beforeDrag
  4274. });
  4275. var bodyDiv = K('<div class="ke-dialog-body"></div>');
  4276. contentDiv.append(bodyDiv);
  4277. bodyDiv.append(body);
  4278. var footerDiv = K('<div class="ke-dialog-footer"></div>');
  4279. if (previewBtn || yesBtn || noBtn) {
  4280. contentDiv.append(footerDiv);
  4281. }
  4282. _each([
  4283. { btn : previewBtn, name : 'preview' },
  4284. { btn : yesBtn, name : 'yes' },
  4285. { btn : noBtn, name : 'no' }
  4286. ], function() {
  4287. if (this.btn) {
  4288. var button = _createButton(this.btn);
  4289. button.addClass('ke-dialog-' + this.name);
  4290. footerDiv.append(button);
  4291. }
  4292. });
  4293. if (self.height) {
  4294. bodyDiv.height(_removeUnit(self.height) - headerDiv.height() - footerDiv.height());
  4295. }
  4296. self.div.width(self.div.width());
  4297. self.div.height(self.div.height());
  4298. self.mask = null;
  4299. if (showMask) {
  4300. var docEl = _docElement(self.doc),
  4301. docWidth = Math.max(docEl.scrollWidth, docEl.clientWidth),
  4302. docHeight = Math.max(docEl.scrollHeight, docEl.clientHeight);
  4303. self.mask = _widget({
  4304. x : 0,
  4305. y : 0,
  4306. z : self.z - 1,
  4307. cls : 'ke-dialog-mask',
  4308. width : docWidth,
  4309. height : docHeight
  4310. });
  4311. }
  4312. self.autoPos(self.div.width(), self.div.height());
  4313. self.footerDiv = footerDiv;
  4314. self.bodyDiv = bodyDiv;
  4315. self.headerDiv = headerDiv;
  4316. self.isLoading = false;
  4317. },
  4318. setMaskIndex : function(z) {
  4319. var self = this;
  4320. self.mask.div.css('z-index', z);
  4321. },
  4322. showLoading : function(msg) {
  4323. msg = _undef(msg, '');
  4324. var self = this, body = self.bodyDiv;
  4325. self.loading = K('<div class="ke-dialog-loading"><div class="ke-inline-block ke-dialog-loading-content" style="margin-top:' + Math.round(body.height() / 3) + 'px;">' + msg + '</div></div>')
  4326. .width(body.width()).height(body.height())
  4327. .css('top', self.headerDiv.height() + 'px');
  4328. body.css('visibility', 'hidden').after(self.loading);
  4329. self.isLoading = true;
  4330. return self;
  4331. },
  4332. hideLoading : function() {
  4333. this.loading && this.loading.remove();
  4334. this.bodyDiv.css('visibility', 'visible');
  4335. this.isLoading = false;
  4336. return this;
  4337. },
  4338. remove : function() {
  4339. var self = this;
  4340. if (self.options.beforeRemove) {
  4341. self.options.beforeRemove.call(self);
  4342. }
  4343. self.mask && self.mask.remove();
  4344. self.iframeMask && self.iframeMask.remove();
  4345. self.closeIcon.unbind();
  4346. K('input', self.div).unbind();
  4347. K('button', self.div).unbind();
  4348. self.footerDiv.unbind();
  4349. self.bodyDiv.unbind();
  4350. self.headerDiv.unbind();
  4351. K('iframe', self.div).each(function() {
  4352. K(this).remove();
  4353. });
  4354. KDialog.parent.remove.call(self);
  4355. return self;
  4356. }
  4357. });
  4358. function _dialog(options) {
  4359. return new KDialog(options);
  4360. }
  4361. K.DialogClass = KDialog;
  4362. K.dialog = _dialog;
  4363. function _tabs(options) {
  4364. var self = _widget(options),
  4365. remove = self.remove,
  4366. afterSelect = options.afterSelect,
  4367. div = self.div,
  4368. liList = [];
  4369. div.addClass('ke-tabs')
  4370. .bind('contextmenu,mousedown,mousemove', function(e) {
  4371. e.preventDefault();
  4372. });
  4373. var ul = K('<ul class="ke-tabs-ul ke-clearfix"></ul>');
  4374. div.append(ul);
  4375. self.add = function(tab) {
  4376. var li = K('<li class="ke-tabs-li">' + tab.title + '</li>');
  4377. li.data('tab', tab);
  4378. liList.push(li);
  4379. ul.append(li);
  4380. };
  4381. self.selectedIndex = 0;
  4382. self.select = function(index) {
  4383. self.selectedIndex = index;
  4384. _each(liList, function(i, li) {
  4385. li.unbind();
  4386. if (i === index) {
  4387. li.addClass('ke-tabs-li-selected');
  4388. K(li.data('tab').panel).show('');
  4389. } else {
  4390. li.removeClass('ke-tabs-li-selected').removeClass('ke-tabs-li-on')
  4391. .mouseover(function() {
  4392. K(this).addClass('ke-tabs-li-on');
  4393. })
  4394. .mouseout(function() {
  4395. K(this).removeClass('ke-tabs-li-on');
  4396. })
  4397. .click(function() {
  4398. self.select(i);
  4399. });
  4400. K(li.data('tab').panel).hide();
  4401. }
  4402. });
  4403. if (afterSelect) {
  4404. afterSelect.call(self, index);
  4405. }
  4406. };
  4407. self.remove = function() {
  4408. _each(liList, function() {
  4409. this.remove();
  4410. });
  4411. ul.remove();
  4412. remove.call(self);
  4413. };
  4414. return self;
  4415. }
  4416. K.tabs = _tabs;
  4417. function _loadScript(url, fn) {
  4418. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4419. script = document.createElement('script');
  4420. head.appendChild(script);
  4421. script.src = url;
  4422. script.charset = 'utf-8';
  4423. script.onload = script.onreadystatechange = function() {
  4424. if (!this.readyState || this.readyState === 'loaded') {
  4425. if (fn) {
  4426. fn();
  4427. }
  4428. script.onload = script.onreadystatechange = null;
  4429. head.removeChild(script);
  4430. }
  4431. };
  4432. }
  4433. function _chopQuery(url) {
  4434. var index = url.indexOf('?');
  4435. return index > 0 ? url.substr(0, index) : url;
  4436. }
  4437. function _loadStyle(url) {
  4438. var head = document.getElementsByTagName('head')[0] || (_QUIRKS ? document.body : document.documentElement),
  4439. link = document.createElement('link'),
  4440. absoluteUrl = _chopQuery(_formatUrl(url, 'absolute'));
  4441. var links = K('link[rel="stylesheet"]', head);
  4442. for (var i = 0, len = links.length; i < len; i++) {
  4443. if (_chopQuery(_formatUrl(links[i].href, 'absolute')) === absoluteUrl) {
  4444. return;
  4445. }
  4446. }
  4447. head.appendChild(link);
  4448. link.href = url;
  4449. link.rel = 'stylesheet';
  4450. }
  4451. function _ajax(url, fn, method, param, dataType) {
  4452. method = method || 'GET';
  4453. dataType = dataType || 'json';
  4454. var xhr = window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  4455. xhr.open(method, url, true);
  4456. xhr.onreadystatechange = function () {
  4457. if (xhr.readyState == 4 && xhr.status == 200) {
  4458. if (fn) {
  4459. var data = _trim(xhr.responseText);
  4460. if (dataType == 'json') {
  4461. data = _json(data);
  4462. }
  4463. fn(data);
  4464. }
  4465. }
  4466. };
  4467. if (method == 'POST') {
  4468. var params = [];
  4469. _each(param, function(key, val) {
  4470. params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
  4471. });
  4472. try {
  4473. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  4474. } catch (e) {}
  4475. xhr.send(params.join('&'));
  4476. } else {
  4477. xhr.send(null);
  4478. }
  4479. }
  4480. K.loadScript = _loadScript;
  4481. K.loadStyle = _loadStyle;
  4482. K.ajax = _ajax;
  4483. var _plugins = {};
  4484. function _plugin(name, fn) {
  4485. if (name === undefined) {
  4486. return _plugins;
  4487. }
  4488. if (!fn) {
  4489. return _plugins[name];
  4490. }
  4491. _plugins[name] = fn;
  4492. }
  4493. var _language = {};
  4494. function _parseLangKey(key) {
  4495. var match, ns = 'core';
  4496. if ((match = /^(\w+)\.(\w+)$/.exec(key))) {
  4497. ns = match[1];
  4498. key = match[2];
  4499. }
  4500. return { ns : ns, key : key };
  4501. }
  4502. function _lang(mixed, langType) {
  4503. langType = langType === undefined ? K.options.langType : langType;
  4504. if (typeof mixed === 'string') {
  4505. if (!_language[langType]) {
  4506. return 'no language';
  4507. }
  4508. var pos = mixed.length - 1;
  4509. if (mixed.substr(pos) === '.') {
  4510. return _language[langType][mixed.substr(0, pos)];
  4511. }
  4512. var obj = _parseLangKey(mixed);
  4513. return _language[langType][obj.ns][obj.key];
  4514. }
  4515. _each(mixed, function(key, val) {
  4516. var obj = _parseLangKey(key);
  4517. if (!_language[langType]) {
  4518. _language[langType] = {};
  4519. }
  4520. if (!_language[langType][obj.ns]) {
  4521. _language[langType][obj.ns] = {};
  4522. }
  4523. _language[langType][obj.ns][obj.key] = val;
  4524. });
  4525. }
  4526. function _getImageFromRange(range, fn) {
  4527. if (range.collapsed) {
  4528. return;
  4529. }
  4530. range = range.cloneRange().up();
  4531. var sc = range.startContainer, so = range.startOffset;
  4532. if (!_WEBKIT && !range.isControl()) {
  4533. return;
  4534. }
  4535. var img = K(sc.childNodes[so]);
  4536. if (!img || img.name != 'img') {
  4537. return;
  4538. }
  4539. if (fn(img)) {
  4540. return img;
  4541. }
  4542. }
  4543. function _bindContextmenuEvent() {
  4544. var self = this, doc = self.edit.doc;
  4545. K(doc).contextmenu(function(e) {
  4546. if (self.menu) {
  4547. self.hideMenu();
  4548. }
  4549. if (!self.useContextmenu) {
  4550. e.preventDefault();
  4551. return;
  4552. }
  4553. if (self._contextmenus.length === 0) {
  4554. return;
  4555. }
  4556. var maxWidth = 0, items = [];
  4557. _each(self._contextmenus, function() {
  4558. if (this.title == '-') {
  4559. items.push(this);
  4560. return;
  4561. }
  4562. if (this.cond && this.cond()) {
  4563. items.push(this);
  4564. if (this.width && this.width > maxWidth) {
  4565. maxWidth = this.width;
  4566. }
  4567. }
  4568. });
  4569. while (items.length > 0 && items[0].title == '-') {
  4570. items.shift();
  4571. }
  4572. while (items.length > 0 && items[items.length - 1].title == '-') {
  4573. items.pop();
  4574. }
  4575. var prevItem = null;
  4576. _each(items, function(i) {
  4577. if (this.title == '-' && prevItem.title == '-') {
  4578. delete items[i];
  4579. }
  4580. prevItem = this;
  4581. });
  4582. if (items.length > 0) {
  4583. e.preventDefault();
  4584. var pos = K(self.edit.iframe).pos(),
  4585. menu = _menu({
  4586. x : pos.x + e.clientX,
  4587. y : pos.y + e.clientY,
  4588. width : maxWidth,
  4589. css : { visibility: 'hidden' },
  4590. shadowMode : self.shadowMode
  4591. });
  4592. _each(items, function() {
  4593. if (this.title) {
  4594. menu.addItem(this);
  4595. }
  4596. });
  4597. var docEl = _docElement(menu.doc),
  4598. menuHeight = menu.div.height();
  4599. if (e.clientY + menuHeight >= docEl.clientHeight - 100) {
  4600. menu.pos(menu.x, _removeUnit(menu.y) - menuHeight);
  4601. }
  4602. menu.div.css('visibility', 'visible');
  4603. self.menu = menu;
  4604. }
  4605. });
  4606. }
  4607. function _bindNewlineEvent() {
  4608. var self = this, doc = self.edit.doc, newlineTag = self.newlineTag;
  4609. if (_IE && newlineTag !== 'br') {
  4610. return;
  4611. }
  4612. if (_GECKO && _V < 3 && newlineTag !== 'p') {
  4613. return;
  4614. }
  4615. if (_OPERA && _V < 9) {
  4616. return;
  4617. }
  4618. var brSkipTagMap = _toMap('h1,h2,h3,h4,h5,h6,pre,li'),
  4619. pSkipTagMap = _toMap('p,h1,h2,h3,h4,h5,h6,pre,li,blockquote');
  4620. function getAncestorTagName(range) {
  4621. var ancestor = K(range.commonAncestor());
  4622. while (ancestor) {
  4623. if (ancestor.type == 1 && !ancestor.isStyle()) {
  4624. break;
  4625. }
  4626. ancestor = ancestor.parent();
  4627. }
  4628. return ancestor.name;
  4629. }
  4630. K(doc).keydown(function(e) {
  4631. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4632. return;
  4633. }
  4634. self.cmd.selection();
  4635. var tagName = getAncestorTagName(self.cmd.range);
  4636. if (tagName == 'marquee' || tagName == 'select') {
  4637. return;
  4638. }
  4639. if (newlineTag === 'br' && !brSkipTagMap[tagName]) {
  4640. e.preventDefault();
  4641. self.insertHtml('<br />' + (_IE && _V < 9 ? '' : '\u200B'));
  4642. return;
  4643. }
  4644. if (!pSkipTagMap[tagName]) {
  4645. _nativeCommand(doc, 'formatblock', '<p>');
  4646. }
  4647. });
  4648. K(doc).keyup(function(e) {
  4649. if (e.which != 13 || e.shiftKey || e.ctrlKey || e.altKey) {
  4650. return;
  4651. }
  4652. if (newlineTag == 'br') {
  4653. return;
  4654. }
  4655. if (_GECKO) {
  4656. var root = self.cmd.commonAncestor('p');
  4657. var a = self.cmd.commonAncestor('a');
  4658. if (a && a.text() == '') {
  4659. a.remove(true);
  4660. self.cmd.range.selectNodeContents(root[0]).collapse(true);
  4661. self.cmd.select();
  4662. }
  4663. return;
  4664. }
  4665. self.cmd.selection();
  4666. var tagName = getAncestorTagName(self.cmd.range);
  4667. if (tagName == 'marquee' || tagName == 'select') {
  4668. return;
  4669. }
  4670. if (!pSkipTagMap[tagName]) {
  4671. _nativeCommand(doc, 'formatblock', '<p>');
  4672. }
  4673. var div = self.cmd.commonAncestor('div');
  4674. if (div) {
  4675. var p = K('<p></p>'),
  4676. child = div[0].firstChild;
  4677. while (child) {
  4678. var next = child.nextSibling;
  4679. p.append(child);
  4680. child = next;
  4681. }
  4682. div.before(p);
  4683. div.remove();
  4684. self.cmd.range.selectNodeContents(p[0]);
  4685. self.cmd.select();
  4686. }
  4687. });
  4688. }
  4689. function _bindTabEvent() {
  4690. var self = this, doc = self.edit.doc;
  4691. K(doc).keydown(function(e) {
  4692. if (e.which == 9) {
  4693. e.preventDefault();
  4694. if (self.afterTab) {
  4695. self.afterTab.call(self, e);
  4696. return;
  4697. }
  4698. var cmd = self.cmd, range = cmd.range;
  4699. range.shrink();
  4700. if (range.collapsed && range.startContainer.nodeType == 1) {
  4701. range.insertNode(K('@&nbsp;', doc)[0]);
  4702. cmd.select();
  4703. }
  4704. self.insertHtml('&nbsp;&nbsp;&nbsp;&nbsp;');
  4705. }
  4706. });
  4707. }
  4708. function _bindFocusEvent() {
  4709. var self = this;
  4710. K(self.edit.textarea[0], self.edit.win).focus(function(e) {
  4711. if (self.afterFocus) {
  4712. self.afterFocus.call(self, e);
  4713. }
  4714. }).blur(function(e) {
  4715. if (self.afterBlur) {
  4716. self.afterBlur.call(self, e);
  4717. }
  4718. });
  4719. }
  4720. function _removeBookmarkTag(html) {
  4721. return _trim(html.replace(/<span [^>]*id="?__kindeditor_bookmark_\w+_\d+__"?[^>]*><\/span>/ig, ''));
  4722. }
  4723. function _removeTempTag(html) {
  4724. return html.replace(/<div[^>]+class="?__kindeditor_paste__"?[^>]*>[\s\S]*?<\/div>/ig, '');
  4725. }
  4726. function _addBookmarkToStack(stack, bookmark) {
  4727. if (stack.length === 0) {
  4728. stack.push(bookmark);
  4729. return;
  4730. }
  4731. var prev = stack[stack.length - 1];
  4732. if (_removeBookmarkTag(bookmark.html) !== _removeBookmarkTag(prev.html)) {
  4733. stack.push(bookmark);
  4734. }
  4735. }
  4736. function _undoToRedo(fromStack, toStack) {
  4737. var self = this, edit = self.edit,
  4738. body = edit.doc.body,
  4739. range, bookmark;
  4740. if (fromStack.length === 0) {
  4741. return self;
  4742. }
  4743. if (edit.designMode) {
  4744. range = self.cmd.range;
  4745. bookmark = range.createBookmark(true);
  4746. bookmark.html = body.innerHTML;
  4747. } else {
  4748. bookmark = {
  4749. html : body.innerHTML
  4750. };
  4751. }
  4752. _addBookmarkToStack(toStack, bookmark);
  4753. var prev = fromStack.pop();
  4754. if (_removeBookmarkTag(bookmark.html) === _removeBookmarkTag(prev.html) && fromStack.length > 0) {
  4755. prev = fromStack.pop();
  4756. }
  4757. if (edit.designMode) {
  4758. edit.html(prev.html);
  4759. if (prev.start) {
  4760. range.moveToBookmark(prev);
  4761. self.select();
  4762. }
  4763. } else {
  4764. K(body).html(_removeBookmarkTag(prev.html));
  4765. }
  4766. return self;
  4767. }
  4768. function KEditor(options) {
  4769. var self = this;
  4770. self.options = {};
  4771. function setOption(key, val) {
  4772. if (KEditor.prototype[key] === undefined) {
  4773. self[key] = val;
  4774. }
  4775. self.options[key] = val;
  4776. }
  4777. _each(options, function(key, val) {
  4778. setOption(key, options[key]);
  4779. });
  4780. _each(K.options, function(key, val) {
  4781. if (self[key] === undefined) {
  4782. setOption(key, val);
  4783. }
  4784. });
  4785. var se = K(self.srcElement || '<textarea/>');
  4786. if (!self.width) {
  4787. self.width = se[0].style.width || se.width();
  4788. }
  4789. if (!self.height) {
  4790. self.height = se[0].style.height || se.height();
  4791. }
  4792. setOption('width', _undef(self.width, self.minWidth));
  4793. setOption('height', _undef(self.height, self.minHeight));
  4794. setOption('width', _addUnit(self.width));
  4795. setOption('height', _addUnit(self.height));
  4796. if (_MOBILE && (!_IOS || _V < 534)) {
  4797. self.designMode = false;
  4798. }
  4799. self.srcElement = se;
  4800. self.initContent = '';
  4801. self.plugin = {};
  4802. self.isCreated = false;
  4803. self._handlers = {};
  4804. self._contextmenus = [];
  4805. self._undoStack = [];
  4806. self._redoStack = [];
  4807. self._firstAddBookmark = true;
  4808. self.menu = self.contextmenu = null;
  4809. self.dialogs = [];
  4810. }
  4811. KEditor.prototype = {
  4812. lang : function(mixed) {
  4813. return _lang(mixed, this.langType);
  4814. },
  4815. loadPlugin : function(name, fn) {
  4816. var self = this;
  4817. if (_plugins[name]) {
  4818. if (!_isFunction(_plugins[name])) {
  4819. setTimeout(function() {
  4820. self.loadPlugin(name, fn);
  4821. }, 100);
  4822. return self;
  4823. }
  4824. _plugins[name].call(self, KindEditor);
  4825. if (fn) {
  4826. fn.call(self);
  4827. }
  4828. return self;
  4829. }
  4830. _plugins[name] = 'loading';
  4831. _loadScript(self.pluginsPath + name + '/' + name + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  4832. setTimeout(function() {
  4833. if (_plugins[name]) {
  4834. self.loadPlugin(name, fn);
  4835. }
  4836. }, 0);
  4837. });
  4838. return self;
  4839. },
  4840. handler : function(key, fn) {
  4841. var self = this;
  4842. if (!self._handlers[key]) {
  4843. self._handlers[key] = [];
  4844. }
  4845. if (_isFunction(fn)) {
  4846. self._handlers[key].push(fn);
  4847. return self;
  4848. }
  4849. _each(self._handlers[key], function() {
  4850. fn = this.call(self, fn);
  4851. });
  4852. return fn;
  4853. },
  4854. clickToolbar : function(name, fn) {
  4855. var self = this, key = 'clickToolbar' + name;
  4856. if (fn === undefined) {
  4857. if (self._handlers[key]) {
  4858. return self.handler(key);
  4859. }
  4860. self.loadPlugin(name, function() {
  4861. self.handler(key);
  4862. });
  4863. return self;
  4864. }
  4865. return self.handler(key, fn);
  4866. },
  4867. updateState : function() {
  4868. var self = this;
  4869. _each(('justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,insertunorderedlist,' +
  4870. 'subscript,superscript,bold,italic,underline,strikethrough').split(','), function(i, name) {
  4871. self.cmd.state(name) ? self.toolbar.select(name) : self.toolbar.unselect(name);
  4872. });
  4873. return self;
  4874. },
  4875. addContextmenu : function(item) {
  4876. this._contextmenus.push(item);
  4877. return this;
  4878. },
  4879. afterCreate : function(fn) {
  4880. return this.handler('afterCreate', fn);
  4881. },
  4882. beforeRemove : function(fn) {
  4883. return this.handler('beforeRemove', fn);
  4884. },
  4885. beforeGetHtml : function(fn) {
  4886. return this.handler('beforeGetHtml', fn);
  4887. },
  4888. beforeSetHtml : function(fn) {
  4889. return this.handler('beforeSetHtml', fn);
  4890. },
  4891. afterSetHtml : function(fn) {
  4892. return this.handler('afterSetHtml', fn);
  4893. },
  4894. create : function() {
  4895. var self = this, fullscreenMode = self.fullscreenMode;
  4896. if (self.isCreated) {
  4897. return self;
  4898. }
  4899. if (self.srcElement.data('kindeditor')) {
  4900. return self;
  4901. }
  4902. self.srcElement.data('kindeditor', 'true');
  4903. if (fullscreenMode) {
  4904. _docElement().style.overflow = 'hidden';
  4905. } else {
  4906. _docElement().style.overflow = '';
  4907. }
  4908. var width = fullscreenMode ? _docElement().clientWidth + 'px' : self.width,
  4909. height = fullscreenMode ? _docElement().clientHeight + 'px' : self.height;
  4910. if ((_IE && _V < 8) || _QUIRKS) {
  4911. height = _addUnit(_removeUnit(height) + 2);
  4912. }
  4913. var container = self.container = K(self.layout);
  4914. if (fullscreenMode) {
  4915. K(document.body).append(container);
  4916. } else {
  4917. self.srcElement.before(container);
  4918. }
  4919. var toolbarDiv = K('.toolbar', container),
  4920. editDiv = K('.edit', container),
  4921. statusbar = self.statusbar = K('.statusbar', container);
  4922. container.removeClass('container')
  4923. .addClass('ke-container ke-container-' + self.themeType).css('width', width);
  4924. if (fullscreenMode) {
  4925. container.css({
  4926. position : 'absolute',
  4927. left : 0,
  4928. top : 0,
  4929. 'z-index' : 811211
  4930. });
  4931. if (!_GECKO) {
  4932. self._scrollPos = _getScrollPos();
  4933. }
  4934. window.scrollTo(0, 0);
  4935. K(document.body).css({
  4936. 'height' : '1px',
  4937. 'overflow' : 'hidden'
  4938. });
  4939. K(document.body.parentNode).css('overflow', 'hidden');
  4940. self._fullscreenExecuted = true;
  4941. } else {
  4942. if (self._fullscreenExecuted) {
  4943. K(document.body).css({
  4944. 'height' : '',
  4945. 'overflow' : ''
  4946. });
  4947. K(document.body.parentNode).css('overflow', '');
  4948. }
  4949. if (self._scrollPos) {
  4950. window.scrollTo(self._scrollPos.x, self._scrollPos.y);
  4951. }
  4952. }
  4953. var htmlList = [];
  4954. K.each(self.items, function(i, name) {
  4955. if (name == '|') {
  4956. htmlList.push('<span class="ke-inline-block ke-separator"></span>');
  4957. } else if (name == '/') {
  4958. htmlList.push('<div class="ke-hr"></div>');
  4959. } else {
  4960. htmlList.push('<span class="ke-outline" data-name="' + name + '" title="' + self.lang(name) + '" unselectable="on">');
  4961. htmlList.push('<span class="ke-toolbar-icon ke-toolbar-icon-url ke-icon-' + name + '" unselectable="on"></span></span>');
  4962. }
  4963. });
  4964. var toolbar = self.toolbar = _toolbar({
  4965. src : toolbarDiv,
  4966. html : htmlList.join(''),
  4967. noDisableItems : self.noDisableItems,
  4968. click : function(e, name) {
  4969. e.stop();
  4970. if (self.menu) {
  4971. var menuName = self.menu.name;
  4972. self.hideMenu();
  4973. if (menuName === name) {
  4974. return;
  4975. }
  4976. }
  4977. self.clickToolbar(name);
  4978. }
  4979. });
  4980. var editHeight = _removeUnit(height) - toolbar.div.height();
  4981. var edit = self.edit = _edit({
  4982. height : editHeight > 0 && _removeUnit(height) > self.minHeight ? editHeight : self.minHeight,
  4983. src : editDiv,
  4984. srcElement : self.srcElement,
  4985. designMode : self.designMode,
  4986. themesPath : self.themesPath,
  4987. bodyClass : self.bodyClass,
  4988. cssPath : self.cssPath,
  4989. cssData : self.cssData,
  4990. beforeGetHtml : function(html) {
  4991. html = self.beforeGetHtml(html);
  4992. html = _removeBookmarkTag(_removeTempTag(html));
  4993. return _formatHtml(html, self.filterMode ? self.htmlTags : null, self.urlType, self.wellFormatMode, self.indentChar);
  4994. },
  4995. beforeSetHtml : function(html) {
  4996. html = _formatHtml(html, self.filterMode ? self.htmlTags : null, '', false);
  4997. return self.beforeSetHtml(html);
  4998. },
  4999. afterSetHtml : function() {
  5000. self.edit = edit = this;
  5001. self.afterSetHtml();
  5002. },
  5003. afterCreate : function() {
  5004. self.edit = edit = this;
  5005. self.cmd = edit.cmd;
  5006. self._docMousedownFn = function(e) {
  5007. if (self.menu) {
  5008. self.hideMenu();
  5009. }
  5010. };
  5011. K(edit.doc, document).mousedown(self._docMousedownFn);
  5012. _bindContextmenuEvent.call(self);
  5013. _bindNewlineEvent.call(self);
  5014. _bindTabEvent.call(self);
  5015. _bindFocusEvent.call(self);
  5016. edit.afterChange(function(e) {
  5017. if (!edit.designMode) {
  5018. return;
  5019. }
  5020. self.updateState();
  5021. self.addBookmark();
  5022. if (self.options.afterChange) {
  5023. self.options.afterChange.call(self);
  5024. }
  5025. });
  5026. edit.textarea.keyup(function(e) {
  5027. if (!e.ctrlKey && !e.altKey && _INPUT_KEY_MAP[e.which]) {
  5028. if (self.options.afterChange) {
  5029. self.options.afterChange.call(self);
  5030. }
  5031. }
  5032. });
  5033. if (self.readonlyMode) {
  5034. self.readonly();
  5035. }
  5036. self.isCreated = true;
  5037. if (self.initContent === '') {
  5038. self.initContent = self.html();
  5039. }
  5040. if (self._undoStack.length > 0) {
  5041. var prev = self._undoStack.pop();
  5042. if (prev.start) {
  5043. self.html(prev.html);
  5044. edit.cmd.range.moveToBookmark(prev);
  5045. self.select();
  5046. }
  5047. }
  5048. self.afterCreate();
  5049. if (self.options.afterCreate) {
  5050. self.options.afterCreate.call(self);
  5051. }
  5052. }
  5053. });
  5054. statusbar.removeClass('statusbar').addClass('ke-statusbar')
  5055. .append('<span class="ke-inline-block ke-statusbar-center-icon"></span>')
  5056. .append('<span class="ke-inline-block ke-statusbar-right-icon"></span>');
  5057. if (self._fullscreenResizeHandler) {
  5058. K(window).unbind('resize', self._fullscreenResizeHandler);
  5059. self._fullscreenResizeHandler = null;
  5060. }
  5061. function initResize() {
  5062. if (statusbar.height() === 0) {
  5063. setTimeout(initResize, 100);
  5064. return;
  5065. }
  5066. self.resize(width, height, false);
  5067. }
  5068. initResize();
  5069. if (fullscreenMode) {
  5070. self._fullscreenResizeHandler = function(e) {
  5071. if (self.isCreated) {
  5072. self.resize(_docElement().clientWidth, _docElement().clientHeight, false);
  5073. }
  5074. };
  5075. K(window).bind('resize', self._fullscreenResizeHandler);
  5076. toolbar.select('fullscreen');
  5077. statusbar.first().css('visibility', 'hidden');
  5078. statusbar.last().css('visibility', 'hidden');
  5079. } else {
  5080. if (_GECKO) {
  5081. K(window).bind('scroll', function(e) {
  5082. self._scrollPos = _getScrollPos();
  5083. });
  5084. }
  5085. if (self.resizeType > 0) {
  5086. _drag({
  5087. moveEl : container,
  5088. clickEl : statusbar,
  5089. moveFn : function(x, y, width, height, diffX, diffY) {
  5090. height += diffY;
  5091. self.resize(null, height);
  5092. }
  5093. });
  5094. } else {
  5095. statusbar.first().css('visibility', 'hidden');
  5096. }
  5097. if (self.resizeType === 2) {
  5098. _drag({
  5099. moveEl : container,
  5100. clickEl : statusbar.last(),
  5101. moveFn : function(x, y, width, height, diffX, diffY) {
  5102. width += diffX;
  5103. height += diffY;
  5104. self.resize(width, height);
  5105. }
  5106. });
  5107. } else {
  5108. statusbar.last().css('visibility', 'hidden');
  5109. }
  5110. }
  5111. return self;
  5112. },
  5113. remove : function() {
  5114. var self = this;
  5115. if (!self.isCreated) {
  5116. return self;
  5117. }
  5118. self.beforeRemove();
  5119. self.srcElement.data('kindeditor', '');
  5120. if (self.menu) {
  5121. self.hideMenu();
  5122. }
  5123. _each(self.dialogs, function() {
  5124. self.hideDialog();
  5125. });
  5126. K(document).unbind('mousedown', self._docMousedownFn);
  5127. self.toolbar.remove();
  5128. self.edit.remove();
  5129. self.statusbar.last().unbind();
  5130. self.statusbar.unbind();
  5131. self.container.remove();
  5132. self.container = self.toolbar = self.edit = self.menu = null;
  5133. self.dialogs = [];
  5134. self.isCreated = false;
  5135. return self;
  5136. },
  5137. resize : function(width, height, updateProp) {
  5138. var self = this;
  5139. updateProp = _undef(updateProp, true);
  5140. if (width) {
  5141. if (!/%/.test(width)) {
  5142. width = _removeUnit(width);
  5143. width = width < self.minWidth ? self.minWidth : width;
  5144. }
  5145. self.container.css('width', _addUnit(width));
  5146. if (updateProp) {
  5147. self.width = _addUnit(width);
  5148. }
  5149. }
  5150. if (height) {
  5151. height = _removeUnit(height);
  5152. editHeight = _removeUnit(height) - self.toolbar.div.height() - self.statusbar.height();
  5153. editHeight = editHeight < self.minHeight ? self.minHeight : editHeight;
  5154. self.edit.setHeight(editHeight);
  5155. if (updateProp) {
  5156. self.height = _addUnit(height);
  5157. }
  5158. }
  5159. return self;
  5160. },
  5161. select : function() {
  5162. this.isCreated && this.cmd.select();
  5163. return this;
  5164. },
  5165. html : function(val) {
  5166. var self = this;
  5167. if (val === undefined) {
  5168. return self.isCreated ? self.edit.html() : _elementVal(self.srcElement);
  5169. }
  5170. self.isCreated ? self.edit.html(val) : _elementVal(self.srcElement, val);
  5171. if (self.isCreated) {
  5172. self.cmd.selection();
  5173. }
  5174. return self;
  5175. },
  5176. fullHtml : function() {
  5177. return this.isCreated ? this.edit.html(undefined, true) : '';
  5178. },
  5179. text : function(val) {
  5180. var self = this;
  5181. if (val === undefined) {
  5182. return _trim(self.html().replace(/<(?!img|embed).*?>/ig, '').replace(/&nbsp;/ig, ' '));
  5183. } else {
  5184. return self.html(_escape(val));
  5185. }
  5186. },
  5187. isEmpty : function() {
  5188. return _trim(this.text().replace(/\r\n|\n|\r/, '')) === '';
  5189. },
  5190. isDirty : function() {
  5191. return _trim(this.initContent.replace(/\r\n|\n|\r|t/g, '')) !== _trim(this.html().replace(/\r\n|\n|\r|t/g, ''));
  5192. },
  5193. selectedHtml : function() {
  5194. var val = this.isCreated ? this.cmd.range.html() : '';
  5195. val = _removeBookmarkTag(_removeTempTag(val));
  5196. return val;
  5197. },
  5198. count : function(mode) {
  5199. var self = this;
  5200. mode = (mode || 'html').toLowerCase();
  5201. if (mode === 'html') {
  5202. return self.html().length;
  5203. }
  5204. if (mode === 'text') {
  5205. return self.text().replace(/<(?:img|embed).*?>/ig, 'K').replace(/\r\n|\n|\r/g, '').length;
  5206. }
  5207. return 0;
  5208. },
  5209. exec : function(key) {
  5210. key = key.toLowerCase();
  5211. var self = this, cmd = self.cmd,
  5212. changeFlag = _inArray(key, 'selectall,copy,paste,print'.split(',')) < 0;
  5213. if (changeFlag) {
  5214. self.addBookmark(false);
  5215. }
  5216. cmd[key].apply(cmd, _toArray(arguments, 1));
  5217. if (changeFlag) {
  5218. self.updateState();
  5219. self.addBookmark(false);
  5220. if (self.options.afterChange) {
  5221. self.options.afterChange.call(self);
  5222. }
  5223. }
  5224. return self;
  5225. },
  5226. insertHtml : function(val, quickMode) {
  5227. if (!this.isCreated) {
  5228. return this;
  5229. }
  5230. val = this.beforeSetHtml(val);
  5231. this.exec('inserthtml', val, quickMode);
  5232. return this;
  5233. },
  5234. appendHtml : function(val) {
  5235. this.html(this.html() + val);
  5236. if (this.isCreated) {
  5237. var cmd = this.cmd;
  5238. cmd.range.selectNodeContents(cmd.doc.body).collapse(false);
  5239. cmd.select();
  5240. }
  5241. return this;
  5242. },
  5243. sync : function() {
  5244. _elementVal(this.srcElement, this.html());
  5245. return this;
  5246. },
  5247. focus : function() {
  5248. this.isCreated ? this.edit.focus() : this.srcElement[0].focus();
  5249. return this;
  5250. },
  5251. blur : function() {
  5252. this.isCreated ? this.edit.blur() : this.srcElement[0].blur();
  5253. return this;
  5254. },
  5255. addBookmark : function(checkSize) {
  5256. checkSize = _undef(checkSize, true);
  5257. var self = this, edit = self.edit,
  5258. body = edit.doc.body,
  5259. html = _removeTempTag(body.innerHTML), bookmark;
  5260. if (checkSize && self._undoStack.length > 0) {
  5261. var prev = self._undoStack[self._undoStack.length - 1];
  5262. if (Math.abs(html.length - _removeBookmarkTag(prev.html).length) < self.minChangeSize) {
  5263. return self;
  5264. }
  5265. }
  5266. if (edit.designMode && !self._firstAddBookmark) {
  5267. var range = self.cmd.range;
  5268. bookmark = range.createBookmark(true);
  5269. bookmark.html = _removeTempTag(body.innerHTML);
  5270. range.moveToBookmark(bookmark);
  5271. } else {
  5272. bookmark = {
  5273. html : html
  5274. };
  5275. }
  5276. self._firstAddBookmark = false;
  5277. _addBookmarkToStack(self._undoStack, bookmark);
  5278. return self;
  5279. },
  5280. undo : function() {
  5281. return _undoToRedo.call(this, this._undoStack, this._redoStack);
  5282. },
  5283. redo : function() {
  5284. return _undoToRedo.call(this, this._redoStack, this._undoStack);
  5285. },
  5286. fullscreen : function(bool) {
  5287. this.fullscreenMode = (bool === undefined ? !this.fullscreenMode : bool);
  5288. this.addBookmark(false);
  5289. return this.remove().create();
  5290. },
  5291. readonly : function(isReadonly) {
  5292. isReadonly = _undef(isReadonly, true);
  5293. var self = this, edit = self.edit, doc = edit.doc;
  5294. if (self.designMode) {
  5295. self.toolbar.disableAll(isReadonly, []);
  5296. } else {
  5297. _each(self.noDisableItems, function() {
  5298. self.toolbar[isReadonly ? 'disable' : 'enable'](this);
  5299. });
  5300. }
  5301. if (_IE) {
  5302. doc.body.contentEditable = !isReadonly;
  5303. } else {
  5304. doc.designMode = isReadonly ? 'off' : 'on';
  5305. }
  5306. edit.textarea[0].disabled = isReadonly;
  5307. },
  5308. createMenu : function(options) {
  5309. var self = this,
  5310. name = options.name,
  5311. knode = self.toolbar.get(name),
  5312. pos = knode.pos();
  5313. options.x = pos.x;
  5314. options.y = pos.y + knode.height();
  5315. options.z = self.options.zIndex;
  5316. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5317. if (options.selectedColor !== undefined) {
  5318. options.cls = 'ke-colorpicker-' + self.themeType;
  5319. options.noColor = self.lang('noColor');
  5320. self.menu = _colorpicker(options);
  5321. } else {
  5322. options.cls = 'ke-menu-' + self.themeType;
  5323. options.centerLineMode = false;
  5324. self.menu = _menu(options);
  5325. }
  5326. return self.menu;
  5327. },
  5328. hideMenu : function() {
  5329. this.menu.remove();
  5330. this.menu = null;
  5331. return this;
  5332. },
  5333. hideContextmenu : function() {
  5334. this.contextmenu.remove();
  5335. this.contextmenu = null;
  5336. return this;
  5337. },
  5338. createDialog : function(options) {
  5339. var self = this, name = options.name;
  5340. options.z = self.options.zIndex;
  5341. options.shadowMode = _undef(options.shadowMode, self.shadowMode);
  5342. options.closeBtn = _undef(options.closeBtn, {
  5343. name : self.lang('close'),
  5344. click : function(e) {
  5345. self.hideDialog();
  5346. if (_IE && self.cmd) {
  5347. self.cmd.select();
  5348. }
  5349. }
  5350. });
  5351. options.noBtn = _undef(options.noBtn, {
  5352. name : self.lang(options.yesBtn ? 'no' : 'close'),
  5353. click : function(e) {
  5354. self.hideDialog();
  5355. if (_IE && self.cmd) {
  5356. self.cmd.select();
  5357. }
  5358. }
  5359. });
  5360. if (self.dialogAlignType != 'page') {
  5361. options.alignEl = self.container;
  5362. }
  5363. options.cls = 'ke-dialog-' + self.themeType;
  5364. if (self.dialogs.length > 0) {
  5365. var firstDialog = self.dialogs[0],
  5366. parentDialog = self.dialogs[self.dialogs.length - 1];
  5367. firstDialog.setMaskIndex(parentDialog.z + 2);
  5368. options.z = parentDialog.z + 3;
  5369. options.showMask = false;
  5370. }
  5371. var dialog = _dialog(options);
  5372. self.dialogs.push(dialog);
  5373. return dialog;
  5374. },
  5375. hideDialog : function() {
  5376. var self = this;
  5377. if (self.dialogs.length > 0) {
  5378. self.dialogs.pop().remove();
  5379. }
  5380. if (self.dialogs.length > 0) {
  5381. var firstDialog = self.dialogs[0],
  5382. parentDialog = self.dialogs[self.dialogs.length - 1];
  5383. firstDialog.setMaskIndex(parentDialog.z - 1);
  5384. }
  5385. return self;
  5386. },
  5387. errorDialog : function(html) {
  5388. var self = this;
  5389. var dialog = self.createDialog({
  5390. width : 750,
  5391. title : self.lang('uploadError'),
  5392. body : '<div style="padding:10px 20px;"><iframe frameborder="0" style="width:708px;height:400px;"></iframe></div>'
  5393. });
  5394. var iframe = K('iframe', dialog.div), doc = K.iframeDoc(iframe);
  5395. doc.open();
  5396. doc.write(html);
  5397. doc.close();
  5398. K(doc.body).css('background-color', '#FFF');
  5399. iframe[0].contentWindow.focus();
  5400. return self;
  5401. }
  5402. };
  5403. function _editor(options) {
  5404. return new KEditor(options);
  5405. }
  5406. _instances = [];
  5407. function _create(expr, options) {
  5408. options = options || {};
  5409. options.basePath = _undef(options.basePath, K.basePath);
  5410. options.themesPath = _undef(options.themesPath, options.basePath + 'themes/');
  5411. options.langPath = _undef(options.langPath, options.basePath + 'lang/');
  5412. options.pluginsPath = _undef(options.pluginsPath, options.basePath + 'plugins/');
  5413. if (_undef(options.loadStyleMode, K.options.loadStyleMode)) {
  5414. var themeType = _undef(options.themeType, K.options.themeType);
  5415. _loadStyle(options.themesPath + 'default/default.css');
  5416. _loadStyle(options.themesPath + themeType + '/' + themeType + '.css');
  5417. }
  5418. function create(editor) {
  5419. _each(_plugins, function(name, fn) {
  5420. if (_isFunction(fn)) {
  5421. fn.call(editor, KindEditor);
  5422. }
  5423. });
  5424. return editor.create();
  5425. }
  5426. var knode = K(expr);
  5427. if (!knode || knode.length === 0) {
  5428. return;
  5429. }
  5430. if (knode.length > 1) {
  5431. knode.each(function() {
  5432. _create(this, options);
  5433. });
  5434. return _instances[0];
  5435. }
  5436. options.srcElement = knode[0];
  5437. var editor = new KEditor(options);
  5438. _instances.push(editor);
  5439. if (_language[editor.langType]) {
  5440. return create(editor);
  5441. }
  5442. _loadScript(editor.langPath + editor.langType + '.js?ver=' + encodeURIComponent(K.DEBUG ? _TIME : _VERSION), function() {
  5443. create(editor);
  5444. });
  5445. return editor;
  5446. }
  5447. function _eachEditor(expr, fn) {
  5448. K(expr).each(function(i, el) {
  5449. K.each(_instances, function(j, editor) {
  5450. if (editor && editor.srcElement[0] == el) {
  5451. fn.call(editor, j);
  5452. return false;
  5453. }
  5454. });
  5455. });
  5456. }
  5457. K.remove = function(expr) {
  5458. _eachEditor(expr, function(i) {
  5459. this.remove();
  5460. _instances.splice(i, 1);
  5461. });
  5462. };
  5463. K.sync = function(expr) {
  5464. _eachEditor(expr, function() {
  5465. this.sync();
  5466. });
  5467. };
  5468. K.html = function(expr, val) {
  5469. _eachEditor(expr, function() {
  5470. this.html(val);
  5471. });
  5472. };
  5473. K.insertHtml = function(expr, val) {
  5474. _eachEditor(expr, function() {
  5475. this.insertHtml(val);
  5476. });
  5477. };
  5478. K.appendHtml = function(expr, val) {
  5479. _eachEditor(expr, function() {
  5480. this.appendHtml(val);
  5481. });
  5482. };
  5483. if (_IE && _V < 7) {
  5484. _nativeCommand(document, 'BackgroundImageCache', true);
  5485. }
  5486. K.EditorClass = KEditor;
  5487. K.editor = _editor;
  5488. K.create = _create;
  5489. K.instances = _instances;
  5490. K.plugin = _plugin;
  5491. K.lang = _lang;
  5492. _plugin('core', function(K) {
  5493. var self = this,
  5494. shortcutKeys = {
  5495. undo : 'Z', redo : 'Y', bold : 'B', italic : 'I', underline : 'U', print : 'P', selectall : 'A'
  5496. };
  5497. self.afterSetHtml(function() {
  5498. if (self.options.afterChange) {
  5499. self.options.afterChange.call(self);
  5500. }
  5501. });
  5502. self.afterCreate(function() {
  5503. if (self.syncType != 'form') {
  5504. return;
  5505. }
  5506. var el = K(self.srcElement), hasForm = false;
  5507. while ((el = el.parent())) {
  5508. if (el.name == 'form') {
  5509. hasForm = true;
  5510. break;
  5511. }
  5512. }
  5513. if (hasForm) {
  5514. el.bind('submit', function(e) {
  5515. self.sync();
  5516. K(window).bind('unload', function() {
  5517. self.edit.textarea.remove();
  5518. });
  5519. });
  5520. var resetBtn = K('[type="reset"]', el);
  5521. resetBtn.click(function() {
  5522. self.html(self.initContent);
  5523. self.cmd.selection();
  5524. });
  5525. self.beforeRemove(function() {
  5526. el.unbind();
  5527. resetBtn.unbind();
  5528. });
  5529. }
  5530. });
  5531. self.clickToolbar('source', function() {
  5532. if (self.edit.designMode) {
  5533. self.toolbar.disableAll(true);
  5534. self.edit.design(false);
  5535. self.toolbar.select('source');
  5536. } else {
  5537. self.toolbar.disableAll(false);
  5538. self.edit.design(true);
  5539. self.toolbar.unselect('source');
  5540. if (_GECKO) {
  5541. setTimeout(function() {
  5542. self.cmd.selection();
  5543. }, 0);
  5544. } else {
  5545. self.cmd.selection();
  5546. }
  5547. }
  5548. self.designMode = self.edit.designMode;
  5549. });
  5550. self.afterCreate(function() {
  5551. if (!self.designMode) {
  5552. self.toolbar.disableAll(true).select('source');
  5553. }
  5554. });
  5555. self.clickToolbar('fullscreen', function() {
  5556. self.fullscreen();
  5557. });
  5558. if (self.fullscreenShortcut) {
  5559. var loaded = false;
  5560. self.afterCreate(function() {
  5561. K(self.edit.doc, self.edit.textarea).keyup(function(e) {
  5562. if (e.which == 27) {
  5563. setTimeout(function() {
  5564. self.fullscreen();
  5565. }, 0);
  5566. }
  5567. });
  5568. if (loaded) {
  5569. if (_IE && !self.designMode) {
  5570. return;
  5571. }
  5572. self.focus();
  5573. }
  5574. if (!loaded) {
  5575. loaded = true;
  5576. }
  5577. });
  5578. }
  5579. _each('undo,redo'.split(','), function(i, name) {
  5580. if (shortcutKeys[name]) {
  5581. self.afterCreate(function() {
  5582. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  5583. self.clickToolbar(name);
  5584. });
  5585. });
  5586. }
  5587. self.clickToolbar(name, function() {
  5588. self[name]();
  5589. });
  5590. });
  5591. self.clickToolbar('formatblock', function() {
  5592. var blocks = self.lang('formatblock.formatBlock'),
  5593. heights = {
  5594. h1 : 28,
  5595. h2 : 24,
  5596. h3 : 18,
  5597. H4 : 14,
  5598. p : 12
  5599. },
  5600. curVal = self.cmd.val('formatblock'),
  5601. menu = self.createMenu({
  5602. name : 'formatblock',
  5603. width : self.langType == 'en' ? 200 : 150
  5604. });
  5605. _each(blocks, function(key, val) {
  5606. var style = 'font-size:' + heights[key] + 'px;';
  5607. if (key.charAt(0) === 'h') {
  5608. style += 'font-weight:bold;';
  5609. }
  5610. menu.addItem({
  5611. title : '<span style="' + style + '" unselectable="on">' + val + '</span>',
  5612. height : heights[key] + 12,
  5613. checked : (curVal === key || curVal === val),
  5614. click : function() {
  5615. self.select().exec('formatblock', '<' + key + '>').hideMenu();
  5616. }
  5617. });
  5618. });
  5619. });
  5620. self.clickToolbar('fontname', function() {
  5621. var curVal = self.cmd.val('fontname'),
  5622. menu = self.createMenu({
  5623. name : 'fontname',
  5624. width : 150
  5625. });
  5626. _each(self.lang('fontname.fontName'), function(key, val) {
  5627. menu.addItem({
  5628. title : '<span style="font-family: ' + key + ';" unselectable="on">' + val + '</span>',
  5629. checked : (curVal === key.toLowerCase() || curVal === val.toLowerCase()),
  5630. click : function() {
  5631. self.exec('fontname', key).hideMenu();
  5632. }
  5633. });
  5634. });
  5635. });
  5636. self.clickToolbar('fontsize', function() {
  5637. var curVal = self.cmd.val('fontsize'),
  5638. menu = self.createMenu({
  5639. name : 'fontsize',
  5640. width : 150
  5641. });
  5642. _each(self.fontSizeTable, function(i, val) {
  5643. menu.addItem({
  5644. title : '<span style="font-size:' + val + ';" unselectable="on">' + val + '</span>',
  5645. height : _removeUnit(val) + 12,
  5646. checked : curVal === val,
  5647. click : function() {
  5648. self.exec('fontsize', val).hideMenu();
  5649. }
  5650. });
  5651. });
  5652. });
  5653. _each('forecolor,hilitecolor'.split(','), function(i, name) {
  5654. self.clickToolbar(name, function() {
  5655. self.createMenu({
  5656. name : name,
  5657. selectedColor : self.cmd.val(name) || 'default',
  5658. colors : self.colorTable,
  5659. click : function(color) {
  5660. self.exec(name, color).hideMenu();
  5661. }
  5662. });
  5663. });
  5664. });
  5665. _each(('cut,copy,paste').split(','), function(i, name) {
  5666. self.clickToolbar(name, function() {
  5667. self.focus();
  5668. try {
  5669. self.exec(name, null);
  5670. } catch(e) {
  5671. alert(self.lang(name + 'Error'));
  5672. }
  5673. });
  5674. });
  5675. self.clickToolbar('about', function() {
  5676. var html = '<div style="margin:20px;">' +
  5677. '<div>KindEditor ' + _VERSION + '</div>' +
  5678. '<div>Copyright &copy; <a href="http://www.kindsoft.net/" target="_blank">kindsoft.net</a> All rights reserved.</div>' +
  5679. '</div>';
  5680. self.createDialog({
  5681. name : 'about',
  5682. width : 350,
  5683. title : self.lang('about'),
  5684. body : html
  5685. });
  5686. });
  5687. self.plugin.getSelectedLink = function() {
  5688. return self.cmd.commonAncestor('a');
  5689. };
  5690. self.plugin.getSelectedImage = function() {
  5691. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5692. return !/^ke-\w+$/i.test(img[0].className);
  5693. });
  5694. };
  5695. self.plugin.getSelectedFlash = function() {
  5696. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5697. return img[0].className == 'ke-flash';
  5698. });
  5699. };
  5700. self.plugin.getSelectedMedia = function() {
  5701. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5702. return img[0].className == 'ke-media' || img[0].className == 'ke-rm';
  5703. });
  5704. };
  5705. self.plugin.getSelectedAnchor = function() {
  5706. return _getImageFromRange(self.edit.cmd.range, function(img) {
  5707. return img[0].className == 'ke-anchor';
  5708. });
  5709. };
  5710. _each('link,image,flash,media,anchor'.split(','), function(i, name) {
  5711. var uName = name.charAt(0).toUpperCase() + name.substr(1);
  5712. _each('edit,delete'.split(','), function(j, val) {
  5713. self.addContextmenu({
  5714. title : self.lang(val + uName),
  5715. click : function() {
  5716. self.loadPlugin(name, function() {
  5717. self.plugin[name][val]();
  5718. self.hideMenu();
  5719. });
  5720. },
  5721. cond : self.plugin['getSelected' + uName],
  5722. width : 150,
  5723. iconClass : val == 'edit' ? 'ke-icon-' + name : undefined
  5724. });
  5725. });
  5726. self.addContextmenu({ title : '-' });
  5727. });
  5728. self.plugin.getSelectedTable = function() {
  5729. return self.cmd.commonAncestor('table');
  5730. };
  5731. self.plugin.getSelectedRow = function() {
  5732. return self.cmd.commonAncestor('tr');
  5733. };
  5734. self.plugin.getSelectedCell = function() {
  5735. return self.cmd.commonAncestor('td');
  5736. };
  5737. _each(('prop,cellprop,colinsertleft,colinsertright,rowinsertabove,rowinsertbelow,rowmerge,colmerge,' +
  5738. 'rowsplit,colsplit,coldelete,rowdelete,insert,delete').split(','), function(i, val) {
  5739. var cond = _inArray(val, ['prop', 'delete']) < 0 ? self.plugin.getSelectedCell : self.plugin.getSelectedTable;
  5740. self.addContextmenu({
  5741. title : self.lang('table' + val),
  5742. click : function() {
  5743. self.loadPlugin('table', function() {
  5744. self.plugin.table[val]();
  5745. self.hideMenu();
  5746. });
  5747. },
  5748. cond : cond,
  5749. width : 170,
  5750. iconClass : 'ke-icon-table' + val
  5751. });
  5752. });
  5753. self.addContextmenu({ title : '-' });
  5754. _each(('selectall,justifyleft,justifycenter,justifyright,justifyfull,insertorderedlist,' +
  5755. 'insertunorderedlist,indent,outdent,subscript,superscript,hr,print,' +
  5756. 'bold,italic,underline,strikethrough,removeformat,unlink').split(','), function(i, name) {
  5757. if (shortcutKeys[name]) {
  5758. self.afterCreate(function() {
  5759. _ctrl(this.edit.doc, shortcutKeys[name], function() {
  5760. self.cmd.selection();
  5761. self.clickToolbar(name);
  5762. });
  5763. });
  5764. }
  5765. self.clickToolbar(name, function() {
  5766. self.focus().exec(name, null);
  5767. });
  5768. });
  5769. self.afterCreate(function() {
  5770. var doc = self.edit.doc, cmd, bookmark, div,
  5771. cls = '__kindeditor_paste__', pasting = false;
  5772. function movePastedData() {
  5773. cmd.range.moveToBookmark(bookmark);
  5774. cmd.select();
  5775. if (_WEBKIT) {
  5776. K('div.' + cls, div).each(function() {
  5777. K(this).after('<br />').remove(true);
  5778. });
  5779. K('span.Apple-style-span', div).remove(true);
  5780. K('span.Apple-tab-span', div).remove(true);
  5781. K('span[style]', div).each(function() {
  5782. if (K(this).css('white-space') == 'nowrap') {
  5783. K(this).remove(true);
  5784. }
  5785. });
  5786. K('meta', div).remove();
  5787. }
  5788. var html = div[0].innerHTML;
  5789. div.remove();
  5790. if (html === '') {
  5791. return;
  5792. }
  5793. if (_WEBKIT) {
  5794. html = html.replace(/(<br>)\1/ig, '$1');
  5795. }
  5796. if (self.pasteType === 2) {
  5797. html = html.replace(/(<(?:p|p\s[^>]*)>) *(<\/p>)/ig, '');
  5798. if (/schemas-microsoft-com|worddocument|mso-\w+/i.test(html)) {
  5799. html = _clearMsWord(html, self.filterMode ? self.htmlTags : K.options.htmlTags);
  5800. } else {
  5801. html = _formatHtml(html, self.filterMode ? self.htmlTags : null);
  5802. html = self.beforeSetHtml(html);
  5803. }
  5804. }
  5805. if (self.pasteType === 1) {
  5806. html = html.replace(/&nbsp;/ig, ' ');
  5807. html = html.replace(/\n\s*\n/g, '\n');
  5808. html = html.replace(/<br[^>]*>/ig, '\n');
  5809. html = html.replace(/<\/p><p[^>]*>/ig, '\n');
  5810. html = html.replace(/<[^>]+>/g, '');
  5811. html = html.replace(/ {2}/g, ' &nbsp;');
  5812. if (self.newlineTag == 'p') {
  5813. if (/\n/.test(html)) {
  5814. html = html.replace(/^/, '<p>').replace(/$/, '<br /></p>').replace(/\n/g, '<br /></p><p>');
  5815. }
  5816. } else {
  5817. html = html.replace(/\n/g, '<br />$&');
  5818. }
  5819. }
  5820. self.insertHtml(html, true);
  5821. }
  5822. K(doc.body).bind('paste', function(e){
  5823. if (self.pasteType === 0) {
  5824. e.stop();
  5825. return;
  5826. }
  5827. if (pasting) {
  5828. return;
  5829. }
  5830. pasting = true;
  5831. K('div.' + cls, doc).remove();
  5832. cmd = self.cmd.selection();
  5833. bookmark = cmd.range.createBookmark();
  5834. div = K('<div class="' + cls + '"></div>', doc).css({
  5835. position : 'absolute',
  5836. width : '1px',
  5837. height : '1px',
  5838. overflow : 'hidden',
  5839. left : '-1981px',
  5840. top : K(bookmark.start).pos().y + 'px',
  5841. 'white-space' : 'nowrap'
  5842. });
  5843. K(doc.body).append(div);
  5844. if (_IE) {
  5845. var rng = cmd.range.get(true);
  5846. rng.moveToElementText(div[0]);
  5847. rng.select();
  5848. rng.execCommand('paste');
  5849. e.preventDefault();
  5850. } else {
  5851. cmd.range.selectNodeContents(div[0]);
  5852. cmd.select();
  5853. }
  5854. setTimeout(function() {
  5855. movePastedData();
  5856. pasting = false;
  5857. }, 0);
  5858. });
  5859. });
  5860. self.beforeGetHtml(function(html) {
  5861. if (_IE && _V <= 8) {
  5862. html = html.replace(/<div\s+[^>]*data-ke-input-tag="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, tag) {
  5863. return unescape(tag);
  5864. });
  5865. html = html.replace(/(<input)((?:\s+[^>]*)?>)/ig, function($0, $1, $2) {
  5866. if (!/\s+type="[^"]+"/i.test($0)) {
  5867. return $1 + ' type="text"' + $2;
  5868. }
  5869. return $0;
  5870. });
  5871. }
  5872. return html.replace(/(<(?:noscript|noscript\s[^>]*)>)([\s\S]*?)(<\/noscript>)/ig, function($0, $1, $2, $3) {
  5873. return $1 + _unescape($2).replace(/\s+/g, ' ') + $3;
  5874. })
  5875. .replace(/<img[^>]*class="?ke-(flash|rm|media)"?[^>]*>/ig, function(full) {
  5876. var imgAttrs = _getAttrList(full);
  5877. var styles = _getCssList(imgAttrs.style || '');
  5878. var attrs = _mediaAttrs(imgAttrs['data-ke-tag']);
  5879. var width = _undef(styles.width, '');
  5880. var height = _undef(styles.height, '');
  5881. if (/px/i.test(width)) {
  5882. width = _removeUnit(width);
  5883. }
  5884. if (/px/i.test(height)) {
  5885. height = _removeUnit(height);
  5886. }
  5887. attrs.width = _undef(imgAttrs.width, width);
  5888. attrs.height = _undef(imgAttrs.height, height);
  5889. return _mediaEmbed(attrs);
  5890. })
  5891. .replace(/<img[^>]*class="?ke-anchor"?[^>]*>/ig, function(full) {
  5892. var imgAttrs = _getAttrList(full);
  5893. return '<a name="' + unescape(imgAttrs['data-ke-name']) + '"></a>';
  5894. })
  5895. .replace(/<div\s+[^>]*data-ke-script-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  5896. return '<script' + unescape(attr) + '>' + unescape(code) + '</script>';
  5897. })
  5898. .replace(/<div\s+[^>]*data-ke-noscript-attr="([^"]*)"[^>]*>([\s\S]*?)<\/div>/ig, function(full, attr, code) {
  5899. return '<noscript' + unescape(attr) + '>' + unescape(code) + '</noscript>';
  5900. })
  5901. .replace(/(<[^>]*)data-ke-src="([^"]*)"([^>]*>)/ig, function(full, start, src, end) {
  5902. full = full.replace(/(\s+(?:href|src)=")[^"]*(")/i, function($0, $1, $2) {
  5903. return $1 + _unescape(src) + $2;
  5904. });
  5905. full = full.replace(/\s+data-ke-src="[^"]*"/i, '');
  5906. return full;
  5907. })
  5908. .replace(/(<[^>]+\s)data-ke-(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  5909. return start + end;
  5910. });
  5911. });
  5912. self.beforeSetHtml(function(html) {
  5913. if (_IE && _V <= 8) {
  5914. html = html.replace(/<input[^>]*>|<(select|button)[^>]*>[\s\S]*?<\/\1>/ig, function(full) {
  5915. var attrs = _getAttrList(full);
  5916. var styles = _getCssList(attrs.style || '');
  5917. if (styles.display == 'none') {
  5918. return '<div class="ke-display-none" data-ke-input-tag="' + escape(full) + '"></div>';
  5919. }
  5920. return full;
  5921. });
  5922. }
  5923. return html.replace(/<embed[^>]*type="([^"]+)"[^>]*>(?:<\/embed>)?/ig, function(full) {
  5924. var attrs = _getAttrList(full);
  5925. attrs.src = _undef(attrs.src, '');
  5926. attrs.width = _undef(attrs.width, 0);
  5927. attrs.height = _undef(attrs.height, 0);
  5928. return _mediaImg(self.themesPath + 'common/blank.gif', attrs);
  5929. })
  5930. .replace(/<a[^>]*name="([^"]+)"[^>]*>(?:<\/a>)?/ig, function(full) {
  5931. var attrs = _getAttrList(full);
  5932. if (attrs.href !== undefined) {
  5933. return full;
  5934. }
  5935. return '<img class="ke-anchor" src="' + self.themesPath + 'common/anchor.gif" data-ke-name="' + escape(attrs.name) + '" />';
  5936. })
  5937. .replace(/<script([^>]*)>([\s\S]*?)<\/script>/ig, function(full, attr, code) {
  5938. return '<div class="ke-script" data-ke-script-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  5939. })
  5940. .replace(/<noscript([^>]*)>([\s\S]*?)<\/noscript>/ig, function(full, attr, code) {
  5941. return '<div class="ke-noscript" data-ke-noscript-attr="' + escape(attr) + '">' + escape(code) + '</div>';
  5942. })
  5943. .replace(/(<[^>]*)(href|src)="([^"]*)"([^>]*>)/ig, function(full, start, key, src, end) {
  5944. if (full.match(/\sdata-ke-src="[^"]*"/i)) {
  5945. return full;
  5946. }
  5947. full = start + key + '="' + src + '"' + ' data-ke-src="' + _escape(src) + '"' + end;
  5948. return full;
  5949. })
  5950. .replace(/(<[^>]+\s)(on\w+="[^"]*"[^>]*>)/ig, function(full, start, end) {
  5951. return start + 'data-ke-' + end;
  5952. })
  5953. .replace(/<table[^>]*\s+border="0"[^>]*>/ig, function(full) {
  5954. if (full.indexOf('ke-zeroborder') >= 0) {
  5955. return full;
  5956. }
  5957. return _addClassToTag(full, 'ke-zeroborder');
  5958. });
  5959. });
  5960. });
  5961. })(window);