kindeditor.js 154 KB

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