redactor.js 238 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542
  1. /*
  2. Redactor 10.2.5
  3. Updated: October 1, 2015
  4. http://imperavi.com/redactor/
  5. Copyright (c) 2009-2015, Imperavi LLC.
  6. License: http://imperavi.com/redactor/license/
  7. Usage: $('#content').redactor();
  8. */
  9. (function($)
  10. {
  11. 'use strict';
  12. if (!Function.prototype.bind)
  13. {
  14. Function.prototype.bind = function(scope)
  15. {
  16. var fn = this;
  17. return function()
  18. {
  19. return fn.apply(scope);
  20. };
  21. };
  22. }
  23. var uuid = 0;
  24. // Plugin
  25. $.fn.redactor = function(options)
  26. {
  27. var val = [];
  28. var args = Array.prototype.slice.call(arguments, 1);
  29. if (typeof options === 'string')
  30. {
  31. this.each(function()
  32. {
  33. var instance = $.data(this, 'redactor');
  34. var func;
  35. if (options.search(/\./) != '-1')
  36. {
  37. func = options.split('.');
  38. if (typeof instance[func[0]] != 'undefined')
  39. {
  40. func = instance[func[0]][func[1]];
  41. }
  42. }
  43. else
  44. {
  45. func = instance[options];
  46. }
  47. if (typeof instance !== 'undefined' && $.isFunction(func))
  48. {
  49. var methodVal = func.apply(instance, args);
  50. if (methodVal !== undefined && methodVal !== instance)
  51. {
  52. val.push(methodVal);
  53. }
  54. }
  55. else
  56. {
  57. $.error('No such method "' + options + '" for Redactor');
  58. }
  59. });
  60. }
  61. else
  62. {
  63. this.each(function()
  64. {
  65. $.data(this, 'redactor', {});
  66. $.data(this, 'redactor', Redactor(this, options));
  67. });
  68. }
  69. if (val.length === 0) return this;
  70. else if (val.length === 1) return val[0];
  71. else return val;
  72. };
  73. // Initialization
  74. function Redactor(el, options)
  75. {
  76. return new Redactor.prototype.init(el, options);
  77. }
  78. // Functionality
  79. $.Redactor = Redactor;
  80. $.Redactor.VERSION = '10.2.5';
  81. $.Redactor.modules = ['alignment', 'autosave', 'block', 'buffer', 'build', 'button',
  82. 'caret', 'clean', 'code', 'core', 'dropdown', 'file', 'focus',
  83. 'image', 'indent', 'inline', 'insert', 'keydown', 'keyup',
  84. 'lang', 'line', 'link', 'linkify', 'list', 'modal', 'observe', 'paragraphize',
  85. 'paste', 'placeholder', 'progress', 'selection', 'shortcuts',
  86. 'tabifier', 'tidy', 'toolbar', 'upload', 'utils'];
  87. $.Redactor.opts = {
  88. // settings
  89. lang: 'en',
  90. direction: 'ltr', // ltr or rtl
  91. plugins: false, // array
  92. focus: false,
  93. focusEnd: false,
  94. placeholder: false,
  95. visual: true,
  96. tabindex: false,
  97. minHeight: false,
  98. maxHeight: false,
  99. linebreaks: false,
  100. replaceDivs: true,
  101. paragraphize: true,
  102. cleanStyleOnEnter: false,
  103. enterKey: true,
  104. cleanOnPaste: true,
  105. cleanSpaces: true,
  106. pastePlainText: false,
  107. autosave: false, // false or url
  108. autosaveName: false,
  109. autosaveInterval: 60, // seconds
  110. autosaveOnChange: false,
  111. autosaveFields: false,
  112. linkTooltip: true,
  113. linkProtocol: 'http',
  114. linkNofollow: false,
  115. linkSize: 50,
  116. imageEditable: true,
  117. imageLink: true,
  118. imagePosition: true,
  119. imageFloatMargin: '10px',
  120. imageResizable: true,
  121. imageUpload: null,
  122. imageUploadParam: 'file',
  123. uploadImageField: false,
  124. dragImageUpload: true,
  125. fileUpload: null,
  126. fileUploadParam: 'file',
  127. dragFileUpload: true,
  128. s3: false,
  129. convertLinks: true,
  130. convertUrlLinks: true,
  131. convertImageLinks: true,
  132. convertVideoLinks: true,
  133. preSpaces: 4, // or false
  134. tabAsSpaces: false, // true or number of spaces
  135. tabKey: true,
  136. scrollTarget: false,
  137. toolbar: true,
  138. toolbarFixed: true,
  139. toolbarFixedTarget: document,
  140. toolbarFixedTopOffset: 0, // pixels
  141. toolbarExternal: false, // ID selector
  142. toolbarOverflow: false,
  143. source: true,
  144. buttons: ['html', 'formatting', 'bold', 'italic', 'deleted', 'unorderedlist', 'orderedlist',
  145. 'outdent', 'indent', 'image', 'file', 'link', 'alignment', 'horizontalrule'], // + 'underline'
  146. buttonsHide: [],
  147. buttonsHideOnMobile: [],
  148. formatting: ['p', 'blockquote', 'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'],
  149. formattingAdd: false,
  150. tabifier: true,
  151. deniedTags: ['script', 'style'],
  152. allowedTags: false, // or array
  153. paragraphizeBlocks: ['table', 'div', 'pre', 'form', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'dl', 'blockquote', 'figcaption',
  154. 'address', 'section', 'header', 'footer', 'aside', 'article', 'object', 'style', 'script', 'iframe', 'select', 'input', 'textarea',
  155. 'button', 'option', 'map', 'area', 'math', 'hr', 'fieldset', 'legend', 'hgroup', 'nav', 'figure', 'details', 'menu', 'summary', 'p'],
  156. removeComments: false,
  157. replaceTags: [
  158. ['strike', 'del'],
  159. ['b', 'strong']
  160. ],
  161. replaceStyles: [
  162. ['font-weight:\\s?bold', "strong"],
  163. ['font-style:\\s?italic', "em"],
  164. ['text-decoration:\\s?underline', "u"],
  165. ['text-decoration:\\s?line-through', 'del']
  166. ],
  167. removeDataAttr: false,
  168. removeAttr: false, // or multi array
  169. allowedAttr: false, // or multi array
  170. removeWithoutAttr: ['span'], // or false
  171. removeEmpty: ['p'], // or false;
  172. activeButtons: ['deleted', 'italic', 'bold', 'underline', 'unorderedlist', 'orderedlist',
  173. 'alignleft', 'aligncenter', 'alignright', 'justify'],
  174. activeButtonsStates: {
  175. b: 'bold',
  176. strong: 'bold',
  177. i: 'italic',
  178. em: 'italic',
  179. del: 'deleted',
  180. strike: 'deleted',
  181. ul: 'unorderedlist',
  182. ol: 'orderedlist',
  183. u: 'underline'
  184. },
  185. shortcuts: {
  186. 'ctrl+shift+m, meta+shift+m': { func: 'inline.removeFormat' },
  187. 'ctrl+b, meta+b': { func: 'inline.format', params: ['bold'] },
  188. 'ctrl+i, meta+i': { func: 'inline.format', params: ['italic'] },
  189. 'ctrl+h, meta+h': { func: 'inline.format', params: ['superscript'] },
  190. 'ctrl+l, meta+l': { func: 'inline.format', params: ['subscript'] },
  191. 'ctrl+k, meta+k': { func: 'link.show' },
  192. 'ctrl+shift+7': { func: 'list.toggle', params: ['orderedlist'] },
  193. 'ctrl+shift+8': { func: 'list.toggle', params: ['unorderedlist'] }
  194. },
  195. shortcutsAdd: false,
  196. // private
  197. buffer: [],
  198. rebuffer: [],
  199. emptyHtml: '<p>&#x200b;</p>',
  200. invisibleSpace: '&#x200b;',
  201. imageTypes: ['image/png', 'image/jpeg', 'image/gif'],
  202. indentValue: 20,
  203. verifiedTags: ['a', 'img', 'b', 'strong', 'sub', 'sup', 'i', 'em', 'u', 'small', 'strike', 'del', 'cite', 'ul', 'ol', 'li'], // and for span tag special rule
  204. inlineTags: ['strong', 'b', 'u', 'em', 'i', 'code', 'del', 'ins', 'samp', 'kbd', 'sup', 'sub', 'mark', 'var', 'cite', 'small'],
  205. alignmentTags: ['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'DL', 'DT', 'DD', 'DIV', 'TD', 'BLOCKQUOTE', 'OUTPUT', 'FIGCAPTION', 'ADDRESS', 'SECTION', 'HEADER', 'FOOTER', 'ASIDE', 'ARTICLE'],
  206. blockLevelElements: ['PRE', 'UL', 'OL', 'LI'],
  207. highContrast: false,
  208. observe: {
  209. dropdowns: []
  210. },
  211. // lang
  212. langs: {
  213. en: {
  214. html: 'HTML',
  215. video: 'Insert Video',
  216. image: 'Insert Image',
  217. table: 'Table',
  218. link: 'Link',
  219. link_insert: 'Insert link',
  220. link_edit: 'Edit link',
  221. unlink: 'Unlink',
  222. formatting: 'Formatting',
  223. paragraph: 'Normal text',
  224. quote: 'Quote',
  225. code: 'Code',
  226. header1: 'Header 1',
  227. header2: 'Header 2',
  228. header3: 'Header 3',
  229. header4: 'Header 4',
  230. header5: 'Header 5',
  231. bold: 'Bold',
  232. italic: 'Italic',
  233. fontcolor: 'Font Color',
  234. backcolor: 'Back Color',
  235. unorderedlist: 'Unordered List',
  236. orderedlist: 'Ordered List',
  237. outdent: 'Outdent',
  238. indent: 'Indent',
  239. cancel: 'Cancel',
  240. insert: 'Insert',
  241. save: 'Save',
  242. _delete: 'Delete',
  243. insert_table: 'Insert Table',
  244. insert_row_above: 'Add Row Above',
  245. insert_row_below: 'Add Row Below',
  246. insert_column_left: 'Add Column Left',
  247. insert_column_right: 'Add Column Right',
  248. delete_column: 'Delete Column',
  249. delete_row: 'Delete Row',
  250. delete_table: 'Delete Table',
  251. rows: 'Rows',
  252. columns: 'Columns',
  253. add_head: 'Add Head',
  254. delete_head: 'Delete Head',
  255. title: 'Title',
  256. image_position: 'Position',
  257. none: 'None',
  258. left: 'Left',
  259. right: 'Right',
  260. center: 'Center',
  261. image_web_link: 'Image Web Link',
  262. text: 'Text',
  263. mailto: 'Email',
  264. web: 'URL',
  265. video_html_code: 'Video Embed Code or Youtube/Vimeo Link',
  266. file: 'Insert File',
  267. upload: 'Upload',
  268. download: 'Download',
  269. choose: 'Choose',
  270. or_choose: 'Or choose',
  271. drop_file_here: 'Drop file here',
  272. align_left: 'Align text to the left',
  273. align_center: 'Center text',
  274. align_right: 'Align text to the right',
  275. align_justify: 'Justify text',
  276. horizontalrule: 'Insert Horizontal Rule',
  277. deleted: 'Deleted',
  278. anchor: 'Anchor',
  279. link_new_tab: 'Open link in new tab',
  280. underline: 'Underline',
  281. alignment: 'Alignment',
  282. filename: 'Name (optional)',
  283. edit: 'Edit',
  284. upload_label: 'Drop file here or '
  285. }
  286. },
  287. linkify: {
  288. regexps: {
  289. youtube: /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube\.com\S*[^\w\-\s])([\w\-]{11})(?=[^\w\-]|$)(?![?=&+%\w.\-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig,
  290. vimeo: /https?:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/,
  291. image: /((https?|www)[^\s]+\.)(jpe?g|png|gif)(\?[^\s-]+)?/ig,
  292. url: /(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})/ig,
  293. }
  294. },
  295. codemirror: false
  296. };
  297. // Functionality
  298. Redactor.fn = $.Redactor.prototype = {
  299. keyCode: {
  300. BACKSPACE: 8,
  301. DELETE: 46,
  302. UP: 38,
  303. DOWN: 40,
  304. ENTER: 13,
  305. SPACE: 32,
  306. ESC: 27,
  307. TAB: 9,
  308. CTRL: 17,
  309. META: 91,
  310. SHIFT: 16,
  311. ALT: 18,
  312. RIGHT: 39,
  313. LEFT: 37,
  314. LEFT_WIN: 91
  315. },
  316. // Initialization
  317. init: function(el, options)
  318. {
  319. this.$element = $(el);
  320. this.uuid = uuid++;
  321. // if paste event detected = true
  322. this.rtePaste = false;
  323. this.$pasteBox = false;
  324. this.loadOptions(options);
  325. this.loadModules();
  326. // formatting storage
  327. this.formatting = {};
  328. // block level tags
  329. $.merge(this.opts.blockLevelElements, this.opts.alignmentTags);
  330. this.reIsBlock = new RegExp('^(' + this.opts.blockLevelElements.join('|' ) + ')$', 'i');
  331. // setup allowed and denied tags
  332. this.tidy.setupAllowed();
  333. // setup denied tags
  334. if (this.opts.deniedTags !== false)
  335. {
  336. var tags = ['html', 'head', 'link', 'body', 'meta', 'applet'];
  337. for (var i = 0; i < tags.length; i++)
  338. {
  339. this.opts.deniedTags.push(tags[i]);
  340. }
  341. }
  342. // load lang
  343. this.lang.load();
  344. // extend shortcuts
  345. $.extend(this.opts.shortcuts, this.opts.shortcutsAdd);
  346. // start callback
  347. this.core.setCallback('start');
  348. // build
  349. this.start = true;
  350. this.build.run();
  351. },
  352. loadOptions: function(options)
  353. {
  354. this.opts = $.extend(
  355. {},
  356. $.extend(true, {}, $.Redactor.opts),
  357. this.$element.data(),
  358. options
  359. );
  360. },
  361. getModuleMethods: function(object)
  362. {
  363. return Object.getOwnPropertyNames(object).filter(function(property)
  364. {
  365. return typeof object[property] == 'function';
  366. });
  367. },
  368. loadModules: function()
  369. {
  370. var len = $.Redactor.modules.length;
  371. for (var i = 0; i < len; i++)
  372. {
  373. this.bindModuleMethods($.Redactor.modules[i]);
  374. }
  375. },
  376. bindModuleMethods: function(module)
  377. {
  378. if (typeof this[module] == 'undefined') return;
  379. // init module
  380. this[module] = this[module]();
  381. var methods = this.getModuleMethods(this[module]);
  382. var len = methods.length;
  383. // bind methods
  384. for (var z = 0; z < len; z++)
  385. {
  386. this[module][methods[z]] = this[module][methods[z]].bind(this);
  387. }
  388. },
  389. alignment: function()
  390. {
  391. return {
  392. left: function()
  393. {
  394. this.alignment.set('');
  395. },
  396. right: function()
  397. {
  398. this.alignment.set('right');
  399. },
  400. center: function()
  401. {
  402. this.alignment.set('center');
  403. },
  404. justify: function()
  405. {
  406. this.alignment.set('justify');
  407. },
  408. set: function(type)
  409. {
  410. // focus
  411. if (!this.utils.browser('msie') && !this.opts.linebreaks)
  412. {
  413. this.$editor.focus();
  414. }
  415. // get blocks
  416. this.alignment.blocks = this.selection.getBlocks();
  417. this.alignment.type = type;
  418. this.buffer.set();
  419. this.selection.save();
  420. // set alignment
  421. if (this.alignment.isLinebreaksOrNoBlocks())
  422. {
  423. this.alignment.setText();
  424. }
  425. else
  426. {
  427. this.alignment.setBlocks();
  428. }
  429. // sync
  430. this.selection.restore();
  431. this.code.sync();
  432. },
  433. setText: function()
  434. {
  435. var wrapper = this.selection.wrap('div');
  436. $(wrapper).attr('data-tagblock', 'redactor').css('text-align', this.alignment.type);
  437. },
  438. setBlocks: function()
  439. {
  440. $.each(this.alignment.blocks, $.proxy(function(i, el)
  441. {
  442. var $el = this.utils.getAlignmentElement(el);
  443. if (!$el) return;
  444. if (this.alignment.isNeedReplaceElement($el))
  445. {
  446. this.alignment.replaceElement($el);
  447. }
  448. else
  449. {
  450. this.alignment.alignElement($el);
  451. }
  452. }, this));
  453. },
  454. isLinebreaksOrNoBlocks: function()
  455. {
  456. return (this.opts.linebreaks && this.alignment.blocks[0] === false);
  457. },
  458. isNeedReplaceElement: function($el)
  459. {
  460. return (this.alignment.type === '' && typeof($el.data('tagblock')) !== 'undefined');
  461. },
  462. replaceElement: function($el)
  463. {
  464. $el.replaceWith($el.html());
  465. },
  466. alignElement: function($el)
  467. {
  468. $el.css('text-align', this.alignment.type);
  469. this.utils.removeEmptyAttr($el, 'style');
  470. }
  471. };
  472. },
  473. autosave: function()
  474. {
  475. return {
  476. html: false,
  477. enable: function()
  478. {
  479. if (!this.opts.autosave) return;
  480. this.autosave.name = (this.opts.autosaveName) ? this.opts.autosaveName : this.$textarea.attr('name');
  481. if (this.opts.autosaveOnChange) return;
  482. this.autosaveInterval = setInterval(this.autosave.load, this.opts.autosaveInterval * 1000);
  483. },
  484. onChange: function()
  485. {
  486. if (!this.opts.autosaveOnChange) return;
  487. this.autosave.load();
  488. },
  489. load: function()
  490. {
  491. if (!this.opts.autosave) return;
  492. this.autosave.source = this.code.get();
  493. if (this.autosave.html === this.autosave.source) return;
  494. // data
  495. var data = {};
  496. data['name'] = this.autosave.name;
  497. data[this.autosave.name] = this.autosave.source;
  498. data = this.autosave.getHiddenFields(data);
  499. // ajax
  500. var jsxhr = $.ajax({
  501. url: this.opts.autosave,
  502. type: 'post',
  503. data: data
  504. });
  505. jsxhr.done(this.autosave.success);
  506. },
  507. getHiddenFields: function(data)
  508. {
  509. if (this.opts.autosaveFields === false || typeof this.opts.autosaveFields !== 'object')
  510. {
  511. return data;
  512. }
  513. $.each(this.opts.autosaveFields, $.proxy(function(k, v)
  514. {
  515. if (v !== null && v.toString().indexOf('#') === 0) v = $(v).val();
  516. data[k] = v;
  517. }, this));
  518. return data;
  519. },
  520. success: function(data)
  521. {
  522. var json;
  523. try
  524. {
  525. json = $.parseJSON(data);
  526. }
  527. catch(e)
  528. {
  529. //data has already been parsed
  530. json = data;
  531. }
  532. var callbackName = (typeof json.error == 'undefined') ? 'autosave' : 'autosaveError';
  533. this.core.setCallback(callbackName, this.autosave.name, json);
  534. this.autosave.html = this.autosave.source;
  535. },
  536. disable: function()
  537. {
  538. clearInterval(this.autosaveInterval);
  539. }
  540. };
  541. },
  542. block: function()
  543. {
  544. return {
  545. formatting: function(name)
  546. {
  547. this.block.clearStyle = false;
  548. var type, value;
  549. if (typeof this.formatting[name].data != 'undefined') type = 'data';
  550. else if (typeof this.formatting[name].attr != 'undefined') type = 'attr';
  551. else if (typeof this.formatting[name]['class'] != 'undefined') type = 'class';
  552. if (typeof this.formatting[name].clear != 'undefined')
  553. {
  554. this.block.clearStyle = true;
  555. }
  556. if (type) value = this.formatting[name][type];
  557. this.block.format(this.formatting[name].tag, type, value);
  558. },
  559. format: function(tag, type, value)
  560. {
  561. if (tag == 'quote') tag = 'blockquote';
  562. var formatTags = ['p', 'pre', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  563. if ($.inArray(tag, formatTags) == -1) return;
  564. this.block.isRemoveInline = (tag == 'pre' || tag.search(/h[1-6]/i) != -1);
  565. // focus
  566. if (!this.utils.browser('msie')) this.$editor.focus();
  567. var html = $.trim(this.$editor.html());
  568. this.block.isEmpty = this.utils.isEmpty(html);
  569. // FF focus
  570. if (this.utils.browser('mozilla') && !this.focus.isFocused())
  571. {
  572. if (this.block.isEmpty)
  573. {
  574. var $first;
  575. if (!this.opts.linebreaks)
  576. {
  577. $first = this.$editor.children().first();
  578. this.caret.setEnd($first);
  579. }
  580. }
  581. }
  582. this.block.blocks = this.selection.getBlocks();
  583. this.block.blocksSize = this.block.blocks.length;
  584. this.block.type = type;
  585. this.block.value = value;
  586. this.buffer.set();
  587. this.selection.save();
  588. this.block.set(tag);
  589. this.selection.restore();
  590. this.code.sync();
  591. this.observe.load();
  592. },
  593. set: function(tag)
  594. {
  595. this.selection.get();
  596. this.block.containerTag = this.range.commonAncestorContainer.tagName;
  597. if (this.range.collapsed)
  598. {
  599. this.block.setCollapsed(tag);
  600. }
  601. else
  602. {
  603. this.block.setMultiple(tag);
  604. }
  605. },
  606. setCollapsed: function(tag)
  607. {
  608. if (this.opts.linebreaks && this.block.isEmpty && tag != 'p')
  609. {
  610. var node = document.createElement(tag);
  611. this.$editor.html(node);
  612. this.caret.setEnd(node);
  613. return;
  614. }
  615. var block = this.block.blocks[0];
  616. if (block === false) return;
  617. if (block.tagName == 'LI')
  618. {
  619. if (tag != 'blockquote') return;
  620. this.block.formatListToBlockquote();
  621. return;
  622. }
  623. var isContainerTable = (this.block.containerTag == 'TD' || this.block.containerTag == 'TH');
  624. if (isContainerTable && !this.opts.linebreaks)
  625. {
  626. document.execCommand('formatblock', false, '<' + tag + '>');
  627. block = this.selection.getBlock();
  628. this.block.toggle($(block));
  629. }
  630. else if (block.tagName.toLowerCase() != tag)
  631. {
  632. if (this.opts.linebreaks && tag == 'p')
  633. {
  634. $(block).append('<br>');
  635. this.utils.replaceWithContents(block);
  636. }
  637. else
  638. {
  639. var $formatted = this.utils.replaceToTag(block, tag);
  640. this.block.toggle($formatted);
  641. if (tag != 'p' && tag != 'blockquote') $formatted.find('img').remove();
  642. if (this.block.isRemoveInline) this.utils.removeInlineTags($formatted);
  643. if (tag == 'p' || this.block.headTag) $formatted.find('p').contents().unwrap();
  644. this.block.formatTableWrapping($formatted);
  645. }
  646. }
  647. else if (tag == 'blockquote' && block.tagName.toLowerCase() == tag)
  648. {
  649. // blockquote off
  650. if (this.opts.linebreaks)
  651. {
  652. $(block).append('<br>');
  653. this.utils.replaceWithContents(block);
  654. }
  655. else
  656. {
  657. var $el = this.utils.replaceToTag(block, 'p');
  658. this.block.toggle($el);
  659. }
  660. }
  661. else if (block.tagName.toLowerCase() == tag)
  662. {
  663. this.block.toggle($(block));
  664. }
  665. if (typeof this.block.type == 'undefined' && typeof this.block.value == 'undefined')
  666. {
  667. $(block).removeAttr('class').removeAttr('style');
  668. }
  669. },
  670. setMultiple: function(tag)
  671. {
  672. var block = this.block.blocks[0];
  673. var isContainerTable = (this.block.containerTag == 'TD' || this.block.containerTag == 'TH');
  674. if (block !== false && this.block.blocksSize === 1)
  675. {
  676. if (block.tagName.toLowerCase() == tag && tag == 'blockquote')
  677. {
  678. // blockquote off
  679. if (this.opts.linebreaks)
  680. {
  681. $(block).append('<br>');
  682. this.utils.replaceWithContents(block);
  683. }
  684. else
  685. {
  686. var $el = this.utils.replaceToTag(block, 'p');
  687. this.block.toggle($el);
  688. }
  689. }
  690. else if (block.tagName == 'LI')
  691. {
  692. if (tag != 'blockquote') return;
  693. this.block.formatListToBlockquote();
  694. }
  695. else if (this.block.containerTag == 'BLOCKQUOTE')
  696. {
  697. this.block.formatBlockquote(tag);
  698. }
  699. else if (this.opts.linebreaks && ((isContainerTable) || (this.range.commonAncestorContainer != block)))
  700. {
  701. this.block.formatWrap(tag);
  702. }
  703. else
  704. {
  705. if (this.opts.linebreaks && tag == 'p')
  706. {
  707. $(block).prepend('<br>').append('<br>');
  708. this.utils.replaceWithContents(block);
  709. }
  710. else if (block.tagName === 'TD')
  711. {
  712. this.block.formatWrap(tag);
  713. }
  714. else
  715. {
  716. var $formatted = this.utils.replaceToTag(block, tag);
  717. this.block.toggle($formatted);
  718. if (this.block.isRemoveInline) this.utils.removeInlineTags($formatted);
  719. if (tag == 'p' || this.block.headTag) $formatted.find('p').contents().unwrap();
  720. }
  721. }
  722. }
  723. else
  724. {
  725. if (this.opts.linebreaks || tag != 'p')
  726. {
  727. if (tag == 'blockquote')
  728. {
  729. var count = 0;
  730. for (var i = 0; i < this.block.blocksSize; i++)
  731. {
  732. if (this.block.blocks[i].tagName == 'BLOCKQUOTE') count++;
  733. }
  734. // only blockquote selected
  735. if (count == this.block.blocksSize)
  736. {
  737. $.each(this.block.blocks, $.proxy(function(i,s)
  738. {
  739. var $formatted = false;
  740. if (this.opts.linebreaks)
  741. {
  742. $(s).prepend('<br>').append('<br>');
  743. $formatted = this.utils.replaceWithContents(s);
  744. }
  745. else
  746. {
  747. $formatted = this.utils.replaceToTag(s, 'p');
  748. }
  749. if ($formatted && typeof this.block.type == 'undefined' && typeof this.block.value == 'undefined')
  750. {
  751. $formatted.removeAttr('class').removeAttr('style');
  752. }
  753. }, this));
  754. return;
  755. }
  756. }
  757. this.block.formatWrap(tag);
  758. }
  759. else
  760. {
  761. var classSize = 0;
  762. var toggleType = false;
  763. if (this.block.type == 'class')
  764. {
  765. toggleType = 'toggle';
  766. classSize = $(this.block.blocks).filter('.' + this.block.value).length;
  767. if (this.block.blocksSize == classSize) toggleType = 'toggle';
  768. else if (this.block.blocksSize > classSize) toggleType = 'set';
  769. else if (classSize === 0) toggleType = 'set';
  770. }
  771. var exceptTags = ['ul', 'ol', 'li', 'td', 'th', 'dl', 'dt', 'dd'];
  772. $.each(this.block.blocks, $.proxy(function(i,s)
  773. {
  774. if ($.inArray(s.tagName.toLowerCase(), exceptTags) != -1) return;
  775. var $formatted = this.utils.replaceToTag(s, tag);
  776. if (toggleType)
  777. {
  778. if (toggleType == 'toggle') this.block.toggle($formatted);
  779. else if (toggleType == 'remove') this.block.remove($formatted);
  780. else if (toggleType == 'set') this.block.setForce($formatted);
  781. }
  782. else this.block.toggle($formatted);
  783. if (tag != 'p' && tag != 'blockquote') $formatted.find('img').remove();
  784. if (this.block.isRemoveInline) this.utils.removeInlineTags($formatted);
  785. if (tag == 'p' || this.block.headTag) $formatted.find('p').contents().unwrap();
  786. if (typeof this.block.type == 'undefined' && typeof this.block.value == 'undefined')
  787. {
  788. $formatted.removeAttr('class').removeAttr('style');
  789. }
  790. }, this));
  791. }
  792. }
  793. },
  794. setForce: function($el)
  795. {
  796. // remove style and class if the specified setting
  797. if (this.block.clearStyle)
  798. {
  799. $el.removeAttr('class').removeAttr('style');
  800. }
  801. if (this.block.type == 'class')
  802. {
  803. $el.addClass(this.block.value);
  804. return;
  805. }
  806. else if (this.block.type == 'attr' || this.block.type == 'data')
  807. {
  808. $el.attr(this.block.value.name, this.block.value.value);
  809. return;
  810. }
  811. },
  812. toggle: function($el)
  813. {
  814. // remove style and class if the specified setting
  815. if (this.block.clearStyle)
  816. {
  817. $el.removeAttr('class').removeAttr('style');
  818. }
  819. if (this.block.type == 'class')
  820. {
  821. $el.toggleClass(this.block.value);
  822. return;
  823. }
  824. else if (this.block.type == 'attr' || this.block.type == 'data')
  825. {
  826. if ($el.attr(this.block.value.name) == this.block.value.value)
  827. {
  828. $el.removeAttr(this.block.value.name);
  829. }
  830. else
  831. {
  832. $el.attr(this.block.value.name, this.block.value.value);
  833. }
  834. return;
  835. }
  836. else
  837. {
  838. $el.removeAttr('style class');
  839. return;
  840. }
  841. },
  842. remove: function($el)
  843. {
  844. $el.removeClass(this.block.value);
  845. },
  846. formatListToBlockquote: function()
  847. {
  848. var block = $(this.block.blocks[0]).closest('ul, ol', this.$editor[0]);
  849. $(block).find('ul, ol').contents().unwrap();
  850. $(block).find('li').append($('<br>')).contents().unwrap();
  851. var $el = this.utils.replaceToTag(block, 'blockquote');
  852. this.block.toggle($el);
  853. },
  854. formatBlockquote: function(tag)
  855. {
  856. document.execCommand('outdent');
  857. document.execCommand('formatblock', false, tag);
  858. this.clean.clearUnverified();
  859. this.$editor.find('p:empty').remove();
  860. var formatted = this.selection.getBlock();
  861. if (tag != 'p')
  862. {
  863. $(formatted).find('img').remove();
  864. }
  865. if (!this.opts.linebreaks)
  866. {
  867. this.block.toggle($(formatted));
  868. }
  869. this.$editor.find('ul, ol, tr, blockquote, p').each($.proxy(this.utils.removeEmpty, this));
  870. if (this.opts.linebreaks && tag == 'p')
  871. {
  872. this.utils.replaceWithContents(formatted);
  873. }
  874. },
  875. formatWrap: function(tag)
  876. {
  877. if (this.block.containerTag == 'UL' || this.block.containerTag == 'OL')
  878. {
  879. if (tag == 'blockquote')
  880. {
  881. this.block.formatListToBlockquote();
  882. }
  883. else
  884. {
  885. return;
  886. }
  887. }
  888. var formatted = this.selection.wrap(tag);
  889. if (formatted === false) return;
  890. var $formatted = $(formatted);
  891. this.block.formatTableWrapping($formatted);
  892. var $elements = $formatted.find(this.opts.blockLevelElements.join(',') + ', td, table, thead, tbody, tfoot, th, tr');
  893. $elements.contents().unwrap();
  894. if (tag != 'p' && tag != 'blockquote') $formatted.find('img').remove();
  895. $.each(this.block.blocks, $.proxy(this.utils.removeEmpty, this));
  896. $formatted.append(this.selection.getMarker(2));
  897. if (!this.opts.linebreaks)
  898. {
  899. this.block.toggle($formatted);
  900. }
  901. this.$editor.find('ul, ol, tr, blockquote, p').each($.proxy(this.utils.removeEmpty, this));
  902. $formatted.find('blockquote:empty').remove();
  903. if (this.block.isRemoveInline)
  904. {
  905. this.utils.removeInlineTags($formatted);
  906. }
  907. if (this.opts.linebreaks && tag == 'p')
  908. {
  909. this.utils.replaceWithContents($formatted);
  910. }
  911. if (this.opts.linebreaks)
  912. {
  913. var $next = $formatted.next().next();
  914. if ($next.size() != 0 && $next[0].tagName === 'BR')
  915. {
  916. $next.remove();
  917. }
  918. }
  919. },
  920. formatTableWrapping: function($formatted)
  921. {
  922. if ($formatted.closest('table', this.$editor[0]).length === 0) return;
  923. if ($formatted.closest('tr', this.$editor[0]).length === 0) $formatted.wrap('<tr>');
  924. if ($formatted.closest('td', this.$editor[0]).length === 0 && $formatted.closest('th').length === 0)
  925. {
  926. $formatted.wrap('<td>');
  927. }
  928. },
  929. removeData: function(name, value)
  930. {
  931. var blocks = this.selection.getBlocks();
  932. $(blocks).removeAttr('data-' + name);
  933. this.code.sync();
  934. },
  935. setData: function(name, value)
  936. {
  937. var blocks = this.selection.getBlocks();
  938. $(blocks).attr('data-' + name, value);
  939. this.code.sync();
  940. },
  941. toggleData: function(name, value)
  942. {
  943. var blocks = this.selection.getBlocks();
  944. $.each(blocks, function()
  945. {
  946. if ($(this).attr('data-' + name))
  947. {
  948. $(this).removeAttr('data-' + name);
  949. }
  950. else
  951. {
  952. $(this).attr('data-' + name, value);
  953. }
  954. });
  955. },
  956. removeAttr: function(attr, value)
  957. {
  958. var blocks = this.selection.getBlocks();
  959. $(blocks).removeAttr(attr);
  960. this.code.sync();
  961. },
  962. setAttr: function(attr, value)
  963. {
  964. var blocks = this.selection.getBlocks();
  965. $(blocks).attr(attr, value);
  966. this.code.sync();
  967. },
  968. toggleAttr: function(attr, value)
  969. {
  970. var blocks = this.selection.getBlocks();
  971. $.each(blocks, function()
  972. {
  973. if ($(this).attr(name))
  974. {
  975. $(this).removeAttr(name);
  976. }
  977. else
  978. {
  979. $(this).attr(name, value);
  980. }
  981. });
  982. },
  983. removeClass: function(className)
  984. {
  985. var blocks = this.selection.getBlocks();
  986. $(blocks).removeClass(className);
  987. this.utils.removeEmptyAttr(blocks, 'class');
  988. this.code.sync();
  989. },
  990. setClass: function(className)
  991. {
  992. var blocks = this.selection.getBlocks();
  993. $(blocks).addClass(className);
  994. this.code.sync();
  995. },
  996. toggleClass: function(className)
  997. {
  998. var blocks = this.selection.getBlocks();
  999. $(blocks).toggleClass(className);
  1000. this.code.sync();
  1001. }
  1002. };
  1003. },
  1004. buffer: function()
  1005. {
  1006. return {
  1007. set: function(type)
  1008. {
  1009. if (typeof type == 'undefined' || type == 'undo')
  1010. {
  1011. this.buffer.setUndo();
  1012. }
  1013. else
  1014. {
  1015. this.buffer.setRedo();
  1016. }
  1017. },
  1018. setUndo: function()
  1019. {
  1020. this.selection.save();
  1021. this.opts.buffer.push(this.$editor.html());
  1022. this.selection.restore();
  1023. },
  1024. setRedo: function()
  1025. {
  1026. this.selection.save();
  1027. this.opts.rebuffer.push(this.$editor.html());
  1028. this.selection.restore();
  1029. },
  1030. getUndo: function()
  1031. {
  1032. this.$editor.html(this.opts.buffer.pop());
  1033. },
  1034. getRedo: function()
  1035. {
  1036. this.$editor.html(this.opts.rebuffer.pop());
  1037. },
  1038. add: function()
  1039. {
  1040. this.opts.buffer.push(this.$editor.html());
  1041. },
  1042. undo: function()
  1043. {
  1044. if (this.opts.buffer.length === 0) return;
  1045. this.buffer.set('redo');
  1046. this.buffer.getUndo();
  1047. this.selection.restore();
  1048. setTimeout($.proxy(this.observe.load, this), 50);
  1049. },
  1050. redo: function()
  1051. {
  1052. if (this.opts.rebuffer.length === 0) return;
  1053. this.buffer.set('undo');
  1054. this.buffer.getRedo();
  1055. this.selection.restore();
  1056. setTimeout($.proxy(this.observe.load, this), 50);
  1057. }
  1058. };
  1059. },
  1060. build: function()
  1061. {
  1062. return {
  1063. focused: false,
  1064. blured: true,
  1065. run: function()
  1066. {
  1067. this.build.createContainerBox();
  1068. this.build.loadContent();
  1069. this.build.loadEditor();
  1070. this.build.enableEditor();
  1071. this.build.setCodeAndCall();
  1072. },
  1073. isTextarea: function()
  1074. {
  1075. return (this.$element[0].tagName === 'TEXTAREA');
  1076. },
  1077. createContainerBox: function()
  1078. {
  1079. this.$box = $('<div class="redactor-box" role="application" />');
  1080. },
  1081. createTextarea: function()
  1082. {
  1083. this.$textarea = $('<textarea />').attr('name', this.build.getTextareaName());
  1084. },
  1085. getTextareaName: function()
  1086. {
  1087. return ((typeof(name) == 'undefined')) ? 'content-' + this.uuid : this.$element.attr('id');
  1088. },
  1089. loadContent: function()
  1090. {
  1091. var func = (this.build.isTextarea()) ? 'val' : 'html';
  1092. this.content = $.trim(this.$element[func]());
  1093. },
  1094. enableEditor: function()
  1095. {
  1096. this.$editor.attr({ 'contenteditable': true, 'dir': this.opts.direction });
  1097. },
  1098. loadEditor: function()
  1099. {
  1100. var func = (this.build.isTextarea()) ? 'fromTextarea' : 'fromElement';
  1101. this.build[func]();
  1102. },
  1103. fromTextarea: function()
  1104. {
  1105. this.$editor = $('<div />');
  1106. this.$textarea = this.$element;
  1107. this.$box.insertAfter(this.$element).append(this.$editor).append(this.$element);
  1108. this.$editor.addClass('redactor-editor');
  1109. this.$element.hide();
  1110. },
  1111. fromElement: function()
  1112. {
  1113. this.$editor = this.$element;
  1114. this.build.createTextarea();
  1115. this.$box.insertAfter(this.$editor).append(this.$editor).append(this.$textarea);
  1116. this.$editor.addClass('redactor-editor');
  1117. this.$textarea.hide();
  1118. },
  1119. setCodeAndCall: function()
  1120. {
  1121. // set code
  1122. this.code.set(this.content);
  1123. this.build.setOptions();
  1124. this.build.callEditor();
  1125. // code mode
  1126. if (this.opts.visual) return;
  1127. setTimeout($.proxy(this.code.showCode, this), 200);
  1128. },
  1129. callEditor: function()
  1130. {
  1131. this.build.disableMozillaEditing();
  1132. this.build.disableIeLinks();
  1133. this.build.setEvents();
  1134. this.build.setHelpers();
  1135. // load toolbar
  1136. if (this.opts.toolbar)
  1137. {
  1138. this.opts.toolbar = this.toolbar.init();
  1139. this.toolbar.build();
  1140. }
  1141. // modal templates init
  1142. this.modal.loadTemplates();
  1143. // plugins
  1144. this.build.plugins();
  1145. // observers
  1146. setTimeout($.proxy(this.observe.load, this), 4);
  1147. // init callback
  1148. this.core.setCallback('init');
  1149. },
  1150. setOptions: function()
  1151. {
  1152. // textarea direction
  1153. $(this.$textarea).attr('dir', this.opts.direction);
  1154. if (this.opts.linebreaks) this.$editor.addClass('redactor-linebreaks');
  1155. if (this.opts.tabindex) this.$editor.attr('tabindex', this.opts.tabindex);
  1156. if (this.opts.minHeight) this.$editor.css('minHeight', this.opts.minHeight);
  1157. if (this.opts.maxHeight) this.$editor.css('maxHeight', this.opts.maxHeight);
  1158. },
  1159. setEventDropUpload: function(e)
  1160. {
  1161. e.preventDefault();
  1162. if (!this.opts.dragImageUpload || !this.opts.dragFileUpload) return;
  1163. var files = e.dataTransfer.files;
  1164. this.upload.directUpload(files[0], e);
  1165. },
  1166. setEventDrop: function(e)
  1167. {
  1168. this.code.sync();
  1169. setTimeout(this.clean.clearUnverified, 1);
  1170. this.core.setCallback('drop', e);
  1171. },
  1172. setEvents: function()
  1173. {
  1174. // drop
  1175. this.$editor.on('dragover.redactor dragenter.redactor', function(e)
  1176. {
  1177. e.preventDefault();
  1178. e.stopPropagation();
  1179. });
  1180. this.$editor.on('drop.redactor', $.proxy(function(e)
  1181. {
  1182. e = e.originalEvent || e;
  1183. if (window.FormData === undefined || !e.dataTransfer) return true;
  1184. if (e.dataTransfer.files.length === 0)
  1185. {
  1186. return this.build.setEventDrop(e);
  1187. }
  1188. else
  1189. {
  1190. this.build.setEventDropUpload(e);
  1191. }
  1192. setTimeout(this.clean.clearUnverified, 1);
  1193. this.core.setCallback('drop', e);
  1194. }, this));
  1195. // click
  1196. this.$editor.on('click.redactor', $.proxy(function(e)
  1197. {
  1198. var event = this.core.getEvent();
  1199. var type = (event == 'click' || event == 'arrow') ? false : 'click';
  1200. this.core.addEvent(type);
  1201. this.utils.disableSelectAll();
  1202. this.core.setCallback('click', e);
  1203. }, this));
  1204. // paste
  1205. this.$editor.on('paste.redactor', $.proxy(this.paste.init, this));
  1206. // cut
  1207. this.$editor.on('cut.redactor', $.proxy(this.code.sync, this));
  1208. // keydown
  1209. this.$editor.on('keydown.redactor', $.proxy(this.keydown.init, this));
  1210. // keyup
  1211. this.$editor.on('keyup.redactor', $.proxy(this.keyup.init, this));
  1212. // textarea keydown
  1213. if ($.isFunction(this.opts.codeKeydownCallback))
  1214. {
  1215. this.$textarea.on('keydown.redactor-textarea', $.proxy(this.opts.codeKeydownCallback, this));
  1216. }
  1217. // textarea keyup
  1218. if ($.isFunction(this.opts.codeKeyupCallback))
  1219. {
  1220. this.$textarea.on('keyup.redactor-textarea', $.proxy(this.opts.codeKeyupCallback, this));
  1221. }
  1222. // focus
  1223. this.$editor.on('focus.redactor', $.proxy(function(e)
  1224. {
  1225. if ($.isFunction(this.opts.focusCallback))
  1226. {
  1227. this.core.setCallback('focus', e);
  1228. }
  1229. this.build.focused = true;
  1230. this.build.blured = false;
  1231. if (this.selection.getCurrent() === false)
  1232. {
  1233. this.selection.get();
  1234. this.range.setStart(this.$editor[0], 0);
  1235. this.range.setEnd(this.$editor[0], 0);
  1236. this.selection.addRange();
  1237. }
  1238. }, this));
  1239. // blur
  1240. $(document).on('mousedown.redactor-blur.' + this.uuid, $.proxy(function(e)
  1241. {
  1242. if (this.start) return;
  1243. if (this.rtePaste) return;
  1244. if ($(e.target).closest('.redactor-editor, .redactor-toolbar, .redactor-dropdown').size() !== 0)
  1245. {
  1246. return;
  1247. }
  1248. this.utils.disableSelectAll();
  1249. if (!this.build.blured && $.isFunction(this.opts.blurCallback))
  1250. {
  1251. this.core.setCallback('blur', e);
  1252. }
  1253. this.build.focused = false;
  1254. this.build.blured = true;
  1255. }, this));
  1256. },
  1257. setHelpers: function()
  1258. {
  1259. // linkify
  1260. if (this.linkify.isEnabled())
  1261. {
  1262. this.linkify.format();
  1263. }
  1264. // placeholder
  1265. this.placeholder.enable();
  1266. // focus
  1267. if (this.opts.focus) setTimeout(this.focus.setStart, 100);
  1268. if (this.opts.focusEnd) setTimeout(this.focus.setEnd, 100);
  1269. },
  1270. plugins: function()
  1271. {
  1272. if (!this.opts.plugins) return;
  1273. $.each(this.opts.plugins, $.proxy(function(i, s)
  1274. {
  1275. var func = (typeof RedactorPlugins !== 'undefined' && typeof RedactorPlugins[s] !== 'undefined') ? RedactorPlugins : Redactor.fn;
  1276. if (!$.isFunction(func[s]))
  1277. {
  1278. return;
  1279. }
  1280. this[s] = func[s]();
  1281. // get methods
  1282. var methods = this.getModuleMethods(this[s]);
  1283. var len = methods.length;
  1284. // bind methods
  1285. for (var z = 0; z < len; z++)
  1286. {
  1287. this[s][methods[z]] = this[s][methods[z]].bind(this);
  1288. }
  1289. if ($.isFunction(this[s].init))
  1290. {
  1291. this[s].init();
  1292. }
  1293. }, this));
  1294. },
  1295. disableMozillaEditing: function()
  1296. {
  1297. if (!this.utils.browser('mozilla')) return;
  1298. // FF fix
  1299. try {
  1300. document.execCommand('enableObjectResizing', false, false);
  1301. document.execCommand('enableInlineTableEditing', false, false);
  1302. } catch (e) {}
  1303. },
  1304. disableIeLinks: function()
  1305. {
  1306. if (!this.utils.browser('msie')) return;
  1307. // IE prevent converting links
  1308. document.execCommand("AutoUrlDetect", false, false);
  1309. }
  1310. };
  1311. },
  1312. button: function()
  1313. {
  1314. return {
  1315. build: function(btnName, btnObject)
  1316. {
  1317. var $button = $('<a href="#" class="re-icon re-' + btnName + '" rel="' + btnName + '" />').attr({'role': 'button', 'aria-label': btnObject.title, 'tabindex': '-1'});
  1318. // click
  1319. if (btnObject.func || btnObject.command || btnObject.dropdown)
  1320. {
  1321. this.button.setEvent($button, btnName, btnObject);
  1322. }
  1323. // dropdown
  1324. if (btnObject.dropdown)
  1325. {
  1326. $button.addClass('redactor-toolbar-link-dropdown').attr('aria-haspopup', true);
  1327. var $dropdown = $('<div class="redactor-dropdown redactor-dropdown-' + this.uuid + ' redactor-dropdown-box-' + btnName + '" style="display: none;">');
  1328. $button.data('dropdown', $dropdown);
  1329. this.dropdown.build(btnName, $dropdown, btnObject.dropdown);
  1330. }
  1331. // tooltip
  1332. if (this.utils.isDesktop())
  1333. {
  1334. this.button.createTooltip($button, btnName, btnObject.title);
  1335. }
  1336. return $button;
  1337. },
  1338. setEvent: function($button, btnName, btnObject)
  1339. {
  1340. $button.on('touchstart click', $.proxy(function(e)
  1341. {
  1342. if ($button.hasClass('redactor-button-disabled')) return false;
  1343. var type = 'func';
  1344. var callback = btnObject.func;
  1345. if (btnObject.command)
  1346. {
  1347. type = 'command';
  1348. callback = btnObject.command;
  1349. }
  1350. else if (btnObject.dropdown)
  1351. {
  1352. type = 'dropdown';
  1353. callback = false;
  1354. }
  1355. this.button.onClick(e, btnName, type, callback);
  1356. }, this));
  1357. },
  1358. createTooltip: function($button, name, title)
  1359. {
  1360. var $tooltip = $('<span>').addClass('redactor-toolbar-tooltip redactor-toolbar-tooltip-' + this.uuid + ' redactor-toolbar-tooltip-' + name).hide().html(title);
  1361. $tooltip.appendTo('body');
  1362. $button.on('mouseover', function()
  1363. {
  1364. if ($(this).hasClass('redactor-button-disabled'))
  1365. {
  1366. return;
  1367. }
  1368. var pos = $button.offset();
  1369. $tooltip.css({
  1370. top: (pos.top + $button.innerHeight()) + 'px',
  1371. left: (pos.left + $button.innerWidth()/2 - $tooltip.innerWidth()/2) + 'px'
  1372. });
  1373. $tooltip.show();
  1374. });
  1375. $button.on('mouseout', function()
  1376. {
  1377. $tooltip.hide();
  1378. });
  1379. },
  1380. onClick: function(e, btnName, type, callback)
  1381. {
  1382. this.button.caretOffset = this.caret.getOffset();
  1383. e.preventDefault();
  1384. $(document).find('.redactor-toolbar-tooltip').hide();
  1385. if (this.utils.browser('msie')) e.returnValue = false;
  1386. if (type == 'command') this.inline.format(callback);
  1387. else if (type == 'dropdown') this.dropdown.show(e, btnName);
  1388. else this.button.onClickCallback(e, callback, btnName);
  1389. },
  1390. onClickCallback: function(e, callback, btnName)
  1391. {
  1392. var func;
  1393. if ($.isFunction(callback)) callback.call(this, btnName);
  1394. else if (callback.search(/\./) != '-1')
  1395. {
  1396. func = callback.split('.');
  1397. if (typeof this[func[0]] == 'undefined') return;
  1398. this[func[0]][func[1]](btnName);
  1399. }
  1400. else this[callback](btnName);
  1401. this.observe.buttons(e, btnName);
  1402. },
  1403. get: function(key)
  1404. {
  1405. return this.$toolbar.find('a.re-' + key);
  1406. },
  1407. setActive: function(key)
  1408. {
  1409. this.button.get(key).addClass('redactor-act');
  1410. },
  1411. setInactive: function(key)
  1412. {
  1413. this.button.get(key).removeClass('redactor-act');
  1414. },
  1415. setInactiveAll: function(key)
  1416. {
  1417. if (typeof key === 'undefined')
  1418. {
  1419. this.$toolbar.find('a.re-icon').removeClass('redactor-act');
  1420. }
  1421. else
  1422. {
  1423. this.$toolbar.find('a.re-icon').not('.re-' + key).removeClass('redactor-act');
  1424. }
  1425. },
  1426. setActiveInVisual: function()
  1427. {
  1428. this.$toolbar.find('a.re-icon').not('a.re-html, a.re-fullscreen').removeClass('redactor-button-disabled');
  1429. },
  1430. setInactiveInCode: function()
  1431. {
  1432. this.$toolbar.find('a.re-icon').not('a.re-html, a.re-fullscreen').addClass('redactor-button-disabled');
  1433. },
  1434. changeIcon: function(key, classname)
  1435. {
  1436. this.button.get(key).addClass('re-' + classname);
  1437. },
  1438. removeIcon: function(key, classname)
  1439. {
  1440. this.button.get(key).removeClass('re-' + classname);
  1441. },
  1442. setAwesome: function(key, name)
  1443. {
  1444. var $button = this.button.get(key);
  1445. $button.removeClass('redactor-btn-image').addClass('fa-redactor-btn');
  1446. $button.html('<i class="fa ' + name + '"></i>');
  1447. },
  1448. addCallback: function($btn, callback)
  1449. {
  1450. if ($btn == "buffer") return;
  1451. var type = (callback == 'dropdown') ? 'dropdown' : 'func';
  1452. var key = $btn.attr('rel');
  1453. $btn.on('touchstart click', $.proxy(function(e)
  1454. {
  1455. if ($btn.hasClass('redactor-button-disabled')) return false;
  1456. this.button.onClick(e, key, type, callback);
  1457. }, this));
  1458. },
  1459. addDropdown: function($btn, dropdown)
  1460. {
  1461. $btn.addClass('redactor-toolbar-link-dropdown').attr('aria-haspopup', true);
  1462. var key = $btn.attr('rel');
  1463. this.button.addCallback($btn, 'dropdown');
  1464. var $dropdown = $('<div class="redactor-dropdown redactor-dropdown-' + this.uuid + ' redactor-dropdown-box-' + key + '" style="display: none;">');
  1465. $btn.data('dropdown', $dropdown);
  1466. // build dropdown
  1467. if (dropdown) this.dropdown.build(key, $dropdown, dropdown);
  1468. return $dropdown;
  1469. },
  1470. add: function(key, title)
  1471. {
  1472. if (!this.opts.toolbar) return;
  1473. if (this.button.isMobileUndoRedo(key)) return "buffer";
  1474. var btn = this.button.build(key, { title: title });
  1475. btn.addClass('redactor-btn-image');
  1476. this.$toolbar.append($('<li>').append(btn));
  1477. return btn;
  1478. },
  1479. addFirst: function(key, title)
  1480. {
  1481. if (!this.opts.toolbar) return;
  1482. if (this.button.isMobileUndoRedo(key)) return "buffer";
  1483. var btn = this.button.build(key, { title: title });
  1484. btn.addClass('redactor-btn-image');
  1485. this.$toolbar.prepend($('<li>').append(btn));
  1486. return btn;
  1487. },
  1488. addAfter: function(afterkey, key, title)
  1489. {
  1490. if (!this.opts.toolbar) return;
  1491. if (this.button.isMobileUndoRedo(key)) return "buffer";
  1492. var btn = this.button.build(key, { title: title });
  1493. btn.addClass('redactor-btn-image');
  1494. var $btn = this.button.get(afterkey);
  1495. if ($btn.length !== 0) $btn.parent().after($('<li>').append(btn));
  1496. else this.$toolbar.append($('<li>').append(btn));
  1497. return btn;
  1498. },
  1499. addBefore: function(beforekey, key, title)
  1500. {
  1501. if (!this.opts.toolbar) return;
  1502. if (this.button.isMobileUndoRedo(key)) return "buffer";
  1503. var btn = this.button.build(key, { title: title });
  1504. btn.addClass('redactor-btn-image');
  1505. var $btn = this.button.get(beforekey);
  1506. if ($btn.length !== 0) $btn.parent().before($('<li>').append(btn));
  1507. else this.$toolbar.append($('<li>').append(btn));
  1508. return btn;
  1509. },
  1510. remove: function(key)
  1511. {
  1512. this.button.get(key).remove();
  1513. },
  1514. isMobileUndoRedo: function(key)
  1515. {
  1516. return (key == "undo" || key == "redo") && !this.utils.isDesktop();
  1517. }
  1518. };
  1519. },
  1520. caret: function()
  1521. {
  1522. return {
  1523. setStart: function(node)
  1524. {
  1525. // inline tag
  1526. if (!this.utils.isBlock(node))
  1527. {
  1528. var space = this.utils.createSpaceElement();
  1529. $(node).prepend(space);
  1530. this.caret.setEnd(space);
  1531. }
  1532. else
  1533. {
  1534. this.caret.set(node, 0, node, 0);
  1535. }
  1536. },
  1537. setEnd: function(node)
  1538. {
  1539. node = node[0] || node;
  1540. if (node.lastChild.nodeType == 1)
  1541. {
  1542. return this.caret.setAfter(node.lastChild);
  1543. }
  1544. this.caret.set(node, 1, node, 1);
  1545. },
  1546. set: function(orgn, orgo, focn, foco)
  1547. {
  1548. // focus
  1549. // disabled in 10.0.7
  1550. // if (!this.utils.browser('msie')) this.$editor.focus();
  1551. orgn = orgn[0] || orgn;
  1552. focn = focn[0] || focn;
  1553. if (this.utils.isBlockTag(orgn.tagName) && orgn.innerHTML === '')
  1554. {
  1555. orgn.innerHTML = this.opts.invisibleSpace;
  1556. }
  1557. if (orgn.tagName == 'BR' && this.opts.linebreaks === false)
  1558. {
  1559. var parent = $(this.opts.emptyHtml)[0];
  1560. $(orgn).replaceWith(parent);
  1561. orgn = parent;
  1562. focn = orgn;
  1563. }
  1564. this.selection.get();
  1565. try
  1566. {
  1567. this.range.setStart(orgn, orgo);
  1568. this.range.setEnd(focn, foco);
  1569. }
  1570. catch (e) {}
  1571. this.selection.addRange();
  1572. },
  1573. setAfter: function(node)
  1574. {
  1575. try
  1576. {
  1577. var tag = $(node)[0].tagName;
  1578. // inline tag
  1579. if (tag != 'BR' && !this.utils.isBlock(node))
  1580. {
  1581. var space = this.utils.createSpaceElement();
  1582. $(node).after(space);
  1583. this.caret.setEnd(space);
  1584. }
  1585. else
  1586. {
  1587. if (tag != 'BR' && this.utils.browser('msie'))
  1588. {
  1589. this.caret.setStart($(node).next());
  1590. }
  1591. else
  1592. {
  1593. this.caret.setAfterOrBefore(node, 'after');
  1594. }
  1595. }
  1596. }
  1597. catch (e)
  1598. {
  1599. var space = this.utils.createSpaceElement();
  1600. $(node).after(space);
  1601. this.caret.setEnd(space);
  1602. }
  1603. },
  1604. setBefore: function(node)
  1605. {
  1606. // block tag
  1607. if (this.utils.isBlock(node))
  1608. {
  1609. this.caret.setEnd($(node).prev());
  1610. }
  1611. else
  1612. {
  1613. this.caret.setAfterOrBefore(node, 'before');
  1614. }
  1615. },
  1616. setAfterOrBefore: function(node, type)
  1617. {
  1618. // focus
  1619. if (!this.utils.browser('msie')) this.$editor.focus();
  1620. node = node[0] || node;
  1621. this.selection.get();
  1622. if (type == 'after')
  1623. {
  1624. try {
  1625. this.range.setStartAfter(node);
  1626. this.range.setEndAfter(node);
  1627. }
  1628. catch (e) {}
  1629. }
  1630. else
  1631. {
  1632. try {
  1633. this.range.setStartBefore(node);
  1634. this.range.setEndBefore(node);
  1635. }
  1636. catch (e) {}
  1637. }
  1638. this.range.collapse(false);
  1639. this.selection.addRange();
  1640. },
  1641. getOffsetOfElement: function(node)
  1642. {
  1643. node = node[0] || node;
  1644. this.selection.get();
  1645. var cloned = this.range.cloneRange();
  1646. cloned.selectNodeContents(node);
  1647. cloned.setEnd(this.range.endContainer, this.range.endOffset);
  1648. return $.trim(cloned.toString()).length;
  1649. },
  1650. getOffset: function()
  1651. {
  1652. var offset = 0;
  1653. var sel = window.getSelection();
  1654. if (sel.rangeCount > 0)
  1655. {
  1656. var range = window.getSelection().getRangeAt(0);
  1657. var caretRange = range.cloneRange();
  1658. caretRange.selectNodeContents(this.$editor[0]);
  1659. caretRange.setEnd(range.endContainer, range.endOffset);
  1660. offset = caretRange.toString().length;
  1661. }
  1662. return offset;
  1663. },
  1664. setOffset: function(start, end)
  1665. {
  1666. if (typeof end == 'undefined') end = start;
  1667. if (!this.focus.isFocused()) this.focus.setStart();
  1668. var sel = this.selection.get();
  1669. var node, offset = 0;
  1670. var walker = document.createTreeWalker(this.$editor[0], NodeFilter.SHOW_TEXT, null, null);
  1671. while (node = walker.nextNode())
  1672. {
  1673. offset += node.nodeValue.length;
  1674. if (offset > start)
  1675. {
  1676. this.range.setStart(node, node.nodeValue.length + start - offset);
  1677. start = Infinity;
  1678. }
  1679. if (offset >= end)
  1680. {
  1681. this.range.setEnd(node, node.nodeValue.length + end - offset);
  1682. break;
  1683. }
  1684. }
  1685. this.range.collapse(false);
  1686. this.selection.addRange();
  1687. },
  1688. // deprecated
  1689. setToPoint: function(start, end)
  1690. {
  1691. this.caret.setOffset(start, end);
  1692. },
  1693. getCoords: function()
  1694. {
  1695. return this.caret.getOffset();
  1696. }
  1697. };
  1698. },
  1699. clean: function()
  1700. {
  1701. return {
  1702. onSet: function(html)
  1703. {
  1704. html = this.clean.savePreCode(html);
  1705. // convert script tag
  1706. html = html.replace(/<script(.*?[^>]?)>([\w\W]*?)<\/script>/gi, '<pre class="redactor-script-tag" style="display: none;" $1>$2</pre>');
  1707. // replace dollar sign to entity
  1708. html = html.replace(/\$/g, '&#36;');
  1709. // replace special characters in links
  1710. html = html.replace(/<a href="(.*?[^>]?)®(.*?[^>]?)">/gi, '<a href="$1&reg$2">');
  1711. if (this.opts.replaceDivs && !this.opts.linebreaks) html = this.clean.replaceDivs(html);
  1712. if (this.opts.linebreaks) html = this.clean.replaceParagraphsToBr(html);
  1713. // save form tag
  1714. html = this.clean.saveFormTags(html);
  1715. // convert font tag to span
  1716. var $div = $('<div>');
  1717. $div.html(html);
  1718. var fonts = $div.find('font[style]');
  1719. if (fonts.length !== 0)
  1720. {
  1721. fonts.replaceWith(function()
  1722. {
  1723. var $el = $(this);
  1724. var $span = $('<span>').attr('style', $el.attr('style'));
  1725. return $span.append($el.contents());
  1726. });
  1727. html = $div.html();
  1728. }
  1729. $div.remove();
  1730. // remove font tag
  1731. html = html.replace(/<font(.*?)>/gi, '');
  1732. html = html.replace(/<\/font>/gi, '');
  1733. // tidy html
  1734. html = this.tidy.load(html);
  1735. // paragraphize
  1736. if (this.opts.paragraphize) html = this.paragraphize.load(html);
  1737. // verified
  1738. html = this.clean.setVerified(html);
  1739. // convert inline tags
  1740. html = this.clean.convertInline(html);
  1741. html = html.replace(/&amp;/g, '&');
  1742. return html;
  1743. },
  1744. onSync: function(html)
  1745. {
  1746. // remove spaces
  1747. html = html.replace(/\u200B/g, '');
  1748. html = html.replace(/&#x200b;/gi, '');
  1749. if (this.opts.cleanSpaces)
  1750. {
  1751. html = html.replace(/&nbsp;/gi, ' ');
  1752. }
  1753. if (html.search(/^<p>(||\s||<br\s?\/?>||&nbsp;)<\/p>$/i) != -1)
  1754. {
  1755. return '';
  1756. }
  1757. // reconvert script tag
  1758. html = html.replace(/<pre class="redactor-script-tag" style="display: none;"(.*?[^>]?)>([\w\W]*?)<\/pre>/gi, '<script$1>$2</script>');
  1759. // restore form tag
  1760. html = this.clean.restoreFormTags(html);
  1761. var chars = {
  1762. '\u2122': '&trade;',
  1763. '\u00a9': '&copy;',
  1764. '\u2026': '&hellip;',
  1765. '\u2014': '&mdash;',
  1766. '\u2010': '&dash;'
  1767. };
  1768. // replace special characters
  1769. $.each(chars, function(i,s)
  1770. {
  1771. html = html.replace(new RegExp(i, 'g'), s);
  1772. });
  1773. // remove last br in FF
  1774. if (this.utils.browser('mozilla'))
  1775. {
  1776. html = html.replace(/<br\s?\/?>$/gi, '');
  1777. }
  1778. // remove br in|of li tags
  1779. html = html.replace(new RegExp('<br\\s?/?></li>', 'gi'), '</li>');
  1780. html = html.replace(new RegExp('</li><br\\s?/?>', 'gi'), '</li>');
  1781. // remove empty attributes
  1782. html = html.replace(/<(.*?)rel="\s*?"(.*?[^>]?)>/gi, '<$1$2">');
  1783. html = html.replace(/<(.*?)style="\s*?"(.*?[^>]?)>/gi, '<$1$2">');
  1784. html = html.replace(/="">/gi, '>');
  1785. html = html.replace(/""">/gi, '">');
  1786. html = html.replace(/"">/gi, '">');
  1787. // remove verified
  1788. html = html.replace(/<div(.*?)data-tagblock="redactor"(.*?[^>])>/gi, '<div$1$2>');
  1789. html = html.replace(/<(.*?) data-verified="redactor"(.*?[^>])>/gi, '<$1$2>');
  1790. var $div = $("<div/>").html($.parseHTML(html, document, true));
  1791. $div.find("span").removeAttr("rel");
  1792. $div.find('pre .redactor-invisible-space').each(function()
  1793. {
  1794. $(this).contents().unwrap();
  1795. });
  1796. html = $div.html();
  1797. // remove rel attribute from img
  1798. html = html.replace(/<img(.*?[^>])rel="(.*?[^>])"(.*?[^>])>/gi, '<img$1$3>');
  1799. html = html.replace(/<span class="redactor-invisible-space">(.*?)<\/span>/gi, '$1');
  1800. html = html.replace(/ data-save-url="(.*?[^>])"/gi, '');
  1801. // remove image resize
  1802. html = html.replace(/<span(.*?)id="redactor-image-box"(.*?[^>])>([\w\W]*?)<img(.*?)><\/span>/gi, '$3<img$4>');
  1803. html = html.replace(/<span(.*?)id="redactor-image-resizer"(.*?[^>])>(.*?)<\/span>/gi, '');
  1804. html = html.replace(/<span(.*?)id="redactor-image-editter"(.*?[^>])>(.*?)<\/span>/gi, '');
  1805. // remove font tag
  1806. html = html.replace(/<font(.*?)>/gi, '');
  1807. html = html.replace(/<\/font>/gi, '');
  1808. // tidy html
  1809. html = this.tidy.load(html);
  1810. // link nofollow
  1811. if (this.opts.linkNofollow)
  1812. {
  1813. html = html.replace(/<a(.*?)rel="nofollow"(.*?[^>])>/gi, '<a$1$2>');
  1814. html = html.replace(/<a(.*?[^>])>/gi, '<a$1 rel="nofollow">');
  1815. }
  1816. // reconvert inline
  1817. html = html.replace(/\sdata-redactor-(tag|class|style)="(.*?[^>])"/gi, '');
  1818. html = html.replace(new RegExp('<(.*?) data-verified="redactor"(.*?[^>])>', 'gi'), '<$1$2>');
  1819. html = html.replace(new RegExp('<(.*?) data-verified="redactor">', 'gi'), '<$1>');
  1820. html = html.replace(/&amp;/g, '&');
  1821. return html;
  1822. },
  1823. onPaste: function(html, setMode)
  1824. {
  1825. html = $.trim(html);
  1826. html = html.replace(/\$/g, '&#36;');
  1827. // convert dirty spaces
  1828. html = html.replace(/<span class="s[0-9]">/gi, '<span>');
  1829. html = html.replace(/<span class="Apple-converted-space">&nbsp;<\/span>/gi, ' ');
  1830. html = html.replace(/<span class="Apple-tab-span"[^>]*>\t<\/span>/gi, '\t');
  1831. html = html.replace(/<span[^>]*>(\s|&nbsp;)<\/span>/gi, ' ');
  1832. if (this.opts.pastePlainText)
  1833. {
  1834. return this.clean.getPlainText(html);
  1835. }
  1836. if (!this.utils.isSelectAll() && typeof setMode == 'undefined')
  1837. {
  1838. if (this.utils.isCurrentOrParent(['FIGCAPTION', 'A']))
  1839. {
  1840. return this.clean.getPlainText(html, false);
  1841. }
  1842. if (this.utils.isCurrentOrParent('PRE'))
  1843. {
  1844. html = html.replace(/”/g, '"');
  1845. html = html.replace(/“/g, '"');
  1846. html = html.replace(/‘/g, '\'');
  1847. html = html.replace(/’/g, '\'');
  1848. return this.clean.getPreCode(html);
  1849. }
  1850. if (this.utils.isCurrentOrParent(['BLOCKQUOTE', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6']))
  1851. {
  1852. html = this.clean.getOnlyImages(html);
  1853. if (!this.utils.browser('msie'))
  1854. {
  1855. var block = this.selection.getBlock();
  1856. if (block && block.tagName == 'P')
  1857. {
  1858. html = html.replace(/<img(.*?)>/gi, '<p><img$1></p>');
  1859. }
  1860. }
  1861. return html;
  1862. }
  1863. if (this.utils.isCurrentOrParent(['TD']))
  1864. {
  1865. html = this.clean.onPasteTidy(html, 'td');
  1866. if (this.opts.linebreaks) html = this.clean.replaceParagraphsToBr(html);
  1867. html = this.clean.replaceDivsToBr(html);
  1868. return html;
  1869. }
  1870. if (this.utils.isCurrentOrParent(['LI']))
  1871. {
  1872. return this.clean.onPasteTidy(html, 'li');
  1873. }
  1874. }
  1875. html = this.clean.isSingleLine(html, setMode);
  1876. if (!this.clean.singleLine)
  1877. {
  1878. if (this.opts.linebreaks) html = this.clean.replaceParagraphsToBr(html);
  1879. if (this.opts.replaceDivs) html = this.clean.replaceDivs(html);
  1880. html = this.clean.saveFormTags(html);
  1881. }
  1882. html = this.clean.onPasteWord(html);
  1883. html = this.clean.onPasteExtra(html);
  1884. html = this.clean.onPasteTidy(html, 'all');
  1885. // paragraphize
  1886. if (!this.clean.singleLine && this.opts.paragraphize)
  1887. {
  1888. html = this.paragraphize.load(html);
  1889. }
  1890. html = this.clean.removeDirtyStyles(html);
  1891. html = this.clean.onPasteRemoveSpans(html);
  1892. html = this.clean.onPasteRemoveEmpty(html);
  1893. html = this.clean.convertInline(html);
  1894. return html;
  1895. },
  1896. onPasteWord: function(html)
  1897. {
  1898. // comments
  1899. html = html.replace(/<!--[\s\S]*?-->/gi, '');
  1900. // style
  1901. html = html.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '');
  1902. // op
  1903. html = html.replace(/<o\:p[^>]*>[\s\S]*?<\/o\:p>/gi, '');
  1904. if (html.match(/class="?Mso|style="[^"]*\bmso-|style='[^'']*\bmso-|w:WordDocument/i))
  1905. {
  1906. // comments
  1907. html = html.replace(/<!--[\s\S]+?-->/gi, '');
  1908. // scripts
  1909. html = html.replace(/<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, '');
  1910. // Convert <s> into <strike>
  1911. html = html.replace(/<(\/?)s>/gi, "<$1strike>");
  1912. // Replace nbsp entites to char since it's easier to handle
  1913. html = html.replace(/ /gi, ' ');
  1914. // Convert <span style="mso-spacerun:yes">___</span> to string of alternating
  1915. // breaking/non-breaking spaces of same length
  1916. html = html.replace(/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function(str, spaces) {
  1917. return (spaces.length > 0) ? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : '';
  1918. });
  1919. html = this.clean.onPasteIeFixLinks(html);
  1920. // shapes
  1921. html = html.replace(/<img(.*?)v:shapes=(.*?)>/gi, '');
  1922. html = html.replace(/src="file\:\/\/(.*?)"/, 'src=""');
  1923. // lists
  1924. var $div = $("<div/>").html(html);
  1925. var lastList = false;
  1926. var lastLevel = 1;
  1927. var listsIds = [];
  1928. $div.find("p[style]").each(function()
  1929. {
  1930. var matches = $(this).attr('style').match(/mso\-list\:l([0-9]+)\slevel([0-9]+)/);
  1931. if (matches)
  1932. {
  1933. var currentList = parseInt(matches[1]);
  1934. var currentLevel = parseInt(matches[2]);
  1935. var listType = $(this).html().match(/^[\w]+\./) ? "ol" : "ul";
  1936. var $li = $("<li/>").html($(this).html());
  1937. $li.html($li.html().replace(/^([\w\.]+)</, '<'));
  1938. $li.find("span:first").remove();
  1939. if (currentLevel == 1 && $.inArray(currentList, listsIds) == -1)
  1940. {
  1941. var $list = $("<" + listType + "/>").attr({"data-level": currentLevel,
  1942. "data-list": currentList})
  1943. .html($li);
  1944. $(this).replaceWith($list);
  1945. lastList = currentList;
  1946. listsIds.push(currentList);
  1947. }
  1948. else
  1949. {
  1950. if (currentLevel > lastLevel)
  1951. {
  1952. var $prevList = $div.find('[data-level="' + lastLevel + '"][data-list="' + lastList + '"]');
  1953. var $lastList = $prevList;
  1954. for(var i = lastLevel; i < currentLevel; i++)
  1955. {
  1956. $list = $("<" + listType + "/>");
  1957. $list.appendTo($lastList.find("li").last());
  1958. $lastList = $list;
  1959. }
  1960. $lastList.attr({"data-level": currentLevel,
  1961. "data-list": currentList})
  1962. .html($li);
  1963. }
  1964. else
  1965. {
  1966. var $prevList = $div.find('[data-level="' + currentLevel + '"][data-list="' + currentList + '"]').last();
  1967. $prevList.append($li);
  1968. }
  1969. lastLevel = currentLevel;
  1970. lastList = currentList;
  1971. $(this).remove();
  1972. }
  1973. }
  1974. });
  1975. $div.find('[data-level][data-list]').removeAttr('data-level data-list');
  1976. html = $div.html();
  1977. // remove ms word's bullet
  1978. html = html.replace(/·/g, '');
  1979. html = html.replace(/<p class="Mso(.*?)"/gi, '<p');
  1980. // classes
  1981. html = html.replace(/ class=\"(mso[^\"]*)\"/gi, "");
  1982. html = html.replace(/ class=(mso\w+)/gi, "");
  1983. // remove ms word tags
  1984. html = html.replace(/<o:p(.*?)>([\w\W]*?)<\/o:p>/gi, '$2');
  1985. // ms word break lines
  1986. html = html.replace(/\n/g, ' ');
  1987. // ms word lists break lines
  1988. html = html.replace(/<p>\n?<li>/gi, '<li>');
  1989. }
  1990. return html;
  1991. },
  1992. onPasteExtra: function(html)
  1993. {
  1994. // remove google docs markers
  1995. html = html.replace(/<b\sid="internal-source-marker(.*?)">([\w\W]*?)<\/b>/gi, "$2");
  1996. html = html.replace(/<b(.*?)id="docs-internal-guid(.*?)">([\w\W]*?)<\/b>/gi, "$3");
  1997. // google docs styles
  1998. html = html.replace(/<span[^>]*(font-style: italic; font-weight: bold|font-weight: bold; font-style: italic)[^>]*>/gi, '<span style="font-weight: bold;"><span style="font-style: italic;">');
  1999. html = html.replace(/<span[^>]*font-style: italic[^>]*>/gi, '<span style="font-style: italic;">');
  2000. html = html.replace(/<span[^>]*font-weight: bold[^>]*>/gi, '<span style="font-weight: bold;">');
  2001. html = html.replace(/<span[^>]*text-decoration: underline[^>]*>/gi, '<span style="text-decoration: underline;">');
  2002. html = html.replace(/<img>/gi, '');
  2003. html = html.replace(/\n{3,}/gi, '\n');
  2004. html = html.replace(/<font(.*?)>([\w\W]*?)<\/font>/gi, '$2');
  2005. // remove dirty p
  2006. html = html.replace(/<p><p>/gi, '<p>');
  2007. html = html.replace(/<\/p><\/p>/gi, '</p>');
  2008. html = html.replace(/<li>(\s*|\t*|\n*)<p>/gi, '<li>');
  2009. html = html.replace(/<\/p>(\s*|\t*|\n*)<\/li>/gi, '</li>');
  2010. // remove space between paragraphs
  2011. html = html.replace(/<\/p>\s<p/gi, '<\/p><p');
  2012. // remove safari local images
  2013. html = html.replace(/<img src="webkit-fake-url\:\/\/(.*?)"(.*?)>/gi, '');
  2014. // bullets
  2015. html = html.replace(/<p>•([\w\W]*?)<\/p>/gi, '<li>$1</li>');
  2016. // FF fix
  2017. if (this.utils.browser('mozilla'))
  2018. {
  2019. html = html.replace(/<br\s?\/?>$/gi, '');
  2020. }
  2021. return html;
  2022. },
  2023. onPasteTidy: function(html, type)
  2024. {
  2025. // remove all tags except these
  2026. var tags = ['span', 'a', 'pre', 'blockquote', 'small', 'em', 'strong', 'code', 'kbd', 'mark', 'address', 'cite', 'var', 'samp', 'dfn', 'sup', 'sub', 'b', 'i', 'u', 'del',
  2027. 'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'p', 'br', 'video', 'audio', 'iframe', 'embed', 'param', 'object', 'img', 'table',
  2028. 'td', 'th', 'tr', 'tbody', 'tfoot', 'thead', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  2029. var tagsEmpty = false;
  2030. var attrAllowed = [
  2031. ['a', '*'],
  2032. ['img', ['src', 'alt']],
  2033. ['span', ['class', 'rel', 'data-verified']],
  2034. ['iframe', '*'],
  2035. ['video', '*'],
  2036. ['audio', '*'],
  2037. ['embed', '*'],
  2038. ['object', '*'],
  2039. ['param', '*'],
  2040. ['source', '*']
  2041. ];
  2042. if (type == 'all')
  2043. {
  2044. tagsEmpty = ['p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  2045. attrAllowed = [
  2046. ['table', 'class'],
  2047. ['td', ['colspan', 'rowspan']],
  2048. ['a', '*'],
  2049. ['img', ['src', 'alt', 'data-redactor-inserted-image']],
  2050. ['span', ['class', 'rel', 'data-verified']],
  2051. ['iframe', '*'],
  2052. ['video', '*'],
  2053. ['audio', '*'],
  2054. ['embed', '*'],
  2055. ['object', '*'],
  2056. ['param', '*'],
  2057. ['source', '*']
  2058. ];
  2059. }
  2060. else if (type == 'td')
  2061. {
  2062. // remove all tags except these and remove all table tags: tr, td etc
  2063. tags = ['ul', 'ol', 'li', 'span', 'a', 'small', 'em', 'strong', 'code', 'kbd', 'mark', 'cite', 'var', 'samp', 'dfn', 'sup', 'sub', 'b', 'i', 'u', 'del',
  2064. 'ol', 'ul', 'li', 'dl', 'dt', 'dd', 'br', 'iframe', 'video', 'audio', 'embed', 'param', 'object', 'img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'];
  2065. }
  2066. else if (type == 'li')
  2067. {
  2068. // only inline tags and ul, ol, li
  2069. tags = ['ul', 'ol', 'li', 'span', 'a', 'small', 'em', 'strong', 'code', 'kbd', 'mark', 'cite', 'var', 'samp', 'dfn', 'sup', 'sub', 'b', 'i', 'u', 'del', 'br',
  2070. 'iframe', 'video', 'audio', 'embed', 'param', 'object', 'img'];
  2071. }
  2072. var options = {
  2073. deniedTags: (this.opts.deniedTags) ? this.opts.deniedTags : false,
  2074. allowedTags: (this.opts.allowedTags) ? this.opts.allowedTags : tags,
  2075. removeComments: true,
  2076. removePhp: true,
  2077. removeAttr: (this.opts.removeAttr) ? this.opts.removeAttr : false,
  2078. allowedAttr: (this.opts.allowedAttr) ? this.opts.allowedAttr : attrAllowed,
  2079. removeEmpty: tagsEmpty
  2080. };
  2081. return this.tidy.load(html, options);
  2082. },
  2083. onPasteRemoveEmpty: function(html)
  2084. {
  2085. html = html.replace(/<(p|h[1-6])>(|\s|\n|\t|<br\s?\/?>)<\/(p|h[1-6])>/gi, '');
  2086. // remove br in the end
  2087. if (!this.opts.linebreaks) html = html.replace(/<br>$/i, '');
  2088. return html;
  2089. },
  2090. onPasteRemoveSpans: function(html)
  2091. {
  2092. html = html.replace(/<span>(.*?)<\/span>/gi, '$1');
  2093. html = html.replace(/<span[^>]*>\s|&nbsp;<\/span>/gi, ' ');
  2094. return html;
  2095. },
  2096. onPasteIeFixLinks: function(html)
  2097. {
  2098. if (!this.utils.browser('msie')) return html;
  2099. var tmp = $.trim(html);
  2100. if (tmp.search(/^<a(.*?)>(.*?)<\/a>$/i) === 0)
  2101. {
  2102. html = html.replace(/^<a(.*?)>(.*?)<\/a>$/i, "$2");
  2103. }
  2104. return html;
  2105. },
  2106. isSingleLine: function(html, setMode)
  2107. {
  2108. this.clean.singleLine = false;
  2109. if (!this.utils.isSelectAll() && typeof setMode == 'undefined')
  2110. {
  2111. var blocks = this.opts.blockLevelElements.join('|').replace('P|', '').replace('DIV|', '');
  2112. var matchBlocks = html.match(new RegExp('</(' + blocks + ')>', 'gi'));
  2113. var matchContainers = html.match(/<\/(p|div)>/gi);
  2114. if (!matchBlocks && (matchContainers === null || (matchContainers && matchContainers.length <= 1)))
  2115. {
  2116. var matchBR = html.match(/<br\s?\/?>/gi);
  2117. //var matchIMG = html.match(/<img(.*?[^>])>/gi);
  2118. if (!matchBR)
  2119. {
  2120. this.clean.singleLine = true;
  2121. html = html.replace(/<\/?(p|div)(.*?)>/gi, '');
  2122. }
  2123. }
  2124. }
  2125. return html;
  2126. },
  2127. stripTags: function(input, allowed)
  2128. {
  2129. allowed = (((allowed || '') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
  2130. var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
  2131. return input.replace(tags, function ($0, $1) {
  2132. return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
  2133. });
  2134. },
  2135. savePreCode: function(html)
  2136. {
  2137. html = this.clean.savePreFormatting(html);
  2138. html = this.clean.saveCodeFormatting(html);
  2139. html = this.clean.restoreSelectionMarker(html);
  2140. return html;
  2141. },
  2142. savePreFormatting: function(html)
  2143. {
  2144. var pre = html.match(/<pre(.*?)>([\w\W]*?)<\/pre>/gi);
  2145. if (pre !== null)
  2146. {
  2147. $.each(pre, $.proxy(function(i,s)
  2148. {
  2149. var arr = s.match(/<pre(.*?)>([\w\W]*?)<\/pre>/i);
  2150. arr[2] = arr[2].replace(/<br\s?\/?>/g, '\n');
  2151. arr[2] = arr[2].replace(/&nbsp;/g, ' ');
  2152. if (this.opts.preSpaces)
  2153. {
  2154. arr[2] = arr[2].replace(/\t/g, Array(this.opts.preSpaces + 1).join(' '));
  2155. }
  2156. arr[2] = this.clean.encodeEntities(arr[2]);
  2157. // $ fix
  2158. arr[2] = arr[2].replace(/\$/g, '&#36;');
  2159. html = html.replace(s, '<pre' + arr[1] + '>' + arr[2] + '</pre>');
  2160. }, this));
  2161. }
  2162. return html;
  2163. },
  2164. saveCodeFormatting: function(html)
  2165. {
  2166. var code = html.match(/<code(.*?)>([\w\W]*?)<\/code>/gi);
  2167. if (code !== null)
  2168. {
  2169. $.each(code, $.proxy(function(i,s)
  2170. {
  2171. var arr = s.match(/<code(.*?)>([\w\W]*?)<\/code>/i);
  2172. arr[2] = arr[2].replace(/&nbsp;/g, ' ');
  2173. arr[2] = this.clean.encodeEntities(arr[2]);
  2174. arr[2] = arr[2].replace(/\$/g, '&#36;');
  2175. html = html.replace(s, '<code' + arr[1] + '>' + arr[2] + '</code>');
  2176. }, this));
  2177. }
  2178. return html;
  2179. },
  2180. restoreSelectionMarker: function(html)
  2181. {
  2182. html = html.replace(/&lt;span id=&quot;selection-marker-([0-9])&quot; class=&quot;redactor-selection-marker&quot; data-verified=&quot;redactor&quot;&gt;​&lt;\/span&gt;/g, '<span id="selection-marker-$1" class="redactor-selection-marker" data-verified="redactor">​</span>');
  2183. return html;
  2184. },
  2185. getTextFromHtml: function(html)
  2186. {
  2187. html = html.replace(/<br\s?\/?>|<\/H[1-6]>|<\/p>|<\/div>|<\/li>|<\/td>/gi, '\n');
  2188. var tmp = document.createElement('div');
  2189. tmp.innerHTML = html;
  2190. html = tmp.textContent || tmp.innerText;
  2191. return $.trim(html);
  2192. },
  2193. getPlainText: function(html, paragraphize)
  2194. {
  2195. html = this.clean.getTextFromHtml(html);
  2196. html = html.replace(/\n\s*\n/g, "\n");
  2197. html = html.replace(/\n\n/g, "\n");
  2198. html = html.replace(/\n/g, '<br />');
  2199. if (this.opts.paragraphize && typeof paragraphize == 'undefined' && !this.utils.browser('mozilla'))
  2200. {
  2201. html = this.paragraphize.load(html);
  2202. }
  2203. return html;
  2204. },
  2205. getPreCode: function(html)
  2206. {
  2207. html = html.replace(/<img(.*?) style="(.*?)"(.*?[^>])>/gi, '<img$1$3>');
  2208. html = html.replace(/<img(.*?)>/gi, '&lt;img$1&gt;');
  2209. html = this.clean.getTextFromHtml(html);
  2210. if (this.opts.preSpaces)
  2211. {
  2212. html = html.replace(/\t/g, Array(this.opts.preSpaces + 1).join(' '));
  2213. }
  2214. html = this.clean.encodeEntities(html);
  2215. return html;
  2216. },
  2217. getOnlyImages: function(html)
  2218. {
  2219. html = html.replace(/<img(.*?)>/gi, '[img$1]');
  2220. // remove all tags
  2221. html = html.replace(/<([Ss]*?)>/gi, '');
  2222. html = html.replace(/\[img(.*?)\]/gi, '<img$1>');
  2223. return html;
  2224. },
  2225. getOnlyLinksAndImages: function(html)
  2226. {
  2227. html = html.replace(/<a(.*?)href="(.*?)"(.*?)>([\w\W]*?)<\/a>/gi, '[a href="$2"]$4[/a]');
  2228. html = html.replace(/<img(.*?)>/gi, '[img$1]');
  2229. // remove all tags
  2230. html = html.replace(/<(.*?)>/gi, '');
  2231. html = html.replace(/\[a href="(.*?)"\]([\w\W]*?)\[\/a\]/gi, '<a href="$1">$2</a>');
  2232. html = html.replace(/\[img(.*?)\]/gi, '<img$1>');
  2233. return html;
  2234. },
  2235. encodeEntities: function(str)
  2236. {
  2237. str = String(str).replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"');
  2238. return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  2239. },
  2240. removeDirtyStyles: function(html)
  2241. {
  2242. if (this.utils.browser('msie')) return html;
  2243. var div = document.createElement('div');
  2244. div.innerHTML = html;
  2245. this.clean.clearUnverifiedRemove($(div));
  2246. html = div.innerHTML;
  2247. $(div).remove();
  2248. return html;
  2249. },
  2250. clearUnverified: function()
  2251. {
  2252. if (this.utils.browser('msie')) return;
  2253. this.clean.clearUnverifiedRemove(this.$editor);
  2254. var headers = this.$editor.find('h1, h2, h3, h4, h5, h6');
  2255. headers.find('span').removeAttr('style');
  2256. headers.find(this.opts.verifiedTags.join(', ')).removeAttr('style');
  2257. this.code.sync();
  2258. },
  2259. clearUnverifiedRemove: function($editor)
  2260. {
  2261. $editor.find(this.opts.verifiedTags.join(', ')).removeAttr('style');
  2262. $editor.find('span').not('[data-verified="redactor"]').removeAttr('style');
  2263. $editor.find('span[data-verified="redactor"], img[data-verified="redactor"]').each(function(i, s)
  2264. {
  2265. var $s = $(s);
  2266. $s.attr('style', $s.attr('rel'));
  2267. });
  2268. },
  2269. cleanEmptyParagraph: function()
  2270. {
  2271. },
  2272. setVerified: function(html)
  2273. {
  2274. if (this.utils.browser('msie')) return html;
  2275. html = html.replace(new RegExp('<img(.*?[^>])>', 'gi'), '<img$1 data-verified="redactor">');
  2276. html = html.replace(new RegExp('<span(.*?[^>])>', 'gi'), '<span$1 data-verified="redactor">');
  2277. var matches = html.match(new RegExp('<(span|img)(.*?)style="(.*?)"(.*?[^>])>', 'gi'));
  2278. if (matches)
  2279. {
  2280. var len = matches.length;
  2281. for (var i = 0; i < len; i++)
  2282. {
  2283. try {
  2284. var newTag = matches[i].replace(/style="(.*?)"/i, 'style="$1" rel="$1"');
  2285. html = html.replace(matches[i], newTag);
  2286. }
  2287. catch (e) {}
  2288. }
  2289. }
  2290. return html;
  2291. },
  2292. convertInline: function(html)
  2293. {
  2294. var $div = $('<div />').html(html);
  2295. var tags = this.opts.inlineTags;
  2296. tags.push('span');
  2297. $div.find(tags.join(',')).each(function()
  2298. {
  2299. var $el = $(this);
  2300. var tag = this.tagName.toLowerCase();
  2301. $el.attr('data-redactor-tag', tag);
  2302. if (tag == 'span')
  2303. {
  2304. if ($el.attr('style')) $el.attr('data-redactor-style', $el.attr('style'));
  2305. else if ($el.attr('class')) $el.attr('data-redactor-class', $el.attr('class'));
  2306. }
  2307. });
  2308. html = $div.html();
  2309. $div.remove();
  2310. return html;
  2311. },
  2312. normalizeLists: function()
  2313. {
  2314. this.$editor.find('li').each(function(i,s)
  2315. {
  2316. var $next = $(s).next();
  2317. if ($next.length !== 0 && ($next[0].tagName == 'UL' || $next[0].tagName == 'OL'))
  2318. {
  2319. $(s).append($next);
  2320. }
  2321. });
  2322. },
  2323. removeSpaces: function(html)
  2324. {
  2325. html = html.replace(/\n/g, '');
  2326. html = html.replace(/[\t]*/g, '');
  2327. html = html.replace(/\n\s*\n/g, "\n");
  2328. html = html.replace(/^[\s\n]*/g, ' ');
  2329. html = html.replace(/[\s\n]*$/g, ' ');
  2330. html = html.replace( />\s{2,}</g, '> <'); // between inline tags can be only one space
  2331. html = html.replace(/\n\n/g, "\n");
  2332. html = html.replace(/\u200B/g, '');
  2333. return html;
  2334. },
  2335. replaceDivs: function(html)
  2336. {
  2337. if (this.opts.linebreaks)
  2338. {
  2339. html = html.replace(/<div><br\s?\/?><\/div>/gi, '<br />');
  2340. html = html.replace(/<div(.*?)>([\w\W]*?)<\/div>/gi, '$2<br />');
  2341. }
  2342. else
  2343. {
  2344. html = html.replace(/<div(.*?)>([\w\W]*?)<\/div>/gi, '<p$1>$2</p>');
  2345. }
  2346. html = html.replace(/<div(.*?[^>])>/gi, '');
  2347. html = html.replace(/<\/div>/gi, '');
  2348. return html;
  2349. },
  2350. replaceDivsToBr: function(html)
  2351. {
  2352. html = html.replace(/<div\s(.*?)>/gi, '<p>');
  2353. html = html.replace(/<div><br\s?\/?><\/div>/gi, '<br /><br />');
  2354. html = html.replace(/<div>([\w\W]*?)<\/div>/gi, '$1<br /><br />');
  2355. return html;
  2356. },
  2357. replaceParagraphsToBr: function(html)
  2358. {
  2359. html = html.replace(/<p\s(.*?)>/gi, '<p>');
  2360. html = html.replace(/<p><br\s?\/?><\/p>/gi, '<br />');
  2361. html = html.replace(/<p>([\w\W]*?)<\/p>/gi, '$1<br /><br />');
  2362. html = html.replace(/(<br\s?\/?>){1,}\n?<\/blockquote>/gi, '</blockquote>');
  2363. return html;
  2364. },
  2365. saveFormTags: function(html)
  2366. {
  2367. return html.replace(/<form(.*?)>([\w\W]*?)<\/form>/gi, '<section$1 rel="redactor-form-tag">$2</section>');
  2368. },
  2369. restoreFormTags: function(html)
  2370. {
  2371. return html.replace(/<section(.*?) rel="redactor-form-tag"(.*?)>([\w\W]*?)<\/section>/gi, '<form$1$2>$3</form>');
  2372. }
  2373. };
  2374. },
  2375. code: function()
  2376. {
  2377. return {
  2378. set: function(html)
  2379. {
  2380. html = $.trim(html.toString());
  2381. // clean
  2382. html = this.clean.onSet(html);
  2383. if (this.utils.browser('msie'))
  2384. {
  2385. html = html.replace(/<span(.*?)id="selection-marker-(1|2)"(.*?)><\/span>/gi, '');
  2386. }
  2387. this.$editor.html(html);
  2388. this.code.sync();
  2389. if (html !== '') this.placeholder.remove();
  2390. setTimeout($.proxy(this.buffer.add, this), 15);
  2391. if (this.start === false) this.observe.load();
  2392. },
  2393. get: function()
  2394. {
  2395. var code = this.$textarea.val();
  2396. if (this.opts.replaceDivs) code = this.clean.replaceDivs(code);
  2397. if (this.opts.linebreaks) code = this.clean.replaceParagraphsToBr(code);
  2398. // indent code
  2399. code = this.tabifier.get(code);
  2400. return code;
  2401. },
  2402. sync: function()
  2403. {
  2404. setTimeout($.proxy(this.code.startSync, this), 10);
  2405. },
  2406. startSync: function()
  2407. {
  2408. var html = this.$editor.html();
  2409. // is there a need to synchronize
  2410. if (this.code.syncCode && this.code.syncCode == html || (this.start && html == '' ))
  2411. {
  2412. // do not sync
  2413. return;
  2414. }
  2415. // save code
  2416. this.code.syncCode = html;
  2417. // before clean callback
  2418. html = this.core.setCallback('syncBefore', html);
  2419. // clean
  2420. html = this.clean.onSync(html);
  2421. // set code
  2422. this.$textarea.val(html);
  2423. // after sync callback
  2424. this.core.setCallback('sync', html);
  2425. if (this.start === false)
  2426. {
  2427. this.core.setCallback('change', html);
  2428. }
  2429. this.start = false;
  2430. if (this.autosave.html == false)
  2431. {
  2432. this.autosave.html = this.code.get();
  2433. }
  2434. if (this.opts.codemirror)
  2435. {
  2436. this.$textarea.next('.CodeMirror').each(function(i, el)
  2437. {
  2438. el.CodeMirror.setValue(html);
  2439. });
  2440. }
  2441. //autosave
  2442. this.autosave.onChange();
  2443. this.autosave.enable();
  2444. },
  2445. toggle: function()
  2446. {
  2447. if (this.opts.visual)
  2448. {
  2449. this.code.showCode();
  2450. }
  2451. else
  2452. {
  2453. this.code.showVisual();
  2454. }
  2455. },
  2456. showCode: function()
  2457. {
  2458. this.selection.save();
  2459. this.code.offset = this.caret.getOffset();
  2460. var scroll = $(window).scrollTop();
  2461. var width = this.$editor.innerWidth(),
  2462. height = this.$editor.innerHeight();
  2463. this.$editor.hide();
  2464. var html = this.$textarea.val();
  2465. this.modified = this.clean.removeSpaces(html);
  2466. // indent code
  2467. html = this.tabifier.get(html);
  2468. // caret position sync
  2469. var start = 0, end = 0;
  2470. var $editorDiv = $("<div/>").append($.parseHTML(this.clean.onSync(this.$editor.html()), document, true));
  2471. var $selectionMarkers = $editorDiv.find("span.redactor-selection-marker");
  2472. if ($selectionMarkers.length > 0)
  2473. {
  2474. var editorHtml = this.tabifier.get($editorDiv.html()).replace(/&amp;/g, '&');
  2475. if ($selectionMarkers.length == 1)
  2476. {
  2477. start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML"));
  2478. end = start;
  2479. }
  2480. else if ($selectionMarkers.length == 2)
  2481. {
  2482. start = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-1").prop("outerHTML"));
  2483. end = this.utils.strpos(editorHtml, $editorDiv.find("#selection-marker-2").prop("outerHTML")) - $editorDiv.find("#selection-marker-1").prop("outerHTML").toString().length;
  2484. }
  2485. }
  2486. this.selection.removeMarkers();
  2487. this.$textarea.val(html);
  2488. if (this.opts.codemirror)
  2489. {
  2490. this.$textarea.next('.CodeMirror').each(function(i, el)
  2491. {
  2492. $(el).show();
  2493. el.CodeMirror.setValue(html);
  2494. el.CodeMirror.setSize('100%', height);
  2495. el.CodeMirror.refresh();
  2496. if (start == end)
  2497. {
  2498. el.CodeMirror.setCursor(el.CodeMirror.posFromIndex(start).line, el.CodeMirror.posFromIndex(end).ch);
  2499. }
  2500. else
  2501. {
  2502. el.CodeMirror.setSelection({line: el.CodeMirror.posFromIndex(start).line,
  2503. ch: el.CodeMirror.posFromIndex(start).ch},
  2504. {line: el.CodeMirror.posFromIndex(end).line,
  2505. ch: el.CodeMirror.posFromIndex(end).ch});
  2506. }
  2507. el.CodeMirror.focus();
  2508. });
  2509. }
  2510. else
  2511. {
  2512. this.$textarea.height(height).show().focus();
  2513. this.$textarea.on('keydown.redactor-textarea-indenting', this.code.textareaIndenting);
  2514. $(window).scrollTop(scroll);
  2515. if (this.$textarea[0].setSelectionRange)
  2516. {
  2517. this.$textarea[0].setSelectionRange(start, end);
  2518. }
  2519. this.$textarea[0].scrollTop = 0;
  2520. }
  2521. this.opts.visual = false;
  2522. this.button.setInactiveInCode();
  2523. this.button.setActive('html');
  2524. this.core.setCallback('source', html);
  2525. },
  2526. showVisual: function()
  2527. {
  2528. var html;
  2529. if (this.opts.visual) return;
  2530. var start = 0, end = 0;
  2531. if (this.opts.codemirror)
  2532. {
  2533. var selection;
  2534. this.$textarea.next('.CodeMirror').each(function(i, el)
  2535. {
  2536. selection = el.CodeMirror.listSelections();
  2537. start = el.CodeMirror.indexFromPos(selection[0].anchor);
  2538. end = el.CodeMirror.indexFromPos(selection[0].head);
  2539. html = el.CodeMirror.getValue();
  2540. });
  2541. }
  2542. else
  2543. {
  2544. start = this.$textarea.get(0).selectionStart;
  2545. end = this.$textarea.get(0).selectionEnd;
  2546. html = this.$textarea.hide().val();
  2547. }
  2548. // if selection starts from end
  2549. if (start > end && end > 0)
  2550. {
  2551. var tempStart = end;
  2552. var tempEnd = start;
  2553. start = tempStart;
  2554. end = tempEnd;
  2555. }
  2556. start = this.code.enlargeOffset(html, start);
  2557. end = this.code.enlargeOffset(html, end);
  2558. html = html.substr(0, start) + this.selection.getMarkerAsHtml(1) + html.substr(start);
  2559. if (end > start)
  2560. {
  2561. var markerLength = this.selection.getMarkerAsHtml(1).toString().length;
  2562. html = html.substr(0, end + markerLength) + this.selection.getMarkerAsHtml(2) + html.substr(end + markerLength);
  2563. }
  2564. if (this.modified !== this.clean.removeSpaces(html))
  2565. {
  2566. this.code.set(html);
  2567. }
  2568. if (this.opts.codemirror)
  2569. {
  2570. this.$textarea.next('.CodeMirror').hide();
  2571. }
  2572. this.$editor.show();
  2573. if (!this.utils.isEmpty(html))
  2574. {
  2575. this.placeholder.remove();
  2576. }
  2577. this.selection.restore();
  2578. this.$textarea.off('keydown.redactor-textarea-indenting');
  2579. this.button.setActiveInVisual();
  2580. this.button.setInactive('html');
  2581. this.observe.load();
  2582. this.opts.visual = true;
  2583. this.core.setCallback('visual', html);
  2584. },
  2585. textareaIndenting: function(e)
  2586. {
  2587. if (e.keyCode !== 9) return true;
  2588. var $el = this.$textarea;
  2589. var start = $el.get(0).selectionStart;
  2590. $el.val($el.val().substring(0, start) + "\t" + $el.val().substring($el.get(0).selectionEnd));
  2591. $el.get(0).selectionStart = $el.get(0).selectionEnd = start + 1;
  2592. return false;
  2593. },
  2594. enlargeOffset: function(html, offset)
  2595. {
  2596. var htmlLength = html.length;
  2597. var c = 0;
  2598. if (html[offset] == '>')
  2599. {
  2600. c++;
  2601. }
  2602. else
  2603. {
  2604. for(var i = offset; i <= htmlLength; i++)
  2605. {
  2606. c++;
  2607. if (html[i] == '>')
  2608. {
  2609. break;
  2610. }
  2611. else if (html[i] == '<' || i == htmlLength)
  2612. {
  2613. c = 0;
  2614. break;
  2615. }
  2616. }
  2617. }
  2618. return offset + c;
  2619. }
  2620. };
  2621. },
  2622. core: function()
  2623. {
  2624. return {
  2625. getObject: function()
  2626. {
  2627. return $.extend({}, this);
  2628. },
  2629. getEditor: function()
  2630. {
  2631. return this.$editor;
  2632. },
  2633. getBox: function()
  2634. {
  2635. return this.$box;
  2636. },
  2637. getElement: function()
  2638. {
  2639. return this.$element;
  2640. },
  2641. getTextarea: function()
  2642. {
  2643. return this.$textarea;
  2644. },
  2645. getToolbar: function()
  2646. {
  2647. return (this.$toolbar) ? this.$toolbar : false;
  2648. },
  2649. addEvent: function(name)
  2650. {
  2651. this.core.event = name;
  2652. },
  2653. getEvent: function()
  2654. {
  2655. return this.core.event;
  2656. },
  2657. setCallback: function(type, e, data)
  2658. {
  2659. var eventName = type + 'Callback';
  2660. var eventNamespace = 'redactor';
  2661. var callback = this.opts[eventName];
  2662. if (this.$textarea)
  2663. {
  2664. var returnValue = false;
  2665. var events = $._data(this.$textarea[0], 'events');
  2666. if (typeof events != 'undefined' && typeof events[eventName] != 'undefined')
  2667. {
  2668. $.each(events[eventName], $.proxy(function(key, value)
  2669. {
  2670. if (value['namespace'] == eventNamespace)
  2671. {
  2672. var data = (typeof data == 'undefined') ? [e] : [e, data];
  2673. returnValue = (typeof data == 'undefined') ? value.handler.call(this, e) : value.handler.call(this, e, data);
  2674. }
  2675. }, this));
  2676. }
  2677. if (returnValue) return returnValue;
  2678. }
  2679. if ($.isFunction(callback))
  2680. {
  2681. return (typeof data == 'undefined') ? callback.call(this, e) : callback.call(this, e, data);
  2682. }
  2683. else
  2684. {
  2685. return (typeof data == 'undefined') ? e : data;
  2686. }
  2687. },
  2688. destroy: function()
  2689. {
  2690. this.opts.destroyed = true;
  2691. this.core.setCallback('destroy');
  2692. // off events and remove data
  2693. this.$element.off('.redactor').removeData('redactor');
  2694. this.$editor.off('.redactor');
  2695. $(document).off('mousedown.redactor-blur.' + this.uuid);
  2696. $(document).off('mousedown.redactor.' + this.uuid);
  2697. $(document).off('click.redactor-image-delete.' + this.uuid);
  2698. $(document).off('click.redactor-image-resize-hide.' + this.uuid);
  2699. $(document).off('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid);
  2700. $("body").off('scroll.redactor.' + this.uuid);
  2701. $(this.opts.toolbarFixedTarget).off('scroll.redactor.' + this.uuid);
  2702. // common
  2703. this.$editor.removeClass('redactor-editor redactor-linebreaks redactor-placeholder');
  2704. this.$editor.removeAttr('contenteditable');
  2705. var html = this.code.get();
  2706. if (this.opts.toolbar)
  2707. {
  2708. // dropdowns off
  2709. this.$toolbar.find('a').each(function()
  2710. {
  2711. var $el = $(this);
  2712. if ($el.data('dropdown'))
  2713. {
  2714. $el.data('dropdown').remove();
  2715. $el.data('dropdown', {});
  2716. }
  2717. });
  2718. }
  2719. if (this.build.isTextarea())
  2720. {
  2721. this.$box.after(this.$element);
  2722. this.$box.remove();
  2723. this.$element.val(html).show();
  2724. }
  2725. else
  2726. {
  2727. this.$box.after(this.$editor);
  2728. this.$box.remove();
  2729. this.$element.html(html).show();
  2730. }
  2731. // paste box
  2732. if (this.$pasteBox) this.$pasteBox.remove();
  2733. // modal
  2734. if (this.$modalBox) this.$modalBox.remove();
  2735. if (this.$modalOverlay) this.$modalOverlay.remove();
  2736. // buttons tooltip
  2737. $('.redactor-toolbar-tooltip-' + this.uuid).remove();
  2738. // autosave
  2739. clearInterval(this.autosaveInterval);
  2740. }
  2741. };
  2742. },
  2743. dropdown: function()
  2744. {
  2745. return {
  2746. build: function(name, $dropdown, dropdownObject)
  2747. {
  2748. if (name == 'formatting' && this.opts.formattingAdd)
  2749. {
  2750. $.each(this.opts.formattingAdd, $.proxy(function(i,s)
  2751. {
  2752. var name = s.tag,
  2753. func;
  2754. if (typeof s['class'] != 'undefined')
  2755. {
  2756. name = name + '-' + s['class'];
  2757. }
  2758. s.type = (this.utils.isBlockTag(s.tag)) ? 'block' : 'inline';
  2759. if (typeof s.func !== "undefined")
  2760. {
  2761. func = s.func;
  2762. }
  2763. else
  2764. {
  2765. func = (s.type == 'inline') ? 'inline.formatting' : 'block.formatting';
  2766. }
  2767. if (this.opts.linebreaks && s.type == 'block' && s.tag == 'p') return;
  2768. this.formatting[name] = {
  2769. tag: s.tag,
  2770. style: s.style,
  2771. 'class': s['class'],
  2772. attr: s.attr,
  2773. data: s.data,
  2774. clear: s.clear
  2775. };
  2776. dropdownObject[name] = {
  2777. func: func,
  2778. title: s.title
  2779. };
  2780. }, this));
  2781. }
  2782. $.each(dropdownObject, $.proxy(function(btnName, btnObject)
  2783. {
  2784. var $item = $('<a href="#" class="redactor-dropdown-' + btnName + '" role="button">' + btnObject.title + '</a>');
  2785. if (name == 'formatting') $item.addClass('redactor-formatting-' + btnName);
  2786. $item.on('click', $.proxy(function(e)
  2787. {
  2788. e.preventDefault();
  2789. var type = 'func';
  2790. var callback = btnObject.func;
  2791. if (btnObject.command)
  2792. {
  2793. type = 'command';
  2794. callback = btnObject.command;
  2795. }
  2796. else if (btnObject.dropdown)
  2797. {
  2798. type = 'dropdown';
  2799. callback = btnObject.dropdown;
  2800. }
  2801. if ($(e.target).hasClass('redactor-dropdown-link-inactive')) return;
  2802. this.button.onClick(e, btnName, type, callback);
  2803. this.dropdown.hideAll();
  2804. }, this));
  2805. this.observe.addDropdown($item, btnName, btnObject);
  2806. $dropdown.append($item);
  2807. }, this));
  2808. },
  2809. show: function(e, key)
  2810. {
  2811. if (!this.opts.visual)
  2812. {
  2813. e.preventDefault();
  2814. return false;
  2815. }
  2816. var $button = this.button.get(key);
  2817. // Always re-append it to the end of <body> so it always has the highest sub-z-index.
  2818. var $dropdown = $button.data('dropdown').appendTo(document.body);
  2819. if (this.opts.highContrast)
  2820. {
  2821. $dropdown.addClass("redactor-dropdown-contrast");
  2822. }
  2823. if ($button.hasClass('dropact'))
  2824. {
  2825. this.dropdown.hideAll();
  2826. }
  2827. else
  2828. {
  2829. this.dropdown.hideAll();
  2830. this.observe.dropdowns();
  2831. this.core.setCallback('dropdownShow', { dropdown: $dropdown, key: key, button: $button });
  2832. this.button.setActive(key);
  2833. $button.addClass('dropact');
  2834. var keyPosition = $button.offset();
  2835. // fix right placement
  2836. var dropdownWidth = $dropdown.width();
  2837. if ((keyPosition.left + dropdownWidth) > $(document).width())
  2838. {
  2839. keyPosition.left = Math.max(0, keyPosition.left - dropdownWidth);
  2840. }
  2841. var left = keyPosition.left + 'px';
  2842. if (this.$toolbar.hasClass('toolbar-fixed-box'))
  2843. {
  2844. var top = this.$toolbar.innerHeight() + this.opts.toolbarFixedTopOffset;
  2845. var position = 'fixed';
  2846. if (this.opts.toolbarFixedTarget !== document)
  2847. {
  2848. top = (this.$toolbar.innerHeight() + this.$toolbar.offset().top) + this.opts.toolbarFixedTopOffset;
  2849. position = 'absolute';
  2850. }
  2851. $dropdown.css({ position: position, left: left, top: top + 'px' }).show();
  2852. }
  2853. else
  2854. {
  2855. var top = ($button.innerHeight() + keyPosition.top) + 'px';
  2856. $dropdown.css({ position: 'absolute', left: left, top: top }).show();
  2857. }
  2858. this.core.setCallback('dropdownShown', { dropdown: $dropdown, key: key, button: $button });
  2859. this.$dropdown = $dropdown;
  2860. }
  2861. $(document).one('click.redactor-dropdown', $.proxy(this.dropdown.hide, this));
  2862. this.$editor.one('click.redactor-dropdown', $.proxy(this.dropdown.hide, this));
  2863. $(document).one('keyup.redactor-dropdown', $.proxy(this.dropdown.closeHandler, this));
  2864. // disable scroll whan dropdown scroll
  2865. $dropdown.on('mouseover.redactor-dropdown', $.proxy(this.utils.disableBodyScroll, this)).on('mouseout.redactor-dropdown', $.proxy(this.utils.enableBodyScroll, this));
  2866. e.stopPropagation();
  2867. },
  2868. closeHandler: function(e)
  2869. {
  2870. if (e.which != this.keyCode.ESC) return;
  2871. this.dropdown.hideAll();
  2872. this.$editor.focus();
  2873. },
  2874. hideAll: function()
  2875. {
  2876. this.$toolbar.find('a.dropact').removeClass('redactor-act').removeClass('dropact');
  2877. this.utils.enableBodyScroll();
  2878. $('.redactor-dropdown-' + this.uuid).hide();
  2879. $('.redactor-dropdown-link-selected').removeClass('redactor-dropdown-link-selected');
  2880. if (this.$dropdown)
  2881. {
  2882. this.$dropdown.off('.redactor-dropdown');
  2883. this.core.setCallback('dropdownHide', this.$dropdown);
  2884. this.$dropdown = false;
  2885. }
  2886. },
  2887. hide: function (e)
  2888. {
  2889. var $dropdown = $(e.target);
  2890. if (!$dropdown.hasClass('dropact') && !$dropdown.hasClass('redactor-dropdown-link-inactive'))
  2891. {
  2892. if ($dropdown.hasClass('redactor-dropdown'))
  2893. {
  2894. $dropdown.removeClass('dropact');
  2895. $dropdown.off('mouseover mouseout');
  2896. }
  2897. this.dropdown.hideAll();
  2898. }
  2899. }
  2900. };
  2901. },
  2902. file: function()
  2903. {
  2904. return {
  2905. show: function()
  2906. {
  2907. this.modal.load('file', this.lang.get('file'), 700);
  2908. this.upload.init('#redactor-modal-file-upload', this.opts.fileUpload, this.file.insert);
  2909. this.selection.save();
  2910. this.selection.get();
  2911. var text = this.sel.toString();
  2912. $('#redactor-filename').val(text);
  2913. this.modal.show();
  2914. },
  2915. insert: function(json, direct, e)
  2916. {
  2917. // error callback
  2918. if (typeof json.error != 'undefined')
  2919. {
  2920. this.modal.close();
  2921. this.selection.restore();
  2922. this.core.setCallback('fileUploadError', json);
  2923. return;
  2924. }
  2925. var link;
  2926. if (typeof json == 'string')
  2927. {
  2928. link = json;
  2929. }
  2930. else
  2931. {
  2932. var text = $('#redactor-filename').val();
  2933. if (typeof text == 'undefined' || text === '') text = json.filename;
  2934. link = '<a href="' + json.filelink + '" id="filelink-marker">' + text + '</a>';
  2935. }
  2936. if (direct)
  2937. {
  2938. this.selection.removeMarkers();
  2939. var marker = this.selection.getMarker();
  2940. this.insert.nodeToCaretPositionFromPoint(e, marker);
  2941. }
  2942. else
  2943. {
  2944. this.modal.close();
  2945. }
  2946. this.selection.restore();
  2947. this.buffer.set();
  2948. this.insert.htmlWithoutClean(link);
  2949. if (typeof json == 'string') return;
  2950. var linkmarker = $(this.$editor.find('a#filelink-marker'));
  2951. if (linkmarker.length !== 0)
  2952. {
  2953. linkmarker.removeAttr('id').removeAttr('style');
  2954. }
  2955. else linkmarker = false;
  2956. this.core.setCallback('fileUpload', linkmarker, json);
  2957. }
  2958. };
  2959. },
  2960. focus: function()
  2961. {
  2962. return {
  2963. setStart: function()
  2964. {
  2965. this.$editor.focus();
  2966. var first = this.$editor.children().first();
  2967. if (first.length === 0) return;
  2968. if (first[0].length === 0 || first[0].tagName == 'BR' || first[0].nodeType == 3)
  2969. {
  2970. return;
  2971. }
  2972. if (first[0].tagName == 'UL' || first[0].tagName == 'OL')
  2973. {
  2974. var child = first.find('li').first();
  2975. if (!this.utils.isBlock(child) && child.text() === '')
  2976. {
  2977. // empty inline tag in li
  2978. this.caret.setStart(child);
  2979. return;
  2980. }
  2981. }
  2982. if (this.opts.linebreaks && !this.utils.isBlockTag(first[0].tagName))
  2983. {
  2984. this.selection.get();
  2985. this.range.setStart(this.$editor[0], 0);
  2986. this.range.setEnd(this.$editor[0], 0);
  2987. this.selection.addRange();
  2988. return;
  2989. }
  2990. // if node is tag
  2991. this.caret.setStart(first);
  2992. },
  2993. setEnd: function()
  2994. {
  2995. var last = this.$editor.children().last();
  2996. this.$editor.focus();
  2997. if (last.size() === 0) return;
  2998. if (this.utils.isEmpty(this.$editor.html()))
  2999. {
  3000. this.selection.get();
  3001. this.range.collapse(true);
  3002. this.range.setStartAfter(last[0]);
  3003. this.range.setEnd(last[0], 0);
  3004. this.selection.addRange();
  3005. }
  3006. else
  3007. {
  3008. this.selection.get();
  3009. this.range.selectNodeContents(last[0]);
  3010. this.range.collapse(false);
  3011. this.selection.addRange();
  3012. }
  3013. },
  3014. isFocused: function()
  3015. {
  3016. return this.$editor[0] === document.activeElement;
  3017. }
  3018. };
  3019. },
  3020. image: function()
  3021. {
  3022. return {
  3023. show: function()
  3024. {
  3025. this.modal.load('image', this.lang.get('image'), 700);
  3026. this.upload.init('#redactor-modal-image-droparea', this.opts.imageUpload, this.image.insert);
  3027. this.selection.save();
  3028. this.modal.show();
  3029. },
  3030. showEdit: function($image)
  3031. {
  3032. var $link = $image.closest('a', this.$editor[0]);
  3033. this.modal.load('imageEdit', this.lang.get('edit'), 705);
  3034. this.modal.createCancelButton();
  3035. this.image.buttonDelete = this.modal.createDeleteButton(this.lang.get('_delete'));
  3036. this.image.buttonSave = this.modal.createActionButton(this.lang.get('save'));
  3037. this.image.buttonDelete.on('click', $.proxy(function()
  3038. {
  3039. this.image.remove($image);
  3040. }, this));
  3041. this.image.buttonSave.on('click', $.proxy(function()
  3042. {
  3043. this.image.update($image);
  3044. }, this));
  3045. // hide link's tooltip
  3046. $('.redactor-link-tooltip').remove();
  3047. $('#redactor-image-title').val($image.attr('alt'));
  3048. if (!this.opts.imageLink) $('.redactor-image-link-option').hide();
  3049. else
  3050. {
  3051. var $redactorImageLink = $('#redactor-image-link');
  3052. $redactorImageLink.attr('href', $image.attr('src'));
  3053. if ($link.length !== 0)
  3054. {
  3055. $redactorImageLink.val($link.attr('href'));
  3056. if ($link.attr('target') == '_blank') $('#redactor-image-link-blank').prop('checked', true);
  3057. }
  3058. }
  3059. if (!this.opts.imagePosition) $('.redactor-image-position-option').hide();
  3060. else
  3061. {
  3062. var floatValue = ($image.css('display') == 'block' && $image.css('float') == 'none') ? 'center' : $image.css('float');
  3063. $('#redactor-image-align').val(floatValue);
  3064. }
  3065. this.modal.show();
  3066. $('#redactor-image-title').focus();
  3067. },
  3068. setFloating: function($image)
  3069. {
  3070. var floating = $('#redactor-image-align').val();
  3071. var imageFloat = '';
  3072. var imageDisplay = '';
  3073. var imageMargin = '';
  3074. switch (floating)
  3075. {
  3076. case 'left':
  3077. imageFloat = 'left';
  3078. imageMargin = '0 ' + this.opts.imageFloatMargin + ' ' + this.opts.imageFloatMargin + ' 0';
  3079. break;
  3080. case 'right':
  3081. imageFloat = 'right';
  3082. imageMargin = '0 0 ' + this.opts.imageFloatMargin + ' ' + this.opts.imageFloatMargin;
  3083. break;
  3084. case 'center':
  3085. imageDisplay = 'block';
  3086. imageMargin = 'auto';
  3087. break;
  3088. }
  3089. $image.css({ 'float': imageFloat, display: imageDisplay, margin: imageMargin });
  3090. $image.attr('rel', $image.attr('style'));
  3091. },
  3092. update: function($image)
  3093. {
  3094. this.image.hideResize();
  3095. this.buffer.set();
  3096. var $link = $image.closest('a', this.$editor[0]);
  3097. var title = $('#redactor-image-title').val().replace(/(<([^>]+)>)/ig,"");
  3098. $image.attr('alt', title);
  3099. this.image.setFloating($image);
  3100. // as link
  3101. var link = $.trim($('#redactor-image-link').val());
  3102. var link = link.replace(/(<([^>]+)>)/ig,"");
  3103. if (link !== '')
  3104. {
  3105. // test url (add protocol)
  3106. var pattern = '((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}';
  3107. var re = new RegExp('^(http|ftp|https)://' + pattern, 'i');
  3108. var re2 = new RegExp('^' + pattern, 'i');
  3109. if (link.search(re) == -1 && link.search(re2) === 0 && this.opts.linkProtocol)
  3110. {
  3111. link = this.opts.linkProtocol + '://' + link;
  3112. }
  3113. var target = ($('#redactor-image-link-blank').prop('checked')) ? true : false;
  3114. if ($link.length === 0)
  3115. {
  3116. var a = $('<a href="' + link + '">' + this.utils.getOuterHtml($image) + '</a>');
  3117. if (target) a.attr('target', '_blank');
  3118. $image.replaceWith(a);
  3119. }
  3120. else
  3121. {
  3122. $link.attr('href', link);
  3123. if (target)
  3124. {
  3125. $link.attr('target', '_blank');
  3126. }
  3127. else
  3128. {
  3129. $link.removeAttr('target');
  3130. }
  3131. }
  3132. }
  3133. else if ($link.length !== 0)
  3134. {
  3135. $link.replaceWith(this.utils.getOuterHtml($image));
  3136. }
  3137. this.modal.close();
  3138. this.observe.images();
  3139. this.code.sync();
  3140. },
  3141. setEditable: function($image)
  3142. {
  3143. if (this.opts.imageEditable)
  3144. {
  3145. $image.on('dragstart', $.proxy(this.image.onDrag, this));
  3146. }
  3147. var handler = $.proxy(function(e)
  3148. {
  3149. this.observe.image = $image;
  3150. this.image.resizer = this.image.loadEditableControls($image);
  3151. $(document).on('mousedown.redactor-image-resize-hide.' + this.uuid, $.proxy(this.image.hideResize, this));
  3152. // resize
  3153. if (!this.opts.imageResizable) return;
  3154. this.image.resizer.on('mousedown.redactor touchstart.redactor', $.proxy(function(e)
  3155. {
  3156. this.image.setResizable(e, $image);
  3157. }, this));
  3158. }, this);
  3159. $image.off('mousedown.redactor').on('mousedown.redactor', $.proxy(this.image.hideResize, this));
  3160. $image.off('click.redactor touchstart.redactor').on('click.redactor touchstart.redactor', handler);
  3161. },
  3162. setResizable: function(e, $image)
  3163. {
  3164. e.preventDefault();
  3165. this.image.resizeHandle = {
  3166. x : e.pageX,
  3167. y : e.pageY,
  3168. el : $image,
  3169. ratio: $image.width() / $image.height(),
  3170. h: $image.height()
  3171. };
  3172. e = e.originalEvent || e;
  3173. if (e.targetTouches)
  3174. {
  3175. this.image.resizeHandle.x = e.targetTouches[0].pageX;
  3176. this.image.resizeHandle.y = e.targetTouches[0].pageY;
  3177. }
  3178. this.image.startResize();
  3179. },
  3180. startResize: function()
  3181. {
  3182. $(document).on('mousemove.redactor-image-resize touchmove.redactor-image-resize', $.proxy(this.image.moveResize, this));
  3183. $(document).on('mouseup.redactor-image-resize touchend.redactor-image-resize', $.proxy(this.image.stopResize, this));
  3184. },
  3185. moveResize: function(e)
  3186. {
  3187. e.preventDefault();
  3188. e = e.originalEvent || e;
  3189. var height = this.image.resizeHandle.h;
  3190. if (e.targetTouches) height += (e.targetTouches[0].pageY - this.image.resizeHandle.y);
  3191. else height += (e.pageY - this.image.resizeHandle.y);
  3192. var width = Math.round(height * this.image.resizeHandle.ratio);
  3193. if (height < 50 || width < 100) return;
  3194. var height = Math.round(this.image.resizeHandle.el.width() / this.image.resizeHandle.ratio);
  3195. this.image.resizeHandle.el.attr({width: width, height: height});
  3196. this.image.resizeHandle.el.width(width);
  3197. this.image.resizeHandle.el.height(height);
  3198. this.code.sync();
  3199. },
  3200. stopResize: function()
  3201. {
  3202. this.handle = false;
  3203. $(document).off('.redactor-image-resize');
  3204. this.image.hideResize();
  3205. },
  3206. onDrag: function(e)
  3207. {
  3208. if (this.$editor.find('#redactor-image-box').length !== 0)
  3209. {
  3210. e.preventDefault();
  3211. return false;
  3212. }
  3213. this.$editor.on('drop.redactor-image-inside-drop', $.proxy(function()
  3214. {
  3215. setTimeout($.proxy(this.image.onDrop, this), 1);
  3216. }, this));
  3217. },
  3218. onDrop: function()
  3219. {
  3220. this.image.fixImageSourceAfterDrop();
  3221. this.observe.images();
  3222. this.$editor.off('drop.redactor-image-inside-drop');
  3223. this.clean.clearUnverified();
  3224. this.code.sync();
  3225. },
  3226. fixImageSourceAfterDrop: function()
  3227. {
  3228. this.$editor.find('img[data-save-url]').each(function()
  3229. {
  3230. var $el = $(this);
  3231. $el.attr('src', $el.attr('data-save-url'));
  3232. $el.removeAttr('data-save-url');
  3233. });
  3234. },
  3235. hideResize: function(e)
  3236. {
  3237. if (e && $(e.target).closest('#redactor-image-box', this.$editor[0]).length !== 0) return;
  3238. if (e && e.target.tagName == 'IMG')
  3239. {
  3240. var $image = $(e.target);
  3241. $image.attr('data-save-url', $image.attr('src'));
  3242. }
  3243. var imageBox = this.$editor.find('#redactor-image-box');
  3244. if (imageBox.length === 0) return;
  3245. $('#redactor-image-editter').remove();
  3246. $('#redactor-image-resizer').remove();
  3247. imageBox.find('img').css({
  3248. marginTop: imageBox[0].style.marginTop,
  3249. marginBottom: imageBox[0].style.marginBottom,
  3250. marginLeft: imageBox[0].style.marginLeft,
  3251. marginRight: imageBox[0].style.marginRight
  3252. });
  3253. imageBox.css('margin', '');
  3254. imageBox.find('img').css('opacity', '');
  3255. imageBox.replaceWith(function()
  3256. {
  3257. return $(this).contents();
  3258. });
  3259. $(document).off('mousedown.redactor-image-resize-hide.' + this.uuid);
  3260. if (typeof this.image.resizeHandle !== 'undefined')
  3261. {
  3262. this.image.resizeHandle.el.attr('rel', this.image.resizeHandle.el.attr('style'));
  3263. }
  3264. this.code.sync();
  3265. },
  3266. loadResizableControls: function($image, imageBox)
  3267. {
  3268. if (this.opts.imageResizable && !this.utils.isMobile())
  3269. {
  3270. var imageResizer = $('<span id="redactor-image-resizer" data-redactor="verified"></span>');
  3271. if (!this.utils.isDesktop())
  3272. {
  3273. imageResizer.css({ width: '15px', height: '15px' });
  3274. }
  3275. imageResizer.attr('contenteditable', false);
  3276. imageBox.append(imageResizer);
  3277. imageBox.append($image);
  3278. return imageResizer;
  3279. }
  3280. else
  3281. {
  3282. imageBox.append($image);
  3283. return false;
  3284. }
  3285. },
  3286. loadEditableControls: function($image)
  3287. {
  3288. var imageBox = $('<span id="redactor-image-box" data-redactor="verified">');
  3289. imageBox.css('float', $image.css('float')).attr('contenteditable', false);
  3290. if ($image[0].style.margin != 'auto')
  3291. {
  3292. imageBox.css({
  3293. marginTop: $image[0].style.marginTop,
  3294. marginBottom: $image[0].style.marginBottom,
  3295. marginLeft: $image[0].style.marginLeft,
  3296. marginRight: $image[0].style.marginRight
  3297. });
  3298. $image.css('margin', '');
  3299. }
  3300. else
  3301. {
  3302. imageBox.css({ 'display': 'block', 'margin': 'auto' });
  3303. }
  3304. $image.css('opacity', '.5').after(imageBox);
  3305. if (this.opts.imageEditable)
  3306. {
  3307. // editter
  3308. this.image.editter = $('<span id="redactor-image-editter" data-redactor="verified">' + this.lang.get('edit') + '</span>');
  3309. this.image.editter.attr('contenteditable', false);
  3310. this.image.editter.on('click', $.proxy(function()
  3311. {
  3312. this.image.showEdit($image);
  3313. }, this));
  3314. imageBox.append(this.image.editter);
  3315. // position correction
  3316. var editerWidth = this.image.editter.innerWidth();
  3317. this.image.editter.css('margin-left', '-' + editerWidth/2 + 'px');
  3318. }
  3319. return this.image.loadResizableControls($image, imageBox);
  3320. },
  3321. remove: function(image)
  3322. {
  3323. var $image = $(image);
  3324. var $link = $image.closest('a', this.$editor[0]);
  3325. var $figure = $image.closest('figure', this.$editor[0]);
  3326. var $parent = $image.parent();
  3327. if ($('#redactor-image-box').length !== 0)
  3328. {
  3329. $parent = $('#redactor-image-box').parent();
  3330. }
  3331. var $next;
  3332. if ($figure.length !== 0)
  3333. {
  3334. $next = $figure.next();
  3335. $figure.remove();
  3336. }
  3337. else if ($link.length !== 0)
  3338. {
  3339. $parent = $link.parent();
  3340. $link.remove();
  3341. }
  3342. else
  3343. {
  3344. $image.remove();
  3345. }
  3346. $('#redactor-image-box').remove();
  3347. if ($figure.length !== 0)
  3348. {
  3349. this.caret.setStart($next);
  3350. }
  3351. else
  3352. {
  3353. this.caret.setStart($parent);
  3354. }
  3355. // delete callback
  3356. this.core.setCallback('imageDelete', $image[0].src, $image);
  3357. this.modal.close();
  3358. this.code.sync();
  3359. },
  3360. insert: function(json, direct, e)
  3361. {
  3362. // error callback
  3363. if (typeof json.error != 'undefined')
  3364. {
  3365. this.modal.close();
  3366. this.selection.restore();
  3367. this.core.setCallback('imageUploadError', json);
  3368. return;
  3369. }
  3370. var $img;
  3371. if (typeof json == 'string')
  3372. {
  3373. $img = $(json).attr('data-redactor-inserted-image', 'true');
  3374. }
  3375. else
  3376. {
  3377. $img = $('<img>');
  3378. $img.attr('src', json.filelink).attr('data-redactor-inserted-image', 'true');
  3379. }
  3380. var node = $img;
  3381. var isP = this.utils.isCurrentOrParent('P');
  3382. if (isP)
  3383. {
  3384. // will replace
  3385. node = $('<blockquote />').append($img);
  3386. }
  3387. if (direct)
  3388. {
  3389. this.selection.removeMarkers();
  3390. var marker = this.selection.getMarker();
  3391. this.insert.nodeToCaretPositionFromPoint(e, marker);
  3392. }
  3393. else
  3394. {
  3395. this.modal.close();
  3396. }
  3397. this.selection.restore();
  3398. this.buffer.set();
  3399. this.insert.html(this.utils.getOuterHtml(node), false);
  3400. var $image = this.$editor.find('img[data-redactor-inserted-image=true]').removeAttr('data-redactor-inserted-image');
  3401. if (isP)
  3402. {
  3403. $image.parent().contents().unwrap().wrap('<p />');
  3404. }
  3405. else if (this.opts.linebreaks)
  3406. {
  3407. if (!this.utils.isEmpty(this.code.get()))
  3408. {
  3409. $image.before('<br>');
  3410. }
  3411. $image.after('<br>');
  3412. }
  3413. if (typeof json == 'string') return;
  3414. this.core.setCallback('imageUpload', $image, json);
  3415. }
  3416. };
  3417. },
  3418. indent: function()
  3419. {
  3420. return {
  3421. increase: function()
  3422. {
  3423. // focus
  3424. if (!this.utils.browser('msie')) this.$editor.focus();
  3425. this.buffer.set();
  3426. this.selection.save();
  3427. var block = this.selection.getBlock();
  3428. if (block && block.tagName == 'LI')
  3429. {
  3430. this.indent.increaseLists();
  3431. }
  3432. else if (block === false && this.opts.linebreaks)
  3433. {
  3434. this.indent.increaseText();
  3435. }
  3436. else
  3437. {
  3438. this.indent.increaseBlocks();
  3439. }
  3440. this.selection.restore();
  3441. this.code.sync();
  3442. },
  3443. increaseLists: function()
  3444. {
  3445. document.execCommand('indent');
  3446. this.indent.fixEmptyIndent();
  3447. this.clean.normalizeLists();
  3448. this.clean.clearUnverified();
  3449. },
  3450. increaseBlocks: function()
  3451. {
  3452. $.each(this.selection.getBlocks(), $.proxy(function(i, elem)
  3453. {
  3454. if (elem.tagName === 'TD' || elem.tagName === 'TH') return;
  3455. var $el = this.utils.getAlignmentElement(elem);
  3456. var left = this.utils.normalize($el.css('margin-left')) + this.opts.indentValue;
  3457. $el.css('margin-left', left + 'px');
  3458. }, this));
  3459. },
  3460. increaseText: function()
  3461. {
  3462. var wrapper = this.selection.wrap('div');
  3463. $(wrapper).attr('data-tagblock', 'redactor');
  3464. $(wrapper).css('margin-left', this.opts.indentValue + 'px');
  3465. },
  3466. decrease: function()
  3467. {
  3468. this.buffer.set();
  3469. this.selection.save();
  3470. var block = this.selection.getBlock();
  3471. if (block && block.tagName == 'LI')
  3472. {
  3473. this.indent.decreaseLists();
  3474. }
  3475. else
  3476. {
  3477. this.indent.decreaseBlocks();
  3478. }
  3479. this.selection.restore();
  3480. this.code.sync();
  3481. },
  3482. decreaseLists: function()
  3483. {
  3484. document.execCommand('outdent');
  3485. var current = this.selection.getCurrent();
  3486. var $item = $(current).closest('li', this.$editor[0]);
  3487. this.indent.fixEmptyIndent();
  3488. if (!this.opts.linebreaks && $item.length === 0)
  3489. {
  3490. document.execCommand('formatblock', false, 'p');
  3491. this.$editor.find('ul, ol, blockquote, p').each($.proxy(this.utils.removeEmpty, this));
  3492. }
  3493. this.clean.clearUnverified();
  3494. },
  3495. decreaseBlocks: function()
  3496. {
  3497. $.each(this.selection.getBlocks(), $.proxy(function(i, elem)
  3498. {
  3499. var $el = this.utils.getAlignmentElement(elem);
  3500. var left = this.utils.normalize($el.css('margin-left')) - this.opts.indentValue;
  3501. if (left <= 0)
  3502. {
  3503. if (this.opts.linebreaks && typeof($el.data('tagblock')) !== 'undefined')
  3504. {
  3505. $el.replaceWith($el.html() + '<br />');
  3506. }
  3507. else
  3508. {
  3509. $el.css('margin-left', '');
  3510. this.utils.removeEmptyAttr($el, 'style');
  3511. }
  3512. }
  3513. else
  3514. {
  3515. $el.css('margin-left', left + 'px');
  3516. }
  3517. }, this));
  3518. },
  3519. fixEmptyIndent: function()
  3520. {
  3521. var block = this.selection.getBlock();
  3522. if (this.range.collapsed && block && block.tagName == 'LI' && this.utils.isEmpty($(block).text()))
  3523. {
  3524. var $block = $(block);
  3525. $block.find('span').not('.redactor-selection-marker').contents().unwrap();
  3526. $block.append('<br>');
  3527. }
  3528. }
  3529. };
  3530. },
  3531. inline: function()
  3532. {
  3533. return {
  3534. formatting: function(name)
  3535. {
  3536. var type, value;
  3537. if (typeof this.formatting[name].style != 'undefined') type = 'style';
  3538. else if (typeof this.formatting[name]['class'] != 'undefined') type = 'class';
  3539. if (type) value = this.formatting[name][type];
  3540. this.inline.format(this.formatting[name].tag, type, value);
  3541. },
  3542. format: function(tag, type, value)
  3543. {
  3544. var current = this.selection.getCurrent();
  3545. if (current && current.tagName === 'TR') return;
  3546. // Stop formatting pre and headers
  3547. if (this.utils.isCurrentOrParent('PRE') || this.utils.isCurrentOrParentHeader()) return;
  3548. var tags = ['b', 'bold', 'i', 'italic', 'underline', 'strikethrough', 'deleted', 'superscript', 'subscript'];
  3549. var replaced = ['strong', 'strong', 'em', 'em', 'u', 'del', 'del', 'sup', 'sub'];
  3550. for (var i = 0; i < tags.length; i++)
  3551. {
  3552. if (tag == tags[i]) tag = replaced[i];
  3553. }
  3554. if (this.opts.allowedTags)
  3555. {
  3556. if ($.inArray(tag, this.opts.allowedTags) == -1) return;
  3557. }
  3558. else
  3559. {
  3560. if ($.inArray(tag, this.opts.deniedTags) !== -1) return;
  3561. }
  3562. this.inline.type = type || false;
  3563. this.inline.value = value || false;
  3564. this.buffer.set();
  3565. if (!this.utils.browser('msie') && !this.opts.linebreaks)
  3566. {
  3567. this.$editor.focus();
  3568. }
  3569. this.selection.get();
  3570. if (this.range.collapsed)
  3571. {
  3572. this.inline.formatCollapsed(tag);
  3573. }
  3574. else
  3575. {
  3576. this.inline.formatMultiple(tag);
  3577. }
  3578. },
  3579. formatCollapsed: function(tag)
  3580. {
  3581. var current = this.selection.getCurrent();
  3582. var $parent = $(current).closest(tag + '[data-redactor-tag=' + tag + ']', this.$editor[0]);
  3583. // inline there is
  3584. if ($parent.length !== 0 && (this.inline.type != 'style' && $parent[0].tagName != 'SPAN'))
  3585. {
  3586. // remove empty
  3587. if (this.utils.isEmpty($parent.text()))
  3588. {
  3589. this.caret.setAfter($parent[0]);
  3590. $parent.remove();
  3591. this.code.sync();
  3592. }
  3593. else if (this.utils.isEndOfElement($parent))
  3594. {
  3595. this.caret.setAfter($parent[0]);
  3596. }
  3597. return;
  3598. }
  3599. // create empty inline
  3600. var node = $('<' + tag + '>').attr('data-verified', 'redactor').attr('data-redactor-tag', tag);
  3601. node.html(this.opts.invisibleSpace);
  3602. node = this.inline.setFormat(node);
  3603. var node = this.insert.node(node);
  3604. this.caret.setEnd(node);
  3605. this.code.sync();
  3606. },
  3607. formatMultiple: function(tag)
  3608. {
  3609. this.inline.formatConvert(tag);
  3610. this.selection.save();
  3611. document.execCommand('strikethrough');
  3612. this.$editor.find('strike').each($.proxy(function(i,s)
  3613. {
  3614. var $el = $(s);
  3615. this.inline.formatRemoveSameChildren($el, tag);
  3616. var $span;
  3617. if (this.inline.type)
  3618. {
  3619. $span = $('<span>').attr('data-redactor-tag', tag).attr('data-verified', 'redactor');
  3620. $span = this.inline.setFormat($span);
  3621. }
  3622. else
  3623. {
  3624. $span = $('<' + tag + '>').attr('data-redactor-tag', tag).attr('data-verified', 'redactor');
  3625. }
  3626. $el.replaceWith($span.html($el.contents()));
  3627. var $parent = $span.parent();
  3628. // remove U tag if selected link + node
  3629. if ($span[0].tagName === 'A' && $parent && $parent[0].tagName === 'U')
  3630. {
  3631. $span.parent().replaceWith($span);
  3632. }
  3633. if (tag == 'span')
  3634. {
  3635. if ($parent && $parent[0].tagName === 'SPAN' && this.inline.type === 'style')
  3636. {
  3637. var arr = this.inline.value.split(';');
  3638. for (var z = 0; z < arr.length; z++)
  3639. {
  3640. if (arr[z] === '') return;
  3641. var style = arr[z].split(':');
  3642. $parent.css(style[0], '');
  3643. if (this.utils.removeEmptyAttr($parent, 'style'))
  3644. {
  3645. $parent.replaceWith($parent.contents());
  3646. }
  3647. }
  3648. }
  3649. }
  3650. }, this));
  3651. // clear text decoration
  3652. if (tag != 'span')
  3653. {
  3654. this.$editor.find(this.opts.inlineTags.join(', ')).each($.proxy(function(i,s)
  3655. {
  3656. var $el = $(s);
  3657. if (s.tagName === 'U' && s.attributes.length === 0)
  3658. {
  3659. $el.replaceWith($el.contents());
  3660. return;
  3661. }
  3662. var property = $el.css('text-decoration');
  3663. if (property === 'line-through')
  3664. {
  3665. $el.css('text-decoration', '');
  3666. this.utils.removeEmptyAttr($el, 'style');
  3667. }
  3668. }, this));
  3669. }
  3670. if (tag != 'del')
  3671. {
  3672. var _this = this;
  3673. this.$editor.find('inline').each(function(i,s)
  3674. {
  3675. _this.utils.replaceToTag(s, 'del');
  3676. });
  3677. }
  3678. if (tag != 'u')
  3679. {
  3680. var _this = this;
  3681. this.$editor.find('unline').each(function(i,s)
  3682. {
  3683. _this.utils.replaceToTag(s, 'u');
  3684. });
  3685. }
  3686. this.selection.restore();
  3687. this.code.sync();
  3688. },
  3689. formatRemoveSameChildren: function($el, tag)
  3690. {
  3691. var self = this;
  3692. $el.children(tag).each(function()
  3693. {
  3694. var $child = $(this);
  3695. if (!$child.hasClass('redactor-selection-marker'))
  3696. {
  3697. if (self.inline.type == 'style')
  3698. {
  3699. var arr = self.inline.value.split(';');
  3700. for (var z = 0; z < arr.length; z++)
  3701. {
  3702. if (arr[z] === '') return;
  3703. var style = arr[z].split(':');
  3704. $child.css(style[0], '');
  3705. if (self.utils.removeEmptyAttr($child , 'style'))
  3706. {
  3707. $child.replaceWith($child.contents());
  3708. }
  3709. }
  3710. }
  3711. else
  3712. {
  3713. $child.contents().unwrap();
  3714. }
  3715. }
  3716. });
  3717. },
  3718. formatConvert: function(tag)
  3719. {
  3720. this.selection.save();
  3721. var find = '';
  3722. if (this.inline.type == 'class') find = '[data-redactor-class=' + this.inline.value + ']';
  3723. else if (this.inline.type == 'style')
  3724. {
  3725. find = '[data-redactor-style="' + this.inline.value + '"]';
  3726. }
  3727. var self = this;
  3728. if (tag != 'del')
  3729. {
  3730. this.$editor.find('del').each(function(i,s)
  3731. {
  3732. self.utils.replaceToTag(s, 'inline');
  3733. });
  3734. }
  3735. if (tag != 'u')
  3736. {
  3737. this.$editor.find('u').each(function(i,s)
  3738. {
  3739. self.utils.replaceToTag(s, 'unline');
  3740. });
  3741. }
  3742. if (tag != 'span')
  3743. {
  3744. this.$editor.find(tag).each(function()
  3745. {
  3746. var $el = $(this);
  3747. $el.replaceWith($('<strike />').html($el.contents()));
  3748. });
  3749. }
  3750. this.$editor.find('[data-redactor-tag="' + tag + '"]' + find).each(function()
  3751. {
  3752. if (find === '' && tag == 'span' && this.tagName.toLowerCase() == tag) return;
  3753. var $el = $(this);
  3754. $el.replaceWith($('<strike />').html($el.contents()));
  3755. });
  3756. this.selection.restore();
  3757. },
  3758. setFormat: function(node)
  3759. {
  3760. switch (this.inline.type)
  3761. {
  3762. case 'class':
  3763. if (node.hasClass(this.inline.value))
  3764. {
  3765. node.removeClass(this.inline.value);
  3766. node.removeAttr('data-redactor-class');
  3767. }
  3768. else
  3769. {
  3770. node.addClass(this.inline.value);
  3771. node.attr('data-redactor-class', this.inline.value);
  3772. }
  3773. break;
  3774. case 'style':
  3775. node[0].style.cssText = this.inline.value;
  3776. node.attr('data-redactor-style', this.inline.value);
  3777. break;
  3778. }
  3779. return node;
  3780. },
  3781. removeStyle: function()
  3782. {
  3783. this.buffer.set();
  3784. var current = this.selection.getCurrent();
  3785. var nodes = this.selection.getInlines();
  3786. this.selection.save();
  3787. if (current && current.tagName === 'SPAN')
  3788. {
  3789. var $s = $(current);
  3790. $s.removeAttr('style');
  3791. if ($s[0].attributes.length === 0)
  3792. {
  3793. $s.replaceWith($s.contents());
  3794. }
  3795. }
  3796. $.each(nodes, $.proxy(function(i,s)
  3797. {
  3798. var $s = $(s);
  3799. if ($.inArray(s.tagName.toLowerCase(), this.opts.inlineTags) != -1 && !$s.hasClass('redactor-selection-marker'))
  3800. {
  3801. $s.removeAttr('style');
  3802. if ($s[0].attributes.length === 0)
  3803. {
  3804. $s.replaceWith($s.contents());
  3805. }
  3806. }
  3807. }, this));
  3808. this.selection.restore();
  3809. this.code.sync();
  3810. },
  3811. removeStyleRule: function(name)
  3812. {
  3813. this.buffer.set();
  3814. var parent = this.selection.getParent();
  3815. var nodes = this.selection.getInlines();
  3816. this.selection.save();
  3817. if (parent && parent.tagName === 'SPAN')
  3818. {
  3819. var $s = $(parent);
  3820. $s.css(name, '');
  3821. this.utils.removeEmptyAttr($s, 'style');
  3822. if ($s[0].attributes.length === 0)
  3823. {
  3824. $s.replaceWith($s.contents());
  3825. }
  3826. }
  3827. $.each(nodes, $.proxy(function(i,s)
  3828. {
  3829. var $s = $(s);
  3830. if ($.inArray(s.tagName.toLowerCase(), this.opts.inlineTags) != -1 && !$s.hasClass('redactor-selection-marker'))
  3831. {
  3832. $s.css(name, '');
  3833. this.utils.removeEmptyAttr($s, 'style');
  3834. if ($s[0].attributes.length === 0)
  3835. {
  3836. $s.replaceWith($s.contents());
  3837. }
  3838. }
  3839. }, this));
  3840. this.selection.restore();
  3841. this.code.sync();
  3842. },
  3843. removeFormat: function()
  3844. {
  3845. this.buffer.set();
  3846. var current = this.selection.getCurrent();
  3847. this.selection.save();
  3848. document.execCommand('removeFormat');
  3849. if (current && current.tagName === 'SPAN')
  3850. {
  3851. $(current).replaceWith($(current).contents());
  3852. }
  3853. $.each(this.selection.getNodes(), $.proxy(function(i,s)
  3854. {
  3855. var $s = $(s);
  3856. if ($.inArray(s.tagName.toLowerCase(), this.opts.inlineTags) != -1 && !$s.hasClass('redactor-selection-marker'))
  3857. {
  3858. $s.replaceWith($s.contents());
  3859. }
  3860. }, this));
  3861. this.selection.restore();
  3862. this.code.sync();
  3863. },
  3864. toggleClass: function(className)
  3865. {
  3866. this.inline.format('span', 'class', className);
  3867. },
  3868. toggleStyle: function(value)
  3869. {
  3870. this.inline.format('span', 'style', value);
  3871. }
  3872. };
  3873. },
  3874. insert: function()
  3875. {
  3876. return {
  3877. set: function(html, clean)
  3878. {
  3879. this.placeholder.remove();
  3880. html = this.clean.setVerified(html);
  3881. if (typeof clean == 'undefined')
  3882. {
  3883. html = this.clean.onPaste(html, false);
  3884. }
  3885. this.$editor.html(html);
  3886. this.selection.remove();
  3887. this.focus.setEnd();
  3888. this.clean.normalizeLists();
  3889. this.code.sync();
  3890. this.observe.load();
  3891. if (typeof clean == 'undefined')
  3892. {
  3893. setTimeout($.proxy(this.clean.clearUnverified, this), 10);
  3894. }
  3895. },
  3896. text: function(text)
  3897. {
  3898. this.placeholder.remove();
  3899. text = text.toString();
  3900. text = $.trim(text);
  3901. text = this.clean.getPlainText(text, false);
  3902. this.$editor.focus();
  3903. if (this.utils.browser('msie'))
  3904. {
  3905. this.insert.htmlIe(text);
  3906. }
  3907. else
  3908. {
  3909. this.selection.get();
  3910. this.range.deleteContents();
  3911. var el = document.createElement("div");
  3912. el.innerHTML = text;
  3913. var frag = document.createDocumentFragment(), node, lastNode;
  3914. while ((node = el.firstChild))
  3915. {
  3916. lastNode = frag.appendChild(node);
  3917. }
  3918. this.range.insertNode(frag);
  3919. if (lastNode)
  3920. {
  3921. var range = this.range.cloneRange();
  3922. range.setStartAfter(lastNode);
  3923. range.collapse(true);
  3924. this.sel.removeAllRanges();
  3925. this.sel.addRange(range);
  3926. }
  3927. }
  3928. this.code.sync();
  3929. this.clean.clearUnverified();
  3930. },
  3931. htmlWithoutClean: function(html)
  3932. {
  3933. this.insert.html(html, false);
  3934. },
  3935. html: function(html, clean)
  3936. {
  3937. this.placeholder.remove();
  3938. if (typeof clean == 'undefined') clean = true;
  3939. if (!this.opts.linebreaks)
  3940. {
  3941. this.$editor.focus();
  3942. }
  3943. html = this.clean.setVerified(html);
  3944. if (clean)
  3945. {
  3946. html = this.clean.onPaste(html);
  3947. }
  3948. if (this.utils.browser('msie'))
  3949. {
  3950. this.insert.htmlIe(html);
  3951. }
  3952. else
  3953. {
  3954. if (this.clean.singleLine) this.insert.execHtml(html);
  3955. else document.execCommand('insertHTML', false, html);
  3956. this.insert.htmlFixMozilla();
  3957. }
  3958. this.clean.normalizeLists();
  3959. // remove empty paragraphs finaly
  3960. if (!this.opts.linebreaks)
  3961. {
  3962. this.$editor.find('p').each($.proxy(this.utils.removeEmpty, this));
  3963. }
  3964. this.code.sync();
  3965. this.observe.load();
  3966. if (clean)
  3967. {
  3968. this.clean.clearUnverified();
  3969. }
  3970. },
  3971. htmlFixMozilla: function()
  3972. {
  3973. // FF inserts empty p when content was selected dblclick
  3974. if (!this.utils.browser('mozilla')) return;
  3975. var $next = $(this.selection.getBlock()).next();
  3976. if ($next.length > 0 && $next[0].tagName == 'P' && $next.html() === '')
  3977. {
  3978. $next.remove();
  3979. }
  3980. },
  3981. htmlIe: function(html)
  3982. {
  3983. if (this.utils.isIe11())
  3984. {
  3985. var parent = this.utils.isCurrentOrParent('P');
  3986. var $html = $('<div>').append(html);
  3987. var blocksMatch = $html.contents().is('p, :header, dl, ul, ol, div, table, td, blockquote, pre, address, section, header, footer, aside, article');
  3988. if (parent && blocksMatch) this.insert.ie11FixInserting(parent, html);
  3989. else this.insert.ie11PasteFrag(html);
  3990. return;
  3991. }
  3992. document.selection.createRange().pasteHTML(html);
  3993. },
  3994. execHtml: function(html)
  3995. {
  3996. html = this.clean.setVerified(html);
  3997. this.selection.get();
  3998. this.range.deleteContents();
  3999. var el = document.createElement('div');
  4000. el.innerHTML = html;
  4001. var frag = document.createDocumentFragment(), node, lastNode;
  4002. while ((node = el.firstChild))
  4003. {
  4004. lastNode = frag.appendChild(node);
  4005. }
  4006. this.range.insertNode(frag);
  4007. this.range.collapse(true);
  4008. this.caret.setAfter(lastNode);
  4009. },
  4010. node: function(node, deleteContents)
  4011. {
  4012. node = node[0] || node;
  4013. var offset = this.caret.getOffset();
  4014. var html = this.utils.getOuterHtml(node);
  4015. html = this.clean.setVerified(html);
  4016. if (html.match(/</g) !== null)
  4017. {
  4018. node = $(html)[0];
  4019. }
  4020. this.selection.get();
  4021. if (deleteContents !== false)
  4022. {
  4023. this.range.deleteContents();
  4024. }
  4025. this.range.insertNode(node);
  4026. this.range.collapse(false);
  4027. this.selection.addRange();
  4028. this.caret.setOffset(offset);
  4029. return node;
  4030. },
  4031. nodeToPoint: function(node, x, y)
  4032. {
  4033. node = node[0] || node;
  4034. this.selection.get();
  4035. var range;
  4036. if (document.caretPositionFromPoint)
  4037. {
  4038. var pos = document.caretPositionFromPoint(x, y);
  4039. this.range.setStart(pos.offsetNode, pos.offset);
  4040. this.range.collapse(true);
  4041. this.range.insertNode(node);
  4042. }
  4043. else if (document.caretRangeFromPoint)
  4044. {
  4045. range = document.caretRangeFromPoint(x, y);
  4046. range.insertNode(node);
  4047. }
  4048. else if (typeof document.body.createTextRange != "undefined")
  4049. {
  4050. range = document.body.createTextRange();
  4051. range.moveToPoint(x, y);
  4052. var endRange = range.duplicate();
  4053. endRange.moveToPoint(x, y);
  4054. range.setEndPoint("EndToEnd", endRange);
  4055. range.select();
  4056. }
  4057. },
  4058. nodeToCaretPositionFromPoint: function(e, node)
  4059. {
  4060. node = node[0] || node;
  4061. var range;
  4062. var x = e.clientX, y = e.clientY;
  4063. if (document.caretPositionFromPoint)
  4064. {
  4065. var pos = document.caretPositionFromPoint(x, y);
  4066. var sel = document.getSelection();
  4067. range = sel.getRangeAt(0);
  4068. range.setStart(pos.offsetNode, pos.offset);
  4069. range.collapse(true);
  4070. range.insertNode(node);
  4071. }
  4072. else if (document.caretRangeFromPoint)
  4073. {
  4074. range = document.caretRangeFromPoint(x, y);
  4075. range.insertNode(node);
  4076. }
  4077. else if (typeof document.body.createTextRange != "undefined")
  4078. {
  4079. range = document.body.createTextRange();
  4080. range.moveToPoint(x, y);
  4081. var endRange = range.duplicate();
  4082. endRange.moveToPoint(x, y);
  4083. range.setEndPoint("EndToEnd", endRange);
  4084. range.select();
  4085. }
  4086. },
  4087. ie11FixInserting: function(parent, html)
  4088. {
  4089. var node = document.createElement('span');
  4090. node.className = 'redactor-ie-paste';
  4091. this.insert.node(node);
  4092. var parHtml = $(parent).html();
  4093. parHtml = '<p>' + parHtml.replace(/<span class="redactor-ie-paste"><\/span>/gi, '</p>' + html + '<p>') + '</p>';
  4094. parHtml = parHtml.replace(/<p><\/p>/gi, '');
  4095. $(parent).replaceWith(parHtml);
  4096. },
  4097. ie11PasteFrag: function(html)
  4098. {
  4099. this.selection.get();
  4100. this.range.deleteContents();
  4101. var el = document.createElement("div");
  4102. el.innerHTML = html;
  4103. var frag = document.createDocumentFragment(), node, lastNode;
  4104. while ((node = el.firstChild))
  4105. {
  4106. lastNode = frag.appendChild(node);
  4107. }
  4108. this.range.insertNode(frag);
  4109. this.range.collapse(false);
  4110. this.selection.addRange();
  4111. }
  4112. };
  4113. },
  4114. keydown: function()
  4115. {
  4116. return {
  4117. init: function(e)
  4118. {
  4119. if (this.rtePaste) return;
  4120. var key = e.which;
  4121. var arrow = (key >= 37 && key <= 40);
  4122. this.keydown.ctrl = e.ctrlKey || e.metaKey;
  4123. this.keydown.current = this.selection.getCurrent();
  4124. this.keydown.parent = this.selection.getParent();
  4125. this.keydown.block = this.selection.getBlock();
  4126. // detect tags
  4127. this.keydown.pre = this.utils.isTag(this.keydown.current, 'pre');
  4128. this.keydown.blockquote = this.utils.isTag(this.keydown.current, 'blockquote');
  4129. this.keydown.figcaption = this.utils.isTag(this.keydown.current, 'figcaption');
  4130. // shortcuts setup
  4131. this.shortcuts.init(e, key);
  4132. if (this.utils.isDesktop())
  4133. {
  4134. this.keydown.checkEvents(arrow, key);
  4135. this.keydown.setupBuffer(e, key);
  4136. }
  4137. this.keydown.addArrowsEvent(arrow);
  4138. this.keydown.setupSelectAll(e, key);
  4139. // callback
  4140. var keydownStop = this.core.setCallback('keydown', e);
  4141. if (keydownStop === false)
  4142. {
  4143. e.preventDefault();
  4144. return false;
  4145. }
  4146. // ie and ff exit from table
  4147. if (this.opts.enterKey && (this.utils.browser('msie') || this.utils.browser('mozilla')) && (key === this.keyCode.DOWN || key === this.keyCode.RIGHT))
  4148. {
  4149. var isEndOfTable = false;
  4150. var $table = false;
  4151. if (this.keydown.block && this.keydown.block.tagName === 'TD')
  4152. {
  4153. $table = $(this.keydown.block).closest('table', this.$editor[0]);
  4154. }
  4155. if ($table && $table.find('td').last()[0] === this.keydown.block)
  4156. {
  4157. isEndOfTable = true;
  4158. }
  4159. if (this.utils.isEndOfElement() && isEndOfTable)
  4160. {
  4161. var node = $(this.opts.emptyHtml);
  4162. $table.after(node);
  4163. this.caret.setStart(node);
  4164. }
  4165. }
  4166. // down
  4167. if (this.opts.enterKey && key === this.keyCode.DOWN)
  4168. {
  4169. this.keydown.onArrowDown();
  4170. }
  4171. // turn off enter key
  4172. if (!this.opts.enterKey && key === this.keyCode.ENTER)
  4173. {
  4174. e.preventDefault();
  4175. // remove selected
  4176. if (!this.range.collapsed) this.range.deleteContents();
  4177. return;
  4178. }
  4179. // on enter
  4180. if (key == this.keyCode.ENTER && !e.shiftKey && !e.ctrlKey && !e.metaKey)
  4181. {
  4182. var stop = this.core.setCallback('enter', e);
  4183. if (stop === false)
  4184. {
  4185. e.preventDefault();
  4186. return false;
  4187. }
  4188. if (this.keydown.blockquote && this.keydown.exitFromBlockquote(e) === true)
  4189. {
  4190. return false;
  4191. }
  4192. var current, $next;
  4193. if (this.keydown.pre)
  4194. {
  4195. return this.keydown.insertNewLine(e);
  4196. }
  4197. else if (this.keydown.blockquote || this.keydown.figcaption)
  4198. {
  4199. current = this.selection.getCurrent();
  4200. $next = $(current).next();
  4201. if ($next.length !== 0 && $next[0].tagName == 'BR')
  4202. {
  4203. return this.keydown.insertBreakLine(e);
  4204. }
  4205. else if (this.utils.isEndOfElement() && (current && current != 'SPAN'))
  4206. {
  4207. return this.keydown.insertDblBreakLine(e);
  4208. }
  4209. else
  4210. {
  4211. return this.keydown.insertBreakLine(e);
  4212. }
  4213. }
  4214. else if (this.opts.linebreaks && !this.keydown.block)
  4215. {
  4216. current = this.selection.getCurrent();
  4217. $next = $(this.keydown.current).next();
  4218. if ($next.length !== 0 && $next[0].tagName == 'BR')
  4219. {
  4220. return this.keydown.insertBreakLine(e);
  4221. }
  4222. else if (current !== false && $(current).hasClass('redactor-invisible-space'))
  4223. {
  4224. this.caret.setAfter(current);
  4225. $(current).contents().unwrap();
  4226. return this.keydown.insertDblBreakLine(e);
  4227. }
  4228. else
  4229. {
  4230. if (this.utils.isEndOfEditor())
  4231. {
  4232. return this.keydown.insertDblBreakLine(e);
  4233. }
  4234. else if ($next.length === 0 && current === false && typeof $next.context != 'undefined')
  4235. {
  4236. return this.keydown.insertBreakLine(e);
  4237. }
  4238. return this.keydown.insertBreakLine(e);
  4239. }
  4240. }
  4241. else if (this.opts.linebreaks && this.keydown.block)
  4242. {
  4243. setTimeout($.proxy(this.keydown.replaceDivToBreakLine, this), 1);
  4244. }
  4245. // paragraphs
  4246. else if (!this.opts.linebreaks && this.keydown.block)
  4247. {
  4248. setTimeout($.proxy(this.keydown.replaceDivToParagraph, this), 1);
  4249. if (this.keydown.block.tagName === 'LI')
  4250. {
  4251. current = this.selection.getCurrent();
  4252. var $parent = $(current).closest('li', this.$editor[0]);
  4253. var $list = $parent.closest('ul,ol', this.$editor[0]);
  4254. if ($parent.length !== 0 && this.utils.isEmpty($parent.html()) && $list.next().length === 0 && this.utils.isEmpty($list.find("li").last().html()))
  4255. {
  4256. $list.find("li").last().remove();
  4257. var node = $(this.opts.emptyHtml);
  4258. $list.after(node);
  4259. this.caret.setStart(node);
  4260. return false;
  4261. }
  4262. }
  4263. }
  4264. else if (!this.opts.linebreaks && !this.keydown.block)
  4265. {
  4266. return this.keydown.insertParagraph(e);
  4267. }
  4268. }
  4269. // Shift+Enter or Ctrl+Enter
  4270. if (key === this.keyCode.ENTER && (e.ctrlKey || e.shiftKey))
  4271. {
  4272. return this.keydown.onShiftEnter(e);
  4273. }
  4274. // tab or cmd + [
  4275. if (key === this.keyCode.TAB || e.metaKey && key === 221 || e.metaKey && key === 219)
  4276. {
  4277. return this.keydown.onTab(e, key);
  4278. }
  4279. // image delete and backspace
  4280. if (key === this.keyCode.BACKSPACE || key === this.keyCode.DELETE)
  4281. {
  4282. var nodes = this.selection.getNodes();
  4283. if (nodes)
  4284. {
  4285. var len = nodes.length;
  4286. var last;
  4287. for (var i = 0; i < len; i++)
  4288. {
  4289. var children = $(nodes[i]).children('img');
  4290. if (children.length !== 0)
  4291. {
  4292. var self = this;
  4293. $.each(children, function(z,s)
  4294. {
  4295. var $s = $(s);
  4296. if ($s.css('float') != 'none') return;
  4297. // image delete callback
  4298. self.core.setCallback('imageDelete', s.src, $s);
  4299. last = s;
  4300. });
  4301. }
  4302. else if (nodes[i].tagName == 'IMG')
  4303. {
  4304. if (last != nodes[i])
  4305. {
  4306. // image delete callback
  4307. this.core.setCallback('imageDelete', nodes[i].src, $(nodes[i]));
  4308. last = nodes[i];
  4309. }
  4310. }
  4311. }
  4312. }
  4313. }
  4314. // backspace
  4315. if (key === this.keyCode.BACKSPACE)
  4316. {
  4317. // backspace as outdent
  4318. var block = this.selection.getBlock();
  4319. var indented = ($(block).css('margin-left') !== '0px');
  4320. if (block && indented && this.range.collapsed && this.utils.isStartOfElement())
  4321. {
  4322. this.indent.decrease();
  4323. e.preventDefault();
  4324. return;
  4325. }
  4326. // remove hr in FF
  4327. if (this.utils.browser('mozilla'))
  4328. {
  4329. var prev = this.selection.getPrev();
  4330. var prev2 = $(prev).prev()[0];
  4331. if (prev && prev.tagName === 'HR') $(prev).remove();
  4332. if (prev2 && prev2.tagName === 'HR') $(prev2).remove();
  4333. }
  4334. this.keydown.removeInvisibleSpace();
  4335. this.keydown.removeEmptyListInTable(e);
  4336. }
  4337. this.code.sync();
  4338. },
  4339. checkEvents: function(arrow, key)
  4340. {
  4341. if (!arrow && (this.core.getEvent() == 'click' || this.core.getEvent() == 'arrow'))
  4342. {
  4343. this.core.addEvent(false);
  4344. if (this.keydown.checkKeyEvents(key))
  4345. {
  4346. this.buffer.set();
  4347. }
  4348. }
  4349. },
  4350. checkKeyEvents: function(key)
  4351. {
  4352. var k = this.keyCode;
  4353. var keys = [k.BACKSPACE, k.DELETE, k.ENTER, k.ESC, k.TAB, k.CTRL, k.META, k.ALT, k.SHIFT];
  4354. return ($.inArray(key, keys) == -1) ? true : false;
  4355. },
  4356. addArrowsEvent: function(arrow)
  4357. {
  4358. if (!arrow) return;
  4359. if ((this.core.getEvent() == 'click' || this.core.getEvent() == 'arrow'))
  4360. {
  4361. this.core.addEvent(false);
  4362. return;
  4363. }
  4364. this.core.addEvent('arrow');
  4365. },
  4366. setupBuffer: function(e, key)
  4367. {
  4368. if (this.keydown.ctrl && key === 90 && !e.shiftKey && !e.altKey && this.opts.buffer.length) // z key
  4369. {
  4370. e.preventDefault();
  4371. this.buffer.undo();
  4372. return;
  4373. }
  4374. // undo
  4375. else if (this.keydown.ctrl && key === 90 && e.shiftKey && !e.altKey && this.opts.rebuffer.length !== 0)
  4376. {
  4377. e.preventDefault();
  4378. this.buffer.redo();
  4379. return;
  4380. }
  4381. else if (!this.keydown.ctrl)
  4382. {
  4383. if (key == this.keyCode.BACKSPACE || key == this.keyCode.DELETE || (key == this.keyCode.ENTER && !e.ctrlKey && !e.shiftKey))
  4384. {
  4385. this.buffer.set();
  4386. }
  4387. }
  4388. },
  4389. setupSelectAll: function(e, key)
  4390. {
  4391. if (this.keydown.ctrl && key === 65)
  4392. {
  4393. this.utils.enableSelectAll();
  4394. }
  4395. else if (key != this.keyCode.LEFT_WIN && !this.keydown.ctrl)
  4396. {
  4397. this.utils.disableSelectAll();
  4398. }
  4399. },
  4400. onArrowDown: function()
  4401. {
  4402. var tags = [this.keydown.blockquote, this.keydown.pre, this.keydown.figcaption];
  4403. for (var i = 0; i < tags.length; i++)
  4404. {
  4405. if (tags[i])
  4406. {
  4407. this.keydown.insertAfterLastElement(tags[i]);
  4408. return false;
  4409. }
  4410. }
  4411. },
  4412. onShiftEnter: function(e)
  4413. {
  4414. this.buffer.set();
  4415. if (this.utils.isEndOfElement())
  4416. {
  4417. return this.keydown.insertDblBreakLine(e);
  4418. }
  4419. return this.keydown.insertBreakLine(e);
  4420. },
  4421. onTab: function(e, key)
  4422. {
  4423. if (!this.opts.tabKey) return true;
  4424. if (this.utils.isEmpty(this.code.get()) && this.opts.tabAsSpaces === false) return true;
  4425. e.preventDefault();
  4426. var node;
  4427. if (this.keydown.pre && !e.shiftKey)
  4428. {
  4429. node = (this.opts.preSpaces) ? document.createTextNode(Array(this.opts.preSpaces + 1).join('\u00a0')) : document.createTextNode('\t');
  4430. this.insert.node(node);
  4431. this.code.sync();
  4432. }
  4433. else if (this.opts.tabAsSpaces !== false)
  4434. {
  4435. node = document.createTextNode(Array(this.opts.tabAsSpaces + 1).join('\u00a0'));
  4436. this.insert.node(node);
  4437. this.code.sync();
  4438. }
  4439. else
  4440. {
  4441. if (e.metaKey && key === 219) this.indent.decrease();
  4442. else if (e.metaKey && key === 221) this.indent.increase();
  4443. else if (!e.shiftKey) this.indent.increase();
  4444. else this.indent.decrease();
  4445. }
  4446. return false;
  4447. },
  4448. replaceDivToBreakLine: function()
  4449. {
  4450. var blockElem = this.selection.getBlock();
  4451. var blockHtml = blockElem.innerHTML.replace(/<br\s?\/?>/gi, '');
  4452. if ((blockElem.tagName === 'DIV' || blockElem.tagName === 'P') && blockHtml === '' && !$(blockElem).hasClass('redactor-editor'))
  4453. {
  4454. var br = document.createElement('br');
  4455. $(blockElem).replaceWith(br);
  4456. this.caret.setBefore(br);
  4457. this.code.sync();
  4458. return false;
  4459. }
  4460. },
  4461. replaceDivToParagraph: function()
  4462. {
  4463. var blockElem = this.selection.getBlock();
  4464. var blockHtml = blockElem.innerHTML.replace(/<br\s?\/?>/gi, '');
  4465. if (blockElem.tagName === 'DIV' && this.utils.isEmpty(blockHtml) && !$(blockElem).hasClass('redactor-editor'))
  4466. {
  4467. var p = document.createElement('p');
  4468. p.innerHTML = this.opts.invisibleSpace;
  4469. $(blockElem).replaceWith(p);
  4470. this.caret.setStart(p);
  4471. this.code.sync();
  4472. return false;
  4473. }
  4474. else if (this.opts.cleanStyleOnEnter && blockElem.tagName == 'P')
  4475. {
  4476. $(blockElem).removeAttr('class').removeAttr('style');
  4477. }
  4478. },
  4479. insertParagraph: function(e)
  4480. {
  4481. e.preventDefault();
  4482. this.selection.get();
  4483. var p = document.createElement('p');
  4484. p.innerHTML = this.opts.invisibleSpace;
  4485. this.range.deleteContents();
  4486. this.range.insertNode(p);
  4487. this.caret.setStart(p);
  4488. this.code.sync();
  4489. return false;
  4490. },
  4491. exitFromBlockquote: function(e)
  4492. {
  4493. if (!this.utils.isEndOfElement()) return;
  4494. var tmp = $.trim($(this.keydown.block).html());
  4495. if (tmp.search(/(<br\s?\/?>){2}$/i) != -1)
  4496. {
  4497. e.preventDefault();
  4498. if (this.opts.linebreaks)
  4499. {
  4500. var br = document.createElement('br');
  4501. $(this.keydown.blockquote).after(br);
  4502. this.caret.setBefore(br);
  4503. $(this.keydown.block).html(tmp.replace(/<br\s?\/?>$/i, ''));
  4504. }
  4505. else
  4506. {
  4507. var node = $(this.opts.emptyHtml);
  4508. $(this.keydown.blockquote).after(node);
  4509. this.caret.setStart(node);
  4510. }
  4511. return true;
  4512. }
  4513. return;
  4514. },
  4515. insertAfterLastElement: function(element)
  4516. {
  4517. if (!this.utils.isEndOfElement()) return;
  4518. this.buffer.set();
  4519. if (this.opts.linebreaks)
  4520. {
  4521. var contents = $('<div>').append($.trim(this.$editor.html())).contents();
  4522. var last = contents.last()[0];
  4523. if (last.tagName == 'SPAN' && last.innerHTML === '')
  4524. {
  4525. last = contents.prev()[0];
  4526. }
  4527. if (this.utils.getOuterHtml(last) != this.utils.getOuterHtml(element)) return;
  4528. var br = document.createElement('br');
  4529. $(element).after(br);
  4530. this.caret.setAfter(br);
  4531. }
  4532. else
  4533. {
  4534. if (this.$editor.contents().last()[0] !== element) return;
  4535. var node = $(this.opts.emptyHtml);
  4536. $(element).after(node);
  4537. this.caret.setStart(node);
  4538. }
  4539. },
  4540. insertNewLine: function(e)
  4541. {
  4542. e.preventDefault();
  4543. var node = document.createTextNode('\n');
  4544. this.selection.get();
  4545. this.range.deleteContents();
  4546. this.range.insertNode(node);
  4547. this.caret.setAfter(node);
  4548. this.code.sync();
  4549. return false;
  4550. },
  4551. insertBreakLine: function(e)
  4552. {
  4553. return this.keydown.insertBreakLineProcessing(e);
  4554. },
  4555. insertDblBreakLine: function(e)
  4556. {
  4557. return this.keydown.insertBreakLineProcessing(e, true);
  4558. },
  4559. insertBreakLineProcessing: function(e, dbl)
  4560. {
  4561. e.stopPropagation();
  4562. this.selection.get();
  4563. var br1 = document.createElement('br');
  4564. if (this.utils.browser('msie'))
  4565. {
  4566. this.range.collapse(false);
  4567. this.range.setEnd(this.range.endContainer, this.range.endOffset);
  4568. }
  4569. else
  4570. {
  4571. this.range.deleteContents();
  4572. }
  4573. this.range.insertNode(br1);
  4574. // move br outside A tag
  4575. var $parentA = $(br1).parent("a");
  4576. if ($parentA.length > 0)
  4577. {
  4578. $parentA.find(br1).remove();
  4579. $parentA.after(br1);
  4580. }
  4581. if (dbl === true)
  4582. {
  4583. var $next = $(br1).next();
  4584. if ($next.length !== 0 && $next[0].tagName === 'BR' && this.utils.isEndOfEditor())
  4585. {
  4586. this.caret.setAfter(br1);
  4587. this.code.sync();
  4588. return false;
  4589. }
  4590. var br2 = document.createElement('br');
  4591. this.range.insertNode(br2);
  4592. this.caret.setAfter(br2);
  4593. }
  4594. else
  4595. {
  4596. // caret does not move after the br visual
  4597. if (this.utils.browser('msie'))
  4598. {
  4599. var space = document.createElement('span');
  4600. space.innerHTML = '&#x200b;';
  4601. $(br1).after(space);
  4602. this.range.setStartAfter(space);
  4603. this.range.setEndAfter(space);
  4604. $(space).remove();
  4605. }
  4606. else
  4607. {
  4608. var range = document.createRange();
  4609. range.setStartAfter(br1);
  4610. range.collapse(true);
  4611. var selection = window.getSelection();
  4612. selection.removeAllRanges();
  4613. selection.addRange(range);
  4614. }
  4615. }
  4616. this.code.sync();
  4617. return false;
  4618. },
  4619. removeInvisibleSpace: function()
  4620. {
  4621. var $current = $(this.keydown.current);
  4622. if ($current.text().search(/^\u200B$/g) === 0)
  4623. {
  4624. $current.remove();
  4625. }
  4626. },
  4627. removeEmptyListInTable: function(e)
  4628. {
  4629. var $current = $(this.keydown.current);
  4630. var $parent = $(this.keydown.parent);
  4631. var td = $current.closest('td', this.$editor[0]);
  4632. if (td.length !== 0 && $current.closest('li', this.$editor[0]) && $parent.children('li').length === 1)
  4633. {
  4634. if (!this.utils.isEmpty($current.text())) return;
  4635. e.preventDefault();
  4636. $current.remove();
  4637. $parent.remove();
  4638. this.caret.setStart(td);
  4639. }
  4640. }
  4641. };
  4642. },
  4643. keyup: function()
  4644. {
  4645. return {
  4646. init: function(e)
  4647. {
  4648. if (this.rtePaste) return;
  4649. var key = e.which;
  4650. this.keyup.current = this.selection.getCurrent();
  4651. this.keyup.parent = this.selection.getParent();
  4652. var $parent = this.utils.isRedactorParent($(this.keyup.parent).parent());
  4653. // callback
  4654. var keyupStop = this.core.setCallback('keyup', e);
  4655. if (keyupStop === false)
  4656. {
  4657. e.preventDefault();
  4658. return false;
  4659. }
  4660. // replace to p before / after the table or body
  4661. if (!this.opts.linebreaks && this.keyup.current.nodeType === 3 && this.keyup.current.length <= 1 && (this.keyup.parent === false || this.keyup.parent.tagName == 'BODY'))
  4662. {
  4663. this.keyup.replaceToParagraph();
  4664. }
  4665. // replace div after lists
  4666. if (!this.opts.linebreaks && this.utils.isRedactorParent(this.keyup.current) && this.keyup.current.tagName === 'DIV')
  4667. {
  4668. this.keyup.replaceToParagraph(false);
  4669. }
  4670. if (!this.opts.linebreaks && $(this.keyup.parent).hasClass('redactor-invisible-space') && ($parent === false || $parent[0].tagName == 'BODY'))
  4671. {
  4672. $(this.keyup.parent).contents().unwrap();
  4673. this.keyup.replaceToParagraph();
  4674. }
  4675. // linkify
  4676. if (this.linkify.isEnabled() && this.linkify.isKey(key)) this.linkify.format();
  4677. if (key === this.keyCode.DELETE || key === this.keyCode.BACKSPACE)
  4678. {
  4679. if (this.utils.browser('mozilla'))
  4680. {
  4681. var td = $(this.keydown.current).closest('td', this.$editor[0]);
  4682. if (td.size() !== 0 && td.text() !== '')
  4683. {
  4684. e.preventDefault();
  4685. return false;
  4686. }
  4687. }
  4688. // clear unverified
  4689. this.clean.clearUnverified();
  4690. if (this.observe.image)
  4691. {
  4692. e.preventDefault();
  4693. this.image.hideResize();
  4694. this.buffer.set();
  4695. this.image.remove(this.observe.image);
  4696. this.observe.image = false;
  4697. return false;
  4698. }
  4699. // remove empty paragraphs
  4700. this.$editor.find('p').each($.proxy(function(i, s)
  4701. {
  4702. this.utils.removeEmpty(i, $(s).html());
  4703. }, this));
  4704. // remove invisible space
  4705. if (this.opts.linebreaks && this.keyup.current && this.keyup.current.tagName == 'DIV' && this.utils.isEmpty(this.keyup.current.innerHTML))
  4706. {
  4707. $(this.keyup.current).after(this.selection.getMarkerAsHtml());
  4708. this.selection.restore();
  4709. $(this.keyup.current).remove();
  4710. }
  4711. this.keyup.removeEmptyLists();
  4712. // if empty
  4713. return this.keyup.formatEmpty(e);
  4714. }
  4715. },
  4716. replaceToParagraph: function(clone)
  4717. {
  4718. var $current = $(this.keyup.current);
  4719. var node;
  4720. if (clone === false)
  4721. {
  4722. node = $('<p>').append($current.html());
  4723. }
  4724. else
  4725. {
  4726. node = $('<p>').append($current.clone());
  4727. }
  4728. $current.replaceWith(node);
  4729. var next = $(node).next();
  4730. if (typeof(next[0]) !== 'undefined' && next[0].tagName == 'BR')
  4731. {
  4732. next.remove();
  4733. }
  4734. this.caret.setEnd(node);
  4735. },
  4736. removeEmptyLists: function()
  4737. {
  4738. var removeIt = function()
  4739. {
  4740. var html = $.trim(this.innerHTML).replace(/\/t\/n/g, '');
  4741. if (html === '')
  4742. {
  4743. $(this).remove();
  4744. }
  4745. };
  4746. this.$editor.find('li').each(removeIt);
  4747. this.$editor.find('ul, ol').each(removeIt);
  4748. },
  4749. formatEmpty: function(e)
  4750. {
  4751. var html = $.trim(this.$editor.html());
  4752. if (!this.utils.isEmpty(html)) return;
  4753. e.preventDefault();
  4754. if (this.opts.linebreaks)
  4755. {
  4756. this.$editor.html(this.selection.getMarkerAsHtml());
  4757. this.selection.restore();
  4758. }
  4759. else
  4760. {
  4761. this.$editor.html(this.opts.emptyHtml);
  4762. this.focus.setStart();
  4763. }
  4764. this.code.sync();
  4765. return false;
  4766. }
  4767. };
  4768. },
  4769. lang: function()
  4770. {
  4771. return {
  4772. load: function()
  4773. {
  4774. this.opts.curLang = this.opts.langs[this.opts.lang];
  4775. },
  4776. get: function(name)
  4777. {
  4778. return (typeof this.opts.curLang[name] != 'undefined') ? this.opts.curLang[name] : '';
  4779. }
  4780. };
  4781. },
  4782. line: function()
  4783. {
  4784. return {
  4785. insert: function()
  4786. {
  4787. this.buffer.set();
  4788. var blocks = this.selection.getBlocks();
  4789. if (blocks[0] !== false && this.line.isExceptLastOrFirst(blocks))
  4790. {
  4791. if (!this.utils.browser('msie')) this.$editor.focus();
  4792. return;
  4793. }
  4794. if (this.utils.browser('msie'))
  4795. {
  4796. this.line.insertInIe();
  4797. }
  4798. else
  4799. {
  4800. this.line.insertInOthersBrowsers();
  4801. }
  4802. },
  4803. isExceptLastOrFirst: function(blocks)
  4804. {
  4805. var exceptTags = ['li', 'td', 'th', 'blockquote', 'figcaption', 'pre', 'dl', 'dt', 'dd'];
  4806. var first = blocks[0].tagName.toLowerCase();
  4807. var last = this.selection.getLastBlock();
  4808. last = (typeof last == 'undefined') ? first : last.tagName.toLowerCase();
  4809. var firstFound = $.inArray(first, exceptTags) != -1;
  4810. var lastFound = $.inArray(last, exceptTags) != -1;
  4811. if ((firstFound && lastFound) || firstFound)
  4812. {
  4813. return true;
  4814. }
  4815. },
  4816. insertInIe: function()
  4817. {
  4818. this.utils.saveScroll();
  4819. this.buffer.set();
  4820. this.insert.node(document.createElement('hr'));
  4821. this.utils.restoreScroll();
  4822. this.code.sync();
  4823. },
  4824. insertInOthersBrowsers: function()
  4825. {
  4826. this.buffer.set();
  4827. var extra = '<p id="redactor-insert-line"><br /></p>';
  4828. if (this.opts.linebreaks) extra = '<br id="redactor-insert-line">';
  4829. document.execCommand('insertHtml', false, '<hr>' + extra);
  4830. this.line.setFocus();
  4831. this.code.sync();
  4832. },
  4833. setFocus: function()
  4834. {
  4835. var node = this.$editor.find('#redactor-insert-line');
  4836. var next = $(node).next()[0];
  4837. var target = next;
  4838. if (this.utils.browser('mozilla') && next && next.innerHTML === '')
  4839. {
  4840. target = $(next).next()[0];
  4841. $(next).remove();
  4842. }
  4843. if (target)
  4844. {
  4845. node.remove();
  4846. if (!this.opts.linebreaks)
  4847. {
  4848. this.$editor.focus();
  4849. this.line.setStart(target);
  4850. }
  4851. }
  4852. else
  4853. {
  4854. node.removeAttr('id');
  4855. this.line.setStart(node[0]);
  4856. }
  4857. },
  4858. setStart: function(node)
  4859. {
  4860. if (typeof node === 'undefined') return;
  4861. var textNode = document.createTextNode('\u200B');
  4862. this.selection.get();
  4863. this.range.setStart(node, 0);
  4864. this.range.insertNode(textNode);
  4865. this.range.collapse(true);
  4866. this.selection.addRange();
  4867. }
  4868. };
  4869. },
  4870. link: function()
  4871. {
  4872. return {
  4873. show: function(e)
  4874. {
  4875. if (typeof e != 'undefined' && e.preventDefault) e.preventDefault();
  4876. if (!this.observe.isCurrent('a'))
  4877. {
  4878. this.modal.load('link', this.lang.get('link_insert'), 600);
  4879. }
  4880. else
  4881. {
  4882. this.modal.load('link', this.lang.get('link_edit'), 600);
  4883. }
  4884. this.modal.createCancelButton();
  4885. var buttonText = !this.observe.isCurrent('a') ? this.lang.get('insert') : this.lang.get('edit');
  4886. this.link.buttonInsert = this.modal.createActionButton(buttonText);
  4887. this.selection.get();
  4888. this.link.getData();
  4889. this.link.cleanUrl();
  4890. if (this.link.target == '_blank') $('#redactor-link-blank').prop('checked', true);
  4891. this.link.$inputUrl = $('#redactor-link-url');
  4892. this.link.$inputText = $('#redactor-link-url-text');
  4893. this.link.$inputText.val(this.link.text);
  4894. this.link.$inputUrl.val(this.link.url);
  4895. this.link.buttonInsert.on('click', $.proxy(this.link.insert, this));
  4896. // hide link's tooltip
  4897. $('.redactor-link-tooltip').remove();
  4898. // show modal
  4899. this.selection.save();
  4900. this.modal.show();
  4901. this.link.$inputUrl.focus();
  4902. },
  4903. cleanUrl: function()
  4904. {
  4905. var thref = self.location.href.replace(/\/$/i, '');
  4906. if (typeof this.link.url !== "undefined")
  4907. {
  4908. this.link.url = this.link.url.replace(thref, '');
  4909. this.link.url = this.link.url.replace(/^\/#/, '#');
  4910. this.link.url = this.link.url.replace('mailto:', '');
  4911. // remove host from href
  4912. if (!this.opts.linkProtocol)
  4913. {
  4914. var re = new RegExp('^(http|ftp|https)://' + self.location.host, 'i');
  4915. this.link.url = this.link.url.replace(re, '');
  4916. }
  4917. }
  4918. },
  4919. getData: function()
  4920. {
  4921. this.link.$node = false;
  4922. var $el = $(this.selection.getCurrent()).closest('a', this.$editor[0]);
  4923. if ($el.length !== 0 && $el[0].tagName === 'A')
  4924. {
  4925. this.link.$node = $el;
  4926. this.link.url = $el.attr('href');
  4927. this.link.text = $el.text();
  4928. this.link.target = $el.attr('target');
  4929. }
  4930. else
  4931. {
  4932. this.link.text = this.sel.toString();
  4933. this.link.url = '';
  4934. this.link.target = '';
  4935. }
  4936. },
  4937. insert: function()
  4938. {
  4939. this.placeholder.remove();
  4940. var target = '';
  4941. var link = this.link.$inputUrl.val();
  4942. var text = this.link.$inputText.val().replace(/(<([^>]+)>)/ig,"");
  4943. if ($.trim(link) === '')
  4944. {
  4945. this.link.$inputUrl.addClass('redactor-input-error').on('keyup', function()
  4946. {
  4947. $(this).removeClass('redactor-input-error');
  4948. $(this).off('keyup');
  4949. });
  4950. return;
  4951. }
  4952. // mailto
  4953. if (link.search('@') != -1 && /(http|ftp|https):\/\//i.test(link) === false)
  4954. {
  4955. link = link.replace('mailto:', '');
  4956. link = 'mailto:' + link;
  4957. }
  4958. // url, not anchor
  4959. else if (link.search('#') !== 0)
  4960. {
  4961. if ($('#redactor-link-blank').prop('checked'))
  4962. {
  4963. target = '_blank';
  4964. }
  4965. // test url (add protocol)
  4966. var pattern = '((xn--)?[a-z0-9]+(-[a-z0-9]+)*\\.)+[a-z]{2,}';
  4967. var re = new RegExp('^(http|ftp|https)://' + pattern, 'i');
  4968. var re2 = new RegExp('^' + pattern, 'i');
  4969. var re3 = new RegExp('\.(html|php)$', 'i');
  4970. if (link.search(re) == -1 && link.search(re3) == -1 && link.search(re2) === 0 && this.opts.linkProtocol)
  4971. {
  4972. link = this.opts.linkProtocol + '://' + link;
  4973. }
  4974. }
  4975. this.link.set(text, link, target);
  4976. this.modal.close();
  4977. },
  4978. set: function(text, link, target)
  4979. {
  4980. text = $.trim(text.replace(/<|>/g, ''));
  4981. this.selection.restore();
  4982. var blocks = this.selection.getBlocks();
  4983. if (text === '' && link === '') return;
  4984. if (text === '' && link !== '') text = link;
  4985. if (this.link.$node)
  4986. {
  4987. this.buffer.set();
  4988. var $link = this.link.$node,
  4989. $el = $link.children();
  4990. if ($el.length > 0)
  4991. {
  4992. while ($el.length)
  4993. {
  4994. $el = $el.children();
  4995. }
  4996. $el = $el.end();
  4997. }
  4998. else
  4999. {
  5000. $el = $link;
  5001. }
  5002. $link.attr('href', link);
  5003. $el.text(text);
  5004. if (target !== '')
  5005. {
  5006. $link.attr('target', target);
  5007. }
  5008. else
  5009. {
  5010. $link.removeAttr('target');
  5011. }
  5012. this.selection.selectElement($link);
  5013. this.code.sync();
  5014. }
  5015. else
  5016. {
  5017. if (this.utils.browser('mozilla') && this.link.text === '')
  5018. {
  5019. var $a = $('<a />').attr('href', link).text(text);
  5020. if (target !== '') $a.attr('target', target);
  5021. $a = $(this.insert.node($a));
  5022. if (this.opts.linebreaks)
  5023. {
  5024. $a.after('&nbsp;');
  5025. }
  5026. this.selection.selectElement($a);
  5027. }
  5028. else
  5029. {
  5030. var $a;
  5031. if (this.utils.browser('msie'))
  5032. {
  5033. $a = $('<a href="' + link + '">').text(text);
  5034. if (target !== '') $a.attr('target', target);
  5035. $a = $(this.insert.node($a));
  5036. if (this.selection.getText().match(/\s$/))
  5037. {
  5038. $a.after(" ");
  5039. }
  5040. this.selection.selectElement($a);
  5041. }
  5042. else
  5043. {
  5044. document.execCommand('createLink', false, link);
  5045. $a = $(this.selection.getCurrent()).closest('a', this.$editor[0]);
  5046. if (this.utils.browser('mozilla'))
  5047. {
  5048. $a = $('a[_moz_dirty=""]');
  5049. }
  5050. if (target !== '') $a.attr('target', target);
  5051. $a.removeAttr('style').removeAttr('_moz_dirty');
  5052. if (this.selection.getText().match(/\s$/))
  5053. {
  5054. $a.after(" ");
  5055. }
  5056. if (this.link.text !== '' || this.link.text != text)
  5057. {
  5058. if (!this.opts.linebreaks && blocks && blocks.length <= 1)
  5059. {
  5060. $a.text(text);
  5061. }
  5062. else if (this.opts.linebreaks)
  5063. {
  5064. $a.text(text);
  5065. }
  5066. this.selection.selectElement($a);
  5067. }
  5068. }
  5069. }
  5070. this.code.sync();
  5071. this.core.setCallback('insertedLink', $a);
  5072. }
  5073. // link tooltip
  5074. setTimeout($.proxy(function()
  5075. {
  5076. this.observe.links();
  5077. }, this), 5);
  5078. },
  5079. unlink: function(e)
  5080. {
  5081. if (typeof e != 'undefined' && e.preventDefault)
  5082. {
  5083. e.preventDefault();
  5084. }
  5085. var nodes = this.selection.getNodes();
  5086. if (!nodes) return;
  5087. this.buffer.set();
  5088. var len = nodes.length;
  5089. var links = [];
  5090. for (var i = 0; i < len; i++)
  5091. {
  5092. if (nodes[i].tagName === 'A')
  5093. {
  5094. links.push(nodes[i]);
  5095. }
  5096. var $node = $(nodes[i]).closest('a', this.$editor[0]);
  5097. $node.replaceWith($node.contents());
  5098. }
  5099. this.core.setCallback('deletedLink', links);
  5100. // hide link's tooltip
  5101. $('.redactor-link-tooltip').remove();
  5102. this.code.sync();
  5103. },
  5104. toggleClass: function(className)
  5105. {
  5106. this.link.setClass(className, 'toggleClass');
  5107. },
  5108. addClass: function(className)
  5109. {
  5110. this.link.setClass(className, 'addClass');
  5111. },
  5112. removeClass: function(className)
  5113. {
  5114. this.link.setClass(className, 'removeClass');
  5115. },
  5116. setClass: function(className, func)
  5117. {
  5118. var links = this.selection.getInlinesTags(['a']);
  5119. if (links === false) return;
  5120. $.each(links, function()
  5121. {
  5122. $(this)[func](className);
  5123. });
  5124. }
  5125. };
  5126. },
  5127. linkify: function()
  5128. {
  5129. return {
  5130. isKey: function(key)
  5131. {
  5132. return key == this.keyCode.ENTER || key == this.keyCode.SPACE;
  5133. },
  5134. isEnabled: function()
  5135. {
  5136. return this.opts.convertLinks && (this.opts.convertUrlLinks || this.opts.convertImageLinks || this.opts.convertVideoLinks) && !this.utils.isCurrentOrParent('PRE');
  5137. },
  5138. format: function()
  5139. {
  5140. var linkify = this.linkify,
  5141. opts = this.opts;
  5142. this.$editor
  5143. .find(":not(iframe,img,a,pre)")
  5144. .addBack()
  5145. .contents()
  5146. .filter(function()
  5147. {
  5148. return this.nodeType === 3 && $.trim(this.nodeValue) != "" && !$(this).parent().is("pre") && (this.nodeValue.match(opts.linkify.regexps.youtube) || this.nodeValue.match(opts.linkify.regexps.vimeo) || this.nodeValue.match(opts.linkify.regexps.image) || this.nodeValue.match(opts.linkify.regexps.url));
  5149. })
  5150. .each(function()
  5151. {
  5152. var text = $(this).text(),
  5153. html = text;
  5154. if (opts.convertVideoLinks && (html.match(opts.linkify.regexps.youtube) || html.match(opts.linkify.regexps.vimeo)) )
  5155. {
  5156. html = linkify.convertVideoLinks(html);
  5157. }
  5158. else if (opts.convertImageLinks && html.match(opts.linkify.regexps.image))
  5159. {
  5160. html = linkify.convertImages(html);
  5161. }
  5162. else if (opts.convertUrlLinks)
  5163. {
  5164. html = linkify.convertLinks(html);
  5165. }
  5166. $(this).before(text.replace(text, html))
  5167. .remove();
  5168. });
  5169. var objects = this.$editor.find('.redactor-linkify-object').each(function()
  5170. {
  5171. var $el = $(this);
  5172. $el.removeClass('redactor-linkify-object');
  5173. if ($el.attr('class') === '') $el.removeAttr('class');
  5174. return $el[0];
  5175. });
  5176. // callback
  5177. setTimeout($.proxy(function()
  5178. {
  5179. this.observe.load();
  5180. this.core.setCallback('linkify', objects);
  5181. }, this), 100);
  5182. // sync
  5183. this.code.sync();
  5184. },
  5185. convertVideoLinks: function(html)
  5186. {
  5187. var iframeStart = '<iframe class="redactor-linkify-object" width="500" height="281" src="',
  5188. iframeEnd = '" frameborder="0" allowfullscreen></iframe>';
  5189. if (html.match(this.opts.linkify.regexps.youtube))
  5190. {
  5191. html = html.replace(this.opts.linkify.regexps.youtube, iframeStart + '//www.youtube.com/embed/$1' + iframeEnd);
  5192. }
  5193. if (html.match(this.opts.linkify.regexps.vimeo))
  5194. {
  5195. html = html.replace(this.opts.linkify.regexps.vimeo, iframeStart + '//player.vimeo.com/video/$2' + iframeEnd);
  5196. }
  5197. return html;
  5198. },
  5199. convertImages: function(html)
  5200. {
  5201. var matches = html.match(this.opts.linkify.regexps.image);
  5202. if (matches)
  5203. {
  5204. html = html.replace(html, '<img src="' + matches + '" class="redactor-linkify-object" />');
  5205. if (this.opts.linebreaks)
  5206. {
  5207. if (!this.utils.isEmpty(this.code.get()))
  5208. {
  5209. html = '<br>' + html;
  5210. }
  5211. }
  5212. html += '<br>';
  5213. }
  5214. return html;
  5215. },
  5216. convertLinks: function(html)
  5217. {
  5218. var matches = html.match(this.opts.linkify.regexps.url);
  5219. if (matches)
  5220. {
  5221. matches = $.grep(matches, function(v, k) { return $.inArray(v, matches) === k; });
  5222. var length = matches.length;
  5223. for (var i = 0; i < length; i++)
  5224. {
  5225. var href = matches[i],
  5226. text = href,
  5227. linkProtocol = this.opts.linkProtocol + '://';
  5228. if (href.match(/(https?|ftp):\/\//i) !== null)
  5229. {
  5230. linkProtocol = "";
  5231. }
  5232. if (text.length > this.opts.linkSize)
  5233. {
  5234. text = text.substring(0, this.opts.linkSize) + '...';
  5235. }
  5236. if (text.search('%') === -1)
  5237. {
  5238. text = decodeURIComponent(text);
  5239. }
  5240. var regexB = "\\b";
  5241. if ($.inArray(href.slice(-1), ["/", "&", "="]) != -1)
  5242. {
  5243. regexB = "";
  5244. }
  5245. // escaping url
  5246. var regexp = new RegExp('(' + href.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + regexB + ')', 'g');
  5247. html = html.replace(regexp, '<a href="' + linkProtocol + $.trim(href) + '" class="redactor-linkify-object">' + $.trim(text) + '</a>');
  5248. }
  5249. }
  5250. return html;
  5251. }
  5252. };
  5253. },
  5254. list: function()
  5255. {
  5256. return {
  5257. toggle: function(cmd)
  5258. {
  5259. this.placeholder.remove();
  5260. if (!this.utils.browser('msie') && !this.opts.linebreaks)
  5261. {
  5262. this.$editor.focus();
  5263. }
  5264. this.buffer.set();
  5265. this.selection.save();
  5266. var parent = this.selection.getParent();
  5267. var $list = $(parent).closest('ol, ul', this.$editor[0]);
  5268. if (!this.utils.isRedactorParent($list) && $list.length !== 0)
  5269. {
  5270. $list = false;
  5271. }
  5272. var isUnorderedCmdOrdered, isOrderedCmdUnordered;
  5273. var remove = false;
  5274. if ($list && $list.length)
  5275. {
  5276. remove = true;
  5277. var listTag = $list[0].tagName;
  5278. isUnorderedCmdOrdered = (cmd === 'orderedlist' && listTag === 'UL');
  5279. isOrderedCmdUnordered = (cmd === 'unorderedlist' && listTag === 'OL');
  5280. }
  5281. if (isUnorderedCmdOrdered)
  5282. {
  5283. this.utils.replaceToTag($list, 'ol');
  5284. }
  5285. else if (isOrderedCmdUnordered)
  5286. {
  5287. this.utils.replaceToTag($list, 'ul');
  5288. }
  5289. else
  5290. {
  5291. if (remove)
  5292. {
  5293. this.list.remove(cmd, $list);
  5294. }
  5295. else
  5296. {
  5297. this.list.insert(cmd);
  5298. }
  5299. }
  5300. this.selection.restore();
  5301. this.code.sync();
  5302. },
  5303. insert: function(cmd)
  5304. {
  5305. var current = this.selection.getCurrent();
  5306. var $td = $(current).closest('td, th', this.$editor[0]);
  5307. if (this.utils.browser('msie') && this.opts.linebreaks)
  5308. {
  5309. this.list.insertInIe(cmd);
  5310. }
  5311. else
  5312. {
  5313. document.execCommand('insert' + cmd);
  5314. }
  5315. var parent = this.selection.getParent();
  5316. var $list = $(parent).closest('ol, ul', this.$editor[0]);
  5317. if ($td.length !== 0)
  5318. {
  5319. var newTd = $td.clone();
  5320. $td.after(newTd).remove('');
  5321. }
  5322. if (this.utils.isEmpty($list.find('li').text()))
  5323. {
  5324. var $children = $list.children('li');
  5325. $children.find('br').remove();
  5326. $children.append(this.selection.getMarkerAsHtml());
  5327. if (this.opts.linebreaks && this.utils.browser('mozilla') && $children.size() == 2 && this.utils.isEmpty($children.eq(1).text()))
  5328. {
  5329. $children.eq(1).remove();
  5330. }
  5331. }
  5332. if ($list.length)
  5333. {
  5334. // remove block-element list wrapper
  5335. var $listParent = $list.parent();
  5336. if (this.utils.isRedactorParent($listParent) && $listParent[0].tagName != 'LI' && this.utils.isBlock($listParent[0]))
  5337. {
  5338. $listParent.replaceWith($listParent.contents());
  5339. }
  5340. }
  5341. if (!this.utils.browser('msie'))
  5342. {
  5343. this.$editor.focus();
  5344. }
  5345. this.clean.clearUnverified();
  5346. },
  5347. insertInIe: function(cmd)
  5348. {
  5349. var wrapper = this.selection.wrap('div');
  5350. var wrapperHtml = $(wrapper).html();
  5351. var tmpList = (cmd == 'orderedlist') ? $('<ol>') : $('<ul>');
  5352. var tmpLi = $('<li>');
  5353. if ($.trim(wrapperHtml) === '')
  5354. {
  5355. tmpLi.append(this.selection.getMarkerAsHtml());
  5356. tmpList.append(tmpLi);
  5357. this.$editor.find('#selection-marker-1').replaceWith(tmpList);
  5358. }
  5359. else
  5360. {
  5361. var items = wrapperHtml.split(/<br\s?\/?>/gi);
  5362. if (items)
  5363. {
  5364. for (var i = 0; i < items.length; i++)
  5365. {
  5366. if ($.trim(items[i]) !== '')
  5367. {
  5368. tmpList.append($('<li>').html(items[i]));
  5369. }
  5370. }
  5371. }
  5372. else
  5373. {
  5374. tmpLi.append(wrapperHtml);
  5375. tmpList.append(tmpLi);
  5376. }
  5377. $(wrapper).replaceWith(tmpList);
  5378. }
  5379. },
  5380. remove: function(cmd, $list)
  5381. {
  5382. if ($.inArray('ul', this.selection.getBlocks())) cmd = 'unorderedlist';
  5383. document.execCommand('insert' + cmd);
  5384. var $current = $(this.selection.getCurrent());
  5385. this.indent.fixEmptyIndent();
  5386. if (!this.opts.linebreaks && $current.closest('li, th, td', this.$editor[0]).length === 0)
  5387. {
  5388. document.execCommand('formatblock', false, 'p');
  5389. this.$editor.find('ul, ol, blockquote').each($.proxy(this.utils.removeEmpty, this));
  5390. }
  5391. var $table = $(this.selection.getCurrent()).closest('table', this.$editor[0]);
  5392. var $prev = $table.prev();
  5393. if (!this.opts.linebreaks && $table.length !== 0 && $prev.length !== 0 && $prev[0].tagName == 'BR')
  5394. {
  5395. $prev.remove();
  5396. }
  5397. this.clean.clearUnverified();
  5398. }
  5399. };
  5400. },
  5401. modal: function()
  5402. {
  5403. return {
  5404. callbacks: {},
  5405. loadTemplates: function()
  5406. {
  5407. this.opts.modal = {
  5408. imageEdit: String()
  5409. + '<section id="redactor-modal-image-edit">'
  5410. + '<label>' + this.lang.get('title') + '</label>'
  5411. + '<input type="text" id="redactor-image-title" />'
  5412. + '<label class="redactor-image-link-option">' + this.lang.get('link') + '</label>'
  5413. + '<input type="text" id="redactor-image-link" class="redactor-image-link-option" aria-label="' + this.lang.get('link') + '" />'
  5414. + '<label class="redactor-image-link-option"><input type="checkbox" id="redactor-image-link-blank" aria-label="' + this.lang.get('link_new_tab') + '"> ' + this.lang.get('link_new_tab') + '</label>'
  5415. + '<label class="redactor-image-position-option">' + this.lang.get('image_position') + '</label>'
  5416. + '<select class="redactor-image-position-option" id="redactor-image-align" aria-label="' + this.lang.get('image_position') + '">'
  5417. + '<option value="none">' + this.lang.get('none') + '</option>'
  5418. + '<option value="left">' + this.lang.get('left') + '</option>'
  5419. + '<option value="center">' + this.lang.get('center') + '</option>'
  5420. + '<option value="right">' + this.lang.get('right') + '</option>'
  5421. + '</select>'
  5422. + '</section>',
  5423. image: String()
  5424. + '<section id="redactor-modal-image-insert">'
  5425. + '<div id="redactor-modal-image-droparea"></div>'
  5426. + '</section>',
  5427. file: String()
  5428. + '<section id="redactor-modal-file-insert">'
  5429. + '<div id="redactor-modal-file-upload-box">'
  5430. + '<label>' + this.lang.get('filename') + '</label>'
  5431. + '<input type="text" id="redactor-filename" aria-label="' + this.lang.get('filename') + '" /><br><br>'
  5432. + '<div id="redactor-modal-file-upload"></div>'
  5433. + '</div>'
  5434. + '</section>',
  5435. link: String()
  5436. + '<section id="redactor-modal-link-insert">'
  5437. + '<label>URL</label>'
  5438. + '<input type="url" id="redactor-link-url" aria-label="URL" />'
  5439. + '<label>' + this.lang.get('text') + '</label>'
  5440. + '<input type="text" id="redactor-link-url-text" aria-label="' + this.lang.get('text') + '" />'
  5441. + '<label><input type="checkbox" id="redactor-link-blank"> ' + this.lang.get('link_new_tab') + '</label>'
  5442. + '</section>'
  5443. };
  5444. $.extend(this.opts, this.opts.modal);
  5445. },
  5446. addCallback: function(name, callback)
  5447. {
  5448. this.modal.callbacks[name] = callback;
  5449. },
  5450. createTabber: function($modal)
  5451. {
  5452. this.modal.$tabber = $('<div>').attr('id', 'redactor-modal-tabber');
  5453. $modal.prepend(this.modal.$tabber);
  5454. },
  5455. addTab: function(id, name, active)
  5456. {
  5457. var $tab = $('<a href="#" rel="tab' + id + '">').text(name);
  5458. if (active)
  5459. {
  5460. $tab.addClass('active');
  5461. }
  5462. var self = this;
  5463. $tab.on('click', function(e)
  5464. {
  5465. e.preventDefault();
  5466. $('.redactor-tab').hide();
  5467. $('.redactor-' + $(this).attr('rel')).show();
  5468. self.modal.$tabber.find('a').removeClass('active');
  5469. $(this).addClass('active');
  5470. });
  5471. this.modal.$tabber.append($tab);
  5472. },
  5473. addTemplate: function(name, template)
  5474. {
  5475. this.opts.modal[name] = template;
  5476. },
  5477. getTemplate: function(name)
  5478. {
  5479. return this.opts.modal[name];
  5480. },
  5481. getModal: function()
  5482. {
  5483. return this.$modalBody.find('section');
  5484. },
  5485. load: function(templateName, title, width)
  5486. {
  5487. this.modal.templateName = templateName;
  5488. this.modal.width = width;
  5489. this.modal.build();
  5490. this.modal.enableEvents();
  5491. this.modal.setTitle(title);
  5492. this.modal.setDraggable();
  5493. this.modal.setContent();
  5494. // callbacks
  5495. if (typeof this.modal.callbacks[templateName] != 'undefined')
  5496. {
  5497. this.modal.callbacks[templateName].call(this);
  5498. }
  5499. },
  5500. show: function()
  5501. {
  5502. this.utils.disableBodyScroll();
  5503. if (this.utils.isMobile())
  5504. {
  5505. this.modal.showOnMobile();
  5506. }
  5507. else
  5508. {
  5509. this.modal.showOnDesktop();
  5510. }
  5511. if (this.opts.highContrast)
  5512. {
  5513. this.$modalBox.addClass("redactor-modal-contrast");
  5514. }
  5515. this.$modalOverlay.show();
  5516. this.$modalBox.show();
  5517. this.$modal.attr('tabindex', '-1');
  5518. this.$modal.focus();
  5519. this.modal.setButtonsWidth();
  5520. this.utils.saveScroll();
  5521. // resize
  5522. if (!this.utils.isMobile())
  5523. {
  5524. setTimeout($.proxy(this.modal.showOnDesktop, this), 0);
  5525. $(window).on('resize.redactor-modal', $.proxy(this.modal.resize, this));
  5526. }
  5527. // modal shown callback
  5528. this.core.setCallback('modalOpened', this.modal.templateName, this.$modal);
  5529. // fix bootstrap modal focus
  5530. $(document).off('focusin.modal');
  5531. // enter
  5532. this.$modal.find('input[type=text],input[type=url],input[type=email]').on('keydown.redactor-modal', $.proxy(this.modal.setEnter, this));
  5533. },
  5534. showOnDesktop: function()
  5535. {
  5536. var height = this.$modal.outerHeight();
  5537. var windowHeight = $(window).height();
  5538. var windowWidth = $(window).width();
  5539. if (this.modal.width > windowWidth)
  5540. {
  5541. this.$modal.css({
  5542. width: '96%',
  5543. marginTop: (windowHeight/2 - height/2) + 'px'
  5544. });
  5545. return;
  5546. }
  5547. if (height > windowHeight)
  5548. {
  5549. this.$modal.css({
  5550. width: this.modal.width + 'px',
  5551. marginTop: '20px'
  5552. });
  5553. }
  5554. else
  5555. {
  5556. this.$modal.css({
  5557. width: this.modal.width + 'px',
  5558. marginTop: (windowHeight/2 - height/2) + 'px'
  5559. });
  5560. }
  5561. },
  5562. showOnMobile: function()
  5563. {
  5564. this.$modal.css({
  5565. width: '96%',
  5566. marginTop: '2%'
  5567. });
  5568. },
  5569. resize: function()
  5570. {
  5571. if (this.utils.isMobile())
  5572. {
  5573. this.modal.showOnMobile();
  5574. }
  5575. else
  5576. {
  5577. this.modal.showOnDesktop();
  5578. }
  5579. },
  5580. setTitle: function(title)
  5581. {
  5582. this.$modalHeader.html(title);
  5583. },
  5584. setContent: function()
  5585. {
  5586. this.$modalBody.html(this.modal.getTemplate(this.modal.templateName));
  5587. },
  5588. setDraggable: function()
  5589. {
  5590. if (typeof $.fn.draggable === 'undefined') return;
  5591. this.$modal.draggable({ handle: this.$modalHeader });
  5592. this.$modalHeader.css('cursor', 'move');
  5593. },
  5594. setEnter: function(e)
  5595. {
  5596. if (e.which != 13) return;
  5597. e.preventDefault();
  5598. this.$modal.find('button.redactor-modal-action-btn').click();
  5599. },
  5600. createCancelButton: function()
  5601. {
  5602. var button = $('<button>').addClass('redactor-modal-btn redactor-modal-close-btn').html(this.lang.get('cancel'));
  5603. button.on('click', $.proxy(this.modal.close, this));
  5604. this.$modalFooter.append(button);
  5605. },
  5606. createDeleteButton: function(label)
  5607. {
  5608. return this.modal.createButton(label, 'delete');
  5609. },
  5610. createActionButton: function(label)
  5611. {
  5612. return this.modal.createButton(label, 'action');
  5613. },
  5614. createButton: function(label, className)
  5615. {
  5616. var button = $('<button>').addClass('redactor-modal-btn').addClass('redactor-modal-' + className + '-btn').html(label);
  5617. this.$modalFooter.append(button);
  5618. return button;
  5619. },
  5620. setButtonsWidth: function()
  5621. {
  5622. var buttons = this.$modalFooter.find('button');
  5623. var buttonsSize = buttons.length;
  5624. if (buttonsSize === 0) return;
  5625. buttons.css('width', (100/buttonsSize) + '%');
  5626. },
  5627. build: function()
  5628. {
  5629. this.modal.buildOverlay();
  5630. this.$modalBox = $('<div id="redactor-modal-box"/>').hide();
  5631. this.$modal = $('<div id="redactor-modal" role="dialog" aria-labelledby="redactor-modal-header" />');
  5632. this.$modalHeader = $('<header id="redactor-modal-header"/>');
  5633. this.$modalClose = $('<button type="button" id="redactor-modal-close" tabindex="1" aria-label="Close" />').html('&times;');
  5634. this.$modalBody = $('<div id="redactor-modal-body" />');
  5635. this.$modalFooter = $('<footer />');
  5636. this.$modal.append(this.$modalHeader);
  5637. this.$modal.append(this.$modalClose);
  5638. this.$modal.append(this.$modalBody);
  5639. this.$modal.append(this.$modalFooter);
  5640. this.$modalBox.append(this.$modal);
  5641. this.$modalBox.appendTo(document.body);
  5642. },
  5643. buildOverlay: function()
  5644. {
  5645. this.$modalOverlay = $('<div id="redactor-modal-overlay">').hide();
  5646. $('body').prepend(this.$modalOverlay);
  5647. },
  5648. enableEvents: function()
  5649. {
  5650. this.$modalClose.on('click.redactor-modal', $.proxy(this.modal.close, this));
  5651. $(document).on('keyup.redactor-modal', $.proxy(this.modal.closeHandler, this));
  5652. this.$editor.on('keyup.redactor-modal', $.proxy(this.modal.closeHandler, this));
  5653. this.$modalBox.on('click.redactor-modal', $.proxy(this.modal.close, this));
  5654. },
  5655. disableEvents: function()
  5656. {
  5657. this.$modalClose.off('click.redactor-modal');
  5658. $(document).off('keyup.redactor-modal');
  5659. this.$editor.off('keyup.redactor-modal');
  5660. this.$modalBox.off('click.redactor-modal');
  5661. $(window).off('resize.redactor-modal');
  5662. },
  5663. closeHandler: function(e)
  5664. {
  5665. if (e.which != this.keyCode.ESC) return;
  5666. this.modal.close(false);
  5667. },
  5668. close: function(e)
  5669. {
  5670. if (e)
  5671. {
  5672. if (!$(e.target).hasClass('redactor-modal-close-btn') && e.target != this.$modalClose[0] && e.target != this.$modalBox[0])
  5673. {
  5674. return;
  5675. }
  5676. e.preventDefault();
  5677. }
  5678. if (!this.$modalBox) return;
  5679. this.modal.disableEvents();
  5680. this.utils.enableBodyScroll();
  5681. this.$modalOverlay.remove();
  5682. this.$modalBox.fadeOut('fast', $.proxy(function()
  5683. {
  5684. this.$modalBox.remove();
  5685. setTimeout($.proxy(this.utils.restoreScroll, this), 0);
  5686. if (e !== undefined) this.selection.restore();
  5687. $(document.body).css('overflow', this.modal.bodyOveflow);
  5688. this.core.setCallback('modalClosed', this.modal.templateName);
  5689. }, this));
  5690. }
  5691. };
  5692. },
  5693. observe: function()
  5694. {
  5695. return {
  5696. load: function()
  5697. {
  5698. if (typeof this.opts.destroyed != "undefined") return;
  5699. if (this.utils.browser('msie'))
  5700. {
  5701. var self = this;
  5702. this.$editor.find('pre, code').on('mouseover',function()
  5703. {
  5704. self.$editor.attr('contenteditable', false);
  5705. $(this).attr('contenteditable', true);
  5706. }).on('mouseout',function()
  5707. {
  5708. self.$editor.attr('contenteditable', true);
  5709. $(this).removeAttr('contenteditable');
  5710. });
  5711. }
  5712. this.observe.images();
  5713. this.observe.links();
  5714. },
  5715. toolbar: function(e, btnName)
  5716. {
  5717. this.observe.buttons(e, btnName);
  5718. this.observe.dropdowns();
  5719. },
  5720. isCurrent: function($el, $current)
  5721. {
  5722. if (typeof $current == 'undefined')
  5723. {
  5724. var $current = $(this.selection.getCurrent());
  5725. }
  5726. return $current.is($el) || $current.parents($el).length > 0;
  5727. },
  5728. dropdowns: function()
  5729. {
  5730. var $current = $(this.selection.getCurrent());
  5731. $.each(this.opts.observe.dropdowns, $.proxy(function(key, value)
  5732. {
  5733. var observe = value.observe,
  5734. element = observe.element,
  5735. $item = value.item,
  5736. inValues = typeof observe['in'] != 'undefined' ? observe['in'] : false,
  5737. outValues = typeof observe['out'] != 'undefined' ? observe['out'] : false;
  5738. if ($current.closest(element).size() > 0)
  5739. {
  5740. this.observe.setDropdownProperties($item, inValues, outValues);
  5741. }
  5742. else
  5743. {
  5744. this.observe.setDropdownProperties($item, outValues, inValues);
  5745. }
  5746. }, this));
  5747. },
  5748. setDropdownProperties: function($item, addProperties, deleteProperties)
  5749. {
  5750. if (deleteProperties && typeof deleteProperties['attr'] != 'undefined')
  5751. {
  5752. this.observe.setDropdownAttr($item, deleteProperties.attr, true);
  5753. }
  5754. if (typeof addProperties['attr'] != 'undefined')
  5755. {
  5756. this.observe.setDropdownAttr($item, addProperties.attr);
  5757. }
  5758. if (typeof addProperties['title'] != 'undefined')
  5759. {
  5760. $item.text(addProperties['title']);
  5761. }
  5762. },
  5763. setDropdownAttr: function($item, properties, isDelete)
  5764. {
  5765. $.each(properties, function(key, value)
  5766. {
  5767. if (key == 'class')
  5768. {
  5769. if (!isDelete)
  5770. {
  5771. $item.addClass(value);
  5772. }
  5773. else
  5774. {
  5775. $item.removeClass(value);
  5776. }
  5777. }
  5778. else
  5779. {
  5780. if (!isDelete)
  5781. {
  5782. $item.attr(key, value);
  5783. }
  5784. else
  5785. {
  5786. $item.removeAttr(key);
  5787. }
  5788. }
  5789. });
  5790. },
  5791. addDropdown: function($item, btnName, btnObject)
  5792. {
  5793. if (typeof btnObject.observe == "undefined") return;
  5794. btnObject.item = $item;
  5795. this.opts.observe.dropdowns.push(btnObject);
  5796. },
  5797. buttons: function(e, btnName)
  5798. {
  5799. var current = this.selection.getCurrent();
  5800. var parent = this.selection.getParent();
  5801. if (e !== false)
  5802. {
  5803. this.button.setInactiveAll();
  5804. }
  5805. else
  5806. {
  5807. this.button.setInactiveAll(btnName);
  5808. }
  5809. if (e === false && btnName !== 'html')
  5810. {
  5811. if ($.inArray(btnName, this.opts.activeButtons) != -1) this.button.toggleActive(btnName);
  5812. return;
  5813. }
  5814. //var linkButtonName = (this.utils.isCurrentOrParent('A')) ? this.lang.get('link_edit') : this.lang.get('link_insert');
  5815. //$('body').find('a.redactor-dropdown-link').text(linkButtonName);
  5816. $.each(this.opts.activeButtonsStates, $.proxy(function(key, value)
  5817. {
  5818. var parentEl = $(parent).closest(key, this.$editor[0]);
  5819. var currentEl = $(current).closest(key, this.$editor[0]);
  5820. if (parentEl.length !== 0 && !this.utils.isRedactorParent(parentEl)) return;
  5821. if (!this.utils.isRedactorParent(currentEl)) return;
  5822. if (parentEl.length !== 0 || currentEl.closest(key, this.$editor[0]).length !== 0)
  5823. {
  5824. this.button.setActive(value);
  5825. }
  5826. }, this));
  5827. var $parent = $(parent).closest(this.opts.alignmentTags.toString().toLowerCase(), this.$editor[0]);
  5828. if (this.utils.isRedactorParent(parent) && $parent.length)
  5829. {
  5830. var align = ($parent.css('text-align') === '') ? 'left' : $parent.css('text-align');
  5831. this.button.setActive('align' + align);
  5832. }
  5833. },
  5834. addButton: function(tag, btnName)
  5835. {
  5836. this.opts.activeButtons.push(btnName);
  5837. this.opts.activeButtonsStates[tag] = btnName;
  5838. },
  5839. images: function()
  5840. {
  5841. this.$editor.find('img').each($.proxy(function(i, img)
  5842. {
  5843. var $img = $(img);
  5844. // IE fix (when we clicked on an image and then press backspace IE does goes to image's url)
  5845. $img.closest('a', this.$editor[0]).on('click', function(e) { e.preventDefault(); });
  5846. if (this.utils.browser('msie')) $img.attr('unselectable', 'on');
  5847. this.image.setEditable($img);
  5848. }, this));
  5849. $(document).on('click.redactor-image-delete.' + this.uuid, $.proxy(function(e)
  5850. {
  5851. this.observe.image = false;
  5852. if (e.target.tagName == 'IMG' && this.utils.isRedactorParent(e.target))
  5853. {
  5854. this.observe.image = (this.observe.image && this.observe.image == e.target) ? false : e.target;
  5855. }
  5856. }, this));
  5857. },
  5858. links: function()
  5859. {
  5860. if (!this.opts.linkTooltip) return;
  5861. this.$editor.find('a').on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.showTooltip, this));
  5862. this.$editor.on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this));
  5863. $(document).on('touchstart.redactor.' + this.uuid + ' click.redactor.' + this.uuid, $.proxy(this.observe.closeTooltip, this));
  5864. },
  5865. getTooltipPosition: function($link)
  5866. {
  5867. return $link.offset();
  5868. },
  5869. showTooltip: function(e)
  5870. {
  5871. var $el = $(e.target);
  5872. if ($el[0].tagName == 'IMG')
  5873. return;
  5874. if ($el[0].tagName !== 'A')
  5875. $el = $el.closest('a', this.$editor[0]);
  5876. if ($el[0].tagName !== 'A')
  5877. return;
  5878. var $link = $el;
  5879. var pos = this.observe.getTooltipPosition($link);
  5880. var tooltip = $('<span class="redactor-link-tooltip"></span>');
  5881. var href = $link.attr('href');
  5882. if (href === undefined)
  5883. {
  5884. href = '';
  5885. }
  5886. if (href.length > 24) href = href.substring(0, 24) + '...';
  5887. var aLink = $('<a href="' + $link.attr('href') + '" target="_blank" />').html(href).addClass('redactor-link-tooltip-action');
  5888. var aEdit = $('<a href="#" />').html(this.lang.get('edit')).on('click', $.proxy(this.link.show, this)).addClass('redactor-link-tooltip-action');
  5889. var aUnlink = $('<a href="#" />').html(this.lang.get('unlink')).on('click', $.proxy(this.link.unlink, this)).addClass('redactor-link-tooltip-action');
  5890. tooltip.append(aLink).append(' | ').append(aEdit).append(' | ').append(aUnlink);
  5891. tooltip.css({
  5892. top: (pos.top + parseInt($link.css('line-height'), 10)) + 'px',
  5893. left: pos.left + 'px'
  5894. });
  5895. $('.redactor-link-tooltip').remove();
  5896. $('body').append(tooltip);
  5897. },
  5898. closeTooltip: function(e)
  5899. {
  5900. e = e.originalEvent || e;
  5901. var target = e.target;
  5902. var $parent = $(target).closest('a', this.$editor[0]);
  5903. if ($parent.length !== 0 && $parent[0].tagName === 'A' && target.tagName !== 'A')
  5904. {
  5905. return;
  5906. }
  5907. else if ((target.tagName === 'A' && this.utils.isRedactorParent(target)) || $(target).hasClass('redactor-link-tooltip-action'))
  5908. {
  5909. return;
  5910. }
  5911. $('.redactor-link-tooltip').remove();
  5912. }
  5913. };
  5914. },
  5915. paragraphize: function()
  5916. {
  5917. return {
  5918. load: function(html)
  5919. {
  5920. if (this.opts.linebreaks) return html;
  5921. if (html === '' || html === '<p></p>') return this.opts.emptyHtml;
  5922. html = html + "\n";
  5923. this.paragraphize.safes = [];
  5924. this.paragraphize.z = 0;
  5925. html = html.replace(/(<br\s?\/?>){1,}\n?<\/blockquote>/gi, '</blockquote>');
  5926. html = this.paragraphize.getSafes(html);
  5927. html = this.paragraphize.getSafesComments(html);
  5928. html = this.paragraphize.replaceBreaksToNewLines(html);
  5929. html = this.paragraphize.replaceBreaksToParagraphs(html);
  5930. html = this.paragraphize.clear(html);
  5931. html = this.paragraphize.restoreSafes(html);
  5932. html = html.replace(new RegExp('<br\\s?/?>\n?<(' + this.opts.paragraphizeBlocks.join('|') + ')(.*?[^>])>', 'gi'), '<p><br /></p>\n<$1$2>');
  5933. return $.trim(html);
  5934. },
  5935. getSafes: function(html)
  5936. {
  5937. var $div = $('<div />').append(html);
  5938. // remove paragraphs in blockquotes
  5939. $div.find('blockquote p').replaceWith(function()
  5940. {
  5941. return $(this).append('<br />').contents();
  5942. });
  5943. html = $div.html();
  5944. $div.find(this.opts.paragraphizeBlocks.join(', ')).each($.proxy(function(i,s)
  5945. {
  5946. this.paragraphize.z++;
  5947. this.paragraphize.safes[this.paragraphize.z] = s.outerHTML;
  5948. html = html.replace(s.outerHTML, '\n{replace' + this.paragraphize.z + '}');
  5949. }, this));
  5950. return html;
  5951. },
  5952. getSafesComments: function(html)
  5953. {
  5954. var commentsMatches = html.match(/<!--([\w\W]*?)-->/gi);
  5955. if (!commentsMatches) return html;
  5956. $.each(commentsMatches, $.proxy(function(i,s)
  5957. {
  5958. this.paragraphize.z++;
  5959. this.paragraphize.safes[this.paragraphize.z] = s;
  5960. html = html.replace(s, '\n{replace' + this.paragraphize.z + '}');
  5961. }, this));
  5962. return html;
  5963. },
  5964. restoreSafes: function(html)
  5965. {
  5966. $.each(this.paragraphize.safes, function(i,s)
  5967. {
  5968. s = (typeof s !== 'undefined') ? s.replace(/\$/g, '&#36;') : s;
  5969. html = html.replace('{replace' + i + '}', s);
  5970. });
  5971. return html;
  5972. },
  5973. replaceBreaksToParagraphs: function(html)
  5974. {
  5975. var htmls = html.split(new RegExp('\n', 'g'), -1);
  5976. html = '';
  5977. if (htmls)
  5978. {
  5979. var len = htmls.length;
  5980. for (var i = 0; i < len; i++)
  5981. {
  5982. if (!htmls.hasOwnProperty(i)) return;
  5983. if (htmls[i].search('{replace') == -1)
  5984. {
  5985. htmls[i] = htmls[i].replace(/<p>\n\t?<\/p>/gi, '');
  5986. htmls[i] = htmls[i].replace(/<p><\/p>/gi, '');
  5987. if (htmls[i] !== '')
  5988. {
  5989. html += '<p>' + htmls[i].replace(/^\n+|\n+$/g, "") + "</p>";
  5990. }
  5991. }
  5992. else html += htmls[i];
  5993. }
  5994. }
  5995. return html;
  5996. },
  5997. replaceBreaksToNewLines: function(html)
  5998. {
  5999. html = html.replace(/<br \/>\s*<br \/>/gi, "\n\n");
  6000. html = html.replace(/<br\s?\/?>\n?<br\s?\/?>/gi, "\n<br /><br />");
  6001. html = html.replace(new RegExp("\r\n", 'g'), "\n");
  6002. html = html.replace(new RegExp("\r", 'g'), "\n");
  6003. html = html.replace(new RegExp("/\n\n+/"), 'g', "\n\n");
  6004. return html;
  6005. },
  6006. clear: function(html)
  6007. {
  6008. html = html.replace(new RegExp('</blockquote></p>', 'gi'), '</blockquote>');
  6009. html = html.replace(new RegExp('<p></blockquote>', 'gi'), '</blockquote>');
  6010. html = html.replace(new RegExp('<p><blockquote>', 'gi'), '<blockquote>');
  6011. html = html.replace(new RegExp('<blockquote></p>', 'gi'), '<blockquote>');
  6012. html = html.replace(new RegExp('<p><p ', 'gi'), '<p ');
  6013. html = html.replace(new RegExp('<p><p>', 'gi'), '<p>');
  6014. html = html.replace(new RegExp('</p></p>', 'gi'), '</p>');
  6015. html = html.replace(new RegExp('<p>\\s?</p>', 'gi'), '');
  6016. html = html.replace(new RegExp("\n</p>", 'gi'), '</p>');
  6017. html = html.replace(new RegExp('<p>\t?\t?\n?<p>', 'gi'), '<p>');
  6018. html = html.replace(new RegExp('<p>\t*</p>', 'gi'), '');
  6019. return html;
  6020. }
  6021. };
  6022. },
  6023. paste: function()
  6024. {
  6025. return {
  6026. init: function(e)
  6027. {
  6028. if (!this.opts.cleanOnPaste)
  6029. {
  6030. setTimeout($.proxy(this.code.sync, this), 1);
  6031. return;
  6032. }
  6033. this.rtePaste = true;
  6034. this.buffer.set();
  6035. this.selection.save();
  6036. this.utils.saveScroll();
  6037. this.paste.createPasteBox();
  6038. $(window).on('scroll.redactor-freeze', $.proxy(function()
  6039. {
  6040. $(window).scrollTop(this.saveBodyScroll);
  6041. }, this));
  6042. setTimeout($.proxy(function()
  6043. {
  6044. var html = this.$pasteBox.html();
  6045. this.$pasteBox.remove();
  6046. this.selection.restore();
  6047. this.utils.restoreScroll();
  6048. this.paste.insert(html);
  6049. $(window).off('scroll.redactor-freeze');
  6050. if (this.linkify.isEnabled())
  6051. {
  6052. this.linkify.format();
  6053. }
  6054. }, this), 1);
  6055. },
  6056. createPasteBox: function()
  6057. {
  6058. this.$pasteBox = $('<div>').html('').attr('contenteditable', 'true').css({ position: 'fixed', width: 0, top: 0, left: '-9999px' });
  6059. if (this.utils.browser('msie'))
  6060. {
  6061. this.$box.append(this.$pasteBox);
  6062. }
  6063. else
  6064. {
  6065. // bootstrap modal
  6066. var $visibleModals = $('.modal-body:visible');
  6067. if ($visibleModals.length > 0)
  6068. {
  6069. $visibleModals.append(this.$pasteBox);
  6070. }
  6071. else
  6072. {
  6073. $('body').append(this.$pasteBox);
  6074. }
  6075. }
  6076. this.$pasteBox.get(0).focus();
  6077. },
  6078. insert: function(html)
  6079. {
  6080. html = this.core.setCallback('pasteBefore', html);
  6081. // clean
  6082. html = (this.utils.isSelectAll()) ? this.clean.onPaste(html, false) : this.clean.onPaste(html);
  6083. html = this.core.setCallback('paste', html);
  6084. if (this.utils.isSelectAll())
  6085. {
  6086. this.insert.set(html, false);
  6087. }
  6088. else
  6089. {
  6090. this.insert.html(html, false);
  6091. }
  6092. this.utils.disableSelectAll();
  6093. this.rtePaste = false;
  6094. setTimeout($.proxy(this.clean.clearUnverified, this), 10);
  6095. // clean empty spans
  6096. setTimeout($.proxy(function()
  6097. {
  6098. var spans = this.$editor.find('span');
  6099. $.each(spans, function(i,s)
  6100. {
  6101. var html = s.innerHTML.replace(/\u200B/, '');
  6102. if (html === '' && s.attributes.length === 0) $(s).remove();
  6103. });
  6104. }, this), 10);
  6105. }
  6106. };
  6107. },
  6108. placeholder: function()
  6109. {
  6110. return {
  6111. enable: function()
  6112. {
  6113. if (!this.placeholder.is()) return;
  6114. this.$editor.attr('placeholder', this.$element.attr('placeholder'));
  6115. this.placeholder.toggle();
  6116. this.$editor.on('keydown.redactor-placeholder', $.proxy(this.placeholder.toggle, this));
  6117. },
  6118. toggle: function()
  6119. {
  6120. setTimeout($.proxy(function()
  6121. {
  6122. var func = this.utils.isEmpty(this.$editor.html(), false) ? 'addClass' : 'removeClass';
  6123. this.$editor[func]('redactor-placeholder');
  6124. }, this), 5);
  6125. },
  6126. remove: function()
  6127. {
  6128. this.$editor.removeClass('redactor-placeholder');
  6129. },
  6130. is: function()
  6131. {
  6132. if (this.opts.placeholder)
  6133. {
  6134. return this.$element.attr('placeholder', this.opts.placeholder);
  6135. }
  6136. else
  6137. {
  6138. return !(typeof this.$element.attr('placeholder') == 'undefined' || this.$element.attr('placeholder') === '');
  6139. }
  6140. }
  6141. };
  6142. },
  6143. progress: function()
  6144. {
  6145. return {
  6146. show: function()
  6147. {
  6148. $(document.body).append($('<div id="redactor-progress"><span></span></div>'));
  6149. $('#redactor-progress').fadeIn();
  6150. },
  6151. hide: function()
  6152. {
  6153. $('#redactor-progress').fadeOut(1500, function()
  6154. {
  6155. $(this).remove();
  6156. });
  6157. }
  6158. };
  6159. },
  6160. selection: function()
  6161. {
  6162. return {
  6163. get: function()
  6164. {
  6165. this.sel = document.getSelection();
  6166. if (document.getSelection && this.sel.getRangeAt && this.sel.rangeCount)
  6167. {
  6168. this.range = this.sel.getRangeAt(0);
  6169. }
  6170. else
  6171. {
  6172. this.range = document.createRange();
  6173. }
  6174. },
  6175. addRange: function()
  6176. {
  6177. try {
  6178. this.sel.removeAllRanges();
  6179. } catch (e) {}
  6180. this.sel.addRange(this.range);
  6181. },
  6182. getCurrent: function()
  6183. {
  6184. var el = false;
  6185. this.selection.get();
  6186. if (this.sel && this.sel.rangeCount > 0)
  6187. {
  6188. el = this.sel.getRangeAt(0).startContainer;
  6189. }
  6190. return this.utils.isRedactorParent(el);
  6191. },
  6192. getParent: function(elem)
  6193. {
  6194. elem = elem || this.selection.getCurrent();
  6195. if (elem)
  6196. {
  6197. return this.utils.isRedactorParent($(elem).parent()[0]);
  6198. }
  6199. return false;
  6200. },
  6201. getPrev: function()
  6202. {
  6203. return window.getSelection().anchorNode.previousSibling;
  6204. },
  6205. getNext: function()
  6206. {
  6207. return window.getSelection().anchorNode.nextSibling;
  6208. },
  6209. getBlock: function(node)
  6210. {
  6211. node = node || this.selection.getCurrent();
  6212. while (node)
  6213. {
  6214. if (this.utils.isBlockTag(node.tagName))
  6215. {
  6216. return ($(node).hasClass('redactor-editor')) ? false : node;
  6217. }
  6218. node = node.parentNode;
  6219. }
  6220. return false;
  6221. },
  6222. getInlines: function(nodes, tags)
  6223. {
  6224. this.selection.get();
  6225. if (this.range && this.range.collapsed)
  6226. {
  6227. return false;
  6228. }
  6229. var inlines = [];
  6230. nodes = (typeof nodes == 'undefined' || nodes === false) ? this.selection.getNodes() : nodes;
  6231. var inlineTags = this.opts.inlineTags;
  6232. inlineTags.push('span');
  6233. if (typeof tags !== 'undefined')
  6234. {
  6235. for (var i = 0; i < tags.length; i++)
  6236. {
  6237. inlineTags.push(tags[i]);
  6238. }
  6239. }
  6240. $.each(nodes, $.proxy(function(i,node)
  6241. {
  6242. if ($.inArray(node.tagName.toLowerCase(), inlineTags) != -1)
  6243. {
  6244. inlines.push(node);
  6245. }
  6246. }, this));
  6247. return (inlines.length === 0) ? false : inlines;
  6248. },
  6249. getInlinesTags: function(tags)
  6250. {
  6251. this.selection.get();
  6252. if (this.range && this.range.collapsed)
  6253. {
  6254. return false;
  6255. }
  6256. var inlines = [];
  6257. var nodes = this.selection.getNodes();
  6258. $.each(nodes, $.proxy(function(i,node)
  6259. {
  6260. if ($.inArray(node.tagName.toLowerCase(), tags) != -1)
  6261. {
  6262. inlines.push(node);
  6263. }
  6264. }, this));
  6265. return (inlines.length === 0) ? false : inlines;
  6266. },
  6267. getBlocks: function(nodes)
  6268. {
  6269. this.selection.get();
  6270. if (this.range && this.range.collapsed)
  6271. {
  6272. return [this.selection.getBlock()];
  6273. }
  6274. var blocks = [];
  6275. nodes = (typeof nodes == 'undefined') ? this.selection.getNodes() : nodes;
  6276. $.each(nodes, $.proxy(function(i,node)
  6277. {
  6278. if (this.utils.isBlock(node))
  6279. {
  6280. blocks.push(node);
  6281. }
  6282. }, this));
  6283. return (blocks.length === 0) ? [this.selection.getBlock()] : blocks;
  6284. },
  6285. getLastBlock: function()
  6286. {
  6287. return this.selection.lastBlock;
  6288. },
  6289. getNodes: function()
  6290. {
  6291. this.selection.get();
  6292. var startNode = this.selection.getNodesMarker(1);
  6293. var endNode = this.selection.getNodesMarker(2);
  6294. if (this.range.collapsed === false)
  6295. {
  6296. if (window.getSelection) {
  6297. var sel = window.getSelection();
  6298. if (sel.rangeCount > 0) {
  6299. var range = sel.getRangeAt(0);
  6300. var startPointNode = range.startContainer, startOffset = range.startOffset;
  6301. var boundaryRange = range.cloneRange();
  6302. boundaryRange.collapse(false);
  6303. boundaryRange.insertNode(endNode);
  6304. boundaryRange.setStart(startPointNode, startOffset);
  6305. boundaryRange.collapse(true);
  6306. boundaryRange.insertNode(startNode);
  6307. // Reselect the original text
  6308. range.setStartAfter(startNode);
  6309. range.setEndBefore(endNode);
  6310. sel.removeAllRanges();
  6311. sel.addRange(range);
  6312. }
  6313. }
  6314. }
  6315. else
  6316. {
  6317. this.selection.setNodesMarker(this.range, startNode, true);
  6318. endNode = startNode;
  6319. }
  6320. var nodes = [];
  6321. var counter = 0;
  6322. var self = this;
  6323. this.$editor.find('*').each(function()
  6324. {
  6325. if (this == startNode)
  6326. {
  6327. var parent = $(this).parent();
  6328. if (parent.length !== 0 && parent[0].tagName != 'BODY' && self.utils.isRedactorParent(parent[0]))
  6329. {
  6330. nodes.push(parent[0]);
  6331. }
  6332. nodes.push(this);
  6333. counter = 1;
  6334. }
  6335. else
  6336. {
  6337. if (counter > 0)
  6338. {
  6339. nodes.push(this);
  6340. counter = counter + 1;
  6341. }
  6342. }
  6343. if (this == endNode)
  6344. {
  6345. return false;
  6346. }
  6347. });
  6348. var finalNodes = [];
  6349. var len = nodes.length;
  6350. for (var i = 0; i < len; i++)
  6351. {
  6352. if (nodes[i].id != 'nodes-marker-1' && nodes[i].id != 'nodes-marker-2')
  6353. {
  6354. finalNodes.push(nodes[i]);
  6355. }
  6356. }
  6357. this.selection.removeNodesMarkers();
  6358. return finalNodes;
  6359. },
  6360. getNodesMarker: function(num)
  6361. {
  6362. return $('<span id="nodes-marker-' + num + '" class="redactor-nodes-marker" data-verified="redactor">' + this.opts.invisibleSpace + '</span>')[0];
  6363. },
  6364. setNodesMarker: function(range, node, type)
  6365. {
  6366. var range = range.cloneRange();
  6367. try {
  6368. range.collapse(type);
  6369. range.insertNode(node);
  6370. }
  6371. catch (e) {}
  6372. },
  6373. removeNodesMarkers: function()
  6374. {
  6375. $(document).find('span.redactor-nodes-marker').remove();
  6376. this.$editor.find('span.redactor-nodes-marker').remove();
  6377. },
  6378. fromPoint: function(start, end)
  6379. {
  6380. this.caret.setOffset(start, end);
  6381. },
  6382. wrap: function(tag)
  6383. {
  6384. this.selection.get();
  6385. if (this.range.collapsed) return false;
  6386. var wrapper = document.createElement(tag);
  6387. wrapper.appendChild(this.range.extractContents());
  6388. this.range.insertNode(wrapper);
  6389. return wrapper;
  6390. },
  6391. selectElement: function(node)
  6392. {
  6393. if (this.utils.browser('mozilla'))
  6394. {
  6395. node = node[0] || node;
  6396. var range = document.createRange();
  6397. range.selectNodeContents(node);
  6398. }
  6399. else
  6400. {
  6401. this.caret.set(node, 0, node, 1);
  6402. }
  6403. },
  6404. selectAll: function()
  6405. {
  6406. this.selection.get();
  6407. this.range.selectNodeContents(this.$editor[0]);
  6408. this.selection.addRange();
  6409. },
  6410. remove: function()
  6411. {
  6412. this.selection.get();
  6413. this.sel.removeAllRanges();
  6414. },
  6415. save: function()
  6416. {
  6417. this.selection.createMarkers();
  6418. },
  6419. createMarkers: function()
  6420. {
  6421. this.selection.get();
  6422. var node1 = this.selection.getMarker(1);
  6423. this.selection.setMarker(this.range, node1, true);
  6424. if (this.range.collapsed === false)
  6425. {
  6426. var node2 = this.selection.getMarker(2);
  6427. this.selection.setMarker(this.range, node2, false);
  6428. }
  6429. this.savedSel = this.$editor.html();
  6430. },
  6431. getMarker: function(num)
  6432. {
  6433. if (typeof num == 'undefined') num = 1;
  6434. return $('<span id="selection-marker-' + num + '" class="redactor-selection-marker" data-verified="redactor">' + this.opts.invisibleSpace + '</span>')[0];
  6435. },
  6436. getMarkerAsHtml: function(num)
  6437. {
  6438. return this.utils.getOuterHtml(this.selection.getMarker(num));
  6439. },
  6440. setMarker: function(range, node, type)
  6441. {
  6442. range = range.cloneRange();
  6443. try {
  6444. range.collapse(type);
  6445. range.insertNode(node);
  6446. }
  6447. catch (e)
  6448. {
  6449. this.focus.setStart();
  6450. }
  6451. },
  6452. restore: function()
  6453. {
  6454. var node1 = this.$editor.find('span#selection-marker-1');
  6455. var node2 = this.$editor.find('span#selection-marker-2');
  6456. if (this.utils.browser('mozilla'))
  6457. {
  6458. this.$editor.focus();
  6459. }
  6460. if (node1.length !== 0 && node2.length !== 0)
  6461. {
  6462. this.caret.set(node1, 0, node2, 0);
  6463. }
  6464. else if (node1.length !== 0)
  6465. {
  6466. this.caret.set(node1, 0, node1, 0);
  6467. }
  6468. else
  6469. {
  6470. this.$editor.focus();
  6471. }
  6472. this.selection.removeMarkers();
  6473. this.savedSel = false;
  6474. },
  6475. removeMarkers: function()
  6476. {
  6477. this.$editor.find('span.redactor-selection-marker').each(function(i,s)
  6478. {
  6479. var text = $(s).text().replace(/\u200B/g, '');
  6480. if (text === '') $(s).remove();
  6481. else $(s).replaceWith(function() { return $(this).contents(); });
  6482. });
  6483. },
  6484. getText: function()
  6485. {
  6486. this.selection.get();
  6487. return this.sel.toString();
  6488. },
  6489. getHtml: function()
  6490. {
  6491. var html = '';
  6492. this.selection.get();
  6493. if (this.sel.rangeCount)
  6494. {
  6495. var container = document.createElement('div');
  6496. var len = this.sel.rangeCount;
  6497. for (var i = 0; i < len; ++i)
  6498. {
  6499. container.appendChild(this.sel.getRangeAt(i).cloneContents());
  6500. }
  6501. html = container.innerHTML;
  6502. }
  6503. return this.clean.onSync(html);
  6504. },
  6505. replaceSelection: function(html)
  6506. {
  6507. this.selection.get();
  6508. this.range.deleteContents();
  6509. var div = document.createElement("div");
  6510. div.innerHTML = html;
  6511. var frag = document.createDocumentFragment(), child;
  6512. while ((child = div.firstChild)) {
  6513. frag.appendChild(child);
  6514. }
  6515. this.range.insertNode(frag);
  6516. },
  6517. replaceWithHtml: function(html)
  6518. {
  6519. html = this.selection.getMarkerAsHtml(1) + html + this.selection.getMarkerAsHtml(2);
  6520. this.selection.get();
  6521. if (window.getSelection && window.getSelection().getRangeAt)
  6522. {
  6523. this.selection.replaceSelection(html);
  6524. }
  6525. else if (document.selection && document.selection.createRange)
  6526. {
  6527. this.range.pasteHTML(html);
  6528. }
  6529. this.selection.restore();
  6530. this.code.sync();
  6531. }
  6532. };
  6533. },
  6534. shortcuts: function()
  6535. {
  6536. return {
  6537. init: function(e, key)
  6538. {
  6539. // disable browser's hot keys for bold and italic
  6540. if (!this.opts.shortcuts)
  6541. {
  6542. if ((e.ctrlKey || e.metaKey) && (key === 66 || key === 73)) e.preventDefault();
  6543. return false;
  6544. }
  6545. $.each(this.opts.shortcuts, $.proxy(function(str, command)
  6546. {
  6547. var keys = str.split(',');
  6548. var len = keys.length;
  6549. for (var i = 0; i < len; i++)
  6550. {
  6551. if (typeof keys[i] === 'string')
  6552. {
  6553. this.shortcuts.handler(e, $.trim(keys[i]), $.proxy(function()
  6554. {
  6555. var func;
  6556. if (command.func.search(/\./) != '-1')
  6557. {
  6558. func = command.func.split('.');
  6559. if (typeof this[func[0]] != 'undefined')
  6560. {
  6561. this[func[0]][func[1]].apply(this, command.params);
  6562. }
  6563. }
  6564. else
  6565. {
  6566. this[command.func].apply(this, command.params);
  6567. }
  6568. }, this));
  6569. }
  6570. }
  6571. }, this));
  6572. },
  6573. handler: function(e, keys, origHandler)
  6574. {
  6575. // based on https://github.com/jeresig/jquery.hotkeys
  6576. var hotkeysSpecialKeys =
  6577. {
  6578. 8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
  6579. 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
  6580. 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=",
  6581. 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
  6582. 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
  6583. 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
  6584. 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=",
  6585. 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"
  6586. };
  6587. var hotkeysShiftNums =
  6588. {
  6589. "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&",
  6590. "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<",
  6591. ".": ">", "/": "?", "\\": "|"
  6592. };
  6593. keys = keys.toLowerCase().split(" ");
  6594. var special = hotkeysSpecialKeys[e.keyCode],
  6595. character = String.fromCharCode( e.which ).toLowerCase(),
  6596. modif = "", possible = {};
  6597. $.each([ "alt", "ctrl", "meta", "shift"], function(index, specialKey)
  6598. {
  6599. if (e[specialKey + 'Key'] && special !== specialKey)
  6600. {
  6601. modif += specialKey + '+';
  6602. }
  6603. });
  6604. if (special) possible[modif + special] = true;
  6605. if (character)
  6606. {
  6607. possible[modif + character] = true;
  6608. possible[modif + hotkeysShiftNums[character]] = true;
  6609. // "$" can be triggered as "Shift+4" or "Shift+$" or just "$"
  6610. if (modif === "shift+")
  6611. {
  6612. possible[hotkeysShiftNums[character]] = true;
  6613. }
  6614. }
  6615. for (var i = 0, len = keys.length; i < len; i++)
  6616. {
  6617. if (possible[keys[i]])
  6618. {
  6619. e.preventDefault();
  6620. return origHandler.apply(this, arguments);
  6621. }
  6622. }
  6623. }
  6624. };
  6625. },
  6626. tabifier: function()
  6627. {
  6628. return {
  6629. get: function(code)
  6630. {
  6631. if (!this.opts.tabifier) return code;
  6632. // clean setup
  6633. var ownLine = ['area', 'body', 'head', 'hr', 'i?frame', 'link', 'meta', 'noscript', 'style', 'script', 'table', 'tbody', 'thead', 'tfoot'];
  6634. var contOwnLine = ['li', 'dt', 'dt', 'h[1-6]', 'option', 'script'];
  6635. var newLevel = ['p', 'blockquote', 'div', 'dl', 'fieldset', 'form', 'frameset', 'map', 'ol', 'pre', 'select', 'td', 'th', 'tr', 'ul'];
  6636. this.tabifier.lineBefore = new RegExp('^<(/?' + ownLine.join('|/?' ) + '|' + contOwnLine.join('|') + ')[ >]');
  6637. this.tabifier.lineAfter = new RegExp('^<(br|/?' + ownLine.join('|/?' ) + '|/' + contOwnLine.join('|/') + ')[ >]');
  6638. this.tabifier.newLevel = new RegExp('^</?(' + newLevel.join('|' ) + ')[ >]');
  6639. var i = 0,
  6640. codeLength = code.length,
  6641. point = 0,
  6642. start = null,
  6643. end = null,
  6644. tag = '',
  6645. out = '',
  6646. cont = '';
  6647. this.tabifier.cleanlevel = 0;
  6648. for (; i < codeLength; i++)
  6649. {
  6650. point = i;
  6651. // if no more tags, copy and exit
  6652. if (-1 == code.substr(i).indexOf( '<' ))
  6653. {
  6654. out += code.substr(i);
  6655. return this.tabifier.finish(out);
  6656. }
  6657. // copy verbatim until a tag
  6658. while (point < codeLength && code.charAt(point) != '<')
  6659. {
  6660. point++;
  6661. }
  6662. if (i != point)
  6663. {
  6664. cont = code.substr(i, point - i);
  6665. if (!cont.match(/^\s{2,}$/g))
  6666. {
  6667. if ('\n' == out.charAt(out.length - 1)) out += this.tabifier.getTabs();
  6668. else if ('\n' == cont.charAt(0))
  6669. {
  6670. out += '\n' + this.tabifier.getTabs();
  6671. cont = cont.replace(/^\s+/, '');
  6672. }
  6673. out += cont;
  6674. }
  6675. if (cont.match(/\n/)) out += '\n' + this.tabifier.getTabs();
  6676. }
  6677. start = point;
  6678. // find the end of the tag
  6679. while (point < codeLength && '>' != code.charAt(point))
  6680. {
  6681. point++;
  6682. }
  6683. tag = code.substr(start, point - start);
  6684. i = point;
  6685. var t;
  6686. if ('!--' == tag.substr(1, 3))
  6687. {
  6688. if (!tag.match(/--$/))
  6689. {
  6690. while ('-->' != code.substr(point, 3))
  6691. {
  6692. point++;
  6693. }
  6694. point += 2;
  6695. tag = code.substr(start, point - start);
  6696. i = point;
  6697. }
  6698. if ('\n' != out.charAt(out.length - 1)) out += '\n';
  6699. out += this.tabifier.getTabs();
  6700. out += tag + '>\n';
  6701. }
  6702. else if ('!' == tag[1])
  6703. {
  6704. out = this.tabifier.placeTag(tag + '>', out);
  6705. }
  6706. else if ('?' == tag[1])
  6707. {
  6708. out += tag + '>\n';
  6709. }
  6710. else if (t = tag.match(/^<(script|style|pre)/i))
  6711. {
  6712. t[1] = t[1].toLowerCase();
  6713. tag = this.tabifier.cleanTag(tag);
  6714. out = this.tabifier.placeTag(tag, out);
  6715. end = String(code.substr(i + 1)).toLowerCase().indexOf('</' + t[1]);
  6716. if (end)
  6717. {
  6718. cont = code.substr(i + 1, end);
  6719. i += end;
  6720. out += cont;
  6721. }
  6722. }
  6723. else
  6724. {
  6725. tag = this.tabifier.cleanTag(tag);
  6726. out = this.tabifier.placeTag(tag, out);
  6727. }
  6728. }
  6729. return this.tabifier.finish(out);
  6730. },
  6731. getTabs: function()
  6732. {
  6733. var s = '';
  6734. for ( var j = 0; j < this.tabifier.cleanlevel; j++ )
  6735. {
  6736. s += '\t';
  6737. }
  6738. return s;
  6739. },
  6740. finish: function(code)
  6741. {
  6742. code = code.replace(/\n\s*\n/g, '\n');
  6743. code = code.replace(/^[\s\n]*/, '');
  6744. code = code.replace(/[\s\n]*$/, '');
  6745. code = code.replace(/<script(.*?)>\n<\/script>/gi, '<script$1></script>');
  6746. this.tabifier.cleanlevel = 0;
  6747. return code;
  6748. },
  6749. cleanTag: function (tag)
  6750. {
  6751. var tagout = '';
  6752. tag = tag.replace(/\n/g, ' ');
  6753. tag = tag.replace(/\s{2,}/g, ' ');
  6754. tag = tag.replace(/^\s+|\s+$/g, ' ');
  6755. var suffix = '';
  6756. if (tag.match(/\/$/))
  6757. {
  6758. suffix = '/';
  6759. tag = tag.replace(/\/+$/, '');
  6760. }
  6761. var m;
  6762. while (m = /\s*([^= ]+)(?:=((['"']).*?\3|[^ ]+))?/.exec(tag))
  6763. {
  6764. if (m[2]) tagout += m[1].toLowerCase() + '=' + m[2];
  6765. else if (m[1]) tagout += m[1].toLowerCase();
  6766. tagout += ' ';
  6767. tag = tag.substr(m[0].length);
  6768. }
  6769. return tagout.replace(/\s*$/, '') + suffix + '>';
  6770. },
  6771. placeTag: function (tag, out)
  6772. {
  6773. var nl = tag.match(this.tabifier.newLevel);
  6774. if (tag.match(this.tabifier.lineBefore) || nl)
  6775. {
  6776. out = out.replace(/\s*$/, '');
  6777. out += '\n';
  6778. }
  6779. if (nl && '/' == tag.charAt(1)) this.tabifier.cleanlevel--;
  6780. if ('\n' == out.charAt(out.length - 1)) out += this.tabifier.getTabs();
  6781. if (nl && '/' != tag.charAt(1)) this.tabifier.cleanlevel++;
  6782. out += tag;
  6783. if (tag.match(this.tabifier.lineAfter) || tag.match(this.tabifier.newLevel))
  6784. {
  6785. out = out.replace(/ *$/, '');
  6786. //out += '\n';
  6787. }
  6788. return out;
  6789. }
  6790. };
  6791. },
  6792. tidy: function()
  6793. {
  6794. return {
  6795. setupAllowed: function()
  6796. {
  6797. var index = $.inArray('span', this.opts.removeEmpty);
  6798. if (index !== -1)
  6799. {
  6800. this.opts.removeEmpty.splice(index, 1);
  6801. }
  6802. if (this.opts.allowedTags) this.opts.deniedTags = false;
  6803. if (this.opts.allowedAttr) this.opts.removeAttr = false;
  6804. if (this.opts.linebreaks) return;
  6805. var tags = ['p', 'section'];
  6806. if (this.opts.allowedTags) this.tidy.addToAllowed(tags);
  6807. if (this.opts.deniedTags) this.tidy.removeFromDenied(tags);
  6808. },
  6809. addToAllowed: function(tags)
  6810. {
  6811. var len = tags.length;
  6812. for (var i = 0; i < len; i++)
  6813. {
  6814. if ($.inArray(tags[i], this.opts.allowedTags) == -1)
  6815. {
  6816. this.opts.allowedTags.push(tags[i]);
  6817. }
  6818. }
  6819. },
  6820. removeFromDenied: function(tags)
  6821. {
  6822. var len = tags.length;
  6823. for (var i = 0; i < len; i++)
  6824. {
  6825. var pos = $.inArray(tags[i], this.opts.deniedTags);
  6826. if (pos != -1)
  6827. {
  6828. this.opts.deniedTags.splice(pos, 1);
  6829. }
  6830. }
  6831. },
  6832. load: function(html, options)
  6833. {
  6834. this.tidy.settings = {
  6835. deniedTags: this.opts.deniedTags,
  6836. allowedTags: this.opts.allowedTags,
  6837. removeComments: this.opts.removeComments,
  6838. replaceTags: this.opts.replaceTags,
  6839. replaceStyles: this.opts.replaceStyles,
  6840. removeDataAttr: this.opts.removeDataAttr,
  6841. removeAttr: this.opts.removeAttr,
  6842. allowedAttr: this.opts.allowedAttr,
  6843. removeWithoutAttr: this.opts.removeWithoutAttr,
  6844. removeEmpty: this.opts.removeEmpty
  6845. };
  6846. $.extend(this.tidy.settings, options);
  6847. html = this.tidy.removeComments(html);
  6848. // create container
  6849. this.tidy.$div = $('<div />').append(html);
  6850. // clean
  6851. this.tidy.replaceTags();
  6852. this.tidy.replaceStyles();
  6853. this.tidy.removeTags();
  6854. this.tidy.removeAttr();
  6855. this.tidy.removeEmpty();
  6856. this.tidy.removeParagraphsInLists();
  6857. this.tidy.removeDataAttr();
  6858. this.tidy.removeWithoutAttr();
  6859. html = this.tidy.$div.html();
  6860. this.tidy.$div.remove();
  6861. return html;
  6862. },
  6863. removeComments: function(html)
  6864. {
  6865. if (!this.tidy.settings.removeComments) return html;
  6866. return html.replace(/<!--[\s\S]*?-->/gi, '');
  6867. },
  6868. replaceTags: function(html)
  6869. {
  6870. if (!this.tidy.settings.replaceTags) return html;
  6871. var len = this.tidy.settings.replaceTags.length;
  6872. var replacement = [], rTags = [];
  6873. for (var i = 0; i < len; i++)
  6874. {
  6875. rTags.push(this.tidy.settings.replaceTags[i][1]);
  6876. replacement.push(this.tidy.settings.replaceTags[i][0]);
  6877. }
  6878. $.each(replacement, $.proxy(function(key, value)
  6879. {
  6880. this.tidy.$div.find(value).replaceWith(function()
  6881. {
  6882. return $("<" + rTags[key] + " />", {html: $(this).html()});
  6883. });
  6884. }, this));
  6885. },
  6886. replaceStyles: function()
  6887. {
  6888. if (!this.tidy.settings.replaceStyles) return;
  6889. var len = this.tidy.settings.replaceStyles.length;
  6890. this.tidy.$div.find('span').each($.proxy(function(n,s)
  6891. {
  6892. var $el = $(s);
  6893. var style = $el.attr('style');
  6894. for (var i = 0; i < len; i++)
  6895. {
  6896. if (style && style.match(new RegExp('^' + this.tidy.settings.replaceStyles[i][0], 'i')))
  6897. {
  6898. var tagName = this.tidy.settings.replaceStyles[i][1];
  6899. $el.replaceWith(function()
  6900. {
  6901. var tag = document.createElement(tagName);
  6902. return $(tag).append($(this).contents());
  6903. });
  6904. }
  6905. }
  6906. }, this));
  6907. },
  6908. removeTags: function()
  6909. {
  6910. if (!this.tidy.settings.deniedTags && this.tidy.settings.allowedTags)
  6911. {
  6912. this.tidy.$div.find('*').not(this.tidy.settings.allowedTags.join(',')).each(function(i, s)
  6913. {
  6914. if (s.innerHTML === '') $(s).remove();
  6915. else $(s).contents().unwrap();
  6916. });
  6917. }
  6918. if (this.tidy.settings.deniedTags)
  6919. {
  6920. this.tidy.$div.find(this.tidy.settings.deniedTags.join(',')).each(function(i, s)
  6921. {
  6922. if ($(s).hasClass('redactor-script-tag') || $(s).hasClass('redactor-selection-marker')) return;
  6923. if (s.innerHTML === '') $(s).remove();
  6924. else $(s).contents().unwrap();
  6925. });
  6926. }
  6927. },
  6928. removeAttr: function()
  6929. {
  6930. var len;
  6931. if (!this.tidy.settings.removeAttr && this.tidy.settings.allowedAttr)
  6932. {
  6933. var allowedAttrTags = [], allowedAttrData = [];
  6934. len = this.tidy.settings.allowedAttr.length;
  6935. for (var i = 0; i < len; i++)
  6936. {
  6937. allowedAttrTags.push(this.tidy.settings.allowedAttr[i][0]);
  6938. allowedAttrData.push(this.tidy.settings.allowedAttr[i][1]);
  6939. }
  6940. this.tidy.$div.find('*').each($.proxy(function(n,s)
  6941. {
  6942. var $el = $(s);
  6943. var pos = $.inArray($el[0].tagName.toLowerCase(), allowedAttrTags);
  6944. var attributesRemove = this.tidy.removeAttrGetRemoves(pos, allowedAttrData, $el);
  6945. if (attributesRemove)
  6946. {
  6947. $.each(attributesRemove, function(z,f) {
  6948. $el.removeAttr(f);
  6949. });
  6950. }
  6951. }, this));
  6952. }
  6953. if (this.tidy.settings.removeAttr)
  6954. {
  6955. len = this.tidy.settings.removeAttr.length;
  6956. for (var i = 0; i < len; i++)
  6957. {
  6958. var attrs = this.tidy.settings.removeAttr[i][1];
  6959. if ($.isArray(attrs)) attrs = attrs.join(' ');
  6960. this.tidy.$div.find(this.tidy.settings.removeAttr[i][0]).removeAttr(attrs);
  6961. }
  6962. }
  6963. },
  6964. removeAttrGetRemoves: function(pos, allowed, $el)
  6965. {
  6966. var attributesRemove = [];
  6967. // remove all attrs
  6968. if (pos == -1)
  6969. {
  6970. $.each($el[0].attributes, function(i, item)
  6971. {
  6972. attributesRemove.push(item.name);
  6973. });
  6974. }
  6975. // allow all attrs
  6976. else if (allowed[pos] == '*')
  6977. {
  6978. attributesRemove = [];
  6979. }
  6980. // allow specific attrs
  6981. else
  6982. {
  6983. $.each($el[0].attributes, function(i, item)
  6984. {
  6985. if ($.isArray(allowed[pos]))
  6986. {
  6987. if ($.inArray(item.name, allowed[pos]) == -1)
  6988. {
  6989. attributesRemove.push(item.name);
  6990. }
  6991. }
  6992. else if (allowed[pos] != item.name)
  6993. {
  6994. attributesRemove.push(item.name);
  6995. }
  6996. });
  6997. }
  6998. return attributesRemove;
  6999. },
  7000. removeAttrs: function (el, regex)
  7001. {
  7002. regex = new RegExp(regex, "g");
  7003. return el.each(function()
  7004. {
  7005. var self = $(this);
  7006. var len = this.attributes.length - 1;
  7007. for (var i = len; i >= 0; i--)
  7008. {
  7009. var item = this.attributes[i];
  7010. if (item && item.specified && item.name.search(regex)>=0)
  7011. {
  7012. self.removeAttr(item.name);
  7013. }
  7014. }
  7015. });
  7016. },
  7017. removeEmpty: function()
  7018. {
  7019. if (!this.tidy.settings.removeEmpty) return;
  7020. this.tidy.$div.find(this.tidy.settings.removeEmpty.join(',')).each(function()
  7021. {
  7022. var $el = $(this);
  7023. var text = $el.text();
  7024. text = text.replace(/\u200B/g, '');
  7025. text = text.replace(/&nbsp;/gi, '');
  7026. text = text.replace(/\s/g, '');
  7027. if (text === '' && $el.children().length === 0)
  7028. {
  7029. $el.remove();
  7030. }
  7031. });
  7032. },
  7033. removeParagraphsInLists: function()
  7034. {
  7035. this.tidy.$div.find('li p').contents().unwrap();
  7036. },
  7037. removeDataAttr: function()
  7038. {
  7039. if (!this.tidy.settings.removeDataAttr) return;
  7040. var tags = this.tidy.settings.removeDataAttr;
  7041. if ($.isArray(this.tidy.settings.removeDataAttr)) tags = this.tidy.settings.removeDataAttr.join(',');
  7042. this.tidy.removeAttrs(this.tidy.$div.find(tags), '^(data-)');
  7043. },
  7044. removeWithoutAttr: function()
  7045. {
  7046. if (!this.tidy.settings.removeWithoutAttr) return;
  7047. this.tidy.$div.find(this.tidy.settings.removeWithoutAttr.join(',')).each(function()
  7048. {
  7049. if (this.attributes.length === 0)
  7050. {
  7051. $(this).contents().unwrap();
  7052. }
  7053. });
  7054. }
  7055. };
  7056. },
  7057. toolbar: function()
  7058. {
  7059. return {
  7060. init: function()
  7061. {
  7062. return {
  7063. html:
  7064. {
  7065. title: this.lang.get('html'),
  7066. func: 'code.toggle'
  7067. },
  7068. formatting:
  7069. {
  7070. title: this.lang.get('formatting'),
  7071. dropdown:
  7072. {
  7073. p:
  7074. {
  7075. title: this.lang.get('paragraph'),
  7076. func: 'block.format'
  7077. },
  7078. blockquote:
  7079. {
  7080. title: this.lang.get('quote'),
  7081. func: 'block.format'
  7082. },
  7083. pre:
  7084. {
  7085. title: this.lang.get('code'),
  7086. func: 'block.format'
  7087. },
  7088. h1:
  7089. {
  7090. title: this.lang.get('header1'),
  7091. func: 'block.format'
  7092. },
  7093. h2:
  7094. {
  7095. title: this.lang.get('header2'),
  7096. func: 'block.format'
  7097. },
  7098. h3:
  7099. {
  7100. title: this.lang.get('header3'),
  7101. func: 'block.format'
  7102. },
  7103. h4:
  7104. {
  7105. title: this.lang.get('header4'),
  7106. func: 'block.format'
  7107. },
  7108. h5:
  7109. {
  7110. title: this.lang.get('header5'),
  7111. func: 'block.format'
  7112. }
  7113. }
  7114. },
  7115. bold:
  7116. {
  7117. title: this.lang.get('bold'),
  7118. func: 'inline.format'
  7119. },
  7120. italic:
  7121. {
  7122. title: this.lang.get('italic'),
  7123. func: 'inline.format'
  7124. },
  7125. deleted:
  7126. {
  7127. title: this.lang.get('deleted'),
  7128. func: 'inline.format'
  7129. },
  7130. underline:
  7131. {
  7132. title: this.lang.get('underline'),
  7133. func: 'inline.format'
  7134. },
  7135. unorderedlist:
  7136. {
  7137. title: '&bull; ' + this.lang.get('unorderedlist'),
  7138. func: 'list.toggle'
  7139. },
  7140. orderedlist:
  7141. {
  7142. title: '1. ' + this.lang.get('orderedlist'),
  7143. func: 'list.toggle'
  7144. },
  7145. outdent:
  7146. {
  7147. title: '< ' + this.lang.get('outdent'),
  7148. func: 'indent.decrease'
  7149. },
  7150. indent:
  7151. {
  7152. title: '> ' + this.lang.get('indent'),
  7153. func: 'indent.increase'
  7154. },
  7155. image:
  7156. {
  7157. title: this.lang.get('image'),
  7158. func: 'image.show'
  7159. },
  7160. file:
  7161. {
  7162. title: this.lang.get('file'),
  7163. func: 'file.show'
  7164. },
  7165. link:
  7166. {
  7167. title: this.lang.get('link'),
  7168. dropdown:
  7169. {
  7170. link:
  7171. {
  7172. title: this.lang.get('link_insert'),
  7173. func: 'link.show',
  7174. observe: {
  7175. element: 'a',
  7176. in: {
  7177. title: this.lang.get('link_edit'),
  7178. },
  7179. out: {
  7180. title: this.lang.get('link_insert')
  7181. }
  7182. }
  7183. },
  7184. unlink:
  7185. {
  7186. title: this.lang.get('unlink'),
  7187. func: 'link.unlink',
  7188. observe: {
  7189. element: 'a',
  7190. out: {
  7191. attr: {
  7192. 'class': 'redactor-dropdown-link-inactive',
  7193. 'aria-disabled': true
  7194. }
  7195. }
  7196. }
  7197. }
  7198. }
  7199. },
  7200. alignment:
  7201. {
  7202. title: this.lang.get('alignment'),
  7203. dropdown:
  7204. {
  7205. left:
  7206. {
  7207. title: this.lang.get('align_left'),
  7208. func: 'alignment.left'
  7209. },
  7210. center:
  7211. {
  7212. title: this.lang.get('align_center'),
  7213. func: 'alignment.center'
  7214. },
  7215. right:
  7216. {
  7217. title: this.lang.get('align_right'),
  7218. func: 'alignment.right'
  7219. },
  7220. justify:
  7221. {
  7222. title: this.lang.get('align_justify'),
  7223. func: 'alignment.justify'
  7224. }
  7225. }
  7226. },
  7227. horizontalrule:
  7228. {
  7229. title: this.lang.get('horizontalrule'),
  7230. func: 'line.insert'
  7231. }
  7232. };
  7233. },
  7234. build: function()
  7235. {
  7236. this.toolbar.hideButtons();
  7237. this.toolbar.hideButtonsOnMobile();
  7238. this.toolbar.isButtonSourceNeeded();
  7239. if (this.opts.buttons.length === 0) return;
  7240. this.$toolbar = this.toolbar.createContainer();
  7241. this.toolbar.setOverflow();
  7242. this.toolbar.append();
  7243. this.toolbar.setFormattingTags();
  7244. this.toolbar.loadButtons();
  7245. this.toolbar.setFixed();
  7246. // buttons response
  7247. if (this.opts.activeButtons)
  7248. {
  7249. this.$editor.on('mouseup.redactor keyup.redactor focus.redactor', $.proxy(this.observe.toolbar, this));
  7250. }
  7251. },
  7252. createContainer: function()
  7253. {
  7254. return $('<ul>').addClass('redactor-toolbar').attr({'id': 'redactor-toolbar-' + this.uuid, 'role': 'toolbar'});
  7255. },
  7256. setFormattingTags: function()
  7257. {
  7258. $.each(this.opts.toolbar.formatting.dropdown, $.proxy(function (i, s)
  7259. {
  7260. if ($.inArray(i, this.opts.formatting) == -1) delete this.opts.toolbar.formatting.dropdown[i];
  7261. }, this));
  7262. },
  7263. loadButtons: function()
  7264. {
  7265. $.each(this.opts.buttons, $.proxy(function(i, btnName)
  7266. {
  7267. if (!this.opts.toolbar[btnName]) return;
  7268. if (btnName === 'file')
  7269. {
  7270. if (this.opts.fileUpload === false) return;
  7271. else if (!this.opts.fileUpload && this.opts.s3 === false) return;
  7272. }
  7273. if (btnName === 'image')
  7274. {
  7275. if (this.opts.imageUpload === false) return;
  7276. else if (!this.opts.imageUpload && this.opts.s3 === false) return;
  7277. }
  7278. var btnObject = this.opts.toolbar[btnName];
  7279. this.$toolbar.append($('<li>').append(this.button.build(btnName, btnObject)));
  7280. }, this));
  7281. },
  7282. append: function()
  7283. {
  7284. if (this.opts.toolbarExternal)
  7285. {
  7286. this.$toolbar.addClass('redactor-toolbar-external');
  7287. $(this.opts.toolbarExternal).html(this.$toolbar);
  7288. }
  7289. else
  7290. {
  7291. this.$box.prepend(this.$toolbar);
  7292. }
  7293. },
  7294. setFixed: function()
  7295. {
  7296. if (!this.utils.isDesktop()) return;
  7297. if (this.opts.toolbarExternal) return;
  7298. if (!this.opts.toolbarFixed) return;
  7299. this.toolbar.observeScroll();
  7300. $(this.opts.toolbarFixedTarget).on('scroll.redactor.' + this.uuid, $.proxy(this.toolbar.observeScroll, this));
  7301. },
  7302. setOverflow: function()
  7303. {
  7304. if (this.utils.isMobile() && this.opts.toolbarOverflow)
  7305. {
  7306. this.$toolbar.addClass('redactor-toolbar-overflow');
  7307. }
  7308. },
  7309. isButtonSourceNeeded: function()
  7310. {
  7311. if (this.opts.source) return;
  7312. var index = this.opts.buttons.indexOf('html');
  7313. if (index !== -1)
  7314. {
  7315. this.opts.buttons.splice(index, 1);
  7316. }
  7317. },
  7318. hideButtons: function()
  7319. {
  7320. if (this.opts.buttonsHide.length === 0) return;
  7321. $.each(this.opts.buttonsHide, $.proxy(function(i, s)
  7322. {
  7323. var index = this.opts.buttons.indexOf(s);
  7324. this.opts.buttons.splice(index, 1);
  7325. }, this));
  7326. },
  7327. hideButtonsOnMobile: function()
  7328. {
  7329. if (!this.utils.isMobile() || this.opts.buttonsHideOnMobile.length === 0) return;
  7330. $.each(this.opts.buttonsHideOnMobile, $.proxy(function(i, s)
  7331. {
  7332. var index = this.opts.buttons.indexOf(s);
  7333. this.opts.buttons.splice(index, 1);
  7334. }, this));
  7335. },
  7336. observeScroll: function()
  7337. {
  7338. var scrollTop = $(this.opts.toolbarFixedTarget).scrollTop();
  7339. var boxTop = 1;
  7340. if (this.opts.toolbarFixedTarget === document)
  7341. {
  7342. boxTop = this.$box.offset().top;
  7343. }
  7344. if ((scrollTop + this.opts.toolbarFixedTopOffset) > boxTop)
  7345. {
  7346. this.toolbar.observeScrollEnable(scrollTop, boxTop);
  7347. }
  7348. else
  7349. {
  7350. this.toolbar.observeScrollDisable();
  7351. }
  7352. },
  7353. observeScrollEnable: function(scrollTop, boxTop)
  7354. {
  7355. var top = this.opts.toolbarFixedTopOffset + scrollTop - boxTop;
  7356. var left = 0;
  7357. var end = boxTop + this.$box.height() - 32;
  7358. var width = this.$box.innerWidth();
  7359. this.$toolbar.addClass('toolbar-fixed-box');
  7360. this.$toolbar.css({
  7361. position: 'absolute',
  7362. width: width,
  7363. top: top + 'px',
  7364. left: left
  7365. });
  7366. if (scrollTop > end)
  7367. $('.redactor-dropdown-' + this.uuid + ':visible').hide();
  7368. this.toolbar.setDropdownsFixed();
  7369. this.$toolbar.css('visibility', (scrollTop < end) ? 'visible' : 'hidden');
  7370. },
  7371. observeScrollDisable: function()
  7372. {
  7373. this.$toolbar.css({
  7374. position: 'relative',
  7375. width: 'auto',
  7376. top: 0,
  7377. left: 0,
  7378. visibility: 'visible'
  7379. });
  7380. this.toolbar.unsetDropdownsFixed();
  7381. this.$toolbar.removeClass('toolbar-fixed-box');
  7382. },
  7383. setDropdownsFixed: function()
  7384. {
  7385. var top = this.$toolbar.innerHeight() + this.opts.toolbarFixedTopOffset;
  7386. var position = 'fixed';
  7387. if (this.opts.toolbarFixedTarget !== document)
  7388. {
  7389. top = (this.$toolbar.innerHeight() + this.$toolbar.offset().top) + this.opts.toolbarFixedTopOffset;
  7390. position = 'absolute';
  7391. }
  7392. $('.redactor-dropdown-' + this.uuid).each(function()
  7393. {
  7394. $(this).css({ position: position, top: top + 'px' });
  7395. });
  7396. },
  7397. unsetDropdownsFixed: function()
  7398. {
  7399. var top = (this.$toolbar.innerHeight() + this.$toolbar.offset().top);
  7400. $('.redactor-dropdown-' + this.uuid).each(function()
  7401. {
  7402. $(this).css({ position: 'absolute', top: top + 'px' });
  7403. });
  7404. }
  7405. };
  7406. },
  7407. upload: function()
  7408. {
  7409. return {
  7410. init: function(id, url, callback)
  7411. {
  7412. this.upload.direct = false;
  7413. this.upload.callback = callback;
  7414. this.upload.url = url;
  7415. this.upload.$el = $(id);
  7416. this.upload.$droparea = $('<div id="redactor-droparea" />');
  7417. this.upload.$placeholdler = $('<div id="redactor-droparea-placeholder" />').text(this.lang.get('upload_label'));
  7418. this.upload.$input = $('<input type="file" name="file" />');
  7419. this.upload.$placeholdler.append(this.upload.$input);
  7420. this.upload.$droparea.append(this.upload.$placeholdler);
  7421. this.upload.$el.append(this.upload.$droparea);
  7422. this.upload.$droparea.off('redactor.upload');
  7423. this.upload.$input.off('redactor.upload');
  7424. this.upload.$droparea.on('dragover.redactor.upload', $.proxy(this.upload.onDrag, this));
  7425. this.upload.$droparea.on('dragleave.redactor.upload', $.proxy(this.upload.onDragLeave, this));
  7426. // change
  7427. this.upload.$input.on('change.redactor.upload', $.proxy(function(e)
  7428. {
  7429. e = e.originalEvent || e;
  7430. this.upload.traverseFile(this.upload.$input[0].files[0], e);
  7431. }, this));
  7432. // drop
  7433. this.upload.$droparea.on('drop.redactor.upload', $.proxy(function(e)
  7434. {
  7435. e.preventDefault();
  7436. this.upload.$droparea.removeClass('drag-hover').addClass('drag-drop');
  7437. this.upload.onDrop(e);
  7438. }, this));
  7439. },
  7440. directUpload: function(file, e)
  7441. {
  7442. this.upload.direct = true;
  7443. this.upload.traverseFile(file, e);
  7444. },
  7445. onDrop: function(e)
  7446. {
  7447. e = e.originalEvent || e;
  7448. var files = e.dataTransfer.files;
  7449. this.upload.traverseFile(files[0], e);
  7450. },
  7451. traverseFile: function(file, e)
  7452. {
  7453. if (this.opts.s3)
  7454. {
  7455. this.upload.setConfig(file);
  7456. this.upload.s3uploadFile(file);
  7457. return;
  7458. }
  7459. var formData = !!window.FormData ? new FormData() : null;
  7460. if (window.FormData)
  7461. {
  7462. this.upload.setConfig(file);
  7463. var name = (this.upload.type == 'image') ? this.opts.imageUploadParam : this.opts.fileUploadParam;
  7464. formData.append(name, file);
  7465. }
  7466. this.progress.show();
  7467. this.core.setCallback('uploadStart', e, formData);
  7468. this.upload.sendData(formData, e);
  7469. },
  7470. setConfig: function(file)
  7471. {
  7472. this.upload.getType(file);
  7473. if (this.upload.direct)
  7474. {
  7475. this.upload.url = (this.upload.type == 'image') ? this.opts.imageUpload : this.opts.fileUpload;
  7476. this.upload.callback = (this.upload.type == 'image') ? this.image.insert : this.file.insert;
  7477. }
  7478. },
  7479. getType: function(file)
  7480. {
  7481. this.upload.type = 'image';
  7482. if (this.opts.imageTypes.indexOf(file.type) == -1)
  7483. {
  7484. this.upload.type = 'file';
  7485. }
  7486. },
  7487. getHiddenFields: function(obj, fd)
  7488. {
  7489. if (obj === false || typeof obj !== 'object') return fd;
  7490. $.each(obj, $.proxy(function(k, v)
  7491. {
  7492. if (v !== null && v.toString().indexOf('#') === 0) v = $(v).val();
  7493. fd.append(k, v);
  7494. }, this));
  7495. return fd;
  7496. },
  7497. sendData: function(formData, e)
  7498. {
  7499. // append hidden fields
  7500. if (this.upload.type == 'image')
  7501. {
  7502. formData = this.upload.getHiddenFields(this.opts.uploadImageFields, formData);
  7503. formData = this.upload.getHiddenFields(this.upload.imageFields, formData);
  7504. }
  7505. else
  7506. {
  7507. formData = this.upload.getHiddenFields(this.opts.uploadFileFields, formData);
  7508. formData = this.upload.getHiddenFields(this.upload.fileFields, formData);
  7509. }
  7510. var xhr = new XMLHttpRequest();
  7511. xhr.open('POST', this.upload.url);
  7512. xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  7513. // complete
  7514. xhr.onreadystatechange = $.proxy(function()
  7515. {
  7516. if (xhr.readyState == 4)
  7517. {
  7518. var data = xhr.responseText;
  7519. data = data.replace(/^\[/, '');
  7520. data = data.replace(/\]$/, '');
  7521. var json;
  7522. try
  7523. {
  7524. json = (typeof data === 'string' ? $.parseJSON(data) : data);
  7525. }
  7526. catch(err)
  7527. {
  7528. json = {
  7529. error: true
  7530. };
  7531. }
  7532. this.progress.hide();
  7533. if (!this.upload.direct)
  7534. {
  7535. this.upload.$droparea.removeClass('drag-drop');
  7536. }
  7537. this.upload.callback(json, this.upload.direct, e);
  7538. }
  7539. }, this);
  7540. /*
  7541. xhr.upload.onprogress = $.proxy(function(e)
  7542. {
  7543. if (e.lengthComputable)
  7544. {
  7545. var complete = (e.loaded / e.total * 100 | 0);
  7546. //progress.value = progress.innerHTML = complete;
  7547. }
  7548. }, this);
  7549. */
  7550. xhr.send(formData);
  7551. },
  7552. onDrag: function(e)
  7553. {
  7554. e.preventDefault();
  7555. this.upload.$droparea.addClass('drag-hover');
  7556. },
  7557. onDragLeave: function(e)
  7558. {
  7559. e.preventDefault();
  7560. this.upload.$droparea.removeClass('drag-hover');
  7561. },
  7562. clearImageFields: function()
  7563. {
  7564. this.upload.imageFields = {};
  7565. },
  7566. addImageFields: function(name, value)
  7567. {
  7568. this.upload.imageFields[name] = value;
  7569. },
  7570. removeImageFields: function(name)
  7571. {
  7572. delete this.upload.imageFields[name];
  7573. },
  7574. clearFileFields: function()
  7575. {
  7576. this.upload.fileFields = {};
  7577. },
  7578. addFileFields: function(name, value)
  7579. {
  7580. this.upload.fileFields[name] = value;
  7581. },
  7582. removeFileFields: function(name)
  7583. {
  7584. delete this.upload.fileFields[name];
  7585. },
  7586. // S3
  7587. s3uploadFile: function(file)
  7588. {
  7589. this.upload.s3executeOnSignedUrl(file, $.proxy(function(signedURL)
  7590. {
  7591. this.upload.s3uploadToS3(file, signedURL);
  7592. }, this));
  7593. },
  7594. s3executeOnSignedUrl: function(file, callback)
  7595. {
  7596. var xhr = new XMLHttpRequest();
  7597. var mark = (this.opts.s3.search(/\?/) !== '-1') ? '?' : '&';
  7598. xhr.open('GET', this.opts.s3 + mark + 'name=' + file.name + '&type=' + file.type, true);
  7599. // Hack to pass bytes through unprocessed.
  7600. if (xhr.overrideMimeType) xhr.overrideMimeType('text/plain; charset=x-user-defined');
  7601. var that = this;
  7602. xhr.onreadystatechange = function(e)
  7603. {
  7604. if (this.readyState == 4 && this.status == 200)
  7605. {
  7606. that.progress.show();
  7607. callback(decodeURIComponent(this.responseText));
  7608. }
  7609. else if (this.readyState == 4 && this.status != 200)
  7610. {
  7611. //setProgress(0, 'Could not contact signing script. Status = ' + this.status);
  7612. }
  7613. };
  7614. xhr.send();
  7615. },
  7616. s3createCORSRequest: function(method, url)
  7617. {
  7618. var xhr = new XMLHttpRequest();
  7619. if ("withCredentials" in xhr)
  7620. {
  7621. xhr.open(method, url, true);
  7622. }
  7623. else if (typeof XDomainRequest != "undefined")
  7624. {
  7625. xhr = new XDomainRequest();
  7626. xhr.open(method, url);
  7627. }
  7628. else
  7629. {
  7630. xhr = null;
  7631. }
  7632. return xhr;
  7633. },
  7634. s3uploadToS3: function(file, url)
  7635. {
  7636. var xhr = this.upload.s3createCORSRequest('PUT', url);
  7637. if (!xhr)
  7638. {
  7639. //setProgress(0, 'CORS not supported');
  7640. }
  7641. else
  7642. {
  7643. xhr.onload = $.proxy(function()
  7644. {
  7645. if (xhr.status == 200)
  7646. {
  7647. //setProgress(100, 'Upload completed.');
  7648. this.progress.hide();
  7649. var s3file = url.split('?');
  7650. if (!s3file[0])
  7651. {
  7652. // url parsing is fail
  7653. return false;
  7654. }
  7655. if (!this.upload.direct)
  7656. {
  7657. this.upload.$droparea.removeClass('drag-drop');
  7658. }
  7659. var json = { filelink: s3file[0] };
  7660. if (this.upload.type == 'file')
  7661. {
  7662. var arr = s3file[0].split('/');
  7663. json.filename = arr[arr.length-1];
  7664. }
  7665. this.upload.callback(json, this.upload.direct, false);
  7666. }
  7667. else
  7668. {
  7669. //setProgress(0, 'Upload error: ' + xhr.status);
  7670. }
  7671. }, this);
  7672. xhr.onerror = function() {};
  7673. xhr.upload.onprogress = function(e) {};
  7674. xhr.setRequestHeader('Content-Type', file.type);
  7675. xhr.setRequestHeader('x-amz-acl', 'public-read');
  7676. xhr.send(file);
  7677. }
  7678. }
  7679. };
  7680. },
  7681. utils: function()
  7682. {
  7683. return {
  7684. isMobile: function()
  7685. {
  7686. return /(iPhone|iPod|BlackBerry|Android)/.test(navigator.userAgent);
  7687. },
  7688. isDesktop: function()
  7689. {
  7690. return !/(iPhone|iPod|iPad|BlackBerry|Android)/.test(navigator.userAgent);
  7691. },
  7692. isString: function(obj)
  7693. {
  7694. return Object.prototype.toString.call(obj) == '[object String]';
  7695. },
  7696. isEmpty: function(html, removeEmptyTags)
  7697. {
  7698. html = html.replace(/[\u200B-\u200D\uFEFF]/g, '');
  7699. html = html.replace(/&nbsp;/gi, '');
  7700. html = html.replace(/<\/?br\s?\/?>/g, '');
  7701. html = html.replace(/\s/g, '');
  7702. html = html.replace(/^<p>[^\W\w\D\d]*?<\/p>$/i, '');
  7703. html = html.replace(/<iframe(.*?[^>])>$/i, 'iframe');
  7704. html = html.replace(/<source(.*?[^>])>$/i, 'source');
  7705. // remove empty tags
  7706. if (removeEmptyTags !== false)
  7707. {
  7708. html = html.replace(/<[^\/>][^>]*><\/[^>]+>/gi, '');
  7709. html = html.replace(/<[^\/>][^>]*><\/[^>]+>/gi, '');
  7710. }
  7711. html = $.trim(html);
  7712. return html === '';
  7713. },
  7714. normalize: function(str)
  7715. {
  7716. if (typeof(str) === 'undefined') return 0;
  7717. return parseInt(str.replace('px',''), 10);
  7718. },
  7719. hexToRgb: function(hex)
  7720. {
  7721. if (typeof hex == 'undefined') return;
  7722. if (hex.search(/^#/) == -1) return hex;
  7723. var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  7724. hex = hex.replace(shorthandRegex, function(m, r, g, b)
  7725. {
  7726. return r + r + g + g + b + b;
  7727. });
  7728. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  7729. return 'rgb(' + parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) + ')';
  7730. },
  7731. getOuterHtml: function(el)
  7732. {
  7733. return $('<div>').append($(el).eq(0).clone()).html();
  7734. },
  7735. getAlignmentElement: function(el)
  7736. {
  7737. if ($.inArray(el.tagName, this.opts.alignmentTags) !== -1)
  7738. {
  7739. return $(el);
  7740. }
  7741. else
  7742. {
  7743. return $(el).closest(this.opts.alignmentTags.toString().toLowerCase(), this.$editor[0]);
  7744. }
  7745. },
  7746. removeEmptyAttr: function(el, attr)
  7747. {
  7748. var $el = $(el);
  7749. if (typeof $el.attr(attr) == 'undefined')
  7750. {
  7751. return true;
  7752. }
  7753. if ($el.attr(attr) === '')
  7754. {
  7755. $el.removeAttr(attr);
  7756. return true;
  7757. }
  7758. return false;
  7759. },
  7760. removeEmpty: function(i, s)
  7761. {
  7762. var $s = $($.parseHTML(s));
  7763. $s.find('.redactor-invisible-space').removeAttr('style').removeAttr('class');
  7764. if ($s.find('hr, br, img, iframe, source').length !== 0) return;
  7765. var text = $.trim($s.text());
  7766. if (this.utils.isEmpty(text, false))
  7767. {
  7768. $s.remove();
  7769. }
  7770. },
  7771. // save and restore scroll
  7772. saveScroll: function()
  7773. {
  7774. this.saveEditorScroll = this.$editor.scrollTop();
  7775. this.saveBodyScroll = $(window).scrollTop();
  7776. if (this.opts.scrollTarget) this.saveTargetScroll = $(this.opts.scrollTarget).scrollTop();
  7777. },
  7778. restoreScroll: function()
  7779. {
  7780. if (typeof this.saveScroll === 'undefined' && typeof this.saveBodyScroll === 'undefined') return;
  7781. $(window).scrollTop(this.saveBodyScroll);
  7782. this.$editor.scrollTop(this.saveEditorScroll);
  7783. if (this.opts.scrollTarget) $(this.opts.scrollTarget).scrollTop(this.saveTargetScroll);
  7784. },
  7785. // get invisible space element
  7786. createSpaceElement: function()
  7787. {
  7788. var space = document.createElement('span');
  7789. space.className = 'redactor-invisible-space';
  7790. space.innerHTML = this.opts.invisibleSpace;
  7791. return space;
  7792. },
  7793. // replace
  7794. removeInlineTags: function(node)
  7795. {
  7796. var tags = this.opts.inlineTags;
  7797. tags.push('span');
  7798. if (node.tagName == 'PRE') tags.push('a');
  7799. $(node).find(tags.join(',')).not('span.redactor-selection-marker').contents().unwrap();
  7800. },
  7801. replaceWithContents: function(node, removeInlineTags)
  7802. {
  7803. var self = this;
  7804. $(node).replaceWith(function()
  7805. {
  7806. if (removeInlineTags === true) self.utils.removeInlineTags(this);
  7807. return $(this).contents();
  7808. });
  7809. return $(node);
  7810. },
  7811. replaceToTag: function(node, tag, removeInlineTags)
  7812. {
  7813. var replacement;
  7814. var self = this;
  7815. $(node).replaceWith(function()
  7816. {
  7817. replacement = $('<' + tag + ' />').append($(this).contents());
  7818. for (var i = 0; i < this.attributes.length; i++)
  7819. {
  7820. replacement.attr(this.attributes[i].name, this.attributes[i].value);
  7821. }
  7822. if (removeInlineTags === true) self.utils.removeInlineTags(replacement);
  7823. return replacement;
  7824. });
  7825. return replacement;
  7826. },
  7827. // start and end of element
  7828. isStartOfElement: function()
  7829. {
  7830. var block = this.selection.getBlock();
  7831. if (!block) return false;
  7832. var offset = this.caret.getOffsetOfElement(block);
  7833. return (offset === 0) ? true : false;
  7834. },
  7835. isEndOfElement: function(element)
  7836. {
  7837. if (typeof element == 'undefined')
  7838. {
  7839. var element = this.selection.getBlock();
  7840. if (!element) return false;
  7841. }
  7842. var offset = this.caret.getOffsetOfElement(element);
  7843. var text = $.trim($(element).text()).replace(/\n\r\n/g, '');
  7844. return (offset == text.length) ? true : false;
  7845. },
  7846. isStartOfEditor: function()
  7847. {
  7848. var offset = this.caret.getOffsetOfElement(this.$editor[0]);
  7849. return (offset === 0) ? true : false;
  7850. },
  7851. isEndOfEditor: function()
  7852. {
  7853. var block = this.$editor[0];
  7854. var offset = this.caret.getOffsetOfElement(block);
  7855. var text = $.trim($(block).html().replace(/(<([^>]+)>)/gi,''));
  7856. return (offset == text.length) ? true : false;
  7857. },
  7858. // test blocks
  7859. isBlock: function(block)
  7860. {
  7861. block = block[0] || block;
  7862. return block && this.utils.isBlockTag(block.tagName);
  7863. },
  7864. isBlockTag: function(tag)
  7865. {
  7866. if (typeof tag == 'undefined') return false;
  7867. return this.reIsBlock.test(tag);
  7868. },
  7869. // tag detection
  7870. isTag: function(current, tag)
  7871. {
  7872. var element = $(current).closest(tag, this.$editor[0]);
  7873. if (element.length == 1)
  7874. {
  7875. return element[0];
  7876. }
  7877. return false;
  7878. },
  7879. // select all
  7880. isSelectAll: function()
  7881. {
  7882. return this.selectAll;
  7883. },
  7884. enableSelectAll: function()
  7885. {
  7886. this.selectAll = true;
  7887. },
  7888. disableSelectAll: function()
  7889. {
  7890. this.selectAll = false;
  7891. },
  7892. // parents detection
  7893. isRedactorParent: function(el)
  7894. {
  7895. if (!el)
  7896. {
  7897. return false;
  7898. }
  7899. if ($(el).parents('.redactor-editor').length === 0 || $(el).hasClass('redactor-editor'))
  7900. {
  7901. return false;
  7902. }
  7903. return el;
  7904. },
  7905. isCurrentOrParentHeader: function()
  7906. {
  7907. return this.utils.isCurrentOrParent(['H1', 'H2', 'H3', 'H4', 'H5', 'H6']);
  7908. },
  7909. isCurrentOrParent: function(tagName)
  7910. {
  7911. var parent = this.selection.getParent();
  7912. var current = this.selection.getCurrent();
  7913. if ($.isArray(tagName))
  7914. {
  7915. var matched = 0;
  7916. $.each(tagName, $.proxy(function(i, s)
  7917. {
  7918. if (this.utils.isCurrentOrParentOne(current, parent, s))
  7919. {
  7920. matched++;
  7921. }
  7922. }, this));
  7923. return (matched === 0) ? false : true;
  7924. }
  7925. else
  7926. {
  7927. return this.utils.isCurrentOrParentOne(current, parent, tagName);
  7928. }
  7929. },
  7930. isCurrentOrParentOne: function(current, parent, tagName)
  7931. {
  7932. tagName = tagName.toUpperCase();
  7933. return parent && parent.tagName === tagName ? parent : current && current.tagName === tagName ? current : false;
  7934. },
  7935. // browsers detection
  7936. isOldIe: function()
  7937. {
  7938. return (this.utils.browser('msie') && parseInt(this.utils.browser('version'), 10) < 9) ? true : false;
  7939. },
  7940. isLessIe10: function()
  7941. {
  7942. return (this.utils.browser('msie') && parseInt(this.utils.browser('version'), 10) < 10) ? true : false;
  7943. },
  7944. isIe11: function()
  7945. {
  7946. return !!navigator.userAgent.match(/Trident\/7\./);
  7947. },
  7948. browser: function(browser)
  7949. {
  7950. var ua = navigator.userAgent.toLowerCase();
  7951. var match = /(opr)[\/]([\w.]+)/.exec( ua ) ||
  7952. /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
  7953. /(webkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(ua) ||
  7954. /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
  7955. /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
  7956. /(msie) ([\w.]+)/.exec( ua ) ||
  7957. ua.indexOf("trident") >= 0 && /(rv)(?::| )([\w.]+)/.exec( ua ) ||
  7958. ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
  7959. [];
  7960. if (browser == 'safari') return (typeof match[3] != 'undefined') ? match[3] == 'safari' : false;
  7961. if (browser == 'version') return match[2];
  7962. if (browser == 'webkit') return (match[1] == 'chrome' || match[1] == 'opr' || match[1] == 'webkit');
  7963. if (match[1] == 'rv') return browser == 'msie';
  7964. if (match[1] == 'opr') return browser == 'webkit';
  7965. return browser == match[1];
  7966. },
  7967. strpos: function(haystack, needle, offset)
  7968. {
  7969. var i = haystack.indexOf(needle, offset);
  7970. return i >= 0 ? i : false;
  7971. },
  7972. disableBodyScroll: function()
  7973. {
  7974. var $body = $('html');
  7975. var windowWidth = window.innerWidth;
  7976. if (!windowWidth)
  7977. {
  7978. var documentElementRect = document.documentElement.getBoundingClientRect();
  7979. windowWidth = documentElementRect.right - Math.abs(documentElementRect.left);
  7980. }
  7981. var isOverflowing = document.body.clientWidth < windowWidth;
  7982. var scrollbarWidth = this.utils.measureScrollbar();
  7983. $body.css('overflow', 'hidden');
  7984. if (isOverflowing) $body.css('padding-right', scrollbarWidth);
  7985. },
  7986. measureScrollbar: function()
  7987. {
  7988. var $body = $('body');
  7989. var scrollDiv = document.createElement('div');
  7990. scrollDiv.className = 'redactor-scrollbar-measure';
  7991. $body.append(scrollDiv);
  7992. var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
  7993. $body[0].removeChild(scrollDiv);
  7994. return scrollbarWidth;
  7995. },
  7996. enableBodyScroll: function()
  7997. {
  7998. $('html').css({ 'overflow': '', 'padding-right': '' });
  7999. $('body').remove('redactor-scrollbar-measure');
  8000. }
  8001. };
  8002. }
  8003. };
  8004. $(window).on('load.tools.redactor', function()
  8005. {
  8006. $('[data-tools="redactor"]').redactor();
  8007. });
  8008. // constructor
  8009. Redactor.prototype.init.prototype = Redactor.prototype;
  8010. })(jQuery);