tinymce.jquery.js 852 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544
  1. // 4.0.23 (2014-04-24)
  2. /**
  3. * Compiled inline version. (Library mode)
  4. */
  5. /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
  6. /*globals $code */
  7. (function(exports, undefined) {
  8. "use strict";
  9. var modules = {};
  10. function require(ids, callback) {
  11. var module, defs = [];
  12. for (var i = 0; i < ids.length; ++i) {
  13. module = modules[ids[i]] || resolve(ids[i]);
  14. if (!module) {
  15. throw 'module definition dependecy not found: ' + ids[i];
  16. }
  17. defs.push(module);
  18. }
  19. callback.apply(null, defs);
  20. }
  21. function define(id, dependencies, definition) {
  22. if (typeof id !== 'string') {
  23. throw 'invalid module definition, module id must be defined and be a string';
  24. }
  25. if (dependencies === undefined) {
  26. throw 'invalid module definition, dependencies must be specified';
  27. }
  28. if (definition === undefined) {
  29. throw 'invalid module definition, definition function must be specified';
  30. }
  31. require(dependencies, function() {
  32. modules[id] = definition.apply(null, arguments);
  33. });
  34. }
  35. function defined(id) {
  36. return !!modules[id];
  37. }
  38. function resolve(id) {
  39. var target = exports;
  40. var fragments = id.split(/[.\/]/);
  41. for (var fi = 0; fi < fragments.length; ++fi) {
  42. if (!target[fragments[fi]]) {
  43. return;
  44. }
  45. target = target[fragments[fi]];
  46. }
  47. return target;
  48. }
  49. function expose(ids) {
  50. for (var i = 0; i < ids.length; i++) {
  51. var target = exports;
  52. var id = ids[i];
  53. var fragments = id.split(/[.\/]/);
  54. for (var fi = 0; fi < fragments.length - 1; ++fi) {
  55. if (target[fragments[fi]] === undefined) {
  56. target[fragments[fi]] = {};
  57. }
  58. target = target[fragments[fi]];
  59. }
  60. target[fragments[fragments.length - 1]] = modules[id];
  61. }
  62. }
  63. // Included from: js/tinymce/classes/dom/Sizzle.jQuery.js
  64. /**
  65. * Sizzle.jQuery.js
  66. *
  67. * Copyright, Moxiecode Systems AB
  68. * Released under LGPL License.
  69. *
  70. * License: http://www.tinymce.com/license
  71. * Contributing: http://www.tinymce.com/contributing
  72. */
  73. /*global jQuery:true */
  74. /*
  75. * Fake Sizzle using jQuery.
  76. */
  77. define("tinymce/dom/Sizzle", [], function() {
  78. // Detect if jQuery is loaded
  79. if (!window.jQuery) {
  80. throw new Error("Load jQuery first");
  81. }
  82. return jQuery.find;
  83. });
  84. // Included from: js/tinymce/classes/html/Styles.js
  85. /**
  86. * Styles.js
  87. *
  88. * Copyright, Moxiecode Systems AB
  89. * Released under LGPL License.
  90. *
  91. * License: http://www.tinymce.com/license
  92. * Contributing: http://www.tinymce.com/contributing
  93. */
  94. /**
  95. * This class is used to parse CSS styles it also compresses styles to reduce the output size.
  96. *
  97. * @example
  98. * var Styles = new tinymce.html.Styles({
  99. * url_converter: function(url) {
  100. * return url;
  101. * }
  102. * });
  103. *
  104. * styles = Styles.parse('border: 1px solid red');
  105. * styles.color = 'red';
  106. *
  107. * console.log(new tinymce.html.StyleSerializer().serialize(styles));
  108. *
  109. * @class tinymce.html.Styles
  110. * @version 3.4
  111. */
  112. define("tinymce/html/Styles", [], function() {
  113. return function(settings, schema) {
  114. /*jshint maxlen:255 */
  115. /*eslint max-len:0 */
  116. var rgbRegExp = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gi,
  117. urlOrStrRegExp = /(?:url(?:(?:\(\s*\"([^\"]+)\"\s*\))|(?:\(\s*\'([^\']+)\'\s*\))|(?:\(\s*([^)\s]+)\s*\))))|(?:\'([^\']+)\')|(?:\"([^\"]+)\")/gi,
  118. styleRegExp = /\s*([^:]+):\s*([^;]+);?/g,
  119. trimRightRegExp = /\s+$/,
  120. undef, i, encodingLookup = {}, encodingItems, invisibleChar = '\uFEFF';
  121. settings = settings || {};
  122. encodingItems = ('\\" \\\' \\; \\: ; : ' + invisibleChar).split(' ');
  123. for (i = 0; i < encodingItems.length; i++) {
  124. encodingLookup[encodingItems[i]] = invisibleChar + i;
  125. encodingLookup[invisibleChar + i] = encodingItems[i];
  126. }
  127. function toHex(match, r, g, b) {
  128. function hex(val) {
  129. val = parseInt(val, 10).toString(16);
  130. return val.length > 1 ? val : '0' + val; // 0 -> 00
  131. }
  132. return '#' + hex(r) + hex(g) + hex(b);
  133. }
  134. return {
  135. /**
  136. * Parses the specified RGB color value and returns a hex version of that color.
  137. *
  138. * @method toHex
  139. * @param {String} color RGB string value like rgb(1,2,3)
  140. * @return {String} Hex version of that RGB value like #FF00FF.
  141. */
  142. toHex: function(color) {
  143. return color.replace(rgbRegExp, toHex);
  144. },
  145. /**
  146. * Parses the specified style value into an object collection. This parser will also
  147. * merge and remove any redundant items that browsers might have added. It will also convert non hex
  148. * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings.
  149. *
  150. * @method parse
  151. * @param {String} css Style value to parse for example: border:1px solid red;.
  152. * @return {Object} Object representation of that style like {border: '1px solid red'}
  153. */
  154. parse: function(css) {
  155. var styles = {}, matches, name, value, isEncoded, urlConverter = settings.url_converter;
  156. var urlConverterScope = settings.url_converter_scope || this;
  157. function compress(prefix, suffix, noJoin) {
  158. var top, right, bottom, left;
  159. top = styles[prefix + '-top' + suffix];
  160. if (!top) {
  161. return;
  162. }
  163. right = styles[prefix + '-right' + suffix];
  164. if (!right) {
  165. return;
  166. }
  167. bottom = styles[prefix + '-bottom' + suffix];
  168. if (!bottom) {
  169. return;
  170. }
  171. left = styles[prefix + '-left' + suffix];
  172. if (!left) {
  173. return;
  174. }
  175. var box = [top, right, bottom, left];
  176. i = box.length - 1;
  177. while (i--) {
  178. if (box[i] !== box[i + 1]) {
  179. break;
  180. }
  181. }
  182. if (i > -1 && noJoin) {
  183. return;
  184. }
  185. styles[prefix + suffix] = i == -1 ? box[0] : box.join(' ');
  186. delete styles[prefix + '-top' + suffix];
  187. delete styles[prefix + '-right' + suffix];
  188. delete styles[prefix + '-bottom' + suffix];
  189. delete styles[prefix + '-left' + suffix];
  190. }
  191. /**
  192. * Checks if the specific style can be compressed in other words if all border-width are equal.
  193. */
  194. function canCompress(key) {
  195. var value = styles[key], i;
  196. if (!value) {
  197. return;
  198. }
  199. value = value.split(' ');
  200. i = value.length;
  201. while (i--) {
  202. if (value[i] !== value[0]) {
  203. return false;
  204. }
  205. }
  206. styles[key] = value[0];
  207. return true;
  208. }
  209. /**
  210. * Compresses multiple styles into one style.
  211. */
  212. function compress2(target, a, b, c) {
  213. if (!canCompress(a)) {
  214. return;
  215. }
  216. if (!canCompress(b)) {
  217. return;
  218. }
  219. if (!canCompress(c)) {
  220. return;
  221. }
  222. // Compress
  223. styles[target] = styles[a] + ' ' + styles[b] + ' ' + styles[c];
  224. delete styles[a];
  225. delete styles[b];
  226. delete styles[c];
  227. }
  228. // Encodes the specified string by replacing all \" \' ; : with _<num>
  229. function encode(str) {
  230. isEncoded = true;
  231. return encodingLookup[str];
  232. }
  233. // Decodes the specified string by replacing all _<num> with it's original value \" \' etc
  234. // It will also decode the \" \' if keep_slashes is set to fale or omitted
  235. function decode(str, keep_slashes) {
  236. if (isEncoded) {
  237. str = str.replace(/\uFEFF[0-9]/g, function(str) {
  238. return encodingLookup[str];
  239. });
  240. }
  241. if (!keep_slashes) {
  242. str = str.replace(/\\([\'\";:])/g, "$1");
  243. }
  244. return str;
  245. }
  246. function processUrl(match, url, url2, url3, str, str2) {
  247. str = str || str2;
  248. if (str) {
  249. str = decode(str);
  250. // Force strings into single quote format
  251. return "'" + str.replace(/\'/g, "\\'") + "'";
  252. }
  253. url = decode(url || url2 || url3);
  254. if (!settings.allow_script_urls) {
  255. var scriptUrl = url.replace(/[\s\r\n]+/, '');
  256. if (/(java|vb)script:/i.test(scriptUrl)) {
  257. return "";
  258. }
  259. if (!settings.allow_svg_data_urls && /^data:image\/svg/i.test(scriptUrl)) {
  260. return "";
  261. }
  262. }
  263. // Convert the URL to relative/absolute depending on config
  264. if (urlConverter) {
  265. url = urlConverter.call(urlConverterScope, url, 'style');
  266. }
  267. // Output new URL format
  268. return "url('" + url.replace(/\'/g, "\\'") + "')";
  269. }
  270. if (css) {
  271. css = css.replace(/[\u0000-\u001F]/g, '');
  272. // Encode \" \' % and ; and : inside strings so they don't interfere with the style parsing
  273. css = css.replace(/\\[\"\';:\uFEFF]/g, encode).replace(/\"[^\"]+\"|\'[^\']+\'/g, function(str) {
  274. return str.replace(/[;:]/g, encode);
  275. });
  276. // Parse styles
  277. while ((matches = styleRegExp.exec(css))) {
  278. name = matches[1].replace(trimRightRegExp, '').toLowerCase();
  279. value = matches[2].replace(trimRightRegExp, '');
  280. // Decode escaped sequences like \65 -> e
  281. /*jshint loopfunc:true*/
  282. /*eslint no-loop-func:0 */
  283. value = value.replace(/\\[0-9a-f]+/g, function(e) {
  284. return String.fromCharCode(parseInt(e.substr(1), 16));
  285. });
  286. if (name && value.length > 0) {
  287. // Don't allow behavior name or expression/comments within the values
  288. if (!settings.allow_script_urls && (name == "behavior" || /expression\s*\(|\/\*|\*\//.test(value))) {
  289. continue;
  290. }
  291. // Opera will produce 700 instead of bold in their style values
  292. if (name === 'font-weight' && value === '700') {
  293. value = 'bold';
  294. } else if (name === 'color' || name === 'background-color') { // Lowercase colors like RED
  295. value = value.toLowerCase();
  296. }
  297. // Convert RGB colors to HEX
  298. value = value.replace(rgbRegExp, toHex);
  299. // Convert URLs and force them into url('value') format
  300. value = value.replace(urlOrStrRegExp, processUrl);
  301. styles[name] = isEncoded ? decode(value, true) : value;
  302. }
  303. styleRegExp.lastIndex = matches.index + matches[0].length;
  304. }
  305. // Compress the styles to reduce it's size for example IE will expand styles
  306. compress("border", "", true);
  307. compress("border", "-width");
  308. compress("border", "-color");
  309. compress("border", "-style");
  310. compress("padding", "");
  311. compress("margin", "");
  312. compress2('border', 'border-width', 'border-style', 'border-color');
  313. // Remove pointless border, IE produces these
  314. if (styles.border === 'medium none') {
  315. delete styles.border;
  316. }
  317. // IE 11 will produce a border-image: none when getting the style attribute from <p style="border: 1px solid red"></p>
  318. // So lets asume it shouldn't be there
  319. if (styles['border-image'] === 'none') {
  320. delete styles['border-image'];
  321. }
  322. }
  323. return styles;
  324. },
  325. /**
  326. * Serializes the specified style object into a string.
  327. *
  328. * @method serialize
  329. * @param {Object} styles Object to serialize as string for example: {border: '1px solid red'}
  330. * @param {String} element_name Optional element name, if specified only the styles that matches the schema will be serialized.
  331. * @return {String} String representation of the style object for example: border: 1px solid red.
  332. */
  333. serialize: function(styles, element_name) {
  334. var css = '', name, value;
  335. function serializeStyles(name) {
  336. var styleList, i, l, value;
  337. styleList = schema.styles[name];
  338. if (styleList) {
  339. for (i = 0, l = styleList.length; i < l; i++) {
  340. name = styleList[i];
  341. value = styles[name];
  342. if (value !== undef && value.length > 0) {
  343. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  344. }
  345. }
  346. }
  347. }
  348. // Serialize styles according to schema
  349. if (element_name && schema && schema.styles) {
  350. // Serialize global styles and element specific styles
  351. serializeStyles('*');
  352. serializeStyles(element_name);
  353. } else {
  354. // Output the styles in the order they are inside the object
  355. for (name in styles) {
  356. value = styles[name];
  357. if (value !== undef && value.length > 0) {
  358. css += (css.length > 0 ? ' ' : '') + name + ': ' + value + ';';
  359. }
  360. }
  361. }
  362. return css;
  363. }
  364. };
  365. };
  366. });
  367. // Included from: js/tinymce/classes/dom/EventUtils.js
  368. /**
  369. * EventUtils.js
  370. *
  371. * Copyright, Moxiecode Systems AB
  372. * Released under LGPL License.
  373. *
  374. * License: http://www.tinymce.com/license
  375. * Contributing: http://www.tinymce.com/contributing
  376. */
  377. /*jshint loopfunc:true*/
  378. /*eslint no-loop-func:0 */
  379. define("tinymce/dom/EventUtils", [], function() {
  380. "use strict";
  381. var eventExpandoPrefix = "mce-data-";
  382. var mouseEventRe = /^(?:mouse|contextmenu)|click/;
  383. var deprecated = {keyLocation: 1, layerX: 1, layerY: 1, returnValue: 1};
  384. /**
  385. * Binds a native event to a callback on the speified target.
  386. */
  387. function addEvent(target, name, callback, capture) {
  388. if (target.addEventListener) {
  389. target.addEventListener(name, callback, capture || false);
  390. } else if (target.attachEvent) {
  391. target.attachEvent('on' + name, callback);
  392. }
  393. }
  394. /**
  395. * Unbinds a native event callback on the specified target.
  396. */
  397. function removeEvent(target, name, callback, capture) {
  398. if (target.removeEventListener) {
  399. target.removeEventListener(name, callback, capture || false);
  400. } else if (target.detachEvent) {
  401. target.detachEvent('on' + name, callback);
  402. }
  403. }
  404. /**
  405. * Normalizes a native event object or just adds the event specific methods on a custom event.
  406. */
  407. function fix(originalEvent, data) {
  408. var name, event = data || {}, undef;
  409. // Dummy function that gets replaced on the delegation state functions
  410. function returnFalse() {
  411. return false;
  412. }
  413. // Dummy function that gets replaced on the delegation state functions
  414. function returnTrue() {
  415. return true;
  416. }
  417. // Copy all properties from the original event
  418. for (name in originalEvent) {
  419. // layerX/layerY is deprecated in Chrome and produces a warning
  420. if (!deprecated[name]) {
  421. event[name] = originalEvent[name];
  422. }
  423. }
  424. // Normalize target IE uses srcElement
  425. if (!event.target) {
  426. event.target = event.srcElement || document;
  427. }
  428. // Calculate pageX/Y if missing and clientX/Y available
  429. if (originalEvent && mouseEventRe.test(originalEvent.type) && originalEvent.pageX === undef && originalEvent.clientX !== undef) {
  430. var eventDoc = event.target.ownerDocument || document;
  431. var doc = eventDoc.documentElement;
  432. var body = eventDoc.body;
  433. event.pageX = originalEvent.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0 ) -
  434. ( doc && doc.clientLeft || body && body.clientLeft || 0);
  435. event.pageY = originalEvent.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0 ) -
  436. ( doc && doc.clientTop || body && body.clientTop || 0);
  437. }
  438. // Add preventDefault method
  439. event.preventDefault = function() {
  440. event.isDefaultPrevented = returnTrue;
  441. // Execute preventDefault on the original event object
  442. if (originalEvent) {
  443. if (originalEvent.preventDefault) {
  444. originalEvent.preventDefault();
  445. } else {
  446. originalEvent.returnValue = false; // IE
  447. }
  448. }
  449. };
  450. // Add stopPropagation
  451. event.stopPropagation = function() {
  452. event.isPropagationStopped = returnTrue;
  453. // Execute stopPropagation on the original event object
  454. if (originalEvent) {
  455. if (originalEvent.stopPropagation) {
  456. originalEvent.stopPropagation();
  457. } else {
  458. originalEvent.cancelBubble = true; // IE
  459. }
  460. }
  461. };
  462. // Add stopImmediatePropagation
  463. event.stopImmediatePropagation = function() {
  464. event.isImmediatePropagationStopped = returnTrue;
  465. event.stopPropagation();
  466. };
  467. // Add event delegation states
  468. if (!event.isDefaultPrevented) {
  469. event.isDefaultPrevented = returnFalse;
  470. event.isPropagationStopped = returnFalse;
  471. event.isImmediatePropagationStopped = returnFalse;
  472. }
  473. return event;
  474. }
  475. /**
  476. * Bind a DOMContentLoaded event across browsers and executes the callback once the page DOM is initialized.
  477. * It will also set/check the domLoaded state of the event_utils instance so ready isn't called multiple times.
  478. */
  479. function bindOnReady(win, callback, eventUtils) {
  480. var doc = win.document, event = {type: 'ready'};
  481. if (eventUtils.domLoaded) {
  482. callback(event);
  483. return;
  484. }
  485. // Gets called when the DOM is ready
  486. function readyHandler() {
  487. if (!eventUtils.domLoaded) {
  488. eventUtils.domLoaded = true;
  489. callback(event);
  490. }
  491. }
  492. function waitForDomLoaded() {
  493. // Check complete or interactive state if there is a body
  494. // element on some iframes IE 8 will produce a null body
  495. if (doc.readyState === "complete" || (doc.readyState === "interactive" && doc.body)) {
  496. removeEvent(doc, "readystatechange", waitForDomLoaded);
  497. readyHandler();
  498. }
  499. }
  500. function tryScroll() {
  501. try {
  502. // If IE is used, use the trick by Diego Perini licensed under MIT by request to the author.
  503. // http://javascript.nwbox.com/IEContentLoaded/
  504. doc.documentElement.doScroll("left");
  505. } catch (ex) {
  506. setTimeout(tryScroll, 0);
  507. return;
  508. }
  509. readyHandler();
  510. }
  511. // Use W3C method
  512. if (doc.addEventListener) {
  513. if (doc.readyState === "complete") {
  514. readyHandler();
  515. } else {
  516. addEvent(win, 'DOMContentLoaded', readyHandler);
  517. }
  518. } else {
  519. // Use IE method
  520. addEvent(doc, "readystatechange", waitForDomLoaded);
  521. // Wait until we can scroll, when we can the DOM is initialized
  522. if (doc.documentElement.doScroll && win.self === win.top) {
  523. tryScroll();
  524. }
  525. }
  526. // Fallback if any of the above methods should fail for some odd reason
  527. addEvent(win, 'load', readyHandler);
  528. }
  529. /**
  530. * This class enables you to bind/unbind native events to elements and normalize it's behavior across browsers.
  531. */
  532. function EventUtils() {
  533. var self = this, events = {}, count, expando, hasFocusIn, hasMouseEnterLeave, mouseEnterLeave;
  534. expando = eventExpandoPrefix + (+new Date()).toString(32);
  535. hasMouseEnterLeave = "onmouseenter" in document.documentElement;
  536. hasFocusIn = "onfocusin" in document.documentElement;
  537. mouseEnterLeave = {mouseenter: 'mouseover', mouseleave: 'mouseout'};
  538. count = 1;
  539. // State if the DOMContentLoaded was executed or not
  540. self.domLoaded = false;
  541. self.events = events;
  542. /**
  543. * Executes all event handler callbacks for a specific event.
  544. *
  545. * @private
  546. * @param {Event} evt Event object.
  547. * @param {String} id Expando id value to look for.
  548. */
  549. function executeHandlers(evt, id) {
  550. var callbackList, i, l, callback, container = events[id];
  551. callbackList = container && container[evt.type];
  552. if (callbackList) {
  553. for (i = 0, l = callbackList.length; i < l; i++) {
  554. callback = callbackList[i];
  555. // Check if callback exists might be removed if a unbind is called inside the callback
  556. if (callback && callback.func.call(callback.scope, evt) === false) {
  557. evt.preventDefault();
  558. }
  559. // Should we stop propagation to immediate listeners
  560. if (evt.isImmediatePropagationStopped()) {
  561. return;
  562. }
  563. }
  564. }
  565. }
  566. /**
  567. * Binds a callback to an event on the specified target.
  568. *
  569. * @method bind
  570. * @param {Object} target Target node/window or custom object.
  571. * @param {String} names Name of the event to bind.
  572. * @param {function} callback Callback function to execute when the event occurs.
  573. * @param {Object} scope Scope to call the callback function on, defaults to target.
  574. * @return {function} Callback function that got bound.
  575. */
  576. self.bind = function(target, names, callback, scope) {
  577. var id, callbackList, i, name, fakeName, nativeHandler, capture, win = window;
  578. // Native event handler function patches the event and executes the callbacks for the expando
  579. function defaultNativeHandler(evt) {
  580. executeHandlers(fix(evt || win.event), id);
  581. }
  582. // Don't bind to text nodes or comments
  583. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  584. return;
  585. }
  586. // Create or get events id for the target
  587. if (!target[expando]) {
  588. id = count++;
  589. target[expando] = id;
  590. events[id] = {};
  591. } else {
  592. id = target[expando];
  593. }
  594. // Setup the specified scope or use the target as a default
  595. scope = scope || target;
  596. // Split names and bind each event, enables you to bind multiple events with one call
  597. names = names.split(' ');
  598. i = names.length;
  599. while (i--) {
  600. name = names[i];
  601. nativeHandler = defaultNativeHandler;
  602. fakeName = capture = false;
  603. // Use ready instead of DOMContentLoaded
  604. if (name === "DOMContentLoaded") {
  605. name = "ready";
  606. }
  607. // DOM is already ready
  608. if (self.domLoaded && name === "ready" && target.readyState == 'complete') {
  609. callback.call(scope, fix({type: name}));
  610. continue;
  611. }
  612. // Handle mouseenter/mouseleaver
  613. if (!hasMouseEnterLeave) {
  614. fakeName = mouseEnterLeave[name];
  615. if (fakeName) {
  616. nativeHandler = function(evt) {
  617. var current, related;
  618. current = evt.currentTarget;
  619. related = evt.relatedTarget;
  620. // Check if related is inside the current target if it's not then the event should
  621. // be ignored since it's a mouseover/mouseout inside the element
  622. if (related && current.contains) {
  623. // Use contains for performance
  624. related = current.contains(related);
  625. } else {
  626. while (related && related !== current) {
  627. related = related.parentNode;
  628. }
  629. }
  630. // Fire fake event
  631. if (!related) {
  632. evt = fix(evt || win.event);
  633. evt.type = evt.type === 'mouseout' ? 'mouseleave' : 'mouseenter';
  634. evt.target = current;
  635. executeHandlers(evt, id);
  636. }
  637. };
  638. }
  639. }
  640. // Fake bubbeling of focusin/focusout
  641. if (!hasFocusIn && (name === "focusin" || name === "focusout")) {
  642. capture = true;
  643. fakeName = name === "focusin" ? "focus" : "blur";
  644. nativeHandler = function(evt) {
  645. evt = fix(evt || win.event);
  646. evt.type = evt.type === 'focus' ? 'focusin' : 'focusout';
  647. executeHandlers(evt, id);
  648. };
  649. }
  650. // Setup callback list and bind native event
  651. callbackList = events[id][name];
  652. if (!callbackList) {
  653. events[id][name] = callbackList = [{func: callback, scope: scope}];
  654. callbackList.fakeName = fakeName;
  655. callbackList.capture = capture;
  656. // Add the nativeHandler to the callback list so that we can later unbind it
  657. callbackList.nativeHandler = nativeHandler;
  658. // Check if the target has native events support
  659. if (name === "ready") {
  660. bindOnReady(target, nativeHandler, self);
  661. } else {
  662. addEvent(target, fakeName || name, nativeHandler, capture);
  663. }
  664. } else {
  665. if (name === "ready" && self.domLoaded) {
  666. callback({type: name});
  667. } else {
  668. // If it already has an native handler then just push the callback
  669. callbackList.push({func: callback, scope: scope});
  670. }
  671. }
  672. }
  673. target = callbackList = 0; // Clean memory for IE
  674. return callback;
  675. };
  676. /**
  677. * Unbinds the specified event by name, name and callback or all events on the target.
  678. *
  679. * @method unbind
  680. * @param {Object} target Target node/window or custom object.
  681. * @param {String} names Optional event name to unbind.
  682. * @param {function} callback Optional callback function to unbind.
  683. * @return {EventUtils} Event utils instance.
  684. */
  685. self.unbind = function(target, names, callback) {
  686. var id, callbackList, i, ci, name, eventMap;
  687. // Don't bind to text nodes or comments
  688. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  689. return self;
  690. }
  691. // Unbind event or events if the target has the expando
  692. id = target[expando];
  693. if (id) {
  694. eventMap = events[id];
  695. // Specific callback
  696. if (names) {
  697. names = names.split(' ');
  698. i = names.length;
  699. while (i--) {
  700. name = names[i];
  701. callbackList = eventMap[name];
  702. // Unbind the event if it exists in the map
  703. if (callbackList) {
  704. // Remove specified callback
  705. if (callback) {
  706. ci = callbackList.length;
  707. while (ci--) {
  708. if (callbackList[ci].func === callback) {
  709. var nativeHandler = callbackList.nativeHandler;
  710. var fakeName = callbackList.fakeName, capture = callbackList.capture;
  711. // Clone callbackList since unbind inside a callback would otherwise break the handlers loop
  712. callbackList = callbackList.slice(0, ci).concat(callbackList.slice(ci + 1));
  713. callbackList.nativeHandler = nativeHandler;
  714. callbackList.fakeName = fakeName;
  715. callbackList.capture = capture;
  716. eventMap[name] = callbackList;
  717. }
  718. }
  719. }
  720. // Remove all callbacks if there isn't a specified callback or there is no callbacks left
  721. if (!callback || callbackList.length === 0) {
  722. delete eventMap[name];
  723. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  724. }
  725. }
  726. }
  727. } else {
  728. // All events for a specific element
  729. for (name in eventMap) {
  730. callbackList = eventMap[name];
  731. removeEvent(target, callbackList.fakeName || name, callbackList.nativeHandler, callbackList.capture);
  732. }
  733. eventMap = {};
  734. }
  735. // Check if object is empty, if it isn't then we won't remove the expando map
  736. for (name in eventMap) {
  737. return self;
  738. }
  739. // Delete event object
  740. delete events[id];
  741. // Remove expando from target
  742. try {
  743. // IE will fail here since it can't delete properties from window
  744. delete target[expando];
  745. } catch (ex) {
  746. // IE will set it to null
  747. target[expando] = null;
  748. }
  749. }
  750. return self;
  751. };
  752. /**
  753. * Fires the specified event on the specified target.
  754. *
  755. * @method fire
  756. * @param {Object} target Target node/window or custom object.
  757. * @param {String} name Event name to fire.
  758. * @param {Object} args Optional arguments to send to the observers.
  759. * @return {EventUtils} Event utils instance.
  760. */
  761. self.fire = function(target, name, args) {
  762. var id;
  763. // Don't bind to text nodes or comments
  764. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  765. return self;
  766. }
  767. // Build event object by patching the args
  768. args = fix(null, args);
  769. args.type = name;
  770. args.target = target;
  771. do {
  772. // Found an expando that means there is listeners to execute
  773. id = target[expando];
  774. if (id) {
  775. executeHandlers(args, id);
  776. }
  777. // Walk up the DOM
  778. target = target.parentNode || target.ownerDocument || target.defaultView || target.parentWindow;
  779. } while (target && !args.isPropagationStopped());
  780. return self;
  781. };
  782. /**
  783. * Removes all bound event listeners for the specified target. This will also remove any bound
  784. * listeners to child nodes within that target.
  785. *
  786. * @method clean
  787. * @param {Object} target Target node/window object.
  788. * @return {EventUtils} Event utils instance.
  789. */
  790. self.clean = function(target) {
  791. var i, children, unbind = self.unbind;
  792. // Don't bind to text nodes or comments
  793. if (!target || target.nodeType === 3 || target.nodeType === 8) {
  794. return self;
  795. }
  796. // Unbind any element on the specificed target
  797. if (target[expando]) {
  798. unbind(target);
  799. }
  800. // Target doesn't have getElementsByTagName it's probably a window object then use it's document to find the children
  801. if (!target.getElementsByTagName) {
  802. target = target.document;
  803. }
  804. // Remove events from each child element
  805. if (target && target.getElementsByTagName) {
  806. unbind(target);
  807. children = target.getElementsByTagName('*');
  808. i = children.length;
  809. while (i--) {
  810. target = children[i];
  811. if (target[expando]) {
  812. unbind(target);
  813. }
  814. }
  815. }
  816. return self;
  817. };
  818. /**
  819. * Destroys the event object. Call this on IE to remove memory leaks.
  820. */
  821. self.destroy = function() {
  822. events = {};
  823. };
  824. // Legacy function for canceling events
  825. self.cancel = function(e) {
  826. if (e) {
  827. e.preventDefault();
  828. e.stopImmediatePropagation();
  829. }
  830. return false;
  831. };
  832. }
  833. EventUtils.Event = new EventUtils();
  834. EventUtils.Event.bind(window, 'ready', function() {});
  835. return EventUtils;
  836. });
  837. // Included from: js/tinymce/classes/dom/TreeWalker.js
  838. /**
  839. * TreeWalker.js
  840. *
  841. * Copyright, Moxiecode Systems AB
  842. * Released under LGPL License.
  843. *
  844. * License: http://www.tinymce.com/license
  845. * Contributing: http://www.tinymce.com/contributing
  846. */
  847. /**
  848. * TreeWalker class enables you to walk the DOM in a linear manner.
  849. *
  850. * @class tinymce.dom.TreeWalker
  851. */
  852. define("tinymce/dom/TreeWalker", [], function() {
  853. return function(start_node, root_node) {
  854. var node = start_node;
  855. function findSibling(node, start_name, sibling_name, shallow) {
  856. var sibling, parent;
  857. if (node) {
  858. // Walk into nodes if it has a start
  859. if (!shallow && node[start_name]) {
  860. return node[start_name];
  861. }
  862. // Return the sibling if it has one
  863. if (node != root_node) {
  864. sibling = node[sibling_name];
  865. if (sibling) {
  866. return sibling;
  867. }
  868. // Walk up the parents to look for siblings
  869. for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
  870. sibling = parent[sibling_name];
  871. if (sibling) {
  872. return sibling;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. /**
  879. * Returns the current node.
  880. *
  881. * @method current
  882. * @return {Node} Current node where the walker is.
  883. */
  884. this.current = function() {
  885. return node;
  886. };
  887. /**
  888. * Walks to the next node in tree.
  889. *
  890. * @method next
  891. * @return {Node} Current node where the walker is after moving to the next node.
  892. */
  893. this.next = function(shallow) {
  894. node = findSibling(node, 'firstChild', 'nextSibling', shallow);
  895. return node;
  896. };
  897. /**
  898. * Walks to the previous node in tree.
  899. *
  900. * @method prev
  901. * @return {Node} Current node where the walker is after moving to the previous node.
  902. */
  903. this.prev = function(shallow) {
  904. node = findSibling(node, 'lastChild', 'previousSibling', shallow);
  905. return node;
  906. };
  907. };
  908. });
  909. // Included from: js/tinymce/classes/util/Tools.js
  910. /**
  911. * Tools.js
  912. *
  913. * Copyright, Moxiecode Systems AB
  914. * Released under LGPL License.
  915. *
  916. * License: http://www.tinymce.com/license
  917. * Contributing: http://www.tinymce.com/contributing
  918. */
  919. /**
  920. * This class contains various utlity functions. These are also exposed
  921. * directly on the tinymce namespace.
  922. *
  923. * @class tinymce.util.Tools
  924. */
  925. define("tinymce/util/Tools", [], function() {
  926. /**
  927. * Removes whitespace from the beginning and end of a string.
  928. *
  929. * @method trim
  930. * @param {String} s String to remove whitespace from.
  931. * @return {String} New string with removed whitespace.
  932. */
  933. var whiteSpaceRegExp = /^\s*|\s*$/g;
  934. function trim(str) {
  935. return (str === null || str === undefined) ? '' : ("" + str).replace(whiteSpaceRegExp, '');
  936. }
  937. /**
  938. * Returns true/false if the object is an array or not.
  939. *
  940. * @method isArray
  941. * @param {Object} obj Object to check.
  942. * @return {boolean} true/false state if the object is an array or not.
  943. */
  944. var isArray = Array.isArray || function(obj) {
  945. return Object.prototype.toString.call(obj) === "[object Array]";
  946. };
  947. /**
  948. * Checks if a object is of a specific type for example an array.
  949. *
  950. * @method is
  951. * @param {Object} o Object to check type of.
  952. * @param {string} t Optional type to check for.
  953. * @return {Boolean} true/false if the object is of the specified type.
  954. */
  955. function is(o, t) {
  956. if (!t) {
  957. return o !== undefined;
  958. }
  959. if (t == 'array' && isArray(o)) {
  960. return true;
  961. }
  962. return typeof(o) == t;
  963. }
  964. /**
  965. * Converts the specified object into a real JavaScript array.
  966. *
  967. * @method toArray
  968. * @param {Object} obj Object to convert into array.
  969. * @return {Array} Array object based in input.
  970. */
  971. function toArray(obj) {
  972. var array = [], i, l;
  973. for (i = 0, l = obj.length; i < l; i++) {
  974. array[i] = obj[i];
  975. }
  976. return array;
  977. }
  978. /**
  979. * Makes a name/object map out of an array with names.
  980. *
  981. * @method makeMap
  982. * @param {Array/String} items Items to make map out of.
  983. * @param {String} delim Optional delimiter to split string by.
  984. * @param {Object} map Optional map to add items to.
  985. * @return {Object} Name/value map of items.
  986. */
  987. function makeMap(items, delim, map) {
  988. var i;
  989. items = items || [];
  990. delim = delim || ',';
  991. if (typeof(items) == "string") {
  992. items = items.split(delim);
  993. }
  994. map = map || {};
  995. i = items.length;
  996. while (i--) {
  997. map[items[i]] = {};
  998. }
  999. return map;
  1000. }
  1001. /**
  1002. * Performs an iteration of all items in a collection such as an object or array. This method will execure the
  1003. * callback function for each item in the collection, if the callback returns false the iteration will terminate.
  1004. * The callback has the following format: cb(value, key_or_index).
  1005. *
  1006. * @method each
  1007. * @param {Object} o Collection to iterate.
  1008. * @param {function} cb Callback function to execute for each item.
  1009. * @param {Object} s Optional scope to execute the callback in.
  1010. * @example
  1011. * // Iterate an array
  1012. * tinymce.each([1,2,3], function(v, i) {
  1013. * console.debug("Value: " + v + ", Index: " + i);
  1014. * });
  1015. *
  1016. * // Iterate an object
  1017. * tinymce.each({a: 1, b: 2, c: 3], function(v, k) {
  1018. * console.debug("Value: " + v + ", Key: " + k);
  1019. * });
  1020. */
  1021. function each(o, cb, s) {
  1022. var n, l;
  1023. if (!o) {
  1024. return 0;
  1025. }
  1026. s = s || o;
  1027. if (o.length !== undefined) {
  1028. // Indexed arrays, needed for Safari
  1029. for (n = 0, l = o.length; n < l; n++) {
  1030. if (cb.call(s, o[n], n, o) === false) {
  1031. return 0;
  1032. }
  1033. }
  1034. } else {
  1035. // Hashtables
  1036. for (n in o) {
  1037. if (o.hasOwnProperty(n)) {
  1038. if (cb.call(s, o[n], n, o) === false) {
  1039. return 0;
  1040. }
  1041. }
  1042. }
  1043. }
  1044. return 1;
  1045. }
  1046. /**
  1047. * Creates a new array by the return value of each iteration function call. This enables you to convert
  1048. * one array list into another.
  1049. *
  1050. * @method map
  1051. * @param {Array} a Array of items to iterate.
  1052. * @param {function} f Function to call for each item. It's return value will be the new value.
  1053. * @return {Array} Array with new values based on function return values.
  1054. */
  1055. function map(a, f) {
  1056. var o = [];
  1057. each(a, function(v) {
  1058. o.push(f(v));
  1059. });
  1060. return o;
  1061. }
  1062. /**
  1063. * Filters out items from the input array by calling the specified function for each item.
  1064. * If the function returns false the item will be excluded if it returns true it will be included.
  1065. *
  1066. * @method grep
  1067. * @param {Array} a Array of items to loop though.
  1068. * @param {function} f Function to call for each item. Include/exclude depends on it's return value.
  1069. * @return {Array} New array with values imported and filtered based in input.
  1070. * @example
  1071. * // Filter out some items, this will return an array with 4 and 5
  1072. * var items = tinymce.grep([1,2,3,4,5], function(v) {return v > 3;});
  1073. */
  1074. function grep(a, f) {
  1075. var o = [];
  1076. each(a, function(v) {
  1077. if (!f || f(v)) {
  1078. o.push(v);
  1079. }
  1080. });
  1081. return o;
  1082. }
  1083. /**
  1084. * Creates a class, subclass or static singleton.
  1085. * More details on this method can be found in the Wiki.
  1086. *
  1087. * @method create
  1088. * @param {String} s Class name, inheritage and prefix.
  1089. * @param {Object} p Collection of methods to add to the class.
  1090. * @param {Object} root Optional root object defaults to the global window object.
  1091. * @example
  1092. * // Creates a basic class
  1093. * tinymce.create('tinymce.somepackage.SomeClass', {
  1094. * SomeClass: function() {
  1095. * // Class constructor
  1096. * },
  1097. *
  1098. * method: function() {
  1099. * // Some method
  1100. * }
  1101. * });
  1102. *
  1103. * // Creates a basic subclass class
  1104. * tinymce.create('tinymce.somepackage.SomeSubClass:tinymce.somepackage.SomeClass', {
  1105. * SomeSubClass: function() {
  1106. * // Class constructor
  1107. * this.parent(); // Call parent constructor
  1108. * },
  1109. *
  1110. * method: function() {
  1111. * // Some method
  1112. * this.parent(); // Call parent method
  1113. * },
  1114. *
  1115. * 'static': {
  1116. * staticMethod: function() {
  1117. * // Static method
  1118. * }
  1119. * }
  1120. * });
  1121. *
  1122. * // Creates a singleton/static class
  1123. * tinymce.create('static tinymce.somepackage.SomeSingletonClass', {
  1124. * method: function() {
  1125. * // Some method
  1126. * }
  1127. * });
  1128. */
  1129. function create(s, p, root) {
  1130. var self = this, sp, ns, cn, scn, c, de = 0;
  1131. // Parse : <prefix> <class>:<super class>
  1132. s = /^((static) )?([\w.]+)(:([\w.]+))?/.exec(s);
  1133. cn = s[3].match(/(^|\.)(\w+)$/i)[2]; // Class name
  1134. // Create namespace for new class
  1135. ns = self.createNS(s[3].replace(/\.\w+$/, ''), root);
  1136. // Class already exists
  1137. if (ns[cn]) {
  1138. return;
  1139. }
  1140. // Make pure static class
  1141. if (s[2] == 'static') {
  1142. ns[cn] = p;
  1143. if (this.onCreate) {
  1144. this.onCreate(s[2], s[3], ns[cn]);
  1145. }
  1146. return;
  1147. }
  1148. // Create default constructor
  1149. if (!p[cn]) {
  1150. p[cn] = function() {};
  1151. de = 1;
  1152. }
  1153. // Add constructor and methods
  1154. ns[cn] = p[cn];
  1155. self.extend(ns[cn].prototype, p);
  1156. // Extend
  1157. if (s[5]) {
  1158. sp = self.resolve(s[5]).prototype;
  1159. scn = s[5].match(/\.(\w+)$/i)[1]; // Class name
  1160. // Extend constructor
  1161. c = ns[cn];
  1162. if (de) {
  1163. // Add passthrough constructor
  1164. ns[cn] = function() {
  1165. return sp[scn].apply(this, arguments);
  1166. };
  1167. } else {
  1168. // Add inherit constructor
  1169. ns[cn] = function() {
  1170. this.parent = sp[scn];
  1171. return c.apply(this, arguments);
  1172. };
  1173. }
  1174. ns[cn].prototype[cn] = ns[cn];
  1175. // Add super methods
  1176. self.each(sp, function(f, n) {
  1177. ns[cn].prototype[n] = sp[n];
  1178. });
  1179. // Add overridden methods
  1180. self.each(p, function(f, n) {
  1181. // Extend methods if needed
  1182. if (sp[n]) {
  1183. ns[cn].prototype[n] = function() {
  1184. this.parent = sp[n];
  1185. return f.apply(this, arguments);
  1186. };
  1187. } else {
  1188. if (n != cn) {
  1189. ns[cn].prototype[n] = f;
  1190. }
  1191. }
  1192. });
  1193. }
  1194. // Add static methods
  1195. /*jshint sub:true*/
  1196. self.each(p['static'], function(f, n) {
  1197. ns[cn][n] = f;
  1198. });
  1199. }
  1200. /**
  1201. * Returns the index of a value in an array, this method will return -1 if the item wasn't found.
  1202. *
  1203. * @method inArray
  1204. * @param {Array} a Array/Object to search for value in.
  1205. * @param {Object} v Value to check for inside the array.
  1206. * @return {Number/String} Index of item inside the array inside an object. Or -1 if it wasn't found.
  1207. * @example
  1208. * // Get index of value in array this will alert 1 since 2 is at that index
  1209. * alert(tinymce.inArray([1,2,3], 2));
  1210. */
  1211. function inArray(a, v) {
  1212. var i, l;
  1213. if (a) {
  1214. for (i = 0, l = a.length; i < l; i++) {
  1215. if (a[i] === v) {
  1216. return i;
  1217. }
  1218. }
  1219. }
  1220. return -1;
  1221. }
  1222. function extend(obj, ext) {
  1223. var i, l, name, args = arguments, value;
  1224. for (i = 1, l = args.length; i < l; i++) {
  1225. ext = args[i];
  1226. for (name in ext) {
  1227. if (ext.hasOwnProperty(name)) {
  1228. value = ext[name];
  1229. if (value !== undefined) {
  1230. obj[name] = value;
  1231. }
  1232. }
  1233. }
  1234. }
  1235. return obj;
  1236. }
  1237. /**
  1238. * Executed the specified function for each item in a object tree.
  1239. *
  1240. * @method walk
  1241. * @param {Object} o Object tree to walk though.
  1242. * @param {function} f Function to call for each item.
  1243. * @param {String} n Optional name of collection inside the objects to walk for example childNodes.
  1244. * @param {String} s Optional scope to execute the function in.
  1245. */
  1246. function walk(o, f, n, s) {
  1247. s = s || this;
  1248. if (o) {
  1249. if (n) {
  1250. o = o[n];
  1251. }
  1252. each(o, function(o, i) {
  1253. if (f.call(s, o, i, n) === false) {
  1254. return false;
  1255. }
  1256. walk(o, f, n, s);
  1257. });
  1258. }
  1259. }
  1260. /**
  1261. * Creates a namespace on a specific object.
  1262. *
  1263. * @method createNS
  1264. * @param {String} n Namespace to create for example a.b.c.d.
  1265. * @param {Object} o Optional object to add namespace to, defaults to window.
  1266. * @return {Object} New namespace object the last item in path.
  1267. * @example
  1268. * // Create some namespace
  1269. * tinymce.createNS('tinymce.somepackage.subpackage');
  1270. *
  1271. * // Add a singleton
  1272. * var tinymce.somepackage.subpackage.SomeSingleton = {
  1273. * method: function() {
  1274. * // Some method
  1275. * }
  1276. * };
  1277. */
  1278. function createNS(n, o) {
  1279. var i, v;
  1280. o = o || window;
  1281. n = n.split('.');
  1282. for (i = 0; i < n.length; i++) {
  1283. v = n[i];
  1284. if (!o[v]) {
  1285. o[v] = {};
  1286. }
  1287. o = o[v];
  1288. }
  1289. return o;
  1290. }
  1291. /**
  1292. * Resolves a string and returns the object from a specific structure.
  1293. *
  1294. * @method resolve
  1295. * @param {String} n Path to resolve for example a.b.c.d.
  1296. * @param {Object} o Optional object to search though, defaults to window.
  1297. * @return {Object} Last object in path or null if it couldn't be resolved.
  1298. * @example
  1299. * // Resolve a path into an object reference
  1300. * var obj = tinymce.resolve('a.b.c.d');
  1301. */
  1302. function resolve(n, o) {
  1303. var i, l;
  1304. o = o || window;
  1305. n = n.split('.');
  1306. for (i = 0, l = n.length; i < l; i++) {
  1307. o = o[n[i]];
  1308. if (!o) {
  1309. break;
  1310. }
  1311. }
  1312. return o;
  1313. }
  1314. /**
  1315. * Splits a string but removes the whitespace before and after each value.
  1316. *
  1317. * @method explode
  1318. * @param {string} s String to split.
  1319. * @param {string} d Delimiter to split by.
  1320. * @example
  1321. * // Split a string into an array with a,b,c
  1322. * var arr = tinymce.explode('a, b, c');
  1323. */
  1324. function explode(s, d) {
  1325. if (!s || is(s, 'array')) {
  1326. return s;
  1327. }
  1328. return map(s.split(d || ','), trim);
  1329. }
  1330. return {
  1331. trim: trim,
  1332. isArray: isArray,
  1333. is: is,
  1334. toArray: toArray,
  1335. makeMap: makeMap,
  1336. each: each,
  1337. map: map,
  1338. grep: grep,
  1339. inArray: inArray,
  1340. extend: extend,
  1341. create: create,
  1342. walk: walk,
  1343. createNS: createNS,
  1344. resolve: resolve,
  1345. explode: explode
  1346. };
  1347. });
  1348. // Included from: js/tinymce/classes/dom/Range.js
  1349. /**
  1350. * Range.js
  1351. *
  1352. * Copyright, Moxiecode Systems AB
  1353. * Released under LGPL License.
  1354. *
  1355. * License: http://www.tinymce.com/license
  1356. * Contributing: http://www.tinymce.com/contributing
  1357. */
  1358. define("tinymce/dom/Range", [
  1359. "tinymce/util/Tools"
  1360. ], function(Tools) {
  1361. // Range constructor
  1362. function Range(dom) {
  1363. var self = this,
  1364. doc = dom.doc,
  1365. EXTRACT = 0,
  1366. CLONE = 1,
  1367. DELETE = 2,
  1368. TRUE = true,
  1369. FALSE = false,
  1370. START_OFFSET = 'startOffset',
  1371. START_CONTAINER = 'startContainer',
  1372. END_CONTAINER = 'endContainer',
  1373. END_OFFSET = 'endOffset',
  1374. extend = Tools.extend,
  1375. nodeIndex = dom.nodeIndex;
  1376. function createDocumentFragment() {
  1377. return doc.createDocumentFragment();
  1378. }
  1379. function setStart(n, o) {
  1380. _setEndPoint(TRUE, n, o);
  1381. }
  1382. function setEnd(n, o) {
  1383. _setEndPoint(FALSE, n, o);
  1384. }
  1385. function setStartBefore(n) {
  1386. setStart(n.parentNode, nodeIndex(n));
  1387. }
  1388. function setStartAfter(n) {
  1389. setStart(n.parentNode, nodeIndex(n) + 1);
  1390. }
  1391. function setEndBefore(n) {
  1392. setEnd(n.parentNode, nodeIndex(n));
  1393. }
  1394. function setEndAfter(n) {
  1395. setEnd(n.parentNode, nodeIndex(n) + 1);
  1396. }
  1397. function collapse(ts) {
  1398. if (ts) {
  1399. self[END_CONTAINER] = self[START_CONTAINER];
  1400. self[END_OFFSET] = self[START_OFFSET];
  1401. } else {
  1402. self[START_CONTAINER] = self[END_CONTAINER];
  1403. self[START_OFFSET] = self[END_OFFSET];
  1404. }
  1405. self.collapsed = TRUE;
  1406. }
  1407. function selectNode(n) {
  1408. setStartBefore(n);
  1409. setEndAfter(n);
  1410. }
  1411. function selectNodeContents(n) {
  1412. setStart(n, 0);
  1413. setEnd(n, n.nodeType === 1 ? n.childNodes.length : n.nodeValue.length);
  1414. }
  1415. function compareBoundaryPoints(h, r) {
  1416. var sc = self[START_CONTAINER], so = self[START_OFFSET], ec = self[END_CONTAINER], eo = self[END_OFFSET],
  1417. rsc = r.startContainer, rso = r.startOffset, rec = r.endContainer, reo = r.endOffset;
  1418. // Check START_TO_START
  1419. if (h === 0) {
  1420. return _compareBoundaryPoints(sc, so, rsc, rso);
  1421. }
  1422. // Check START_TO_END
  1423. if (h === 1) {
  1424. return _compareBoundaryPoints(ec, eo, rsc, rso);
  1425. }
  1426. // Check END_TO_END
  1427. if (h === 2) {
  1428. return _compareBoundaryPoints(ec, eo, rec, reo);
  1429. }
  1430. // Check END_TO_START
  1431. if (h === 3) {
  1432. return _compareBoundaryPoints(sc, so, rec, reo);
  1433. }
  1434. }
  1435. function deleteContents() {
  1436. _traverse(DELETE);
  1437. }
  1438. function extractContents() {
  1439. return _traverse(EXTRACT);
  1440. }
  1441. function cloneContents() {
  1442. return _traverse(CLONE);
  1443. }
  1444. function insertNode(n) {
  1445. var startContainer = this[START_CONTAINER],
  1446. startOffset = this[START_OFFSET], nn, o;
  1447. // Node is TEXT_NODE or CDATA
  1448. if ((startContainer.nodeType === 3 || startContainer.nodeType === 4) && startContainer.nodeValue) {
  1449. if (!startOffset) {
  1450. // At the start of text
  1451. startContainer.parentNode.insertBefore(n, startContainer);
  1452. } else if (startOffset >= startContainer.nodeValue.length) {
  1453. // At the end of text
  1454. dom.insertAfter(n, startContainer);
  1455. } else {
  1456. // Middle, need to split
  1457. nn = startContainer.splitText(startOffset);
  1458. startContainer.parentNode.insertBefore(n, nn);
  1459. }
  1460. } else {
  1461. // Insert element node
  1462. if (startContainer.childNodes.length > 0) {
  1463. o = startContainer.childNodes[startOffset];
  1464. }
  1465. if (o) {
  1466. startContainer.insertBefore(n, o);
  1467. } else {
  1468. if (startContainer.nodeType == 3) {
  1469. dom.insertAfter(n, startContainer);
  1470. } else {
  1471. startContainer.appendChild(n);
  1472. }
  1473. }
  1474. }
  1475. }
  1476. function surroundContents(n) {
  1477. var f = self.extractContents();
  1478. self.insertNode(n);
  1479. n.appendChild(f);
  1480. self.selectNode(n);
  1481. }
  1482. function cloneRange() {
  1483. return extend(new Range(dom), {
  1484. startContainer: self[START_CONTAINER],
  1485. startOffset: self[START_OFFSET],
  1486. endContainer: self[END_CONTAINER],
  1487. endOffset: self[END_OFFSET],
  1488. collapsed: self.collapsed,
  1489. commonAncestorContainer: self.commonAncestorContainer
  1490. });
  1491. }
  1492. // Private methods
  1493. function _getSelectedNode(container, offset) {
  1494. var child;
  1495. if (container.nodeType == 3 /* TEXT_NODE */) {
  1496. return container;
  1497. }
  1498. if (offset < 0) {
  1499. return container;
  1500. }
  1501. child = container.firstChild;
  1502. while (child && offset > 0) {
  1503. --offset;
  1504. child = child.nextSibling;
  1505. }
  1506. if (child) {
  1507. return child;
  1508. }
  1509. return container;
  1510. }
  1511. function _isCollapsed() {
  1512. return (self[START_CONTAINER] == self[END_CONTAINER] && self[START_OFFSET] == self[END_OFFSET]);
  1513. }
  1514. function _compareBoundaryPoints(containerA, offsetA, containerB, offsetB) {
  1515. var c, offsetC, n, cmnRoot, childA, childB;
  1516. // In the first case the boundary-points have the same container. A is before B
  1517. // if its offset is less than the offset of B, A is equal to B if its offset is
  1518. // equal to the offset of B, and A is after B if its offset is greater than the
  1519. // offset of B.
  1520. if (containerA == containerB) {
  1521. if (offsetA == offsetB) {
  1522. return 0; // equal
  1523. }
  1524. if (offsetA < offsetB) {
  1525. return -1; // before
  1526. }
  1527. return 1; // after
  1528. }
  1529. // In the second case a child node C of the container of A is an ancestor
  1530. // container of B. In this case, A is before B if the offset of A is less than or
  1531. // equal to the index of the child node C and A is after B otherwise.
  1532. c = containerB;
  1533. while (c && c.parentNode != containerA) {
  1534. c = c.parentNode;
  1535. }
  1536. if (c) {
  1537. offsetC = 0;
  1538. n = containerA.firstChild;
  1539. while (n != c && offsetC < offsetA) {
  1540. offsetC++;
  1541. n = n.nextSibling;
  1542. }
  1543. if (offsetA <= offsetC) {
  1544. return -1; // before
  1545. }
  1546. return 1; // after
  1547. }
  1548. // In the third case a child node C of the container of B is an ancestor container
  1549. // of A. In this case, A is before B if the index of the child node C is less than
  1550. // the offset of B and A is after B otherwise.
  1551. c = containerA;
  1552. while (c && c.parentNode != containerB) {
  1553. c = c.parentNode;
  1554. }
  1555. if (c) {
  1556. offsetC = 0;
  1557. n = containerB.firstChild;
  1558. while (n != c && offsetC < offsetB) {
  1559. offsetC++;
  1560. n = n.nextSibling;
  1561. }
  1562. if (offsetC < offsetB) {
  1563. return -1; // before
  1564. }
  1565. return 1; // after
  1566. }
  1567. // In the fourth case, none of three other cases hold: the containers of A and B
  1568. // are siblings or descendants of sibling nodes. In this case, A is before B if
  1569. // the container of A is before the container of B in a pre-order traversal of the
  1570. // Ranges' context tree and A is after B otherwise.
  1571. cmnRoot = dom.findCommonAncestor(containerA, containerB);
  1572. childA = containerA;
  1573. while (childA && childA.parentNode != cmnRoot) {
  1574. childA = childA.parentNode;
  1575. }
  1576. if (!childA) {
  1577. childA = cmnRoot;
  1578. }
  1579. childB = containerB;
  1580. while (childB && childB.parentNode != cmnRoot) {
  1581. childB = childB.parentNode;
  1582. }
  1583. if (!childB) {
  1584. childB = cmnRoot;
  1585. }
  1586. if (childA == childB) {
  1587. return 0; // equal
  1588. }
  1589. n = cmnRoot.firstChild;
  1590. while (n) {
  1591. if (n == childA) {
  1592. return -1; // before
  1593. }
  1594. if (n == childB) {
  1595. return 1; // after
  1596. }
  1597. n = n.nextSibling;
  1598. }
  1599. }
  1600. function _setEndPoint(st, n, o) {
  1601. var ec, sc;
  1602. if (st) {
  1603. self[START_CONTAINER] = n;
  1604. self[START_OFFSET] = o;
  1605. } else {
  1606. self[END_CONTAINER] = n;
  1607. self[END_OFFSET] = o;
  1608. }
  1609. // If one boundary-point of a Range is set to have a root container
  1610. // other than the current one for the Range, the Range is collapsed to
  1611. // the new position. This enforces the restriction that both boundary-
  1612. // points of a Range must have the same root container.
  1613. ec = self[END_CONTAINER];
  1614. while (ec.parentNode) {
  1615. ec = ec.parentNode;
  1616. }
  1617. sc = self[START_CONTAINER];
  1618. while (sc.parentNode) {
  1619. sc = sc.parentNode;
  1620. }
  1621. if (sc == ec) {
  1622. // The start position of a Range is guaranteed to never be after the
  1623. // end position. To enforce this restriction, if the start is set to
  1624. // be at a position after the end, the Range is collapsed to that
  1625. // position.
  1626. if (_compareBoundaryPoints(self[START_CONTAINER], self[START_OFFSET], self[END_CONTAINER], self[END_OFFSET]) > 0) {
  1627. self.collapse(st);
  1628. }
  1629. } else {
  1630. self.collapse(st);
  1631. }
  1632. self.collapsed = _isCollapsed();
  1633. self.commonAncestorContainer = dom.findCommonAncestor(self[START_CONTAINER], self[END_CONTAINER]);
  1634. }
  1635. function _traverse(how) {
  1636. var c, endContainerDepth = 0, startContainerDepth = 0, p, depthDiff, startNode, endNode, sp, ep;
  1637. if (self[START_CONTAINER] == self[END_CONTAINER]) {
  1638. return _traverseSameContainer(how);
  1639. }
  1640. for (c = self[END_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
  1641. if (p == self[START_CONTAINER]) {
  1642. return _traverseCommonStartContainer(c, how);
  1643. }
  1644. ++endContainerDepth;
  1645. }
  1646. for (c = self[START_CONTAINER], p = c.parentNode; p; c = p, p = p.parentNode) {
  1647. if (p == self[END_CONTAINER]) {
  1648. return _traverseCommonEndContainer(c, how);
  1649. }
  1650. ++startContainerDepth;
  1651. }
  1652. depthDiff = startContainerDepth - endContainerDepth;
  1653. startNode = self[START_CONTAINER];
  1654. while (depthDiff > 0) {
  1655. startNode = startNode.parentNode;
  1656. depthDiff--;
  1657. }
  1658. endNode = self[END_CONTAINER];
  1659. while (depthDiff < 0) {
  1660. endNode = endNode.parentNode;
  1661. depthDiff++;
  1662. }
  1663. // ascend the ancestor hierarchy until we have a common parent.
  1664. for (sp = startNode.parentNode, ep = endNode.parentNode; sp != ep; sp = sp.parentNode, ep = ep.parentNode) {
  1665. startNode = sp;
  1666. endNode = ep;
  1667. }
  1668. return _traverseCommonAncestors(startNode, endNode, how);
  1669. }
  1670. function _traverseSameContainer(how) {
  1671. var frag, s, sub, n, cnt, sibling, xferNode, start, len;
  1672. if (how != DELETE) {
  1673. frag = createDocumentFragment();
  1674. }
  1675. // If selection is empty, just return the fragment
  1676. if (self[START_OFFSET] == self[END_OFFSET]) {
  1677. return frag;
  1678. }
  1679. // Text node needs special case handling
  1680. if (self[START_CONTAINER].nodeType == 3 /* TEXT_NODE */) {
  1681. // get the substring
  1682. s = self[START_CONTAINER].nodeValue;
  1683. sub = s.substring(self[START_OFFSET], self[END_OFFSET]);
  1684. // set the original text node to its new value
  1685. if (how != CLONE) {
  1686. n = self[START_CONTAINER];
  1687. start = self[START_OFFSET];
  1688. len = self[END_OFFSET] - self[START_OFFSET];
  1689. if (start === 0 && len >= n.nodeValue.length - 1) {
  1690. n.parentNode.removeChild(n);
  1691. } else {
  1692. n.deleteData(start, len);
  1693. }
  1694. // Nothing is partially selected, so collapse to start point
  1695. self.collapse(TRUE);
  1696. }
  1697. if (how == DELETE) {
  1698. return;
  1699. }
  1700. if (sub.length > 0) {
  1701. frag.appendChild(doc.createTextNode(sub));
  1702. }
  1703. return frag;
  1704. }
  1705. // Copy nodes between the start/end offsets.
  1706. n = _getSelectedNode(self[START_CONTAINER], self[START_OFFSET]);
  1707. cnt = self[END_OFFSET] - self[START_OFFSET];
  1708. while (n && cnt > 0) {
  1709. sibling = n.nextSibling;
  1710. xferNode = _traverseFullySelected(n, how);
  1711. if (frag) {
  1712. frag.appendChild(xferNode);
  1713. }
  1714. --cnt;
  1715. n = sibling;
  1716. }
  1717. // Nothing is partially selected, so collapse to start point
  1718. if (how != CLONE) {
  1719. self.collapse(TRUE);
  1720. }
  1721. return frag;
  1722. }
  1723. function _traverseCommonStartContainer(endAncestor, how) {
  1724. var frag, n, endIdx, cnt, sibling, xferNode;
  1725. if (how != DELETE) {
  1726. frag = createDocumentFragment();
  1727. }
  1728. n = _traverseRightBoundary(endAncestor, how);
  1729. if (frag) {
  1730. frag.appendChild(n);
  1731. }
  1732. endIdx = nodeIndex(endAncestor);
  1733. cnt = endIdx - self[START_OFFSET];
  1734. if (cnt <= 0) {
  1735. // Collapse to just before the endAncestor, which
  1736. // is partially selected.
  1737. if (how != CLONE) {
  1738. self.setEndBefore(endAncestor);
  1739. self.collapse(FALSE);
  1740. }
  1741. return frag;
  1742. }
  1743. n = endAncestor.previousSibling;
  1744. while (cnt > 0) {
  1745. sibling = n.previousSibling;
  1746. xferNode = _traverseFullySelected(n, how);
  1747. if (frag) {
  1748. frag.insertBefore(xferNode, frag.firstChild);
  1749. }
  1750. --cnt;
  1751. n = sibling;
  1752. }
  1753. // Collapse to just before the endAncestor, which
  1754. // is partially selected.
  1755. if (how != CLONE) {
  1756. self.setEndBefore(endAncestor);
  1757. self.collapse(FALSE);
  1758. }
  1759. return frag;
  1760. }
  1761. function _traverseCommonEndContainer(startAncestor, how) {
  1762. var frag, startIdx, n, cnt, sibling, xferNode;
  1763. if (how != DELETE) {
  1764. frag = createDocumentFragment();
  1765. }
  1766. n = _traverseLeftBoundary(startAncestor, how);
  1767. if (frag) {
  1768. frag.appendChild(n);
  1769. }
  1770. startIdx = nodeIndex(startAncestor);
  1771. ++startIdx; // Because we already traversed it
  1772. cnt = self[END_OFFSET] - startIdx;
  1773. n = startAncestor.nextSibling;
  1774. while (n && cnt > 0) {
  1775. sibling = n.nextSibling;
  1776. xferNode = _traverseFullySelected(n, how);
  1777. if (frag) {
  1778. frag.appendChild(xferNode);
  1779. }
  1780. --cnt;
  1781. n = sibling;
  1782. }
  1783. if (how != CLONE) {
  1784. self.setStartAfter(startAncestor);
  1785. self.collapse(TRUE);
  1786. }
  1787. return frag;
  1788. }
  1789. function _traverseCommonAncestors(startAncestor, endAncestor, how) {
  1790. var n, frag, startOffset, endOffset, cnt, sibling, nextSibling;
  1791. if (how != DELETE) {
  1792. frag = createDocumentFragment();
  1793. }
  1794. n = _traverseLeftBoundary(startAncestor, how);
  1795. if (frag) {
  1796. frag.appendChild(n);
  1797. }
  1798. startOffset = nodeIndex(startAncestor);
  1799. endOffset = nodeIndex(endAncestor);
  1800. ++startOffset;
  1801. cnt = endOffset - startOffset;
  1802. sibling = startAncestor.nextSibling;
  1803. while (cnt > 0) {
  1804. nextSibling = sibling.nextSibling;
  1805. n = _traverseFullySelected(sibling, how);
  1806. if (frag) {
  1807. frag.appendChild(n);
  1808. }
  1809. sibling = nextSibling;
  1810. --cnt;
  1811. }
  1812. n = _traverseRightBoundary(endAncestor, how);
  1813. if (frag) {
  1814. frag.appendChild(n);
  1815. }
  1816. if (how != CLONE) {
  1817. self.setStartAfter(startAncestor);
  1818. self.collapse(TRUE);
  1819. }
  1820. return frag;
  1821. }
  1822. function _traverseRightBoundary(root, how) {
  1823. var next = _getSelectedNode(self[END_CONTAINER], self[END_OFFSET] - 1), parent, clonedParent;
  1824. var prevSibling, clonedChild, clonedGrandParent, isFullySelected = next != self[END_CONTAINER];
  1825. if (next == root) {
  1826. return _traverseNode(next, isFullySelected, FALSE, how);
  1827. }
  1828. parent = next.parentNode;
  1829. clonedParent = _traverseNode(parent, FALSE, FALSE, how);
  1830. while (parent) {
  1831. while (next) {
  1832. prevSibling = next.previousSibling;
  1833. clonedChild = _traverseNode(next, isFullySelected, FALSE, how);
  1834. if (how != DELETE) {
  1835. clonedParent.insertBefore(clonedChild, clonedParent.firstChild);
  1836. }
  1837. isFullySelected = TRUE;
  1838. next = prevSibling;
  1839. }
  1840. if (parent == root) {
  1841. return clonedParent;
  1842. }
  1843. next = parent.previousSibling;
  1844. parent = parent.parentNode;
  1845. clonedGrandParent = _traverseNode(parent, FALSE, FALSE, how);
  1846. if (how != DELETE) {
  1847. clonedGrandParent.appendChild(clonedParent);
  1848. }
  1849. clonedParent = clonedGrandParent;
  1850. }
  1851. }
  1852. function _traverseLeftBoundary(root, how) {
  1853. var next = _getSelectedNode(self[START_CONTAINER], self[START_OFFSET]), isFullySelected = next != self[START_CONTAINER];
  1854. var parent, clonedParent, nextSibling, clonedChild, clonedGrandParent;
  1855. if (next == root) {
  1856. return _traverseNode(next, isFullySelected, TRUE, how);
  1857. }
  1858. parent = next.parentNode;
  1859. clonedParent = _traverseNode(parent, FALSE, TRUE, how);
  1860. while (parent) {
  1861. while (next) {
  1862. nextSibling = next.nextSibling;
  1863. clonedChild = _traverseNode(next, isFullySelected, TRUE, how);
  1864. if (how != DELETE) {
  1865. clonedParent.appendChild(clonedChild);
  1866. }
  1867. isFullySelected = TRUE;
  1868. next = nextSibling;
  1869. }
  1870. if (parent == root) {
  1871. return clonedParent;
  1872. }
  1873. next = parent.nextSibling;
  1874. parent = parent.parentNode;
  1875. clonedGrandParent = _traverseNode(parent, FALSE, TRUE, how);
  1876. if (how != DELETE) {
  1877. clonedGrandParent.appendChild(clonedParent);
  1878. }
  1879. clonedParent = clonedGrandParent;
  1880. }
  1881. }
  1882. function _traverseNode(n, isFullySelected, isLeft, how) {
  1883. var txtValue, newNodeValue, oldNodeValue, offset, newNode;
  1884. if (isFullySelected) {
  1885. return _traverseFullySelected(n, how);
  1886. }
  1887. if (n.nodeType == 3 /* TEXT_NODE */) {
  1888. txtValue = n.nodeValue;
  1889. if (isLeft) {
  1890. offset = self[START_OFFSET];
  1891. newNodeValue = txtValue.substring(offset);
  1892. oldNodeValue = txtValue.substring(0, offset);
  1893. } else {
  1894. offset = self[END_OFFSET];
  1895. newNodeValue = txtValue.substring(0, offset);
  1896. oldNodeValue = txtValue.substring(offset);
  1897. }
  1898. if (how != CLONE) {
  1899. n.nodeValue = oldNodeValue;
  1900. }
  1901. if (how == DELETE) {
  1902. return;
  1903. }
  1904. newNode = dom.clone(n, FALSE);
  1905. newNode.nodeValue = newNodeValue;
  1906. return newNode;
  1907. }
  1908. if (how == DELETE) {
  1909. return;
  1910. }
  1911. return dom.clone(n, FALSE);
  1912. }
  1913. function _traverseFullySelected(n, how) {
  1914. if (how != DELETE) {
  1915. return how == CLONE ? dom.clone(n, TRUE) : n;
  1916. }
  1917. n.parentNode.removeChild(n);
  1918. }
  1919. function toStringIE() {
  1920. return dom.create('body', null, cloneContents()).outerText;
  1921. }
  1922. extend(self, {
  1923. // Inital states
  1924. startContainer: doc,
  1925. startOffset: 0,
  1926. endContainer: doc,
  1927. endOffset: 0,
  1928. collapsed: TRUE,
  1929. commonAncestorContainer: doc,
  1930. // Range constants
  1931. START_TO_START: 0,
  1932. START_TO_END: 1,
  1933. END_TO_END: 2,
  1934. END_TO_START: 3,
  1935. // Public methods
  1936. setStart: setStart,
  1937. setEnd: setEnd,
  1938. setStartBefore: setStartBefore,
  1939. setStartAfter: setStartAfter,
  1940. setEndBefore: setEndBefore,
  1941. setEndAfter: setEndAfter,
  1942. collapse: collapse,
  1943. selectNode: selectNode,
  1944. selectNodeContents: selectNodeContents,
  1945. compareBoundaryPoints: compareBoundaryPoints,
  1946. deleteContents: deleteContents,
  1947. extractContents: extractContents,
  1948. cloneContents: cloneContents,
  1949. insertNode: insertNode,
  1950. surroundContents: surroundContents,
  1951. cloneRange: cloneRange,
  1952. toStringIE: toStringIE
  1953. });
  1954. return self;
  1955. }
  1956. // Older IE versions doesn't let you override toString by it's constructor so we have to stick it in the prototype
  1957. Range.prototype.toString = function() {
  1958. return this.toStringIE();
  1959. };
  1960. return Range;
  1961. });
  1962. // Included from: js/tinymce/classes/html/Entities.js
  1963. /**
  1964. * Entities.js
  1965. *
  1966. * Copyright, Moxiecode Systems AB
  1967. * Released under LGPL License.
  1968. *
  1969. * License: http://www.tinymce.com/license
  1970. * Contributing: http://www.tinymce.com/contributing
  1971. */
  1972. /*jshint bitwise:false */
  1973. /*eslint no-bitwise:0 */
  1974. /**
  1975. * Entity encoder class.
  1976. *
  1977. * @class tinymce.html.Entities
  1978. * @static
  1979. * @version 3.4
  1980. */
  1981. define("tinymce/html/Entities", [
  1982. "tinymce/util/Tools"
  1983. ], function(Tools) {
  1984. var makeMap = Tools.makeMap;
  1985. var namedEntities, baseEntities, reverseEntities,
  1986. attrsCharsRegExp = /[&<>\"\u0060\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  1987. textCharsRegExp = /[<>&\u007E-\uD7FF\uE000-\uFFEF]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
  1988. rawCharsRegExp = /[<>&\"\']/g,
  1989. entityRegExp = /&(#x|#)?([\w]+);/g,
  1990. asciiMap = {
  1991. 128: "\u20AC", 130: "\u201A", 131: "\u0192", 132: "\u201E", 133: "\u2026", 134: "\u2020",
  1992. 135: "\u2021", 136: "\u02C6", 137: "\u2030", 138: "\u0160", 139: "\u2039", 140: "\u0152",
  1993. 142: "\u017D", 145: "\u2018", 146: "\u2019", 147: "\u201C", 148: "\u201D", 149: "\u2022",
  1994. 150: "\u2013", 151: "\u2014", 152: "\u02DC", 153: "\u2122", 154: "\u0161", 155: "\u203A",
  1995. 156: "\u0153", 158: "\u017E", 159: "\u0178"
  1996. };
  1997. // Raw entities
  1998. baseEntities = {
  1999. '\"': '&quot;', // Needs to be escaped since the YUI compressor would otherwise break the code
  2000. "'": '&#39;',
  2001. '<': '&lt;',
  2002. '>': '&gt;',
  2003. '&': '&amp;',
  2004. '\u0060': '&#96;'
  2005. };
  2006. // Reverse lookup table for raw entities
  2007. reverseEntities = {
  2008. '&lt;': '<',
  2009. '&gt;': '>',
  2010. '&amp;': '&',
  2011. '&quot;': '"',
  2012. '&apos;': "'"
  2013. };
  2014. // Decodes text by using the browser
  2015. function nativeDecode(text) {
  2016. var elm;
  2017. elm = document.createElement("div");
  2018. elm.innerHTML = text;
  2019. return elm.textContent || elm.innerText || text;
  2020. }
  2021. // Build a two way lookup table for the entities
  2022. function buildEntitiesLookup(items, radix) {
  2023. var i, chr, entity, lookup = {};
  2024. if (items) {
  2025. items = items.split(',');
  2026. radix = radix || 10;
  2027. // Build entities lookup table
  2028. for (i = 0; i < items.length; i += 2) {
  2029. chr = String.fromCharCode(parseInt(items[i], radix));
  2030. // Only add non base entities
  2031. if (!baseEntities[chr]) {
  2032. entity = '&' + items[i + 1] + ';';
  2033. lookup[chr] = entity;
  2034. lookup[entity] = chr;
  2035. }
  2036. }
  2037. return lookup;
  2038. }
  2039. }
  2040. // Unpack entities lookup where the numbers are in radix 32 to reduce the size
  2041. namedEntities = buildEntitiesLookup(
  2042. '50,nbsp,51,iexcl,52,cent,53,pound,54,curren,55,yen,56,brvbar,57,sect,58,uml,59,copy,' +
  2043. '5a,ordf,5b,laquo,5c,not,5d,shy,5e,reg,5f,macr,5g,deg,5h,plusmn,5i,sup2,5j,sup3,5k,acute,' +
  2044. '5l,micro,5m,para,5n,middot,5o,cedil,5p,sup1,5q,ordm,5r,raquo,5s,frac14,5t,frac12,5u,frac34,' +
  2045. '5v,iquest,60,Agrave,61,Aacute,62,Acirc,63,Atilde,64,Auml,65,Aring,66,AElig,67,Ccedil,' +
  2046. '68,Egrave,69,Eacute,6a,Ecirc,6b,Euml,6c,Igrave,6d,Iacute,6e,Icirc,6f,Iuml,6g,ETH,6h,Ntilde,' +
  2047. '6i,Ograve,6j,Oacute,6k,Ocirc,6l,Otilde,6m,Ouml,6n,times,6o,Oslash,6p,Ugrave,6q,Uacute,' +
  2048. '6r,Ucirc,6s,Uuml,6t,Yacute,6u,THORN,6v,szlig,70,agrave,71,aacute,72,acirc,73,atilde,74,auml,' +
  2049. '75,aring,76,aelig,77,ccedil,78,egrave,79,eacute,7a,ecirc,7b,euml,7c,igrave,7d,iacute,7e,icirc,' +
  2050. '7f,iuml,7g,eth,7h,ntilde,7i,ograve,7j,oacute,7k,ocirc,7l,otilde,7m,ouml,7n,divide,7o,oslash,' +
  2051. '7p,ugrave,7q,uacute,7r,ucirc,7s,uuml,7t,yacute,7u,thorn,7v,yuml,ci,fnof,sh,Alpha,si,Beta,' +
  2052. 'sj,Gamma,sk,Delta,sl,Epsilon,sm,Zeta,sn,Eta,so,Theta,sp,Iota,sq,Kappa,sr,Lambda,ss,Mu,' +
  2053. 'st,Nu,su,Xi,sv,Omicron,t0,Pi,t1,Rho,t3,Sigma,t4,Tau,t5,Upsilon,t6,Phi,t7,Chi,t8,Psi,' +
  2054. 't9,Omega,th,alpha,ti,beta,tj,gamma,tk,delta,tl,epsilon,tm,zeta,tn,eta,to,theta,tp,iota,' +
  2055. 'tq,kappa,tr,lambda,ts,mu,tt,nu,tu,xi,tv,omicron,u0,pi,u1,rho,u2,sigmaf,u3,sigma,u4,tau,' +
  2056. 'u5,upsilon,u6,phi,u7,chi,u8,psi,u9,omega,uh,thetasym,ui,upsih,um,piv,812,bull,816,hellip,' +
  2057. '81i,prime,81j,Prime,81u,oline,824,frasl,88o,weierp,88h,image,88s,real,892,trade,89l,alefsym,' +
  2058. '8cg,larr,8ch,uarr,8ci,rarr,8cj,darr,8ck,harr,8dl,crarr,8eg,lArr,8eh,uArr,8ei,rArr,8ej,dArr,' +
  2059. '8ek,hArr,8g0,forall,8g2,part,8g3,exist,8g5,empty,8g7,nabla,8g8,isin,8g9,notin,8gb,ni,8gf,prod,' +
  2060. '8gh,sum,8gi,minus,8gn,lowast,8gq,radic,8gt,prop,8gu,infin,8h0,ang,8h7,and,8h8,or,8h9,cap,8ha,cup,' +
  2061. '8hb,int,8hk,there4,8hs,sim,8i5,cong,8i8,asymp,8j0,ne,8j1,equiv,8j4,le,8j5,ge,8k2,sub,8k3,sup,8k4,' +
  2062. 'nsub,8k6,sube,8k7,supe,8kl,oplus,8kn,otimes,8l5,perp,8m5,sdot,8o8,lceil,8o9,rceil,8oa,lfloor,8ob,' +
  2063. 'rfloor,8p9,lang,8pa,rang,9ea,loz,9j0,spades,9j3,clubs,9j5,hearts,9j6,diams,ai,OElig,aj,oelig,b0,' +
  2064. 'Scaron,b1,scaron,bo,Yuml,m6,circ,ms,tilde,802,ensp,803,emsp,809,thinsp,80c,zwnj,80d,zwj,80e,lrm,' +
  2065. '80f,rlm,80j,ndash,80k,mdash,80o,lsquo,80p,rsquo,80q,sbquo,80s,ldquo,80t,rdquo,80u,bdquo,810,dagger,' +
  2066. '811,Dagger,81g,permil,81p,lsaquo,81q,rsaquo,85c,euro', 32);
  2067. var Entities = {
  2068. /**
  2069. * Encodes the specified string using raw entities. This means only the required XML base entities will be endoded.
  2070. *
  2071. * @method encodeRaw
  2072. * @param {String} text Text to encode.
  2073. * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
  2074. * @return {String} Entity encoded text.
  2075. */
  2076. encodeRaw: function(text, attr) {
  2077. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
  2078. return baseEntities[chr] || chr;
  2079. });
  2080. },
  2081. /**
  2082. * Encoded the specified text with both the attributes and text entities. This function will produce larger text contents
  2083. * since it doesn't know if the context is within a attribute or text node. This was added for compatibility
  2084. * and is exposed as the DOMUtils.encode function.
  2085. *
  2086. * @method encodeAllRaw
  2087. * @param {String} text Text to encode.
  2088. * @return {String} Entity encoded text.
  2089. */
  2090. encodeAllRaw: function(text) {
  2091. return ('' + text).replace(rawCharsRegExp, function(chr) {
  2092. return baseEntities[chr] || chr;
  2093. });
  2094. },
  2095. /**
  2096. * Encodes the specified string using numeric entities. The core entities will be
  2097. * encoded as named ones but all non lower ascii characters will be encoded into numeric entities.
  2098. *
  2099. * @method encodeNumeric
  2100. * @param {String} text Text to encode.
  2101. * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
  2102. * @return {String} Entity encoded text.
  2103. */
  2104. encodeNumeric: function(text, attr) {
  2105. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
  2106. // Multi byte sequence convert it to a single entity
  2107. if (chr.length > 1) {
  2108. return '&#' + (((chr.charCodeAt(0) - 0xD800) * 0x400) + (chr.charCodeAt(1) - 0xDC00) + 0x10000) + ';';
  2109. }
  2110. return baseEntities[chr] || '&#' + chr.charCodeAt(0) + ';';
  2111. });
  2112. },
  2113. /**
  2114. * Encodes the specified string using named entities. The core entities will be encoded
  2115. * as named ones but all non lower ascii characters will be encoded into named entities.
  2116. *
  2117. * @method encodeNamed
  2118. * @param {String} text Text to encode.
  2119. * @param {Boolean} attr Optional flag to specify if the text is attribute contents.
  2120. * @param {Object} entities Optional parameter with entities to use.
  2121. * @return {String} Entity encoded text.
  2122. */
  2123. encodeNamed: function(text, attr, entities) {
  2124. entities = entities || namedEntities;
  2125. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
  2126. return baseEntities[chr] || entities[chr] || chr;
  2127. });
  2128. },
  2129. /**
  2130. * Returns an encode function based on the name(s) and it's optional entities.
  2131. *
  2132. * @method getEncodeFunc
  2133. * @param {String} name Comma separated list of encoders for example named,numeric.
  2134. * @param {String} entities Optional parameter with entities to use instead of the built in set.
  2135. * @return {function} Encode function to be used.
  2136. */
  2137. getEncodeFunc: function(name, entities) {
  2138. entities = buildEntitiesLookup(entities) || namedEntities;
  2139. function encodeNamedAndNumeric(text, attr) {
  2140. return text.replace(attr ? attrsCharsRegExp : textCharsRegExp, function(chr) {
  2141. return baseEntities[chr] || entities[chr] || '&#' + chr.charCodeAt(0) + ';' || chr;
  2142. });
  2143. }
  2144. function encodeCustomNamed(text, attr) {
  2145. return Entities.encodeNamed(text, attr, entities);
  2146. }
  2147. // Replace + with , to be compatible with previous TinyMCE versions
  2148. name = makeMap(name.replace(/\+/g, ','));
  2149. // Named and numeric encoder
  2150. if (name.named && name.numeric) {
  2151. return encodeNamedAndNumeric;
  2152. }
  2153. // Named encoder
  2154. if (name.named) {
  2155. // Custom names
  2156. if (entities) {
  2157. return encodeCustomNamed;
  2158. }
  2159. return Entities.encodeNamed;
  2160. }
  2161. // Numeric
  2162. if (name.numeric) {
  2163. return Entities.encodeNumeric;
  2164. }
  2165. // Raw encoder
  2166. return Entities.encodeRaw;
  2167. },
  2168. /**
  2169. * Decodes the specified string, this will replace entities with raw UTF characters.
  2170. *
  2171. * @method decode
  2172. * @param {String} text Text to entity decode.
  2173. * @return {String} Entity decoded string.
  2174. */
  2175. decode: function(text) {
  2176. return text.replace(entityRegExp, function(all, numeric, value) {
  2177. if (numeric) {
  2178. value = parseInt(value, numeric.length === 2 ? 16 : 10);
  2179. // Support upper UTF
  2180. if (value > 0xFFFF) {
  2181. value -= 0x10000;
  2182. return String.fromCharCode(0xD800 + (value >> 10), 0xDC00 + (value & 0x3FF));
  2183. } else {
  2184. return asciiMap[value] || String.fromCharCode(value);
  2185. }
  2186. }
  2187. return reverseEntities[all] || namedEntities[all] || nativeDecode(all);
  2188. });
  2189. }
  2190. };
  2191. return Entities;
  2192. });
  2193. // Included from: js/tinymce/classes/Env.js
  2194. /**
  2195. * Env.js
  2196. *
  2197. * Copyright, Moxiecode Systems AB
  2198. * Released under LGPL License.
  2199. *
  2200. * License: http://www.tinymce.com/license
  2201. * Contributing: http://www.tinymce.com/contributing
  2202. */
  2203. /**
  2204. * This class contains various environment constants like browser versions etc.
  2205. * Normally you don't want to sniff specific browser versions but sometimes you have
  2206. * to when it's impossible to feature detect. So use this with care.
  2207. *
  2208. * @class tinymce.Env
  2209. * @static
  2210. */
  2211. define("tinymce/Env", [], function() {
  2212. var nav = navigator, userAgent = nav.userAgent;
  2213. var opera, webkit, ie, ie11, gecko, mac, iDevice;
  2214. opera = window.opera && window.opera.buildNumber;
  2215. webkit = /WebKit/.test(userAgent);
  2216. ie = !webkit && !opera && (/MSIE/gi).test(userAgent) && (/Explorer/gi).test(nav.appName);
  2217. ie = ie && /MSIE (\w+)\./.exec(userAgent)[1];
  2218. ie11 = userAgent.indexOf('Trident/') != -1 && (userAgent.indexOf('rv:') != -1 || nav.appName.indexOf('Netscape') != -1) ? 11 : false;
  2219. ie = ie || ie11;
  2220. gecko = !webkit && !ie11 && /Gecko/.test(userAgent);
  2221. mac = userAgent.indexOf('Mac') != -1;
  2222. iDevice = /(iPad|iPhone)/.test(userAgent);
  2223. // Is a iPad/iPhone and not on iOS5 sniff the WebKit version since older iOS WebKit versions
  2224. // says it has contentEditable support but there is no visible caret.
  2225. var contentEditable = !iDevice || userAgent.match(/AppleWebKit\/(\d*)/)[1] >= 534;
  2226. return {
  2227. /**
  2228. * Constant that is true if the browser is Opera.
  2229. *
  2230. * @property opera
  2231. * @type Boolean
  2232. * @final
  2233. */
  2234. opera: opera,
  2235. /**
  2236. * Constant that is true if the browser is WebKit (Safari/Chrome).
  2237. *
  2238. * @property webKit
  2239. * @type Boolean
  2240. * @final
  2241. */
  2242. webkit: webkit,
  2243. /**
  2244. * Constant that is more than zero if the browser is IE.
  2245. *
  2246. * @property ie
  2247. * @type Boolean
  2248. * @final
  2249. */
  2250. ie: ie,
  2251. /**
  2252. * Constant that is true if the browser is Gecko.
  2253. *
  2254. * @property gecko
  2255. * @type Boolean
  2256. * @final
  2257. */
  2258. gecko: gecko,
  2259. /**
  2260. * Constant that is true if the os is Mac OS.
  2261. *
  2262. * @property mac
  2263. * @type Boolean
  2264. * @final
  2265. */
  2266. mac: mac,
  2267. /**
  2268. * Constant that is true if the os is iOS.
  2269. *
  2270. * @property iOS
  2271. * @type Boolean
  2272. * @final
  2273. */
  2274. iOS: iDevice,
  2275. /**
  2276. * Constant that is true if the browser supports editing.
  2277. *
  2278. * @property contentEditable
  2279. * @type Boolean
  2280. * @final
  2281. */
  2282. contentEditable: contentEditable,
  2283. /**
  2284. * Transparent image data url.
  2285. *
  2286. * @property transparentSrc
  2287. * @type Boolean
  2288. * @final
  2289. */
  2290. transparentSrc: "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7",
  2291. /**
  2292. * Returns true/false if the browser can or can't place the caret after a inline block like an image.
  2293. *
  2294. * @property noCaretAfter
  2295. * @type Boolean
  2296. * @final
  2297. */
  2298. caretAfter: ie != 8,
  2299. /**
  2300. * Constant that is true if the browser supports native DOM Ranges. IE 9+.
  2301. *
  2302. * @property range
  2303. * @type Boolean
  2304. */
  2305. range: window.getSelection && "Range" in window,
  2306. /**
  2307. * Returns the IE document mode for non IE browsers this will fake IE 10.
  2308. *
  2309. * @property documentMode
  2310. * @type Number
  2311. */
  2312. documentMode: ie ? (document.documentMode || 7) : 10
  2313. };
  2314. });
  2315. // Included from: js/tinymce/classes/dom/StyleSheetLoader.js
  2316. /**
  2317. * StyleSheetLoader.js
  2318. *
  2319. * Copyright, Moxiecode Systems AB
  2320. * Released under LGPL License.
  2321. *
  2322. * License: http://www.tinymce.com/license
  2323. * Contributing: http://www.tinymce.com/contributing
  2324. */
  2325. /**
  2326. * This class handles loading of external stylesheets and fires events when these are loaded.
  2327. *
  2328. * @class tinymce.dom.StyleSheetLoader
  2329. * @private
  2330. */
  2331. define("tinymce/dom/StyleSheetLoader", [], function() {
  2332. "use strict";
  2333. return function(document, settings) {
  2334. var idCount = 0, loadedStates = {}, maxLoadTime;
  2335. settings = settings || {};
  2336. maxLoadTime = settings.maxLoadTime || 5000;
  2337. function appendToHead(node) {
  2338. document.getElementsByTagName('head')[0].appendChild(node);
  2339. }
  2340. /**
  2341. * Loads the specified css style sheet file and call the loadedCallback once it's finished loading.
  2342. *
  2343. * @method load
  2344. * @param {String} url Url to be loaded.
  2345. * @param {Function} loadedCallback Callback to be executed when loaded.
  2346. * @param {Function} errorCallback Callback to be executed when failed loading.
  2347. */
  2348. function load(url, loadedCallback, errorCallback) {
  2349. var link, style, startTime, state;
  2350. function passed() {
  2351. var callbacks = state.passed, i = callbacks.length;
  2352. while (i--) {
  2353. callbacks[i]();
  2354. }
  2355. state.status = 2;
  2356. state.passed = [];
  2357. state.failed = [];
  2358. }
  2359. function failed() {
  2360. var callbacks = state.failed, i = callbacks.length;
  2361. while (i--) {
  2362. callbacks[i]();
  2363. }
  2364. state.status = 3;
  2365. state.passed = [];
  2366. state.failed = [];
  2367. }
  2368. // Sniffs for older WebKit versions that have the link.onload but a broken one
  2369. function isOldWebKit() {
  2370. var webKitChunks = navigator.userAgent.match(/WebKit\/(\d*)/);
  2371. return !!(webKitChunks && webKitChunks[1] < 536);
  2372. }
  2373. // Calls the waitCallback until the test returns true or the timeout occurs
  2374. function wait(testCallback, waitCallback) {
  2375. if (!testCallback()) {
  2376. // Wait for timeout
  2377. if ((new Date().getTime()) - startTime < maxLoadTime) {
  2378. window.setTimeout(waitCallback, 0);
  2379. } else {
  2380. failed();
  2381. }
  2382. }
  2383. }
  2384. // Workaround for WebKit that doesn't properly support the onload event for link elements
  2385. // Or WebKit that fires the onload event before the StyleSheet is added to the document
  2386. function waitForWebKitLinkLoaded() {
  2387. wait(function() {
  2388. var styleSheets = document.styleSheets, styleSheet, i = styleSheets.length, owner;
  2389. while (i--) {
  2390. styleSheet = styleSheets[i];
  2391. owner = styleSheet.ownerNode ? styleSheet.ownerNode : styleSheet.owningElement;
  2392. if (owner && owner.id === link.id) {
  2393. passed();
  2394. return true;
  2395. }
  2396. }
  2397. }, waitForWebKitLinkLoaded);
  2398. }
  2399. // Workaround for older Geckos that doesn't have any onload event for StyleSheets
  2400. function waitForGeckoLinkLoaded() {
  2401. wait(function() {
  2402. try {
  2403. // Accessing the cssRules will throw an exception until the CSS file is loaded
  2404. var cssRules = style.sheet.cssRules;
  2405. passed();
  2406. return !!cssRules;
  2407. } catch (ex) {
  2408. // Ignore
  2409. }
  2410. }, waitForGeckoLinkLoaded);
  2411. }
  2412. if (!loadedStates[url]) {
  2413. state = {
  2414. passed: [],
  2415. failed: []
  2416. };
  2417. loadedStates[url] = state;
  2418. } else {
  2419. state = loadedStates[url];
  2420. }
  2421. if (loadedCallback) {
  2422. state.passed.push(loadedCallback);
  2423. }
  2424. if (errorCallback) {
  2425. state.failed.push(errorCallback);
  2426. }
  2427. // Is loading wait for it to pass
  2428. if (state.status == 1) {
  2429. return;
  2430. }
  2431. // Has finished loading and was success
  2432. if (state.status == 2) {
  2433. passed();
  2434. return;
  2435. }
  2436. // Has finished loading and was a failure
  2437. if (state.status == 3) {
  2438. failed();
  2439. return;
  2440. }
  2441. // Start loading
  2442. state.status = 1;
  2443. link = document.createElement('link');
  2444. link.rel = 'stylesheet';
  2445. link.type = 'text/css';
  2446. link.id = 'u' + (idCount++);
  2447. link.async = false;
  2448. link.defer = false;
  2449. startTime = new Date().getTime();
  2450. // Feature detect onload on link element and sniff older webkits since it has an broken onload event
  2451. if ("onload" in link && !isOldWebKit()) {
  2452. link.onload = waitForWebKitLinkLoaded;
  2453. link.onerror = failed;
  2454. } else {
  2455. // Sniff for old Firefox that doesn't support the onload event on link elements
  2456. // TODO: Remove this in the future when everyone uses modern browsers
  2457. if (navigator.userAgent.indexOf("Firefox") > 0) {
  2458. style = document.createElement('style');
  2459. style.textContent = '@import "' + url + '"';
  2460. waitForGeckoLinkLoaded();
  2461. appendToHead(style);
  2462. return;
  2463. } else {
  2464. // Use the id owner on older webkits
  2465. waitForWebKitLinkLoaded();
  2466. }
  2467. }
  2468. appendToHead(link);
  2469. link.href = url;
  2470. }
  2471. this.load = load;
  2472. };
  2473. });
  2474. // Included from: js/tinymce/classes/dom/DOMUtils.js
  2475. /**
  2476. * DOMUtils.js
  2477. *
  2478. * Copyright, Moxiecode Systems AB
  2479. * Released under LGPL License.
  2480. *
  2481. * License: http://www.tinymce.com/license
  2482. * Contributing: http://www.tinymce.com/contributing
  2483. */
  2484. /**
  2485. * Utility class for various DOM manipulation and retrieval functions.
  2486. *
  2487. * @class tinymce.dom.DOMUtils
  2488. * @example
  2489. * // Add a class to an element by id in the page
  2490. * tinymce.DOM.addClass('someid', 'someclass');
  2491. *
  2492. * // Add a class to an element by id inside the editor
  2493. * tinymce.activeEditor.dom.addClass('someid', 'someclass');
  2494. */
  2495. define("tinymce/dom/DOMUtils", [
  2496. "tinymce/dom/Sizzle",
  2497. "tinymce/html/Styles",
  2498. "tinymce/dom/EventUtils",
  2499. "tinymce/dom/TreeWalker",
  2500. "tinymce/dom/Range",
  2501. "tinymce/html/Entities",
  2502. "tinymce/Env",
  2503. "tinymce/util/Tools",
  2504. "tinymce/dom/StyleSheetLoader"
  2505. ], function(Sizzle, Styles, EventUtils, TreeWalker, Range, Entities, Env, Tools, StyleSheetLoader) {
  2506. // Shorten names
  2507. var each = Tools.each, is = Tools.is, grep = Tools.grep, trim = Tools.trim, extend = Tools.extend;
  2508. var isWebKit = Env.webkit, isIE = Env.ie;
  2509. var simpleSelectorRe = /^([a-z0-9],?)+$/i;
  2510. var whiteSpaceRegExp = /^[ \t\r\n]*$/;
  2511. var numericCssMap = Tools.makeMap('fillOpacity fontWeight lineHeight opacity orphans widows zIndex zoom', ' ');
  2512. /**
  2513. * Constructs a new DOMUtils instance. Consult the Wiki for more details on settings etc for this class.
  2514. *
  2515. * @constructor
  2516. * @method DOMUtils
  2517. * @param {Document} d Document reference to bind the utility class to.
  2518. * @param {settings} s Optional settings collection.
  2519. */
  2520. function DOMUtils(doc, settings) {
  2521. var self = this, blockElementsMap;
  2522. self.doc = doc;
  2523. self.win = window;
  2524. self.files = {};
  2525. self.counter = 0;
  2526. self.stdMode = !isIE || doc.documentMode >= 8;
  2527. self.boxModel = !isIE || doc.compatMode == "CSS1Compat" || self.stdMode;
  2528. self.hasOuterHTML = "outerHTML" in doc.createElement("a");
  2529. self.styleSheetLoader = new StyleSheetLoader(doc);
  2530. this.boundEvents = [];
  2531. self.settings = settings = extend({
  2532. keep_values: false,
  2533. hex_colors: 1
  2534. }, settings);
  2535. self.schema = settings.schema;
  2536. self.styles = new Styles({
  2537. url_converter: settings.url_converter,
  2538. url_converter_scope: settings.url_converter_scope
  2539. }, settings.schema);
  2540. self.fixDoc(doc);
  2541. self.events = settings.ownEvents ? new EventUtils(settings.proxy) : EventUtils.Event;
  2542. blockElementsMap = settings.schema ? settings.schema.getBlockElements() : {};
  2543. /**
  2544. * Returns true/false if the specified element is a block element or not.
  2545. *
  2546. * @method isBlock
  2547. * @param {Node/String} node Element/Node to check.
  2548. * @return {Boolean} True/False state if the node is a block element or not.
  2549. */
  2550. self.isBlock = function(node) {
  2551. // Fix for #5446
  2552. if (!node) {
  2553. return false;
  2554. }
  2555. // This function is called in module pattern style since it might be executed with the wrong this scope
  2556. var type = node.nodeType;
  2557. // If it's a node then check the type and use the nodeName
  2558. if (type) {
  2559. return !!(type === 1 && blockElementsMap[node.nodeName]);
  2560. }
  2561. return !!blockElementsMap[node];
  2562. };
  2563. }
  2564. DOMUtils.prototype = {
  2565. root: null,
  2566. props: {
  2567. "for": "htmlFor",
  2568. "class": "className",
  2569. className: "className",
  2570. checked: "checked",
  2571. disabled: "disabled",
  2572. maxlength: "maxLength",
  2573. readonly: "readOnly",
  2574. selected: "selected",
  2575. value: "value",
  2576. id: "id",
  2577. name: "name",
  2578. type: "type"
  2579. },
  2580. fixDoc: function(doc) {
  2581. var settings = this.settings, name;
  2582. if (isIE && settings.schema) {
  2583. // Add missing HTML 4/5 elements to IE
  2584. ('abbr article aside audio canvas ' +
  2585. 'details figcaption figure footer ' +
  2586. 'header hgroup mark menu meter nav ' +
  2587. 'output progress section summary ' +
  2588. 'time video').replace(/\w+/g, function(name) {
  2589. doc.createElement(name);
  2590. });
  2591. // Create all custom elements
  2592. for (name in settings.schema.getCustomElements()) {
  2593. doc.createElement(name);
  2594. }
  2595. }
  2596. },
  2597. clone: function(node, deep) {
  2598. var self = this, clone, doc;
  2599. // TODO: Add feature detection here in the future
  2600. if (!isIE || node.nodeType !== 1 || deep) {
  2601. return node.cloneNode(deep);
  2602. }
  2603. doc = self.doc;
  2604. // Make a HTML5 safe shallow copy
  2605. if (!deep) {
  2606. clone = doc.createElement(node.nodeName);
  2607. // Copy attribs
  2608. each(self.getAttribs(node), function(attr) {
  2609. self.setAttrib(clone, attr.nodeName, self.getAttrib(node, attr.nodeName));
  2610. });
  2611. return clone;
  2612. }
  2613. /*
  2614. // Setup HTML5 patched document fragment
  2615. if (!self.frag) {
  2616. self.frag = doc.createDocumentFragment();
  2617. self.fixDoc(self.frag);
  2618. }
  2619. // Make a deep copy by adding it to the document fragment then removing it this removed the :section
  2620. clone = doc.createElement('div');
  2621. self.frag.appendChild(clone);
  2622. clone.innerHTML = node.outerHTML;
  2623. self.frag.removeChild(clone);
  2624. */
  2625. return clone.firstChild;
  2626. },
  2627. /**
  2628. * Returns the root node of the document. This is normally the body but might be a DIV. Parents like getParent will not
  2629. * go above the point of this root node.
  2630. *
  2631. * @method getRoot
  2632. * @return {Element} Root element for the utility class.
  2633. */
  2634. getRoot: function() {
  2635. var self = this;
  2636. return self.get(self.settings.root_element) || self.doc.body;
  2637. },
  2638. /**
  2639. * Returns the viewport of the window.
  2640. *
  2641. * @method getViewPort
  2642. * @param {Window} win Optional window to get viewport of.
  2643. * @return {Object} Viewport object with fields x, y, w and h.
  2644. */
  2645. getViewPort: function(win) {
  2646. var doc, rootElm;
  2647. win = !win ? this.win : win;
  2648. doc = win.document;
  2649. rootElm = this.boxModel ? doc.documentElement : doc.body;
  2650. // Returns viewport size excluding scrollbars
  2651. return {
  2652. x: win.pageXOffset || rootElm.scrollLeft,
  2653. y: win.pageYOffset || rootElm.scrollTop,
  2654. w: win.innerWidth || rootElm.clientWidth,
  2655. h: win.innerHeight || rootElm.clientHeight
  2656. };
  2657. },
  2658. /**
  2659. * Returns the rectangle for a specific element.
  2660. *
  2661. * @method getRect
  2662. * @param {Element/String} elm Element object or element ID to get rectangle from.
  2663. * @return {object} Rectangle for specified element object with x, y, w, h fields.
  2664. */
  2665. getRect: function(elm) {
  2666. var self = this, pos, size;
  2667. elm = self.get(elm);
  2668. pos = self.getPos(elm);
  2669. size = self.getSize(elm);
  2670. return {
  2671. x: pos.x, y: pos.y,
  2672. w: size.w, h: size.h
  2673. };
  2674. },
  2675. /**
  2676. * Returns the size dimensions of the specified element.
  2677. *
  2678. * @method getSize
  2679. * @param {Element/String} elm Element object or element ID to get rectangle from.
  2680. * @return {object} Rectangle for specified element object with w, h fields.
  2681. */
  2682. getSize: function(elm) {
  2683. var self = this, w, h;
  2684. elm = self.get(elm);
  2685. w = self.getStyle(elm, 'width');
  2686. h = self.getStyle(elm, 'height');
  2687. // Non pixel value, then force offset/clientWidth
  2688. if (w.indexOf('px') === -1) {
  2689. w = 0;
  2690. }
  2691. // Non pixel value, then force offset/clientWidth
  2692. if (h.indexOf('px') === -1) {
  2693. h = 0;
  2694. }
  2695. return {
  2696. w: parseInt(w, 10) || elm.offsetWidth || elm.clientWidth,
  2697. h: parseInt(h, 10) || elm.offsetHeight || elm.clientHeight
  2698. };
  2699. },
  2700. /**
  2701. * Returns a node by the specified selector function. This function will
  2702. * loop through all parent nodes and call the specified function for each node.
  2703. * If the function then returns true indicating that it has found what it was looking for, the loop execution will then end
  2704. * and the node it found will be returned.
  2705. *
  2706. * @method getParent
  2707. * @param {Node/String} node DOM node to search parents on or ID string.
  2708. * @param {function} selector Selection function or CSS selector to execute on each node.
  2709. * @param {Node} root Optional root element, never go below this point.
  2710. * @return {Node} DOM Node or null if it wasn't found.
  2711. */
  2712. getParent: function(node, selector, root) {
  2713. return this.getParents(node, selector, root, false);
  2714. },
  2715. /**
  2716. * Returns a node list of all parents matching the specified selector function or pattern.
  2717. * If the function then returns true indicating that it has found what it was looking for and that node will be collected.
  2718. *
  2719. * @method getParents
  2720. * @param {Node/String} node DOM node to search parents on or ID string.
  2721. * @param {function} selector Selection function to execute on each node or CSS pattern.
  2722. * @param {Node} root Optional root element, never go below this point.
  2723. * @return {Array} Array of nodes or null if it wasn't found.
  2724. */
  2725. getParents: function(node, selector, root, collect) {
  2726. var self = this, selectorVal, result = [];
  2727. node = self.get(node);
  2728. collect = collect === undefined;
  2729. // Default root on inline mode
  2730. root = root || (self.getRoot().nodeName != 'BODY' ? self.getRoot().parentNode : null);
  2731. // Wrap node name as func
  2732. if (is(selector, 'string')) {
  2733. selectorVal = selector;
  2734. if (selector === '*') {
  2735. selector = function(node) {return node.nodeType == 1;};
  2736. } else {
  2737. selector = function(node) {
  2738. return self.is(node, selectorVal);
  2739. };
  2740. }
  2741. }
  2742. while (node) {
  2743. if (node == root || !node.nodeType || node.nodeType === 9) {
  2744. break;
  2745. }
  2746. if (!selector || selector(node)) {
  2747. if (collect) {
  2748. result.push(node);
  2749. } else {
  2750. return node;
  2751. }
  2752. }
  2753. node = node.parentNode;
  2754. }
  2755. return collect ? result : null;
  2756. },
  2757. /**
  2758. * Returns the specified element by ID or the input element if it isn't a string.
  2759. *
  2760. * @method get
  2761. * @param {String/Element} n Element id to look for or element to just pass though.
  2762. * @return {Element} Element matching the specified id or null if it wasn't found.
  2763. */
  2764. get: function(elm) {
  2765. var name;
  2766. if (elm && this.doc && typeof(elm) == 'string') {
  2767. name = elm;
  2768. elm = this.doc.getElementById(elm);
  2769. // IE and Opera returns meta elements when they match the specified input ID, but getElementsByName seems to do the trick
  2770. if (elm && elm.id !== name) {
  2771. return this.doc.getElementsByName(name)[1];
  2772. }
  2773. }
  2774. return elm;
  2775. },
  2776. /**
  2777. * Returns the next node that matches selector or function
  2778. *
  2779. * @method getNext
  2780. * @param {Node} node Node to find siblings from.
  2781. * @param {String/function} selector Selector CSS expression or function.
  2782. * @return {Node} Next node item matching the selector or null if it wasn't found.
  2783. */
  2784. getNext: function(node, selector) {
  2785. return this._findSib(node, selector, 'nextSibling');
  2786. },
  2787. /**
  2788. * Returns the previous node that matches selector or function
  2789. *
  2790. * @method getPrev
  2791. * @param {Node} node Node to find siblings from.
  2792. * @param {String/function} selector Selector CSS expression or function.
  2793. * @return {Node} Previous node item matching the selector or null if it wasn't found.
  2794. */
  2795. getPrev: function(node, selector) {
  2796. return this._findSib(node, selector, 'previousSibling');
  2797. },
  2798. // #ifndef jquery
  2799. /**
  2800. * Selects specific elements by a CSS level 3 pattern. For example "div#a1 p.test".
  2801. * This function is optimized for the most common patterns needed in TinyMCE but it also performs well enough
  2802. * on more complex patterns.
  2803. *
  2804. * @method select
  2805. * @param {String} selector CSS level 3 pattern to select/find elements by.
  2806. * @param {Object} scope Optional root element/scope element to search in.
  2807. * @return {Array} Array with all matched elements.
  2808. * @example
  2809. * // Adds a class to all paragraphs in the currently active editor
  2810. * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass');
  2811. *
  2812. * // Adds a class to all spans that have the test class in the currently active editor
  2813. * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('span.test'), 'someclass')
  2814. */
  2815. select: function(selector, scope) {
  2816. var self = this;
  2817. //Sizzle.selectors.cacheLength = 0;
  2818. return Sizzle(selector, self.get(scope) || self.get(self.settings.root_element) || self.doc, []);
  2819. },
  2820. /**
  2821. * Returns true/false if the specified element matches the specified css pattern.
  2822. *
  2823. * @method is
  2824. * @param {Node/NodeList} elm DOM node to match or an array of nodes to match.
  2825. * @param {String} selector CSS pattern to match the element against.
  2826. */
  2827. is: function(elm, selector) {
  2828. var i;
  2829. // If it isn't an array then try to do some simple selectors instead of Sizzle for to boost performance
  2830. if (elm.length === undefined) {
  2831. // Simple all selector
  2832. if (selector === '*') {
  2833. return elm.nodeType == 1;
  2834. }
  2835. // Simple selector just elements
  2836. if (simpleSelectorRe.test(selector)) {
  2837. selector = selector.toLowerCase().split(/,/);
  2838. elm = elm.nodeName.toLowerCase();
  2839. for (i = selector.length - 1; i >= 0; i--) {
  2840. if (selector[i] == elm) {
  2841. return true;
  2842. }
  2843. }
  2844. return false;
  2845. }
  2846. }
  2847. // Is non element
  2848. if (elm.nodeType && elm.nodeType != 1) {
  2849. return false;
  2850. }
  2851. var elms = elm.nodeType ? [elm] : elm;
  2852. return Sizzle(selector, elms[0].ownerDocument || elms[0], null, elms).length > 0;
  2853. },
  2854. // #endif
  2855. /**
  2856. * Adds the specified element to another element or elements.
  2857. *
  2858. * @method add
  2859. * @param {String/Element/Array} parentElm Element id string, DOM node element or array of ids or elements to add to.
  2860. * @param {String/Element} name Name of new element to add or existing element to add.
  2861. * @param {Object} attrs Optional object collection with arguments to add to the new element(s).
  2862. * @param {String} html Optional inner HTML contents to add for each element.
  2863. * @return {Element/Array} Element that got created, or an array of created elements if multiple input elements
  2864. * were passed in.
  2865. * @example
  2866. * // Adds a new paragraph to the end of the active editor
  2867. * tinymce.activeEditor.dom.add(tinymce.activeEditor.getBody(), 'p', {title: 'my title'}, 'Some content');
  2868. */
  2869. add: function(parentElm, name, attrs, html, create) {
  2870. var self = this;
  2871. return this.run(parentElm, function(parentElm) {
  2872. var newElm;
  2873. newElm = is(name, 'string') ? self.doc.createElement(name) : name;
  2874. self.setAttribs(newElm, attrs);
  2875. if (html) {
  2876. if (html.nodeType) {
  2877. newElm.appendChild(html);
  2878. } else {
  2879. self.setHTML(newElm, html);
  2880. }
  2881. }
  2882. return !create ? parentElm.appendChild(newElm) : newElm;
  2883. });
  2884. },
  2885. /**
  2886. * Creates a new element.
  2887. *
  2888. * @method create
  2889. * @param {String} name Name of new element.
  2890. * @param {Object} attrs Optional object name/value collection with element attributes.
  2891. * @param {String} html Optional HTML string to set as inner HTML of the element.
  2892. * @return {Element} HTML DOM node element that got created.
  2893. * @example
  2894. * // Adds an element where the caret/selection is in the active editor
  2895. * var el = tinymce.activeEditor.dom.create('div', {id: 'test', 'class': 'myclass'}, 'some content');
  2896. * tinymce.activeEditor.selection.setNode(el);
  2897. */
  2898. create: function(name, attrs, html) {
  2899. return this.add(this.doc.createElement(name), name, attrs, html, 1);
  2900. },
  2901. /**
  2902. * Creates HTML string for element. The element will be closed unless an empty inner HTML string is passed in.
  2903. *
  2904. * @method createHTML
  2905. * @param {String} name Name of new element.
  2906. * @param {Object} attrs Optional object name/value collection with element attributes.
  2907. * @param {String} html Optional HTML string to set as inner HTML of the element.
  2908. * @return {String} String with new HTML element, for example: <a href="#">test</a>.
  2909. * @example
  2910. * // Creates a html chunk and inserts it at the current selection/caret location
  2911. * tinymce.activeEditor.selection.setContent(tinymce.activeEditor.dom.createHTML('a', {href: 'test.html'}, 'some line'));
  2912. */
  2913. createHTML: function(name, attrs, html) {
  2914. var outHtml = '', key;
  2915. outHtml += '<' + name;
  2916. for (key in attrs) {
  2917. if (attrs.hasOwnProperty(key) && attrs[key] !== null) {
  2918. outHtml += ' ' + key + '="' + this.encode(attrs[key]) + '"';
  2919. }
  2920. }
  2921. // A call to tinymce.is doesn't work for some odd reason on IE9 possible bug inside their JS runtime
  2922. if (typeof(html) != "undefined") {
  2923. return outHtml + '>' + html + '</' + name + '>';
  2924. }
  2925. return outHtml + ' />';
  2926. },
  2927. /**
  2928. * Creates a document fragment out of the specified HTML string.
  2929. *
  2930. * @method createFragment
  2931. * @param {String} html Html string to create fragment from.
  2932. * @return {DocumentFragment} Document fragment node.
  2933. */
  2934. createFragment: function(html) {
  2935. var frag, node, doc = this.doc, container;
  2936. container = doc.createElement("div");
  2937. frag = doc.createDocumentFragment();
  2938. if (html) {
  2939. container.innerHTML = html;
  2940. }
  2941. while ((node = container.firstChild)) {
  2942. frag.appendChild(node);
  2943. }
  2944. return frag;
  2945. },
  2946. /**
  2947. * Removes/deletes the specified element(s) from the DOM.
  2948. *
  2949. * @method remove
  2950. * @param {String/Element/Array} node ID of element or DOM element object or array containing multiple elements/ids.
  2951. * @param {Boolean} keep_children Optional state to keep children or not. If set to true all children will be
  2952. * placed at the location of the removed element.
  2953. * @return {Element/Array} HTML DOM element that got removed, or an array of removed elements if multiple input elements
  2954. * were passed in.
  2955. * @example
  2956. * // Removes all paragraphs in the active editor
  2957. * tinymce.activeEditor.dom.remove(tinymce.activeEditor.dom.select('p'));
  2958. *
  2959. * // Removes an element by id in the document
  2960. * tinymce.DOM.remove('mydiv');
  2961. */
  2962. remove: function(node, keep_children) {
  2963. return this.run(node, function(node) {
  2964. var child, parent = node.parentNode;
  2965. if (!parent) {
  2966. return null;
  2967. }
  2968. if (keep_children) {
  2969. while ((child = node.firstChild)) {
  2970. // IE 8 will crash if you don't remove completely empty text nodes
  2971. if (!isIE || child.nodeType !== 3 || child.nodeValue) {
  2972. parent.insertBefore(child, node);
  2973. } else {
  2974. node.removeChild(child);
  2975. }
  2976. }
  2977. }
  2978. return parent.removeChild(node);
  2979. });
  2980. },
  2981. /**
  2982. * Sets the CSS style value on a HTML element. The name can be a camelcase string
  2983. * or the CSS style name like background-color.
  2984. *
  2985. * @method setStyle
  2986. * @param {String/Element/Array} n HTML element/Element ID or Array of elements/ids to set CSS style value on.
  2987. * @param {String} na Name of the style value to set.
  2988. * @param {String} v Value to set on the style.
  2989. * @example
  2990. * // Sets a style value on all paragraphs in the currently active editor
  2991. * tinymce.activeEditor.dom.setStyle(tinymce.activeEditor.dom.select('p'), 'background-color', 'red');
  2992. *
  2993. * // Sets a style value to an element by id in the current document
  2994. * tinymce.DOM.setStyle('mydiv', 'background-color', 'red');
  2995. */
  2996. setStyle: function(elm, name, value) {
  2997. return this.run(elm, function(elm) {
  2998. var self = this, style, key;
  2999. if (name) {
  3000. if (typeof(name) === 'string') {
  3001. style = elm.style;
  3002. // Camelcase it, if needed
  3003. name = name.replace(/-(\D)/g, function(a, b) {
  3004. return b.toUpperCase();
  3005. });
  3006. // Default px suffix on these
  3007. if (typeof(value) === 'number' && !numericCssMap[name]) {
  3008. value += 'px';
  3009. }
  3010. // IE specific opacity
  3011. if (name === "opacity" && elm.runtimeStyle && typeof(elm.runtimeStyle.opacity) === "undefined") {
  3012. style.filter = value === '' ? '' : "alpha(opacity=" + (value * 100) + ")";
  3013. }
  3014. if (name == "float") {
  3015. // Old IE vs modern browsers
  3016. name = "cssFloat" in elm.style ? "cssFloat" : "styleFloat";
  3017. }
  3018. try {
  3019. style[name] = value;
  3020. } catch (ex) {
  3021. // Ignore IE errors
  3022. }
  3023. // Force update of the style data
  3024. if (self.settings.update_styles) {
  3025. elm.removeAttribute('data-mce-style');
  3026. }
  3027. } else {
  3028. for (key in name) {
  3029. self.setStyle(elm, key, name[key]);
  3030. }
  3031. }
  3032. }
  3033. });
  3034. },
  3035. /**
  3036. * Returns the current style or runtime/computed value of an element.
  3037. *
  3038. * @method getStyle
  3039. * @param {String/Element} elm HTML element or element id string to get style from.
  3040. * @param {String} name Style name to return.
  3041. * @param {Boolean} computed Computed style.
  3042. * @return {String} Current style or computed style value of an element.
  3043. */
  3044. getStyle: function(elm, name, computed) {
  3045. elm = this.get(elm);
  3046. if (!elm) {
  3047. return;
  3048. }
  3049. // W3C
  3050. if (this.doc.defaultView && computed) {
  3051. // Remove camelcase
  3052. name = name.replace(/[A-Z]/g, function(a){
  3053. return '-' + a;
  3054. });
  3055. try {
  3056. return this.doc.defaultView.getComputedStyle(elm, null).getPropertyValue(name);
  3057. } catch (ex) {
  3058. // Old safari might fail
  3059. return null;
  3060. }
  3061. }
  3062. // Camelcase it, if needed
  3063. name = name.replace(/-(\D)/g, function(a, b) {
  3064. return b.toUpperCase();
  3065. });
  3066. if (name == 'float') {
  3067. name = isIE ? 'styleFloat' : 'cssFloat';
  3068. }
  3069. // IE & Opera
  3070. if (elm.currentStyle && computed) {
  3071. return elm.currentStyle[name];
  3072. }
  3073. return elm.style ? elm.style[name] : undefined;
  3074. },
  3075. /**
  3076. * Sets multiple styles on the specified element(s).
  3077. *
  3078. * @method setStyles
  3079. * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set styles on.
  3080. * @param {Object} o Name/Value collection of style items to add to the element(s).
  3081. * @example
  3082. * // Sets styles on all paragraphs in the currently active editor
  3083. * tinymce.activeEditor.dom.setStyles(tinymce.activeEditor.dom.select('p'), {'background-color': 'red', 'color': 'green'});
  3084. *
  3085. * // Sets styles to an element by id in the current document
  3086. * tinymce.DOM.setStyles('mydiv', {'background-color': 'red', 'color': 'green'});
  3087. */
  3088. setStyles: function(elm, styles) {
  3089. this.setStyle(elm, styles);
  3090. },
  3091. css: function(elm, name, value) {
  3092. this.setStyle(elm, name, value);
  3093. },
  3094. /**
  3095. * Removes all attributes from an element or elements.
  3096. *
  3097. * @method removeAllAttribs
  3098. * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to remove attributes from.
  3099. */
  3100. removeAllAttribs: function(e) {
  3101. return this.run(e, function(e) {
  3102. var i, attrs = e.attributes;
  3103. for (i = attrs.length - 1; i >= 0; i--) {
  3104. e.removeAttributeNode(attrs.item(i));
  3105. }
  3106. });
  3107. },
  3108. /**
  3109. * Sets the specified attribute of an element or elements.
  3110. *
  3111. * @method setAttrib
  3112. * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set attribute on.
  3113. * @param {String} n Name of attribute to set.
  3114. * @param {String} v Value to set on the attribute - if this value is falsy like null, 0 or '' it will remove the attribute instead.
  3115. * @example
  3116. * // Sets class attribute on all paragraphs in the active editor
  3117. * tinymce.activeEditor.dom.setAttrib(tinymce.activeEditor.dom.select('p'), 'class', 'myclass');
  3118. *
  3119. * // Sets class attribute on a specific element in the current page
  3120. * tinymce.dom.setAttrib('mydiv', 'class', 'myclass');
  3121. */
  3122. setAttrib: function(e, n, v) {
  3123. var self = this;
  3124. // What's the point
  3125. if (!e || !n) {
  3126. return;
  3127. }
  3128. return this.run(e, function(e) {
  3129. var s = self.settings;
  3130. var originalValue = e.getAttribute(n);
  3131. if (v !== null) {
  3132. switch (n) {
  3133. case "style":
  3134. if (!is(v, 'string')) {
  3135. each(v, function(v, n) {
  3136. self.setStyle(e, n, v);
  3137. });
  3138. return;
  3139. }
  3140. // No mce_style for elements with these since they might get resized by the user
  3141. if (s.keep_values) {
  3142. if (v) {
  3143. e.setAttribute('data-mce-style', v, 2);
  3144. } else {
  3145. e.removeAttribute('data-mce-style', 2);
  3146. }
  3147. }
  3148. e.style.cssText = v;
  3149. break;
  3150. case "class":
  3151. e.className = v || ''; // Fix IE null bug
  3152. break;
  3153. case "src":
  3154. case "href":
  3155. if (s.keep_values) {
  3156. if (s.url_converter) {
  3157. v = s.url_converter.call(s.url_converter_scope || self, v, n, e);
  3158. }
  3159. self.setAttrib(e, 'data-mce-' + n, v, 2);
  3160. }
  3161. break;
  3162. case "shape":
  3163. e.setAttribute('data-mce-style', v);
  3164. break;
  3165. }
  3166. }
  3167. if (is(v) && v !== null && v.length !== 0) {
  3168. e.setAttribute(n, '' + v, 2);
  3169. } else {
  3170. e.removeAttribute(n, 2);
  3171. }
  3172. // fire onChangeAttrib event for attributes that have changed
  3173. if (originalValue != v && s.onSetAttrib) {
  3174. s.onSetAttrib({attrElm: e, attrName: n, attrValue: v});
  3175. }
  3176. });
  3177. },
  3178. /**
  3179. * Sets two or more specified attributes of an element or elements.
  3180. *
  3181. * @method setAttribs
  3182. * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set attributes on.
  3183. * @param {Object} attrs Name/Value collection of attribute items to add to the element(s).
  3184. * @example
  3185. * // Sets class and title attributes on all paragraphs in the active editor
  3186. * tinymce.activeEditor.dom.setAttribs(tinymce.activeEditor.dom.select('p'), {'class': 'myclass', title: 'some title'});
  3187. *
  3188. * // Sets class and title attributes on a specific element in the current page
  3189. * tinymce.DOM.setAttribs('mydiv', {'class': 'myclass', title: 'some title'});
  3190. */
  3191. setAttribs: function(elm, attrs) {
  3192. var self = this;
  3193. return this.run(elm, function(elm) {
  3194. each(attrs, function(value, name) {
  3195. self.setAttrib(elm, name, value);
  3196. });
  3197. });
  3198. },
  3199. /**
  3200. * Returns the specified attribute by name.
  3201. *
  3202. * @method getAttrib
  3203. * @param {String/Element} elm Element string id or DOM element to get attribute from.
  3204. * @param {String} name Name of attribute to get.
  3205. * @param {String} defaultVal Optional default value to return if the attribute didn't exist.
  3206. * @return {String} Attribute value string, default value or null if the attribute wasn't found.
  3207. */
  3208. getAttrib: function(elm, name, defaultVal) {
  3209. var value, self = this, undef;
  3210. elm = self.get(elm);
  3211. if (!elm || elm.nodeType !== 1) {
  3212. return defaultVal === undef ? false : defaultVal;
  3213. }
  3214. if (!is(defaultVal)) {
  3215. defaultVal = '';
  3216. }
  3217. // Try the mce variant for these
  3218. if (/^(src|href|style|coords|shape)$/.test(name)) {
  3219. value = elm.getAttribute("data-mce-" + name);
  3220. if (value) {
  3221. return value;
  3222. }
  3223. }
  3224. if (isIE && self.props[name]) {
  3225. value = elm[self.props[name]];
  3226. value = value && value.nodeValue ? value.nodeValue : value;
  3227. }
  3228. if (!value) {
  3229. value = elm.getAttribute(name, 2);
  3230. }
  3231. // Check boolean attribs
  3232. if (/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noshade|nowrap|readonly|selected)$/.test(name)) {
  3233. if (elm[self.props[name]] === true && value === '') {
  3234. return name;
  3235. }
  3236. return value ? name : '';
  3237. }
  3238. // Inner input elements will override attributes on form elements
  3239. if (elm.nodeName === "FORM" && elm.getAttributeNode(name)) {
  3240. return elm.getAttributeNode(name).nodeValue;
  3241. }
  3242. if (name === 'style') {
  3243. value = value || elm.style.cssText;
  3244. if (value) {
  3245. value = self.serializeStyle(self.parseStyle(value), elm.nodeName);
  3246. if (self.settings.keep_values) {
  3247. elm.setAttribute('data-mce-style', value);
  3248. }
  3249. }
  3250. }
  3251. // Remove Apple and WebKit stuff
  3252. if (isWebKit && name === "class" && value) {
  3253. value = value.replace(/(apple|webkit)\-[a-z\-]+/gi, '');
  3254. }
  3255. // Handle IE issues
  3256. if (isIE) {
  3257. switch (name) {
  3258. case 'rowspan':
  3259. case 'colspan':
  3260. // IE returns 1 as default value
  3261. if (value === 1) {
  3262. value = '';
  3263. }
  3264. break;
  3265. case 'size':
  3266. // IE returns +0 as default value for size
  3267. if (value === '+0' || value === 20 || value === 0) {
  3268. value = '';
  3269. }
  3270. break;
  3271. case 'width':
  3272. case 'height':
  3273. case 'vspace':
  3274. case 'checked':
  3275. case 'disabled':
  3276. case 'readonly':
  3277. if (value === 0) {
  3278. value = '';
  3279. }
  3280. break;
  3281. case 'hspace':
  3282. // IE returns -1 as default value
  3283. if (value === -1) {
  3284. value = '';
  3285. }
  3286. break;
  3287. case 'maxlength':
  3288. case 'tabindex':
  3289. // IE returns default value
  3290. if (value === 32768 || value === 2147483647 || value === '32768') {
  3291. value = '';
  3292. }
  3293. break;
  3294. case 'multiple':
  3295. case 'compact':
  3296. case 'noshade':
  3297. case 'nowrap':
  3298. if (value === 65535) {
  3299. return name;
  3300. }
  3301. return defaultVal;
  3302. case 'shape':
  3303. value = value.toLowerCase();
  3304. break;
  3305. default:
  3306. // IE has odd anonymous function for event attributes
  3307. if (name.indexOf('on') === 0 && value) {
  3308. value = ('' + value).replace(/^function\s+\w+\(\)\s+\{\s+(.*)\s+\}$/, '$1');
  3309. }
  3310. }
  3311. }
  3312. return (value !== undef && value !== null && value !== '') ? '' + value : defaultVal;
  3313. },
  3314. /**
  3315. * Returns the absolute x, y position of a node. The position will be returned in an object with x, y fields.
  3316. *
  3317. * @method getPos
  3318. * @param {Element/String} elm HTML element or element id to get x, y position from.
  3319. * @param {Element} rootElm Optional root element to stop calculations at.
  3320. * @return {object} Absolute position of the specified element object with x, y fields.
  3321. */
  3322. getPos: function(elm, rootElm) {
  3323. var self = this, x = 0, y = 0, offsetParent, doc = self.doc, pos;
  3324. elm = self.get(elm);
  3325. rootElm = rootElm || doc.body;
  3326. if (elm) {
  3327. // Use getBoundingClientRect if it exists since it's faster than looping offset nodes
  3328. if (rootElm === doc.body && elm.getBoundingClientRect) {
  3329. pos = elm.getBoundingClientRect();
  3330. rootElm = self.boxModel ? doc.documentElement : doc.body;
  3331. // Add scroll offsets from documentElement or body since IE with the wrong box model will use d.body and so do WebKit
  3332. // Also remove the body/documentelement clientTop/clientLeft on IE 6, 7 since they offset the position
  3333. x = pos.left + (doc.documentElement.scrollLeft || doc.body.scrollLeft) - rootElm.clientLeft;
  3334. y = pos.top + (doc.documentElement.scrollTop || doc.body.scrollTop) - rootElm.clientTop;
  3335. return {x: x, y: y};
  3336. }
  3337. offsetParent = elm;
  3338. while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) {
  3339. x += offsetParent.offsetLeft || 0;
  3340. y += offsetParent.offsetTop || 0;
  3341. offsetParent = offsetParent.offsetParent;
  3342. }
  3343. offsetParent = elm.parentNode;
  3344. while (offsetParent && offsetParent != rootElm && offsetParent.nodeType) {
  3345. x -= offsetParent.scrollLeft || 0;
  3346. y -= offsetParent.scrollTop || 0;
  3347. offsetParent = offsetParent.parentNode;
  3348. }
  3349. }
  3350. return {x: x, y: y};
  3351. },
  3352. /**
  3353. * Parses the specified style value into an object collection. This parser will also
  3354. * merge and remove any redundant items that browsers might have added. It will also convert non-hex
  3355. * colors to hex values. Urls inside the styles will also be converted to absolute/relative based on settings.
  3356. *
  3357. * @method parseStyle
  3358. * @param {String} cssText Style value to parse, for example: border:1px solid red;.
  3359. * @return {Object} Object representation of that style, for example: {border: '1px solid red'}
  3360. */
  3361. parseStyle: function(cssText) {
  3362. return this.styles.parse(cssText);
  3363. },
  3364. /**
  3365. * Serializes the specified style object into a string.
  3366. *
  3367. * @method serializeStyle
  3368. * @param {Object} styles Object to serialize as string, for example: {border: '1px solid red'}
  3369. * @param {String} name Optional element name.
  3370. * @return {String} String representation of the style object, for example: border: 1px solid red.
  3371. */
  3372. serializeStyle: function(styles, name) {
  3373. return this.styles.serialize(styles, name);
  3374. },
  3375. /**
  3376. * Adds a style element at the top of the document with the specified cssText content.
  3377. *
  3378. * @method addStyle
  3379. * @param {String} cssText CSS Text style to add to top of head of document.
  3380. */
  3381. addStyle: function(cssText) {
  3382. var self = this, doc = self.doc, head, styleElm;
  3383. // Prevent inline from loading the same styles twice
  3384. if (self !== DOMUtils.DOM && doc === document) {
  3385. var addedStyles = DOMUtils.DOM.addedStyles;
  3386. addedStyles = addedStyles || [];
  3387. if (addedStyles[cssText]) {
  3388. return;
  3389. }
  3390. addedStyles[cssText] = true;
  3391. DOMUtils.DOM.addedStyles = addedStyles;
  3392. }
  3393. // Create style element if needed
  3394. styleElm = doc.getElementById('mceDefaultStyles');
  3395. if (!styleElm) {
  3396. styleElm = doc.createElement('style');
  3397. styleElm.id = 'mceDefaultStyles';
  3398. styleElm.type = 'text/css';
  3399. head = doc.getElementsByTagName('head')[0];
  3400. if (head.firstChild) {
  3401. head.insertBefore(styleElm, head.firstChild);
  3402. } else {
  3403. head.appendChild(styleElm);
  3404. }
  3405. }
  3406. // Append style data to old or new style element
  3407. if (styleElm.styleSheet) {
  3408. styleElm.styleSheet.cssText += cssText;
  3409. } else {
  3410. styleElm.appendChild(doc.createTextNode(cssText));
  3411. }
  3412. },
  3413. /**
  3414. * Imports/loads the specified CSS file into the document bound to the class.
  3415. *
  3416. * @method loadCSS
  3417. * @param {String} u URL to CSS file to load.
  3418. * @example
  3419. * // Loads a CSS file dynamically into the current document
  3420. * tinymce.DOM.loadCSS('somepath/some.css');
  3421. *
  3422. * // Loads a CSS file into the currently active editor instance
  3423. * tinymce.activeEditor.dom.loadCSS('somepath/some.css');
  3424. *
  3425. * // Loads a CSS file into an editor instance by id
  3426. * tinymce.get('someid').dom.loadCSS('somepath/some.css');
  3427. *
  3428. * // Loads multiple CSS files into the current document
  3429. * tinymce.DOM.loadCSS('somepath/some.css,somepath/someother.css');
  3430. */
  3431. loadCSS: function(url) {
  3432. var self = this, doc = self.doc, head;
  3433. // Prevent inline from loading the same CSS file twice
  3434. if (self !== DOMUtils.DOM && doc === document) {
  3435. DOMUtils.DOM.loadCSS(url);
  3436. return;
  3437. }
  3438. if (!url) {
  3439. url = '';
  3440. }
  3441. head = doc.getElementsByTagName('head')[0];
  3442. each(url.split(','), function(url) {
  3443. var link;
  3444. if (self.files[url]) {
  3445. return;
  3446. }
  3447. self.files[url] = true;
  3448. link = self.create('link', {rel: 'stylesheet', href: url});
  3449. // IE 8 has a bug where dynamically loading stylesheets would produce a 1 item remaining bug
  3450. // This fix seems to resolve that issue by recalcing the document once a stylesheet finishes loading
  3451. // It's ugly but it seems to work fine.
  3452. if (isIE && doc.documentMode && doc.recalc) {
  3453. link.onload = function() {
  3454. if (doc.recalc) {
  3455. doc.recalc();
  3456. }
  3457. link.onload = null;
  3458. };
  3459. }
  3460. head.appendChild(link);
  3461. });
  3462. },
  3463. /**
  3464. * Adds a class to the specified element or elements.
  3465. *
  3466. * @method addClass
  3467. * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs.
  3468. * @param {String} cls Class name to add to each element.
  3469. * @return {String/Array} String with new class value or array with new class values for all elements.
  3470. * @example
  3471. * // Adds a class to all paragraphs in the active editor
  3472. * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'myclass');
  3473. *
  3474. * // Adds a class to a specific element in the current page
  3475. * tinymce.DOM.addClass('mydiv', 'myclass');
  3476. */
  3477. addClass: function(elm, cls) {
  3478. return this.run(elm, function(elm) {
  3479. var clsVal;
  3480. if (!cls) {
  3481. return 0;
  3482. }
  3483. if (this.hasClass(elm, cls)) {
  3484. return elm.className;
  3485. }
  3486. clsVal = this.removeClass(elm, cls);
  3487. elm.className = clsVal = (clsVal !== '' ? (clsVal + ' ') : '') + cls;
  3488. return clsVal;
  3489. });
  3490. },
  3491. /**
  3492. * Removes a class from the specified element or elements.
  3493. *
  3494. * @method removeClass
  3495. * @param {String/Element/Array} elm Element ID string or DOM element or array with elements or IDs.
  3496. * @param {String} cls Class name to remove from each element.
  3497. * @return {String/Array} String of remaining class name(s), or an array of strings if multiple input elements
  3498. * were passed in.
  3499. * @example
  3500. * // Removes a class from all paragraphs in the active editor
  3501. * tinymce.activeEditor.dom.removeClass(tinymce.activeEditor.dom.select('p'), 'myclass');
  3502. *
  3503. * // Removes a class from a specific element in the current page
  3504. * tinymce.DOM.removeClass('mydiv', 'myclass');
  3505. */
  3506. removeClass: function(elm, cls) {
  3507. var self = this, re;
  3508. return self.run(elm, function(elm) {
  3509. var val;
  3510. if (self.hasClass(elm, cls)) {
  3511. if (!re) {
  3512. re = new RegExp("(^|\\s+)" + cls + "(\\s+|$)", "g");
  3513. }
  3514. val = elm.className.replace(re, ' ');
  3515. val = trim(val != ' ' ? val : '');
  3516. elm.className = val;
  3517. // Empty class attr
  3518. if (!val) {
  3519. elm.removeAttribute('class');
  3520. elm.removeAttribute('className');
  3521. }
  3522. return val;
  3523. }
  3524. return elm.className;
  3525. });
  3526. },
  3527. /**
  3528. * Returns true if the specified element has the specified class.
  3529. *
  3530. * @method hasClass
  3531. * @param {String/Element} n HTML element or element id string to check CSS class on.
  3532. * @param {String} c CSS class to check for.
  3533. * @return {Boolean} true/false if the specified element has the specified class.
  3534. */
  3535. hasClass: function(elm, cls) {
  3536. elm = this.get(elm);
  3537. if (!elm || !cls) {
  3538. return false;
  3539. }
  3540. return (' ' + elm.className + ' ').indexOf(' ' + cls + ' ') !== -1;
  3541. },
  3542. /**
  3543. * Toggles the specified class on/off.
  3544. *
  3545. * @method toggleClass
  3546. * @param {Element} elm Element to toggle class on.
  3547. * @param {[type]} cls Class to toggle on/off.
  3548. * @param {[type]} state Optional state to set.
  3549. */
  3550. toggleClass: function(elm, cls, state) {
  3551. state = state === undefined ? !this.hasClass(elm, cls) : state;
  3552. if (this.hasClass(elm, cls) !== state) {
  3553. if (state) {
  3554. this.addClass(elm, cls);
  3555. } else {
  3556. this.removeClass(elm, cls);
  3557. }
  3558. }
  3559. },
  3560. /**
  3561. * Shows the specified element(s) by ID by setting the "display" style.
  3562. *
  3563. * @method show
  3564. * @param {String/Element/Array} elm ID of DOM element or DOM element or array with elements or IDs to show.
  3565. */
  3566. show: function(elm) {
  3567. return this.setStyle(elm, 'display', 'block');
  3568. },
  3569. /**
  3570. * Hides the specified element(s) by ID by setting the "display" style.
  3571. *
  3572. * @method hide
  3573. * @param {String/Element/Array} e ID of DOM element or DOM element or array with elements or IDs to hide.
  3574. * @example
  3575. * // Hides an element by id in the document
  3576. * tinymce.DOM.hide('myid');
  3577. */
  3578. hide: function(elm) {
  3579. return this.setStyle(elm, 'display', 'none');
  3580. },
  3581. /**
  3582. * Returns true/false if the element is hidden or not by checking the "display" style.
  3583. *
  3584. * @method isHidden
  3585. * @param {String/Element} e Id or element to check display state on.
  3586. * @return {Boolean} true/false if the element is hidden or not.
  3587. */
  3588. isHidden: function(elm) {
  3589. elm = this.get(elm);
  3590. return !elm || elm.style.display == 'none' || this.getStyle(elm, 'display') == 'none';
  3591. },
  3592. /**
  3593. * Returns a unique id. This can be useful when generating elements on the fly.
  3594. * This method will not check if the element already exists.
  3595. *
  3596. * @method uniqueId
  3597. * @param {String} prefix Optional prefix to add in front of all ids - defaults to "mce_".
  3598. * @return {String} Unique id.
  3599. */
  3600. uniqueId: function(prefix) {
  3601. return (!prefix ? 'mce_' : prefix) + (this.counter++);
  3602. },
  3603. /**
  3604. * Sets the specified HTML content inside the element or elements. The HTML will first be processed. This means
  3605. * URLs will get converted, hex color values fixed etc. Check processHTML for details.
  3606. *
  3607. * @method setHTML
  3608. * @param {Element/String/Array} e DOM element, element id string or array of elements/ids to set HTML inside of.
  3609. * @param {String} h HTML content to set as inner HTML of the element.
  3610. * @example
  3611. * // Sets the inner HTML of all paragraphs in the active editor
  3612. * tinymce.activeEditor.dom.setHTML(tinymce.activeEditor.dom.select('p'), 'some inner html');
  3613. *
  3614. * // Sets the inner HTML of an element by id in the document
  3615. * tinymce.DOM.setHTML('mydiv', 'some inner html');
  3616. */
  3617. setHTML: function(element, html) {
  3618. var self = this;
  3619. return self.run(element, function(element) {
  3620. if (isIE) {
  3621. // Remove all child nodes, IE keeps empty text nodes in DOM
  3622. while (element.firstChild) {
  3623. element.removeChild(element.firstChild);
  3624. }
  3625. try {
  3626. // IE will remove comments from the beginning
  3627. // unless you padd the contents with something
  3628. element.innerHTML = '<br />' + html;
  3629. element.removeChild(element.firstChild);
  3630. } catch (ex) {
  3631. // IE sometimes produces an unknown runtime error on innerHTML if it's a block element
  3632. // within a block element for example a div inside a p
  3633. // This seems to fix this problem
  3634. // Create new div with HTML contents and a BR in front to keep comments
  3635. var newElement = self.create('div');
  3636. newElement.innerHTML = '<br />' + html;
  3637. // Add all children from div to target
  3638. each(grep(newElement.childNodes), function(node, i) {
  3639. // Skip br element
  3640. if (i && element.canHaveHTML) {
  3641. element.appendChild(node);
  3642. }
  3643. });
  3644. }
  3645. } else {
  3646. element.innerHTML = html;
  3647. }
  3648. return html;
  3649. });
  3650. },
  3651. /**
  3652. * Returns the outer HTML of an element.
  3653. *
  3654. * @method getOuterHTML
  3655. * @param {String/Element} elm Element ID or element object to get outer HTML from.
  3656. * @return {String} Outer HTML string.
  3657. * @example
  3658. * tinymce.DOM.getOuterHTML(editorElement);
  3659. * tinymce.activeEditor.getOuterHTML(tinymce.activeEditor.getBody());
  3660. */
  3661. getOuterHTML: function(elm) {
  3662. var doc, self = this;
  3663. elm = self.get(elm);
  3664. if (!elm) {
  3665. return null;
  3666. }
  3667. if (elm.nodeType === 1 && self.hasOuterHTML) {
  3668. return elm.outerHTML;
  3669. }
  3670. doc = (elm.ownerDocument || self.doc).createElement("body");
  3671. doc.appendChild(elm.cloneNode(true));
  3672. return doc.innerHTML;
  3673. },
  3674. /**
  3675. * Sets the specified outer HTML on an element or elements.
  3676. *
  3677. * @method setOuterHTML
  3678. * @param {Element/String/Array} elm DOM element, element id string or array of elements/ids to set outer HTML on.
  3679. * @param {Object} html HTML code to set as outer value for the element.
  3680. * @param {Document} doc Optional document scope to use in this process - defaults to the document of the DOM class.
  3681. * @example
  3682. * // Sets the outer HTML of all paragraphs in the active editor
  3683. * tinymce.activeEditor.dom.setOuterHTML(tinymce.activeEditor.dom.select('p'), '<div>some html</div>');
  3684. *
  3685. * // Sets the outer HTML of an element by id in the document
  3686. * tinymce.DOM.setOuterHTML('mydiv', '<div>some html</div>');
  3687. */
  3688. setOuterHTML: function(elm, html, doc) {
  3689. var self = this;
  3690. return self.run(elm, function(elm) {
  3691. function set() {
  3692. var node, tempElm;
  3693. tempElm = doc.createElement("body");
  3694. tempElm.innerHTML = html;
  3695. node = tempElm.lastChild;
  3696. while (node) {
  3697. self.insertAfter(node.cloneNode(true), elm);
  3698. node = node.previousSibling;
  3699. }
  3700. self.remove(elm);
  3701. }
  3702. // Only set HTML on elements
  3703. if (elm.nodeType == 1) {
  3704. doc = doc || elm.ownerDocument || self.doc;
  3705. if (isIE) {
  3706. try {
  3707. // Try outerHTML for IE it sometimes produces an unknown runtime error
  3708. if (elm.nodeType == 1 && self.hasOuterHTML) {
  3709. elm.outerHTML = html;
  3710. } else {
  3711. set();
  3712. }
  3713. } catch (ex) {
  3714. // Fix for unknown runtime error
  3715. set();
  3716. }
  3717. } else {
  3718. set();
  3719. }
  3720. }
  3721. });
  3722. },
  3723. /**
  3724. * Entity decodes a string. This method decodes any HTML entities, such as &aring;.
  3725. *
  3726. * @method decode
  3727. * @param {String} s String to decode entities on.
  3728. * @return {String} Entity decoded string.
  3729. */
  3730. decode: Entities.decode,
  3731. /**
  3732. * Entity encodes a string. This method encodes the most common entities, such as <>"&.
  3733. *
  3734. * @method encode
  3735. * @param {String} text String to encode with entities.
  3736. * @return {String} Entity encoded string.
  3737. */
  3738. encode: Entities.encodeAllRaw,
  3739. /**
  3740. * Inserts an element after the reference element.
  3741. *
  3742. * @method insertAfter
  3743. * @param {Element} node Element to insert after the reference.
  3744. * @param {Element/String/Array} reference_node Reference element, element id or array of elements to insert after.
  3745. * @return {Element/Array} Element that got added or an array with elements.
  3746. */
  3747. insertAfter: function(node, reference_node) {
  3748. reference_node = this.get(reference_node);
  3749. return this.run(node, function(node) {
  3750. var parent, nextSibling;
  3751. parent = reference_node.parentNode;
  3752. nextSibling = reference_node.nextSibling;
  3753. if (nextSibling) {
  3754. parent.insertBefore(node, nextSibling);
  3755. } else {
  3756. parent.appendChild(node);
  3757. }
  3758. return node;
  3759. });
  3760. },
  3761. /**
  3762. * Replaces the specified element or elements with the new element specified. The new element will
  3763. * be cloned if multiple input elements are passed in.
  3764. *
  3765. * @method replace
  3766. * @param {Element} newElm New element to replace old ones with.
  3767. * @param {Element/String/Array} oldELm Element DOM node, element id or array of elements or ids to replace.
  3768. * @param {Boolean} k Optional keep children state, if set to true child nodes from the old object will be added to new ones.
  3769. */
  3770. replace: function(newElm, oldElm, keepChildren) {
  3771. var self = this;
  3772. return self.run(oldElm, function(oldElm) {
  3773. if (is(oldElm, 'array')) {
  3774. newElm = newElm.cloneNode(true);
  3775. }
  3776. if (keepChildren) {
  3777. each(grep(oldElm.childNodes), function(node) {
  3778. newElm.appendChild(node);
  3779. });
  3780. }
  3781. return oldElm.parentNode.replaceChild(newElm, oldElm);
  3782. });
  3783. },
  3784. /**
  3785. * Renames the specified element and keeps its attributes and children.
  3786. *
  3787. * @method rename
  3788. * @param {Element} elm Element to rename.
  3789. * @param {String} name Name of the new element.
  3790. * @return {Element} New element or the old element if it needed renaming.
  3791. */
  3792. rename: function(elm, name) {
  3793. var self = this, newElm;
  3794. if (elm.nodeName != name.toUpperCase()) {
  3795. // Rename block element
  3796. newElm = self.create(name);
  3797. // Copy attribs to new block
  3798. each(self.getAttribs(elm), function(attr_node) {
  3799. self.setAttrib(newElm, attr_node.nodeName, self.getAttrib(elm, attr_node.nodeName));
  3800. });
  3801. // Replace block
  3802. self.replace(newElm, elm, 1);
  3803. }
  3804. return newElm || elm;
  3805. },
  3806. /**
  3807. * Find the common ancestor of two elements. This is a shorter method than using the DOM Range logic.
  3808. *
  3809. * @method findCommonAncestor
  3810. * @param {Element} a Element to find common ancestor of.
  3811. * @param {Element} b Element to find common ancestor of.
  3812. * @return {Element} Common ancestor element of the two input elements.
  3813. */
  3814. findCommonAncestor: function(a, b) {
  3815. var ps = a, pe;
  3816. while (ps) {
  3817. pe = b;
  3818. while (pe && ps != pe) {
  3819. pe = pe.parentNode;
  3820. }
  3821. if (ps == pe) {
  3822. break;
  3823. }
  3824. ps = ps.parentNode;
  3825. }
  3826. if (!ps && a.ownerDocument) {
  3827. return a.ownerDocument.documentElement;
  3828. }
  3829. return ps;
  3830. },
  3831. /**
  3832. * Parses the specified RGB color value and returns a hex version of that color.
  3833. *
  3834. * @method toHex
  3835. * @param {String} rgbVal RGB string value like rgb(1,2,3)
  3836. * @return {String} Hex version of that RGB value like #FF00FF.
  3837. */
  3838. toHex: function(rgbVal) {
  3839. return this.styles.toHex(Tools.trim(rgbVal));
  3840. },
  3841. /**
  3842. * Executes the specified function on the element by id or dom element node or array of elements/id.
  3843. *
  3844. * @method run
  3845. * @param {String/Element/Array} Element ID or DOM element object or array with ids or elements.
  3846. * @param {function} f Function to execute for each item.
  3847. * @param {Object} s Optional scope to execute the function in.
  3848. * @return {Object/Array} Single object, or an array of objects if multiple input elements were passed in.
  3849. */
  3850. run: function(elm, func, scope) {
  3851. var self = this, result;
  3852. if (typeof(elm) === 'string') {
  3853. elm = self.get(elm);
  3854. }
  3855. if (!elm) {
  3856. return false;
  3857. }
  3858. scope = scope || this;
  3859. if (!elm.nodeType && (elm.length || elm.length === 0)) {
  3860. result = [];
  3861. each(elm, function(elm, i) {
  3862. if (elm) {
  3863. if (typeof(elm) == 'string') {
  3864. elm = self.get(elm);
  3865. }
  3866. result.push(func.call(scope, elm, i));
  3867. }
  3868. });
  3869. return result;
  3870. }
  3871. return func.call(scope, elm);
  3872. },
  3873. /**
  3874. * Returns a NodeList with attributes for the element.
  3875. *
  3876. * @method getAttribs
  3877. * @param {HTMLElement/string} elm Element node or string id to get attributes from.
  3878. * @return {NodeList} NodeList with attributes.
  3879. */
  3880. getAttribs: function(elm) {
  3881. var attrs;
  3882. elm = this.get(elm);
  3883. if (!elm) {
  3884. return [];
  3885. }
  3886. if (isIE) {
  3887. attrs = [];
  3888. // Object will throw exception in IE
  3889. if (elm.nodeName == 'OBJECT') {
  3890. return elm.attributes;
  3891. }
  3892. // IE doesn't keep the selected attribute if you clone option elements
  3893. if (elm.nodeName === 'OPTION' && this.getAttrib(elm, 'selected')) {
  3894. attrs.push({specified: 1, nodeName: 'selected'});
  3895. }
  3896. // It's crazy that this is faster in IE but it's because it returns all attributes all the time
  3897. var attrRegExp = /<\/?[\w:\-]+ ?|=[\"][^\"]+\"|=\'[^\']+\'|=[\w\-]+|>/gi;
  3898. elm.cloneNode(false).outerHTML.replace(attrRegExp, '').replace(/[\w:\-]+/gi, function(a) {
  3899. attrs.push({specified: 1, nodeName: a});
  3900. });
  3901. return attrs;
  3902. }
  3903. return elm.attributes;
  3904. },
  3905. /**
  3906. * Returns true/false if the specified node is to be considered empty or not.
  3907. *
  3908. * @example
  3909. * tinymce.DOM.isEmpty(node, {img: true});
  3910. * @method isEmpty
  3911. * @param {Object} elements Optional name/value object with elements that are automatically treated as non-empty elements.
  3912. * @return {Boolean} true/false if the node is empty or not.
  3913. */
  3914. isEmpty: function(node, elements) {
  3915. var self = this, i, attributes, type, walker, name, brCount = 0;
  3916. node = node.firstChild;
  3917. if (node) {
  3918. walker = new TreeWalker(node, node.parentNode);
  3919. elements = elements || self.schema ? self.schema.getNonEmptyElements() : null;
  3920. do {
  3921. type = node.nodeType;
  3922. if (type === 1) {
  3923. // Ignore bogus elements
  3924. if (node.getAttribute('data-mce-bogus')) {
  3925. continue;
  3926. }
  3927. // Keep empty elements like <img />
  3928. name = node.nodeName.toLowerCase();
  3929. if (elements && elements[name]) {
  3930. // Ignore single BR elements in blocks like <p><br /></p> or <p><span><br /></span></p>
  3931. if (name === 'br') {
  3932. brCount++;
  3933. continue;
  3934. }
  3935. return false;
  3936. }
  3937. // Keep elements with data-bookmark attributes or name attribute like <a name="1"></a>
  3938. attributes = self.getAttribs(node);
  3939. i = attributes.length;
  3940. while (i--) {
  3941. name = attributes[i].nodeName;
  3942. if (name === "name" || name === 'data-mce-bookmark') {
  3943. return false;
  3944. }
  3945. }
  3946. }
  3947. // Keep comment nodes
  3948. if (type == 8) {
  3949. return false;
  3950. }
  3951. // Keep non whitespace text nodes
  3952. if ((type === 3 && !whiteSpaceRegExp.test(node.nodeValue))) {
  3953. return false;
  3954. }
  3955. } while ((node = walker.next()));
  3956. }
  3957. return brCount <= 1;
  3958. },
  3959. /**
  3960. * Creates a new DOM Range object. This will use the native DOM Range API if it's
  3961. * available. If it's not, it will fall back to the custom TinyMCE implementation.
  3962. *
  3963. * @method createRng
  3964. * @return {DOMRange} DOM Range object.
  3965. * @example
  3966. * var rng = tinymce.DOM.createRng();
  3967. * alert(rng.startContainer + "," + rng.startOffset);
  3968. */
  3969. createRng: function() {
  3970. var doc = this.doc;
  3971. return doc.createRange ? doc.createRange() : new Range(this);
  3972. },
  3973. /**
  3974. * Returns the index of the specified node within its parent.
  3975. *
  3976. * @method nodeIndex
  3977. * @param {Node} node Node to look for.
  3978. * @param {boolean} normalized Optional true/false state if the index is what it would be after a normalization.
  3979. * @return {Number} Index of the specified node.
  3980. */
  3981. nodeIndex: function(node, normalized) {
  3982. var idx = 0, lastNodeType, nodeType;
  3983. if (node) {
  3984. for (lastNodeType = node.nodeType, node = node.previousSibling; node; node = node.previousSibling) {
  3985. nodeType = node.nodeType;
  3986. // Normalize text nodes
  3987. if (normalized && nodeType == 3) {
  3988. if (nodeType == lastNodeType || !node.nodeValue.length) {
  3989. continue;
  3990. }
  3991. }
  3992. idx++;
  3993. lastNodeType = nodeType;
  3994. }
  3995. }
  3996. return idx;
  3997. },
  3998. /**
  3999. * Splits an element into two new elements and places the specified split
  4000. * element or elements between the new ones. For example splitting the paragraph at the bold element in
  4001. * this example <p>abc<b>abc</b>123</p> would produce <p>abc</p><b>abc</b><p>123</p>.
  4002. *
  4003. * @method split
  4004. * @param {Element} parentElm Parent element to split.
  4005. * @param {Element} splitElm Element to split at.
  4006. * @param {Element} replacementElm Optional replacement element to replace the split element with.
  4007. * @return {Element} Returns the split element or the replacement element if that is specified.
  4008. */
  4009. split: function(parentElm, splitElm, replacementElm) {
  4010. var self = this, r = self.createRng(), bef, aft, pa;
  4011. // W3C valid browsers tend to leave empty nodes to the left/right side of the contents - this makes sense
  4012. // but we don't want that in our code since it serves no purpose for the end user
  4013. // For example splitting this html at the bold element:
  4014. // <p>text 1<span><b>CHOP</b></span>text 2</p>
  4015. // would produce:
  4016. // <p>text 1<span></span></p><b>CHOP</b><p><span></span>text 2</p>
  4017. // this function will then trim off empty edges and produce:
  4018. // <p>text 1</p><b>CHOP</b><p>text 2</p>
  4019. function trimNode(node) {
  4020. var i, children = node.childNodes, type = node.nodeType;
  4021. function surroundedBySpans(node) {
  4022. var previousIsSpan = node.previousSibling && node.previousSibling.nodeName == 'SPAN';
  4023. var nextIsSpan = node.nextSibling && node.nextSibling.nodeName == 'SPAN';
  4024. return previousIsSpan && nextIsSpan;
  4025. }
  4026. if (type == 1 && node.getAttribute('data-mce-type') == 'bookmark') {
  4027. return;
  4028. }
  4029. for (i = children.length - 1; i >= 0; i--) {
  4030. trimNode(children[i]);
  4031. }
  4032. if (type != 9) {
  4033. // Keep non whitespace text nodes
  4034. if (type == 3 && node.nodeValue.length > 0) {
  4035. // If parent element isn't a block or there isn't any useful contents for example "<p> </p>"
  4036. // Also keep text nodes with only spaces if surrounded by spans.
  4037. // eg. "<p><span>a</span> <span>b</span></p>" should keep space between a and b
  4038. var trimmedLength = trim(node.nodeValue).length;
  4039. if (!self.isBlock(node.parentNode) || trimmedLength > 0 || trimmedLength === 0 && surroundedBySpans(node)) {
  4040. return;
  4041. }
  4042. } else if (type == 1) {
  4043. // If the only child is a bookmark then move it up
  4044. children = node.childNodes;
  4045. // TODO fix this complex if
  4046. if (children.length == 1 && children[0] && children[0].nodeType == 1 &&
  4047. children[0].getAttribute('data-mce-type') == 'bookmark') {
  4048. node.parentNode.insertBefore(children[0], node);
  4049. }
  4050. // Keep non empty elements or img, hr etc
  4051. if (children.length || /^(br|hr|input|img)$/i.test(node.nodeName)) {
  4052. return;
  4053. }
  4054. }
  4055. self.remove(node);
  4056. }
  4057. return node;
  4058. }
  4059. if (parentElm && splitElm) {
  4060. // Get before chunk
  4061. r.setStart(parentElm.parentNode, self.nodeIndex(parentElm));
  4062. r.setEnd(splitElm.parentNode, self.nodeIndex(splitElm));
  4063. bef = r.extractContents();
  4064. // Get after chunk
  4065. r = self.createRng();
  4066. r.setStart(splitElm.parentNode, self.nodeIndex(splitElm) + 1);
  4067. r.setEnd(parentElm.parentNode, self.nodeIndex(parentElm) + 1);
  4068. aft = r.extractContents();
  4069. // Insert before chunk
  4070. pa = parentElm.parentNode;
  4071. pa.insertBefore(trimNode(bef), parentElm);
  4072. // Insert middle chunk
  4073. if (replacementElm) {
  4074. pa.replaceChild(replacementElm, splitElm);
  4075. } else {
  4076. pa.insertBefore(splitElm, parentElm);
  4077. }
  4078. // Insert after chunk
  4079. pa.insertBefore(trimNode(aft), parentElm);
  4080. self.remove(parentElm);
  4081. return replacementElm || splitElm;
  4082. }
  4083. },
  4084. /**
  4085. * Adds an event handler to the specified object.
  4086. *
  4087. * @method bind
  4088. * @param {Element/Document/Window/Array} target Target element to bind events to.
  4089. * handler to or an array of elements/ids/documents.
  4090. * @param {String} name Name of event handler to add, for example: click.
  4091. * @param {function} func Function to execute when the event occurs.
  4092. * @param {Object} scope Optional scope to execute the function in.
  4093. * @return {function} Function callback handler the same as the one passed in.
  4094. */
  4095. bind: function(target, name, func, scope) {
  4096. var self = this;
  4097. if (Tools.isArray(target)) {
  4098. var i = target.length;
  4099. while (i--) {
  4100. target[i] = self.bind(target[i], name, func, scope);
  4101. }
  4102. return target;
  4103. }
  4104. // Collect all window/document events bound by editor instance
  4105. if (self.settings.collect && (target === self.doc || target === self.win)) {
  4106. self.boundEvents.push([target, name, func, scope]);
  4107. }
  4108. return self.events.bind(target, name, func, scope || self);
  4109. },
  4110. /**
  4111. * Removes the specified event handler by name and function from an element or collection of elements.
  4112. *
  4113. * @method unbind
  4114. * @param {Element/Document/Window/Array} target Target element to unbind events on.
  4115. * @param {String} name Event handler name, for example: "click"
  4116. * @param {function} func Function to remove.
  4117. * @return {bool/Array} Bool state of true if the handler was removed, or an array of states if multiple input elements
  4118. * were passed in.
  4119. */
  4120. unbind: function(target, name, func) {
  4121. var self = this, i;
  4122. if (Tools.isArray(target)) {
  4123. i = target.length;
  4124. while (i--) {
  4125. target[i] = self.unbind(target[i], name, func);
  4126. }
  4127. return target;
  4128. }
  4129. // Remove any bound events matching the input
  4130. if (self.boundEvents && (target === self.doc || target === self.win)) {
  4131. i = self.boundEvents.length;
  4132. while (i--) {
  4133. var item = self.boundEvents[i];
  4134. if (target == item[0] && (!name || name == item[1]) && (!func || func == item[2])) {
  4135. this.events.unbind(item[0], item[1], item[2]);
  4136. }
  4137. }
  4138. }
  4139. return this.events.unbind(target, name, func);
  4140. },
  4141. /**
  4142. * Fires the specified event name with object on target.
  4143. *
  4144. * @method fire
  4145. * @param {Node/Document/Window} target Target element or object to fire event on.
  4146. * @param {String} name Name of the event to fire.
  4147. * @param {Object} evt Event object to send.
  4148. * @return {Event} Event object.
  4149. */
  4150. fire: function(target, name, evt) {
  4151. return this.events.fire(target, name, evt);
  4152. },
  4153. // Returns the content editable state of a node
  4154. getContentEditable: function(node) {
  4155. var contentEditable;
  4156. // Check type
  4157. if (!node || node.nodeType != 1) {
  4158. return null;
  4159. }
  4160. // Check for fake content editable
  4161. contentEditable = node.getAttribute("data-mce-contenteditable");
  4162. if (contentEditable && contentEditable !== "inherit") {
  4163. return contentEditable;
  4164. }
  4165. // Check for real content editable
  4166. return node.contentEditable !== "inherit" ? node.contentEditable : null;
  4167. },
  4168. getContentEditableParent: function(node) {
  4169. var root = this.getRoot(), state = null;
  4170. for (; node && node !== root; node = node.parentNode) {
  4171. state = this.getContentEditable(node);
  4172. if (state !== null) {
  4173. break;
  4174. }
  4175. }
  4176. return state;
  4177. },
  4178. /**
  4179. * Destroys all internal references to the DOM to solve IE leak issues.
  4180. *
  4181. * @method destroy
  4182. */
  4183. destroy: function() {
  4184. var self = this;
  4185. // Unbind all events bound to window/document by editor instance
  4186. if (self.boundEvents) {
  4187. var i = self.boundEvents.length;
  4188. while (i--) {
  4189. var item = self.boundEvents[i];
  4190. this.events.unbind(item[0], item[1], item[2]);
  4191. }
  4192. self.boundEvents = null;
  4193. }
  4194. // Restore sizzle document to window.document
  4195. // Since the current document might be removed producing "Permission denied" on IE see #6325
  4196. if (Sizzle.setDocument) {
  4197. Sizzle.setDocument();
  4198. }
  4199. self.win = self.doc = self.root = self.events = self.frag = null;
  4200. },
  4201. isChildOf: function(node, parent) {
  4202. while (node) {
  4203. if (parent === node) {
  4204. return true;
  4205. }
  4206. node = node.parentNode;
  4207. }
  4208. return false;
  4209. },
  4210. // #ifdef debug
  4211. dumpRng: function(r) {
  4212. return (
  4213. 'startContainer: ' + r.startContainer.nodeName +
  4214. ', startOffset: ' + r.startOffset +
  4215. ', endContainer: ' + r.endContainer.nodeName +
  4216. ', endOffset: ' + r.endOffset
  4217. );
  4218. },
  4219. // #endif
  4220. _findSib: function(node, selector, name) {
  4221. var self = this, func = selector;
  4222. if (node) {
  4223. // If expression make a function of it using is
  4224. if (typeof(func) == 'string') {
  4225. func = function(node) {
  4226. return self.is(node, selector);
  4227. };
  4228. }
  4229. // Loop all siblings
  4230. for (node = node[name]; node; node = node[name]) {
  4231. if (func(node)) {
  4232. return node;
  4233. }
  4234. }
  4235. }
  4236. return null;
  4237. }
  4238. };
  4239. /**
  4240. * Instance of DOMUtils for the current document.
  4241. *
  4242. * @static
  4243. * @property DOM
  4244. * @type tinymce.dom.DOMUtils
  4245. * @example
  4246. * // Example of how to add a class to some element by id
  4247. * tinymce.DOM.addClass('someid', 'someclass');
  4248. */
  4249. DOMUtils.DOM = new DOMUtils(document);
  4250. return DOMUtils;
  4251. });
  4252. // Included from: js/tinymce/classes/dom/ScriptLoader.js
  4253. /**
  4254. * ScriptLoader.js
  4255. *
  4256. * Copyright, Moxiecode Systems AB
  4257. * Released under LGPL License.
  4258. *
  4259. * License: http://www.tinymce.com/license
  4260. * Contributing: http://www.tinymce.com/contributing
  4261. */
  4262. /*globals console*/
  4263. /**
  4264. * This class handles asynchronous/synchronous loading of JavaScript files it will execute callbacks
  4265. * when various items gets loaded. This class is useful to load external JavaScript files.
  4266. *
  4267. * @class tinymce.dom.ScriptLoader
  4268. * @example
  4269. * // Load a script from a specific URL using the global script loader
  4270. * tinymce.ScriptLoader.load('somescript.js');
  4271. *
  4272. * // Load a script using a unique instance of the script loader
  4273. * var scriptLoader = new tinymce.dom.ScriptLoader();
  4274. *
  4275. * scriptLoader.load('somescript.js');
  4276. *
  4277. * // Load multiple scripts
  4278. * var scriptLoader = new tinymce.dom.ScriptLoader();
  4279. *
  4280. * scriptLoader.add('somescript1.js');
  4281. * scriptLoader.add('somescript2.js');
  4282. * scriptLoader.add('somescript3.js');
  4283. *
  4284. * scriptLoader.loadQueue(function() {
  4285. * alert('All scripts are now loaded.');
  4286. * });
  4287. */
  4288. define("tinymce/dom/ScriptLoader", [
  4289. "tinymce/dom/DOMUtils",
  4290. "tinymce/util/Tools"
  4291. ], function(DOMUtils, Tools) {
  4292. var DOM = DOMUtils.DOM;
  4293. var each = Tools.each, grep = Tools.grep;
  4294. function ScriptLoader() {
  4295. var QUEUED = 0,
  4296. LOADING = 1,
  4297. LOADED = 2,
  4298. states = {},
  4299. queue = [],
  4300. scriptLoadedCallbacks = {},
  4301. queueLoadedCallbacks = [],
  4302. loading = 0,
  4303. undef;
  4304. /**
  4305. * Loads a specific script directly without adding it to the load queue.
  4306. *
  4307. * @method load
  4308. * @param {String} url Absolute URL to script to add.
  4309. * @param {function} callback Optional callback function to execute ones this script gets loaded.
  4310. * @param {Object} scope Optional scope to execute callback in.
  4311. */
  4312. function loadScript(url, callback) {
  4313. var dom = DOM, elm, id;
  4314. // Execute callback when script is loaded
  4315. function done() {
  4316. dom.remove(id);
  4317. if (elm) {
  4318. elm.onreadystatechange = elm.onload = elm = null;
  4319. }
  4320. callback();
  4321. }
  4322. function error() {
  4323. /*eslint no-console:0 */
  4324. // Report the error so it's easier for people to spot loading errors
  4325. if (typeof(console) !== "undefined" && console.log) {
  4326. console.log("Failed to load: " + url);
  4327. }
  4328. // We can't mark it as done if there is a load error since
  4329. // A) We don't want to produce 404 errors on the server and
  4330. // B) the onerror event won't fire on all browsers.
  4331. // done();
  4332. }
  4333. id = dom.uniqueId();
  4334. // Create new script element
  4335. elm = document.createElement('script');
  4336. elm.id = id;
  4337. elm.type = 'text/javascript';
  4338. elm.src = url;
  4339. // Seems that onreadystatechange works better on IE 10 onload seems to fire incorrectly
  4340. if ("onreadystatechange" in elm) {
  4341. elm.onreadystatechange = function() {
  4342. if (/loaded|complete/.test(elm.readyState)) {
  4343. done();
  4344. }
  4345. };
  4346. } else {
  4347. elm.onload = done;
  4348. }
  4349. // Add onerror event will get fired on some browsers but not all of them
  4350. elm.onerror = error;
  4351. // Add script to document
  4352. (document.getElementsByTagName('head')[0] || document.body).appendChild(elm);
  4353. }
  4354. /**
  4355. * Returns true/false if a script has been loaded or not.
  4356. *
  4357. * @method isDone
  4358. * @param {String} url URL to check for.
  4359. * @return {Boolean} true/false if the URL is loaded.
  4360. */
  4361. this.isDone = function(url) {
  4362. return states[url] == LOADED;
  4363. };
  4364. /**
  4365. * Marks a specific script to be loaded. This can be useful if a script got loaded outside
  4366. * the script loader or to skip it from loading some script.
  4367. *
  4368. * @method markDone
  4369. * @param {string} u Absolute URL to the script to mark as loaded.
  4370. */
  4371. this.markDone = function(url) {
  4372. states[url] = LOADED;
  4373. };
  4374. /**
  4375. * Adds a specific script to the load queue of the script loader.
  4376. *
  4377. * @method add
  4378. * @param {String} url Absolute URL to script to add.
  4379. * @param {function} callback Optional callback function to execute ones this script gets loaded.
  4380. * @param {Object} scope Optional scope to execute callback in.
  4381. */
  4382. this.add = this.load = function(url, callback, scope) {
  4383. var state = states[url];
  4384. // Add url to load queue
  4385. if (state == undef) {
  4386. queue.push(url);
  4387. states[url] = QUEUED;
  4388. }
  4389. if (callback) {
  4390. // Store away callback for later execution
  4391. if (!scriptLoadedCallbacks[url]) {
  4392. scriptLoadedCallbacks[url] = [];
  4393. }
  4394. scriptLoadedCallbacks[url].push({
  4395. func: callback,
  4396. scope: scope || this
  4397. });
  4398. }
  4399. };
  4400. /**
  4401. * Starts the loading of the queue.
  4402. *
  4403. * @method loadQueue
  4404. * @param {function} callback Optional callback to execute when all queued items are loaded.
  4405. * @param {Object} scope Optional scope to execute the callback in.
  4406. */
  4407. this.loadQueue = function(callback, scope) {
  4408. this.loadScripts(queue, callback, scope);
  4409. };
  4410. /**
  4411. * Loads the specified queue of files and executes the callback ones they are loaded.
  4412. * This method is generally not used outside this class but it might be useful in some scenarios.
  4413. *
  4414. * @method loadScripts
  4415. * @param {Array} scripts Array of queue items to load.
  4416. * @param {function} callback Optional callback to execute ones all items are loaded.
  4417. * @param {Object} scope Optional scope to execute callback in.
  4418. */
  4419. this.loadScripts = function(scripts, callback, scope) {
  4420. var loadScripts;
  4421. function execScriptLoadedCallbacks(url) {
  4422. // Execute URL callback functions
  4423. each(scriptLoadedCallbacks[url], function(callback) {
  4424. callback.func.call(callback.scope);
  4425. });
  4426. scriptLoadedCallbacks[url] = undef;
  4427. }
  4428. queueLoadedCallbacks.push({
  4429. func: callback,
  4430. scope: scope || this
  4431. });
  4432. loadScripts = function() {
  4433. var loadingScripts = grep(scripts);
  4434. // Current scripts has been handled
  4435. scripts.length = 0;
  4436. // Load scripts that needs to be loaded
  4437. each(loadingScripts, function(url) {
  4438. // Script is already loaded then execute script callbacks directly
  4439. if (states[url] == LOADED) {
  4440. execScriptLoadedCallbacks(url);
  4441. return;
  4442. }
  4443. // Is script not loading then start loading it
  4444. if (states[url] != LOADING) {
  4445. states[url] = LOADING;
  4446. loading++;
  4447. loadScript(url, function() {
  4448. states[url] = LOADED;
  4449. loading--;
  4450. execScriptLoadedCallbacks(url);
  4451. // Load more scripts if they where added by the recently loaded script
  4452. loadScripts();
  4453. });
  4454. }
  4455. });
  4456. // No scripts are currently loading then execute all pending queue loaded callbacks
  4457. if (!loading) {
  4458. each(queueLoadedCallbacks, function(callback) {
  4459. callback.func.call(callback.scope);
  4460. });
  4461. queueLoadedCallbacks.length = 0;
  4462. }
  4463. };
  4464. loadScripts();
  4465. };
  4466. }
  4467. ScriptLoader.ScriptLoader = new ScriptLoader();
  4468. return ScriptLoader;
  4469. });
  4470. // Included from: js/tinymce/classes/AddOnManager.js
  4471. /**
  4472. * AddOnManager.js
  4473. *
  4474. * Copyright, Moxiecode Systems AB
  4475. * Released under LGPL License.
  4476. *
  4477. * License: http://www.tinymce.com/license
  4478. * Contributing: http://www.tinymce.com/contributing
  4479. */
  4480. /**
  4481. * This class handles the loading of themes/plugins or other add-ons and their language packs.
  4482. *
  4483. * @class tinymce.AddOnManager
  4484. */
  4485. define("tinymce/AddOnManager", [
  4486. "tinymce/dom/ScriptLoader",
  4487. "tinymce/util/Tools"
  4488. ], function(ScriptLoader, Tools) {
  4489. var each = Tools.each;
  4490. function AddOnManager() {
  4491. var self = this;
  4492. self.items = [];
  4493. self.urls = {};
  4494. self.lookup = {};
  4495. }
  4496. AddOnManager.prototype = {
  4497. /**
  4498. * Returns the specified add on by the short name.
  4499. *
  4500. * @method get
  4501. * @param {String} name Add-on to look for.
  4502. * @return {tinymce.Theme/tinymce.Plugin} Theme or plugin add-on instance or undefined.
  4503. */
  4504. get: function(name) {
  4505. if (this.lookup[name]) {
  4506. return this.lookup[name].instance;
  4507. } else {
  4508. return undefined;
  4509. }
  4510. },
  4511. dependencies: function(name) {
  4512. var result;
  4513. if (this.lookup[name]) {
  4514. result = this.lookup[name].dependencies;
  4515. }
  4516. return result || [];
  4517. },
  4518. /**
  4519. * Loads a language pack for the specified add-on.
  4520. *
  4521. * @method requireLangPack
  4522. * @param {String} name Short name of the add-on.
  4523. * @param {String} languages Optional comma or space separated list of languages to check if it matches the name.
  4524. */
  4525. requireLangPack: function(name, languages) {
  4526. var language = AddOnManager.language;
  4527. if (language && AddOnManager.languageLoad !== false) {
  4528. if (languages) {
  4529. languages = ',' + languages + ',';
  4530. // Load short form sv.js or long form sv_SE.js
  4531. if (languages.indexOf(',' + language.substr(0, 2) + ',') != -1) {
  4532. language = language.substr(0, 2);
  4533. } else if (languages.indexOf(',' + language + ',') == -1) {
  4534. return;
  4535. }
  4536. }
  4537. ScriptLoader.ScriptLoader.add(this.urls[name] + '/langs/' + language + '.js');
  4538. }
  4539. },
  4540. /**
  4541. * Adds a instance of the add-on by it's short name.
  4542. *
  4543. * @method add
  4544. * @param {String} id Short name/id for the add-on.
  4545. * @param {tinymce.Theme/tinymce.Plugin} addOn Theme or plugin to add.
  4546. * @return {tinymce.Theme/tinymce.Plugin} The same theme or plugin instance that got passed in.
  4547. * @example
  4548. * // Create a simple plugin
  4549. * tinymce.create('tinymce.plugins.TestPlugin', {
  4550. * TestPlugin: function(ed, url) {
  4551. * ed.on('click', function(e) {
  4552. * ed.windowManager.alert('Hello World!');
  4553. * });
  4554. * }
  4555. * });
  4556. *
  4557. * // Register plugin using the add method
  4558. * tinymce.PluginManager.add('test', tinymce.plugins.TestPlugin);
  4559. *
  4560. * // Initialize TinyMCE
  4561. * tinymce.init({
  4562. * ...
  4563. * plugins: '-test' // Init the plugin but don't try to load it
  4564. * });
  4565. */
  4566. add: function(id, addOn, dependencies) {
  4567. this.items.push(addOn);
  4568. this.lookup[id] = {instance: addOn, dependencies: dependencies};
  4569. return addOn;
  4570. },
  4571. createUrl: function(baseUrl, dep) {
  4572. if (typeof dep === "object") {
  4573. return dep;
  4574. } else {
  4575. return {prefix: baseUrl.prefix, resource: dep, suffix: baseUrl.suffix};
  4576. }
  4577. },
  4578. /**
  4579. * Add a set of components that will make up the add-on. Using the url of the add-on name as the base url.
  4580. * This should be used in development mode. A new compressor/javascript munger process will ensure that the
  4581. * components are put together into the plugin.js file and compressed correctly.
  4582. *
  4583. * @method addComponents
  4584. * @param {String} pluginName name of the plugin to load scripts from (will be used to get the base url for the plugins).
  4585. * @param {Array} scripts Array containing the names of the scripts to load.
  4586. */
  4587. addComponents: function(pluginName, scripts) {
  4588. var pluginUrl = this.urls[pluginName];
  4589. each(scripts, function(script) {
  4590. ScriptLoader.ScriptLoader.add(pluginUrl + "/" + script);
  4591. });
  4592. },
  4593. /**
  4594. * Loads an add-on from a specific url.
  4595. *
  4596. * @method load
  4597. * @param {String} name Short name of the add-on that gets loaded.
  4598. * @param {String} addOnUrl URL to the add-on that will get loaded.
  4599. * @param {function} callback Optional callback to execute ones the add-on is loaded.
  4600. * @param {Object} scope Optional scope to execute the callback in.
  4601. * @example
  4602. * // Loads a plugin from an external URL
  4603. * tinymce.PluginManager.load('myplugin', '/some/dir/someplugin/plugin.js');
  4604. *
  4605. * // Initialize TinyMCE
  4606. * tinymce.init({
  4607. * ...
  4608. * plugins: '-myplugin' // Don't try to load it again
  4609. * });
  4610. */
  4611. load: function(name, addOnUrl, callback, scope) {
  4612. var self = this, url = addOnUrl;
  4613. function loadDependencies() {
  4614. var dependencies = self.dependencies(name);
  4615. each(dependencies, function(dep) {
  4616. var newUrl = self.createUrl(addOnUrl, dep);
  4617. self.load(newUrl.resource, newUrl, undefined, undefined);
  4618. });
  4619. if (callback) {
  4620. if (scope) {
  4621. callback.call(scope);
  4622. } else {
  4623. callback.call(ScriptLoader);
  4624. }
  4625. }
  4626. }
  4627. if (self.urls[name]) {
  4628. return;
  4629. }
  4630. if (typeof addOnUrl === "object") {
  4631. url = addOnUrl.prefix + addOnUrl.resource + addOnUrl.suffix;
  4632. }
  4633. if (url.indexOf('/') !== 0 && url.indexOf('://') == -1) {
  4634. url = AddOnManager.baseURL + '/' + url;
  4635. }
  4636. self.urls[name] = url.substring(0, url.lastIndexOf('/'));
  4637. if (self.lookup[name]) {
  4638. loadDependencies();
  4639. } else {
  4640. ScriptLoader.ScriptLoader.add(url, loadDependencies, scope);
  4641. }
  4642. }
  4643. };
  4644. AddOnManager.PluginManager = new AddOnManager();
  4645. AddOnManager.ThemeManager = new AddOnManager();
  4646. return AddOnManager;
  4647. });
  4648. /**
  4649. * TinyMCE theme class.
  4650. *
  4651. * @class tinymce.Theme
  4652. */
  4653. /**
  4654. * This method is responsible for rendering/generating the overall user interface with toolbars, buttons, iframe containers etc.
  4655. *
  4656. * @method renderUI
  4657. * @param {Object} obj Object parameter containing the targetNode DOM node that will be replaced visually with an editor instance.
  4658. * @return {Object} an object with items like iframeContainer, editorContainer, sizeContainer, deltaWidth, deltaHeight.
  4659. */
  4660. /**
  4661. * Plugin base class, this is a pseudo class that describes how a plugin is to be created for TinyMCE. The methods below are all optional.
  4662. *
  4663. * @class tinymce.Plugin
  4664. * @example
  4665. * tinymce.PluginManager.add('example', function(editor, url) {
  4666. * // Add a button that opens a window
  4667. * editor.addButton('example', {
  4668. * text: 'My button',
  4669. * icon: false,
  4670. * onclick: function() {
  4671. * // Open window
  4672. * editor.windowManager.open({
  4673. * title: 'Example plugin',
  4674. * body: [
  4675. * {type: 'textbox', name: 'title', label: 'Title'}
  4676. * ],
  4677. * onsubmit: function(e) {
  4678. * // Insert content when the window form is submitted
  4679. * editor.insertContent('Title: ' + e.data.title);
  4680. * }
  4681. * });
  4682. * }
  4683. * });
  4684. *
  4685. * // Adds a menu item to the tools menu
  4686. * editor.addMenuItem('example', {
  4687. * text: 'Example plugin',
  4688. * context: 'tools',
  4689. * onclick: function() {
  4690. * // Open window with a specific url
  4691. * editor.windowManager.open({
  4692. * title: 'TinyMCE site',
  4693. * url: 'http://www.tinymce.com',
  4694. * width: 800,
  4695. * height: 600,
  4696. * buttons: [{
  4697. * text: 'Close',
  4698. * onclick: 'close'
  4699. * }]
  4700. * });
  4701. * }
  4702. * });
  4703. * });
  4704. */
  4705. // Included from: js/tinymce/classes/html/Node.js
  4706. /**
  4707. * Node.js
  4708. *
  4709. * Copyright, Moxiecode Systems AB
  4710. * Released under LGPL License.
  4711. *
  4712. * License: http://www.tinymce.com/license
  4713. * Contributing: http://www.tinymce.com/contributing
  4714. */
  4715. /**
  4716. * This class is a minimalistic implementation of a DOM like node used by the DomParser class.
  4717. *
  4718. * @example
  4719. * var node = new tinymce.html.Node('strong', 1);
  4720. * someRoot.append(node);
  4721. *
  4722. * @class tinymce.html.Node
  4723. * @version 3.4
  4724. */
  4725. define("tinymce/html/Node", [], function() {
  4726. var whiteSpaceRegExp = /^[ \t\r\n]*$/, typeLookup = {
  4727. '#text': 3,
  4728. '#comment': 8,
  4729. '#cdata': 4,
  4730. '#pi': 7,
  4731. '#doctype': 10,
  4732. '#document-fragment': 11
  4733. };
  4734. // Walks the tree left/right
  4735. function walk(node, root_node, prev) {
  4736. var sibling, parent, startName = prev ? 'lastChild' : 'firstChild', siblingName = prev ? 'prev' : 'next';
  4737. // Walk into nodes if it has a start
  4738. if (node[startName]) {
  4739. return node[startName];
  4740. }
  4741. // Return the sibling if it has one
  4742. if (node !== root_node) {
  4743. sibling = node[siblingName];
  4744. if (sibling) {
  4745. return sibling;
  4746. }
  4747. // Walk up the parents to look for siblings
  4748. for (parent = node.parent; parent && parent !== root_node; parent = parent.parent) {
  4749. sibling = parent[siblingName];
  4750. if (sibling) {
  4751. return sibling;
  4752. }
  4753. }
  4754. }
  4755. }
  4756. /**
  4757. * Constructs a new Node instance.
  4758. *
  4759. * @constructor
  4760. * @method Node
  4761. * @param {String} name Name of the node type.
  4762. * @param {Number} type Numeric type representing the node.
  4763. */
  4764. function Node(name, type) {
  4765. this.name = name;
  4766. this.type = type;
  4767. if (type === 1) {
  4768. this.attributes = [];
  4769. this.attributes.map = {};
  4770. }
  4771. }
  4772. Node.prototype = {
  4773. /**
  4774. * Replaces the current node with the specified one.
  4775. *
  4776. * @example
  4777. * someNode.replace(someNewNode);
  4778. *
  4779. * @method replace
  4780. * @param {tinymce.html.Node} node Node to replace the current node with.
  4781. * @return {tinymce.html.Node} The old node that got replaced.
  4782. */
  4783. replace: function(node) {
  4784. var self = this;
  4785. if (node.parent) {
  4786. node.remove();
  4787. }
  4788. self.insert(node, self);
  4789. self.remove();
  4790. return self;
  4791. },
  4792. /**
  4793. * Gets/sets or removes an attribute by name.
  4794. *
  4795. * @example
  4796. * someNode.attr("name", "value"); // Sets an attribute
  4797. * console.log(someNode.attr("name")); // Gets an attribute
  4798. * someNode.attr("name", null); // Removes an attribute
  4799. *
  4800. * @method attr
  4801. * @param {String} name Attribute name to set or get.
  4802. * @param {String} value Optional value to set.
  4803. * @return {String/tinymce.html.Node} String or undefined on a get operation or the current node on a set operation.
  4804. */
  4805. attr: function(name, value) {
  4806. var self = this, attrs, i, undef;
  4807. if (typeof name !== "string") {
  4808. for (i in name) {
  4809. self.attr(i, name[i]);
  4810. }
  4811. return self;
  4812. }
  4813. if ((attrs = self.attributes)) {
  4814. if (value !== undef) {
  4815. // Remove attribute
  4816. if (value === null) {
  4817. if (name in attrs.map) {
  4818. delete attrs.map[name];
  4819. i = attrs.length;
  4820. while (i--) {
  4821. if (attrs[i].name === name) {
  4822. attrs = attrs.splice(i, 1);
  4823. return self;
  4824. }
  4825. }
  4826. }
  4827. return self;
  4828. }
  4829. // Set attribute
  4830. if (name in attrs.map) {
  4831. // Set attribute
  4832. i = attrs.length;
  4833. while (i--) {
  4834. if (attrs[i].name === name) {
  4835. attrs[i].value = value;
  4836. break;
  4837. }
  4838. }
  4839. } else {
  4840. attrs.push({name: name, value: value});
  4841. }
  4842. attrs.map[name] = value;
  4843. return self;
  4844. } else {
  4845. return attrs.map[name];
  4846. }
  4847. }
  4848. },
  4849. /**
  4850. * Does a shallow clones the node into a new node. It will also exclude id attributes since
  4851. * there should only be one id per document.
  4852. *
  4853. * @example
  4854. * var clonedNode = node.clone();
  4855. *
  4856. * @method clone
  4857. * @return {tinymce.html.Node} New copy of the original node.
  4858. */
  4859. clone: function() {
  4860. var self = this, clone = new Node(self.name, self.type), i, l, selfAttrs, selfAttr, cloneAttrs;
  4861. // Clone element attributes
  4862. if ((selfAttrs = self.attributes)) {
  4863. cloneAttrs = [];
  4864. cloneAttrs.map = {};
  4865. for (i = 0, l = selfAttrs.length; i < l; i++) {
  4866. selfAttr = selfAttrs[i];
  4867. // Clone everything except id
  4868. if (selfAttr.name !== 'id') {
  4869. cloneAttrs[cloneAttrs.length] = {name: selfAttr.name, value: selfAttr.value};
  4870. cloneAttrs.map[selfAttr.name] = selfAttr.value;
  4871. }
  4872. }
  4873. clone.attributes = cloneAttrs;
  4874. }
  4875. clone.value = self.value;
  4876. clone.shortEnded = self.shortEnded;
  4877. return clone;
  4878. },
  4879. /**
  4880. * Wraps the node in in another node.
  4881. *
  4882. * @example
  4883. * node.wrap(wrapperNode);
  4884. *
  4885. * @method wrap
  4886. */
  4887. wrap: function(wrapper) {
  4888. var self = this;
  4889. self.parent.insert(wrapper, self);
  4890. wrapper.append(self);
  4891. return self;
  4892. },
  4893. /**
  4894. * Unwraps the node in other words it removes the node but keeps the children.
  4895. *
  4896. * @example
  4897. * node.unwrap();
  4898. *
  4899. * @method unwrap
  4900. */
  4901. unwrap: function() {
  4902. var self = this, node, next;
  4903. for (node = self.firstChild; node; ) {
  4904. next = node.next;
  4905. self.insert(node, self, true);
  4906. node = next;
  4907. }
  4908. self.remove();
  4909. },
  4910. /**
  4911. * Removes the node from it's parent.
  4912. *
  4913. * @example
  4914. * node.remove();
  4915. *
  4916. * @method remove
  4917. * @return {tinymce.html.Node} Current node that got removed.
  4918. */
  4919. remove: function() {
  4920. var self = this, parent = self.parent, next = self.next, prev = self.prev;
  4921. if (parent) {
  4922. if (parent.firstChild === self) {
  4923. parent.firstChild = next;
  4924. if (next) {
  4925. next.prev = null;
  4926. }
  4927. } else {
  4928. prev.next = next;
  4929. }
  4930. if (parent.lastChild === self) {
  4931. parent.lastChild = prev;
  4932. if (prev) {
  4933. prev.next = null;
  4934. }
  4935. } else {
  4936. next.prev = prev;
  4937. }
  4938. self.parent = self.next = self.prev = null;
  4939. }
  4940. return self;
  4941. },
  4942. /**
  4943. * Appends a new node as a child of the current node.
  4944. *
  4945. * @example
  4946. * node.append(someNode);
  4947. *
  4948. * @method append
  4949. * @param {tinymce.html.Node} node Node to append as a child of the current one.
  4950. * @return {tinymce.html.Node} The node that got appended.
  4951. */
  4952. append: function(node) {
  4953. var self = this, last;
  4954. if (node.parent) {
  4955. node.remove();
  4956. }
  4957. last = self.lastChild;
  4958. if (last) {
  4959. last.next = node;
  4960. node.prev = last;
  4961. self.lastChild = node;
  4962. } else {
  4963. self.lastChild = self.firstChild = node;
  4964. }
  4965. node.parent = self;
  4966. return node;
  4967. },
  4968. /**
  4969. * Inserts a node at a specific position as a child of the current node.
  4970. *
  4971. * @example
  4972. * parentNode.insert(newChildNode, oldChildNode);
  4973. *
  4974. * @method insert
  4975. * @param {tinymce.html.Node} node Node to insert as a child of the current node.
  4976. * @param {tinymce.html.Node} ref_node Reference node to set node before/after.
  4977. * @param {Boolean} before Optional state to insert the node before the reference node.
  4978. * @return {tinymce.html.Node} The node that got inserted.
  4979. */
  4980. insert: function(node, ref_node, before) {
  4981. var parent;
  4982. if (node.parent) {
  4983. node.remove();
  4984. }
  4985. parent = ref_node.parent || this;
  4986. if (before) {
  4987. if (ref_node === parent.firstChild) {
  4988. parent.firstChild = node;
  4989. } else {
  4990. ref_node.prev.next = node;
  4991. }
  4992. node.prev = ref_node.prev;
  4993. node.next = ref_node;
  4994. ref_node.prev = node;
  4995. } else {
  4996. if (ref_node === parent.lastChild) {
  4997. parent.lastChild = node;
  4998. } else {
  4999. ref_node.next.prev = node;
  5000. }
  5001. node.next = ref_node.next;
  5002. node.prev = ref_node;
  5003. ref_node.next = node;
  5004. }
  5005. node.parent = parent;
  5006. return node;
  5007. },
  5008. /**
  5009. * Get all children by name.
  5010. *
  5011. * @method getAll
  5012. * @param {String} name Name of the child nodes to collect.
  5013. * @return {Array} Array with child nodes matchin the specified name.
  5014. */
  5015. getAll: function(name) {
  5016. var self = this, node, collection = [];
  5017. for (node = self.firstChild; node; node = walk(node, self)) {
  5018. if (node.name === name) {
  5019. collection.push(node);
  5020. }
  5021. }
  5022. return collection;
  5023. },
  5024. /**
  5025. * Removes all children of the current node.
  5026. *
  5027. * @method empty
  5028. * @return {tinymce.html.Node} The current node that got cleared.
  5029. */
  5030. empty: function() {
  5031. var self = this, nodes, i, node;
  5032. // Remove all children
  5033. if (self.firstChild) {
  5034. nodes = [];
  5035. // Collect the children
  5036. for (node = self.firstChild; node; node = walk(node, self)) {
  5037. nodes.push(node);
  5038. }
  5039. // Remove the children
  5040. i = nodes.length;
  5041. while (i--) {
  5042. node = nodes[i];
  5043. node.parent = node.firstChild = node.lastChild = node.next = node.prev = null;
  5044. }
  5045. }
  5046. self.firstChild = self.lastChild = null;
  5047. return self;
  5048. },
  5049. /**
  5050. * Returns true/false if the node is to be considered empty or not.
  5051. *
  5052. * @example
  5053. * node.isEmpty({img: true});
  5054. * @method isEmpty
  5055. * @param {Object} elements Name/value object with elements that are automatically treated as non empty elements.
  5056. * @return {Boolean} true/false if the node is empty or not.
  5057. */
  5058. isEmpty: function(elements) {
  5059. var self = this, node = self.firstChild, i, name;
  5060. if (node) {
  5061. do {
  5062. if (node.type === 1) {
  5063. // Ignore bogus elements
  5064. if (node.attributes.map['data-mce-bogus']) {
  5065. continue;
  5066. }
  5067. // Keep empty elements like <img />
  5068. if (elements[node.name]) {
  5069. return false;
  5070. }
  5071. // Keep elements with data attributes or name attribute like <a name="1"></a>
  5072. i = node.attributes.length;
  5073. while (i--) {
  5074. name = node.attributes[i].name;
  5075. if (name === "name" || name.indexOf('data-mce-') === 0) {
  5076. return false;
  5077. }
  5078. }
  5079. }
  5080. // Keep comments
  5081. if (node.type === 8) {
  5082. return false;
  5083. }
  5084. // Keep non whitespace text nodes
  5085. if ((node.type === 3 && !whiteSpaceRegExp.test(node.value))) {
  5086. return false;
  5087. }
  5088. } while ((node = walk(node, self)));
  5089. }
  5090. return true;
  5091. },
  5092. /**
  5093. * Walks to the next or previous node and returns that node or null if it wasn't found.
  5094. *
  5095. * @method walk
  5096. * @param {Boolean} prev Optional previous node state defaults to false.
  5097. * @return {tinymce.html.Node} Node that is next to or previous of the current node.
  5098. */
  5099. walk: function(prev) {
  5100. return walk(this, null, prev);
  5101. }
  5102. };
  5103. /**
  5104. * Creates a node of a specific type.
  5105. *
  5106. * @static
  5107. * @method create
  5108. * @param {String} name Name of the node type to create for example "b" or "#text".
  5109. * @param {Object} attrs Name/value collection of attributes that will be applied to elements.
  5110. */
  5111. Node.create = function(name, attrs) {
  5112. var node, attrName;
  5113. // Create node
  5114. node = new Node(name, typeLookup[name] || 1);
  5115. // Add attributes if needed
  5116. if (attrs) {
  5117. for (attrName in attrs) {
  5118. node.attr(attrName, attrs[attrName]);
  5119. }
  5120. }
  5121. return node;
  5122. };
  5123. return Node;
  5124. });
  5125. // Included from: js/tinymce/classes/html/Schema.js
  5126. /**
  5127. * Schema.js
  5128. *
  5129. * Copyright, Moxiecode Systems AB
  5130. * Released under LGPL License.
  5131. *
  5132. * License: http://www.tinymce.com/license
  5133. * Contributing: http://www.tinymce.com/contributing
  5134. */
  5135. /**
  5136. * Schema validator class.
  5137. *
  5138. * @class tinymce.html.Schema
  5139. * @example
  5140. * if (tinymce.activeEditor.schema.isValidChild('p', 'span'))
  5141. * alert('span is valid child of p.');
  5142. *
  5143. * if (tinymce.activeEditor.schema.getElementRule('p'))
  5144. * alert('P is a valid element.');
  5145. *
  5146. * @class tinymce.html.Schema
  5147. * @version 3.4
  5148. */
  5149. define("tinymce/html/Schema", [
  5150. "tinymce/util/Tools"
  5151. ], function(Tools) {
  5152. var mapCache = {};
  5153. var makeMap = Tools.makeMap, each = Tools.each, extend = Tools.extend, explode = Tools.explode, inArray = Tools.inArray;
  5154. function split(items, delim) {
  5155. return items ? items.split(delim || ' ') : [];
  5156. }
  5157. /**
  5158. * Builds a schema lookup table
  5159. *
  5160. * @private
  5161. * @param {String} type html4, html5 or html5-strict schema type.
  5162. * @return {Object} Schema lookup table.
  5163. */
  5164. function compileSchema(type) {
  5165. var schema = {}, globalAttributes, blockContent;
  5166. var phrasingContent, flowContent, html4BlockContent, html4PhrasingContent;
  5167. function add(name, attributes, children) {
  5168. var ni, i, attributesOrder, args = arguments;
  5169. function arrayToMap(array) {
  5170. var map = {}, i, l;
  5171. for (i = 0, l = array.length; i < l; i++) {
  5172. map[array[i]] = {};
  5173. }
  5174. return map;
  5175. }
  5176. children = children || [];
  5177. attributes = attributes || "";
  5178. if (typeof(children) === "string") {
  5179. children = split(children);
  5180. }
  5181. // Split string children
  5182. for (i = 3; i < args.length; i++) {
  5183. if (typeof(args[i]) === "string") {
  5184. args[i] = split(args[i]);
  5185. }
  5186. children.push.apply(children, args[i]);
  5187. }
  5188. name = split(name);
  5189. ni = name.length;
  5190. while (ni--) {
  5191. attributesOrder = [].concat(globalAttributes, split(attributes));
  5192. schema[name[ni]] = {
  5193. attributes: arrayToMap(attributesOrder),
  5194. attributesOrder: attributesOrder,
  5195. children: arrayToMap(children)
  5196. };
  5197. }
  5198. }
  5199. function addAttrs(name, attributes) {
  5200. var ni, schemaItem, i, l;
  5201. name = split(name);
  5202. ni = name.length;
  5203. attributes = split(attributes);
  5204. while (ni--) {
  5205. schemaItem = schema[name[ni]];
  5206. for (i = 0, l = attributes.length; i < l; i++) {
  5207. schemaItem.attributes[attributes[i]] = {};
  5208. schemaItem.attributesOrder.push(attributes[i]);
  5209. }
  5210. }
  5211. }
  5212. // Use cached schema
  5213. if (mapCache[type]) {
  5214. return mapCache[type];
  5215. }
  5216. // Attributes present on all elements
  5217. globalAttributes = split("id accesskey class dir lang style tabindex title");
  5218. // Event attributes can be opt-in/opt-out
  5219. /*eventAttributes = split("onabort onblur oncancel oncanplay oncanplaythrough onchange onclick onclose oncontextmenu oncuechange " +
  5220. "ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop ondurationchange onemptied onended " +
  5221. "onerror onfocus oninput oninvalid onkeydown onkeypress onkeyup onload onloadeddata onloadedmetadata onloadstart " +
  5222. "onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onpause onplay onplaying onprogress onratechange " +
  5223. "onreset onscroll onseeked onseeking onseeking onselect onshow onstalled onsubmit onsuspend ontimeupdate onvolumechange " +
  5224. "onwaiting"
  5225. );*/
  5226. // Block content elements
  5227. blockContent = split(
  5228. "address blockquote div dl fieldset form h1 h2 h3 h4 h5 h6 hr menu ol p pre table ul"
  5229. );
  5230. // Phrasing content elements from the HTML5 spec (inline)
  5231. phrasingContent = split(
  5232. "a abbr b bdo br button cite code del dfn em embed i iframe img input ins kbd " +
  5233. "label map noscript object q s samp script select small span strong sub sup " +
  5234. "textarea u var #text #comment"
  5235. );
  5236. // Add HTML5 items to globalAttributes, blockContent, phrasingContent
  5237. if (type != "html4") {
  5238. globalAttributes.push.apply(globalAttributes, split("contenteditable contextmenu draggable dropzone " +
  5239. "hidden spellcheck translate"));
  5240. blockContent.push.apply(blockContent, split("article aside details dialog figure header footer hgroup section nav"));
  5241. phrasingContent.push.apply(phrasingContent, split("audio canvas command datalist mark meter output progress time wbr " +
  5242. "video ruby bdi keygen"));
  5243. }
  5244. // Add HTML4 elements unless it's html5-strict
  5245. if (type != "html5-strict") {
  5246. globalAttributes.push("xml:lang");
  5247. html4PhrasingContent = split("acronym applet basefont big font strike tt");
  5248. phrasingContent.push.apply(phrasingContent, html4PhrasingContent);
  5249. each(html4PhrasingContent, function(name) {
  5250. add(name, "", phrasingContent);
  5251. });
  5252. html4BlockContent = split("center dir isindex noframes");
  5253. blockContent.push.apply(blockContent, html4BlockContent);
  5254. // Flow content elements from the HTML5 spec (block+inline)
  5255. flowContent = [].concat(blockContent, phrasingContent);
  5256. each(html4BlockContent, function(name) {
  5257. add(name, "", flowContent);
  5258. });
  5259. }
  5260. // Flow content elements from the HTML5 spec (block+inline)
  5261. flowContent = flowContent || [].concat(blockContent, phrasingContent);
  5262. // HTML4 base schema TODO: Move HTML5 specific attributes to HTML5 specific if statement
  5263. // Schema items <element name>, <specific attributes>, <children ..>
  5264. add("html", "manifest", "head body");
  5265. add("head", "", "base command link meta noscript script style title");
  5266. add("title hr noscript br");
  5267. add("base", "href target");
  5268. add("link", "href rel media hreflang type sizes hreflang");
  5269. add("meta", "name http-equiv content charset");
  5270. add("style", "media type scoped");
  5271. add("script", "src async defer type charset");
  5272. add("body", "onafterprint onbeforeprint onbeforeunload onblur onerror onfocus " +
  5273. "onhashchange onload onmessage onoffline ononline onpagehide onpageshow " +
  5274. "onpopstate onresize onscroll onstorage onunload", flowContent);
  5275. add("address dt dd div caption", "", flowContent);
  5276. add("h1 h2 h3 h4 h5 h6 pre p abbr code var samp kbd sub sup i b u bdo span legend em strong small s cite dfn", "", phrasingContent);
  5277. add("blockquote", "cite", flowContent);
  5278. add("ol", "reversed start type", "li");
  5279. add("ul", "", "li");
  5280. add("li", "value", flowContent);
  5281. add("dl", "", "dt dd");
  5282. add("a", "href target rel media hreflang type", phrasingContent);
  5283. add("q", "cite", phrasingContent);
  5284. add("ins del", "cite datetime", flowContent);
  5285. add("img", "src alt usemap ismap width height");
  5286. add("iframe", "src name width height", flowContent);
  5287. add("embed", "src type width height");
  5288. add("object", "data type typemustmatch name usemap form width height", flowContent, "param");
  5289. add("param", "name value");
  5290. add("map", "name", flowContent, "area");
  5291. add("area", "alt coords shape href target rel media hreflang type");
  5292. add("table", "border", "caption colgroup thead tfoot tbody tr" + (type == "html4" ? " col" : ""));
  5293. add("colgroup", "span", "col");
  5294. add("col", "span");
  5295. add("tbody thead tfoot", "", "tr");
  5296. add("tr", "", "td th");
  5297. add("td", "colspan rowspan headers", flowContent);
  5298. add("th", "colspan rowspan headers scope abbr", flowContent);
  5299. add("form", "accept-charset action autocomplete enctype method name novalidate target", flowContent);
  5300. add("fieldset", "disabled form name", flowContent, "legend");
  5301. add("label", "form for", phrasingContent);
  5302. add("input", "accept alt autocomplete checked dirname disabled form formaction formenctype formmethod formnovalidate " +
  5303. "formtarget height list max maxlength min multiple name pattern readonly required size src step type value width"
  5304. );
  5305. add("button", "disabled form formaction formenctype formmethod formnovalidate formtarget name type value",
  5306. type == "html4" ? flowContent : phrasingContent);
  5307. add("select", "disabled form multiple name required size", "option optgroup");
  5308. add("optgroup", "disabled label", "option");
  5309. add("option", "disabled label selected value");
  5310. add("textarea", "cols dirname disabled form maxlength name readonly required rows wrap");
  5311. add("menu", "type label", flowContent, "li");
  5312. add("noscript", "", flowContent);
  5313. // Extend with HTML5 elements
  5314. if (type != "html4") {
  5315. add("wbr");
  5316. add("ruby", "", phrasingContent, "rt rp");
  5317. add("figcaption", "", flowContent);
  5318. add("mark rt rp summary bdi", "", phrasingContent);
  5319. add("canvas", "width height", flowContent);
  5320. add("video", "src crossorigin poster preload autoplay mediagroup loop " +
  5321. "muted controls width height buffered", flowContent, "track source");
  5322. add("audio", "src crossorigin preload autoplay mediagroup loop muted controls buffered volume", flowContent, "track source");
  5323. add("source", "src type media");
  5324. add("track", "kind src srclang label default");
  5325. add("datalist", "", phrasingContent, "option");
  5326. add("article section nav aside header footer", "", flowContent);
  5327. add("hgroup", "", "h1 h2 h3 h4 h5 h6");
  5328. add("figure", "", flowContent, "figcaption");
  5329. add("time", "datetime", phrasingContent);
  5330. add("dialog", "open", flowContent);
  5331. add("command", "type label icon disabled checked radiogroup command");
  5332. add("output", "for form name", phrasingContent);
  5333. add("progress", "value max", phrasingContent);
  5334. add("meter", "value min max low high optimum", phrasingContent);
  5335. add("details", "open", flowContent, "summary");
  5336. add("keygen", "autofocus challenge disabled form keytype name");
  5337. }
  5338. // Extend with HTML4 attributes unless it's html5-strict
  5339. if (type != "html5-strict") {
  5340. addAttrs("script", "language xml:space");
  5341. addAttrs("style", "xml:space");
  5342. addAttrs("object", "declare classid codebase codetype archive standby align border hspace vspace");
  5343. addAttrs("param", "valuetype type");
  5344. addAttrs("a", "charset name rev shape coords");
  5345. addAttrs("br", "clear");
  5346. addAttrs("applet", "codebase archive code object alt name width height align hspace vspace");
  5347. addAttrs("img", "name longdesc align border hspace vspace");
  5348. addAttrs("iframe", "longdesc frameborder marginwidth marginheight scrolling align");
  5349. addAttrs("font basefont", "size color face");
  5350. addAttrs("input", "usemap align");
  5351. addAttrs("select", "onchange");
  5352. addAttrs("textarea");
  5353. addAttrs("h1 h2 h3 h4 h5 h6 div p legend caption", "align");
  5354. addAttrs("ul", "type compact");
  5355. addAttrs("li", "type");
  5356. addAttrs("ol dl menu dir", "compact");
  5357. addAttrs("pre", "width xml:space");
  5358. addAttrs("hr", "align noshade size width");
  5359. addAttrs("isindex", "prompt");
  5360. addAttrs("table", "summary width frame rules cellspacing cellpadding align bgcolor");
  5361. addAttrs("col", "width align char charoff valign");
  5362. addAttrs("colgroup", "width align char charoff valign");
  5363. addAttrs("thead", "align char charoff valign");
  5364. addAttrs("tr", "align char charoff valign bgcolor");
  5365. addAttrs("th", "axis align char charoff valign nowrap bgcolor width height");
  5366. addAttrs("form", "accept");
  5367. addAttrs("td", "abbr axis scope align char charoff valign nowrap bgcolor width height");
  5368. addAttrs("tfoot", "align char charoff valign");
  5369. addAttrs("tbody", "align char charoff valign");
  5370. addAttrs("area", "nohref");
  5371. addAttrs("body", "background bgcolor text link vlink alink");
  5372. }
  5373. // Extend with HTML5 attributes unless it's html4
  5374. if (type != "html4") {
  5375. addAttrs("input button select textarea", "autofocus");
  5376. addAttrs("input textarea", "placeholder");
  5377. addAttrs("a", "download");
  5378. addAttrs("link script img", "crossorigin");
  5379. addAttrs("iframe", "sandbox seamless allowfullscreen"); // Excluded: srcdoc
  5380. }
  5381. // Special: iframe, ruby, video, audio, label
  5382. // Delete children of the same name from it's parent
  5383. // For example: form can't have a child of the name form
  5384. each(split('a form meter progress dfn'), function(name) {
  5385. if (schema[name]) {
  5386. delete schema[name].children[name];
  5387. }
  5388. });
  5389. // Delete header, footer, sectioning and heading content descendants
  5390. /*each('dt th address', function(name) {
  5391. delete schema[name].children[name];
  5392. });*/
  5393. // Caption can't have tables
  5394. delete schema.caption.children.table;
  5395. // TODO: LI:s can only have value if parent is OL
  5396. // TODO: Handle transparent elements
  5397. // a ins del canvas map
  5398. mapCache[type] = schema;
  5399. return schema;
  5400. }
  5401. /**
  5402. * Constructs a new Schema instance.
  5403. *
  5404. * @constructor
  5405. * @method Schema
  5406. * @param {Object} settings Name/value settings object.
  5407. */
  5408. return function(settings) {
  5409. var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems;
  5410. var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap;
  5411. var blockElementsMap, nonEmptyElementsMap, textBlockElementsMap, customElementsMap = {}, specialElements = {};
  5412. // Creates an lookup table map object for the specified option or the default value
  5413. function createLookupTable(option, default_value, extendWith) {
  5414. var value = settings[option];
  5415. if (!value) {
  5416. // Get cached default map or make it if needed
  5417. value = mapCache[option];
  5418. if (!value) {
  5419. value = makeMap(default_value, ' ', makeMap(default_value.toUpperCase(), ' '));
  5420. value = extend(value, extendWith);
  5421. mapCache[option] = value;
  5422. }
  5423. } else {
  5424. // Create custom map
  5425. value = makeMap(value, /[, ]/, makeMap(value.toUpperCase(), /[, ]/));
  5426. }
  5427. return value;
  5428. }
  5429. settings = settings || {};
  5430. schemaItems = compileSchema(settings.schema);
  5431. // Allow all elements and attributes if verify_html is set to false
  5432. if (settings.verify_html === false) {
  5433. settings.valid_elements = '*[*]';
  5434. }
  5435. // Build styles list
  5436. if (settings.valid_styles) {
  5437. validStyles = {};
  5438. // Convert styles into a rule list
  5439. each(settings.valid_styles, function(value, key) {
  5440. validStyles[key] = explode(value);
  5441. });
  5442. }
  5443. // Setup map objects
  5444. whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea video audio iframe object');
  5445. selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr');
  5446. shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link ' +
  5447. 'meta param embed source wbr track');
  5448. boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize ' +
  5449. 'noshade nowrap readonly selected autoplay loop controls');
  5450. nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object script', shortEndedElementsMap);
  5451. textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' +
  5452. 'blockquote center dir fieldset header footer article section hgroup aside nav figure');
  5453. blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' +
  5454. 'th tr td li ol ul caption dl dt dd noscript menu isindex option ' +
  5455. 'datalist select optgroup', textBlockElementsMap);
  5456. each((settings.special || 'script noscript style textarea').split(' '), function(name) {
  5457. specialElements[name] = new RegExp('<\/' + name + '[^>]*>','gi');
  5458. });
  5459. // Converts a wildcard expression string to a regexp for example *a will become /.*a/.
  5460. function patternToRegExp(str) {
  5461. return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$');
  5462. }
  5463. // Parses the specified valid_elements string and adds to the current rules
  5464. // This function is a bit hard to read since it's heavily optimized for speed
  5465. function addValidElements(valid_elements) {
  5466. var ei, el, ai, al, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder,
  5467. prefix, outputName, globalAttributes, globalAttributesOrder, key, value,
  5468. elementRuleRegExp = /^([#+\-])?([^\[!\/]+)(?:\/([^\[!]+))?(?:(!?)\[([^\]]+)\])?$/,
  5469. attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/,
  5470. hasPatternsRegExp = /[*?+]/;
  5471. if (valid_elements) {
  5472. // Split valid elements into an array with rules
  5473. valid_elements = split(valid_elements, ',');
  5474. if (elements['@']) {
  5475. globalAttributes = elements['@'].attributes;
  5476. globalAttributesOrder = elements['@'].attributesOrder;
  5477. }
  5478. // Loop all rules
  5479. for (ei = 0, el = valid_elements.length; ei < el; ei++) {
  5480. // Parse element rule
  5481. matches = elementRuleRegExp.exec(valid_elements[ei]);
  5482. if (matches) {
  5483. // Setup local names for matches
  5484. prefix = matches[1];
  5485. elementName = matches[2];
  5486. outputName = matches[3];
  5487. attrData = matches[5];
  5488. // Create new attributes and attributesOrder
  5489. attributes = {};
  5490. attributesOrder = [];
  5491. // Create the new element
  5492. element = {
  5493. attributes: attributes,
  5494. attributesOrder: attributesOrder
  5495. };
  5496. // Padd empty elements prefix
  5497. if (prefix === '#') {
  5498. element.paddEmpty = true;
  5499. }
  5500. // Remove empty elements prefix
  5501. if (prefix === '-') {
  5502. element.removeEmpty = true;
  5503. }
  5504. if (matches[4] === '!') {
  5505. element.removeEmptyAttrs = true;
  5506. }
  5507. // Copy attributes from global rule into current rule
  5508. if (globalAttributes) {
  5509. for (key in globalAttributes) {
  5510. attributes[key] = globalAttributes[key];
  5511. }
  5512. attributesOrder.push.apply(attributesOrder, globalAttributesOrder);
  5513. }
  5514. // Attributes defined
  5515. if (attrData) {
  5516. attrData = split(attrData, '|');
  5517. for (ai = 0, al = attrData.length; ai < al; ai++) {
  5518. matches = attrRuleRegExp.exec(attrData[ai]);
  5519. if (matches) {
  5520. attr = {};
  5521. attrType = matches[1];
  5522. attrName = matches[2].replace(/::/g, ':');
  5523. prefix = matches[3];
  5524. value = matches[4];
  5525. // Required
  5526. if (attrType === '!') {
  5527. element.attributesRequired = element.attributesRequired || [];
  5528. element.attributesRequired.push(attrName);
  5529. attr.required = true;
  5530. }
  5531. // Denied from global
  5532. if (attrType === '-') {
  5533. delete attributes[attrName];
  5534. attributesOrder.splice(inArray(attributesOrder, attrName), 1);
  5535. continue;
  5536. }
  5537. // Default value
  5538. if (prefix) {
  5539. // Default value
  5540. if (prefix === '=') {
  5541. element.attributesDefault = element.attributesDefault || [];
  5542. element.attributesDefault.push({name: attrName, value: value});
  5543. attr.defaultValue = value;
  5544. }
  5545. // Forced value
  5546. if (prefix === ':') {
  5547. element.attributesForced = element.attributesForced || [];
  5548. element.attributesForced.push({name: attrName, value: value});
  5549. attr.forcedValue = value;
  5550. }
  5551. // Required values
  5552. if (prefix === '<') {
  5553. attr.validValues = makeMap(value, '?');
  5554. }
  5555. }
  5556. // Check for attribute patterns
  5557. if (hasPatternsRegExp.test(attrName)) {
  5558. element.attributePatterns = element.attributePatterns || [];
  5559. attr.pattern = patternToRegExp(attrName);
  5560. element.attributePatterns.push(attr);
  5561. } else {
  5562. // Add attribute to order list if it doesn't already exist
  5563. if (!attributes[attrName]) {
  5564. attributesOrder.push(attrName);
  5565. }
  5566. attributes[attrName] = attr;
  5567. }
  5568. }
  5569. }
  5570. }
  5571. // Global rule, store away these for later usage
  5572. if (!globalAttributes && elementName == '@') {
  5573. globalAttributes = attributes;
  5574. globalAttributesOrder = attributesOrder;
  5575. }
  5576. // Handle substitute elements such as b/strong
  5577. if (outputName) {
  5578. element.outputName = elementName;
  5579. elements[outputName] = element;
  5580. }
  5581. // Add pattern or exact element
  5582. if (hasPatternsRegExp.test(elementName)) {
  5583. element.pattern = patternToRegExp(elementName);
  5584. patternElements.push(element);
  5585. } else {
  5586. elements[elementName] = element;
  5587. }
  5588. }
  5589. }
  5590. }
  5591. }
  5592. function setValidElements(valid_elements) {
  5593. elements = {};
  5594. patternElements = [];
  5595. addValidElements(valid_elements);
  5596. each(schemaItems, function(element, name) {
  5597. children[name] = element.children;
  5598. });
  5599. }
  5600. // Adds custom non HTML elements to the schema
  5601. function addCustomElements(custom_elements) {
  5602. var customElementRegExp = /^(~)?(.+)$/;
  5603. if (custom_elements) {
  5604. // Flush cached items since we are altering the default maps
  5605. mapCache.text_block_elements = mapCache.block_elements = null;
  5606. each(split(custom_elements, ','), function(rule) {
  5607. var matches = customElementRegExp.exec(rule),
  5608. inline = matches[1] === '~',
  5609. cloneName = inline ? 'span' : 'div',
  5610. name = matches[2];
  5611. children[name] = children[cloneName];
  5612. customElementsMap[name] = cloneName;
  5613. // If it's not marked as inline then add it to valid block elements
  5614. if (!inline) {
  5615. blockElementsMap[name.toUpperCase()] = {};
  5616. blockElementsMap[name] = {};
  5617. }
  5618. // Add elements clone if needed
  5619. if (!elements[name]) {
  5620. var customRule = elements[cloneName];
  5621. customRule = extend({}, customRule);
  5622. delete customRule.removeEmptyAttrs;
  5623. delete customRule.removeEmpty;
  5624. elements[name] = customRule;
  5625. }
  5626. // Add custom elements at span/div positions
  5627. each(children, function(element, elmName) {
  5628. if (element[cloneName]) {
  5629. children[elmName] = element = extend({}, children[elmName]);
  5630. element[name] = element[cloneName];
  5631. }
  5632. });
  5633. });
  5634. }
  5635. }
  5636. // Adds valid children to the schema object
  5637. function addValidChildren(valid_children) {
  5638. var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/;
  5639. if (valid_children) {
  5640. each(split(valid_children, ','), function(rule) {
  5641. var matches = childRuleRegExp.exec(rule), parent, prefix;
  5642. if (matches) {
  5643. prefix = matches[1];
  5644. // Add/remove items from default
  5645. if (prefix) {
  5646. parent = children[matches[2]];
  5647. } else {
  5648. parent = children[matches[2]] = {'#comment': {}};
  5649. }
  5650. parent = children[matches[2]];
  5651. each(split(matches[3], '|'), function(child) {
  5652. if (prefix === '-') {
  5653. // Clone the element before we delete
  5654. // things in it to not mess up default schemas
  5655. children[matches[2]] = parent = extend({}, children[matches[2]]);
  5656. delete parent[child];
  5657. } else {
  5658. parent[child] = {};
  5659. }
  5660. });
  5661. }
  5662. });
  5663. }
  5664. }
  5665. function getElementRule(name) {
  5666. var element = elements[name], i;
  5667. // Exact match found
  5668. if (element) {
  5669. return element;
  5670. }
  5671. // No exact match then try the patterns
  5672. i = patternElements.length;
  5673. while (i--) {
  5674. element = patternElements[i];
  5675. if (element.pattern.test(name)) {
  5676. return element;
  5677. }
  5678. }
  5679. }
  5680. if (!settings.valid_elements) {
  5681. // No valid elements defined then clone the elements from the schema spec
  5682. each(schemaItems, function(element, name) {
  5683. elements[name] = {
  5684. attributes: element.attributes,
  5685. attributesOrder: element.attributesOrder
  5686. };
  5687. children[name] = element.children;
  5688. });
  5689. // Switch these on HTML4
  5690. if (settings.schema != "html5") {
  5691. each(split('strong/b em/i'), function(item) {
  5692. item = split(item, '/');
  5693. elements[item[1]].outputName = item[0];
  5694. });
  5695. }
  5696. // Add default alt attribute for images
  5697. elements.img.attributesDefault = [{name: 'alt', value: ''}];
  5698. // Remove these if they are empty by default
  5699. each(split('ol ul sub sup blockquote span font a table tbody tr strong em b i'), function(name) {
  5700. if (elements[name]) {
  5701. elements[name].removeEmpty = true;
  5702. }
  5703. });
  5704. // Padd these by default
  5705. each(split('p h1 h2 h3 h4 h5 h6 th td pre div address caption'), function(name) {
  5706. elements[name].paddEmpty = true;
  5707. });
  5708. // Remove these if they have no attributes
  5709. each(split('span'), function(name) {
  5710. elements[name].removeEmptyAttrs = true;
  5711. });
  5712. // Remove these by default
  5713. // TODO: Reenable in 4.1
  5714. /*each(split('script style'), function(name) {
  5715. delete elements[name];
  5716. });*/
  5717. } else {
  5718. setValidElements(settings.valid_elements);
  5719. }
  5720. addCustomElements(settings.custom_elements);
  5721. addValidChildren(settings.valid_children);
  5722. addValidElements(settings.extended_valid_elements);
  5723. // Todo: Remove this when we fix list handling to be valid
  5724. addValidChildren('+ol[ul|ol],+ul[ul|ol]');
  5725. // Delete invalid elements
  5726. if (settings.invalid_elements) {
  5727. each(explode(settings.invalid_elements), function(item) {
  5728. if (elements[item]) {
  5729. delete elements[item];
  5730. }
  5731. });
  5732. }
  5733. // If the user didn't allow span only allow internal spans
  5734. if (!getElementRule('span')) {
  5735. addValidElements('span[!data-mce-type|*]');
  5736. }
  5737. /**
  5738. * Name/value map object with valid parents and children to those parents.
  5739. *
  5740. * @example
  5741. * children = {
  5742. * div:{p:{}, h1:{}}
  5743. * };
  5744. * @field children
  5745. * @type Object
  5746. */
  5747. self.children = children;
  5748. /**
  5749. * Name/value map object with valid styles for each element.
  5750. *
  5751. * @field styles
  5752. * @type Object
  5753. */
  5754. self.styles = validStyles;
  5755. /**
  5756. * Returns a map with boolean attributes.
  5757. *
  5758. * @method getBoolAttrs
  5759. * @return {Object} Name/value lookup map for boolean attributes.
  5760. */
  5761. self.getBoolAttrs = function() {
  5762. return boolAttrMap;
  5763. };
  5764. /**
  5765. * Returns a map with block elements.
  5766. *
  5767. * @method getBlockElements
  5768. * @return {Object} Name/value lookup map for block elements.
  5769. */
  5770. self.getBlockElements = function() {
  5771. return blockElementsMap;
  5772. };
  5773. /**
  5774. * Returns a map with text block elements. Such as: p,h1-h6,div,address
  5775. *
  5776. * @method getTextBlockElements
  5777. * @return {Object} Name/value lookup map for block elements.
  5778. */
  5779. self.getTextBlockElements = function() {
  5780. return textBlockElementsMap;
  5781. };
  5782. /**
  5783. * Returns a map with short ended elements such as BR or IMG.
  5784. *
  5785. * @method getShortEndedElements
  5786. * @return {Object} Name/value lookup map for short ended elements.
  5787. */
  5788. self.getShortEndedElements = function() {
  5789. return shortEndedElementsMap;
  5790. };
  5791. /**
  5792. * Returns a map with self closing tags such as <li>.
  5793. *
  5794. * @method getSelfClosingElements
  5795. * @return {Object} Name/value lookup map for self closing tags elements.
  5796. */
  5797. self.getSelfClosingElements = function() {
  5798. return selfClosingElementsMap;
  5799. };
  5800. /**
  5801. * Returns a map with elements that should be treated as contents regardless if it has text
  5802. * content in them or not such as TD, VIDEO or IMG.
  5803. *
  5804. * @method getNonEmptyElements
  5805. * @return {Object} Name/value lookup map for non empty elements.
  5806. */
  5807. self.getNonEmptyElements = function() {
  5808. return nonEmptyElementsMap;
  5809. };
  5810. /**
  5811. * Returns a map with elements where white space is to be preserved like PRE or SCRIPT.
  5812. *
  5813. * @method getWhiteSpaceElements
  5814. * @return {Object} Name/value lookup map for white space elements.
  5815. */
  5816. self.getWhiteSpaceElements = function() {
  5817. return whiteSpaceElementsMap;
  5818. };
  5819. /**
  5820. * Returns a map with special elements. These are elements that needs to be parsed
  5821. * in a special way such as script, style, textarea etc. The map object values
  5822. * are regexps used to find the end of the element.
  5823. *
  5824. * @method getSpecialElements
  5825. * @return {Object} Name/value lookup map for special elements.
  5826. */
  5827. self.getSpecialElements = function() {
  5828. return specialElements;
  5829. };
  5830. /**
  5831. * Returns true/false if the specified element and it's child is valid or not
  5832. * according to the schema.
  5833. *
  5834. * @method isValidChild
  5835. * @param {String} name Element name to check for.
  5836. * @param {String} child Element child to verify.
  5837. * @return {Boolean} True/false if the element is a valid child of the specified parent.
  5838. */
  5839. self.isValidChild = function(name, child) {
  5840. var parent = children[name];
  5841. return !!(parent && parent[child]);
  5842. };
  5843. /**
  5844. * Returns true/false if the specified element name and optional attribute is
  5845. * valid according to the schema.
  5846. *
  5847. * @method isValid
  5848. * @param {String} name Name of element to check.
  5849. * @param {String} attr Optional attribute name to check for.
  5850. * @return {Boolean} True/false if the element and attribute is valid.
  5851. */
  5852. self.isValid = function(name, attr) {
  5853. var attrPatterns, i, rule = getElementRule(name);
  5854. // Check if it's a valid element
  5855. if (rule) {
  5856. if (attr) {
  5857. // Check if attribute name exists
  5858. if (rule.attributes[attr]) {
  5859. return true;
  5860. }
  5861. // Check if attribute matches a regexp pattern
  5862. attrPatterns = rule.attributePatterns;
  5863. if (attrPatterns) {
  5864. i = attrPatterns.length;
  5865. while (i--) {
  5866. if (attrPatterns[i].pattern.test(name)) {
  5867. return true;
  5868. }
  5869. }
  5870. }
  5871. } else {
  5872. return true;
  5873. }
  5874. }
  5875. // No match
  5876. return false;
  5877. };
  5878. /**
  5879. * Returns true/false if the specified element is valid or not
  5880. * according to the schema.
  5881. *
  5882. * @method getElementRule
  5883. * @param {String} name Element name to check for.
  5884. * @return {Object} Element object or undefined if the element isn't valid.
  5885. */
  5886. self.getElementRule = getElementRule;
  5887. /**
  5888. * Returns an map object of all custom elements.
  5889. *
  5890. * @method getCustomElements
  5891. * @return {Object} Name/value map object of all custom elements.
  5892. */
  5893. self.getCustomElements = function() {
  5894. return customElementsMap;
  5895. };
  5896. /**
  5897. * Parses a valid elements string and adds it to the schema. The valid elements
  5898. * format is for example "element[attr=default|otherattr]".
  5899. * Existing rules will be replaced with the ones specified, so this extends the schema.
  5900. *
  5901. * @method addValidElements
  5902. * @param {String} valid_elements String in the valid elements format to be parsed.
  5903. */
  5904. self.addValidElements = addValidElements;
  5905. /**
  5906. * Parses a valid elements string and sets it to the schema. The valid elements
  5907. * format is for example "element[attr=default|otherattr]".
  5908. * Existing rules will be replaced with the ones specified, so this extends the schema.
  5909. *
  5910. * @method setValidElements
  5911. * @param {String} valid_elements String in the valid elements format to be parsed.
  5912. */
  5913. self.setValidElements = setValidElements;
  5914. /**
  5915. * Adds custom non HTML elements to the schema.
  5916. *
  5917. * @method addCustomElements
  5918. * @param {String} custom_elements Comma separated list of custom elements to add.
  5919. */
  5920. self.addCustomElements = addCustomElements;
  5921. /**
  5922. * Parses a valid children string and adds them to the schema structure. The valid children
  5923. * format is for example: "element[child1|child2]".
  5924. *
  5925. * @method addValidChildren
  5926. * @param {String} valid_children Valid children elements string to parse
  5927. */
  5928. self.addValidChildren = addValidChildren;
  5929. self.elements = elements;
  5930. };
  5931. });
  5932. // Included from: js/tinymce/classes/html/SaxParser.js
  5933. /**
  5934. * SaxParser.js
  5935. *
  5936. * Copyright, Moxiecode Systems AB
  5937. * Released under LGPL License.
  5938. *
  5939. * License: http://www.tinymce.com/license
  5940. * Contributing: http://www.tinymce.com/contributing
  5941. */
  5942. /*eslint max-depth:[2, 9] */
  5943. /**
  5944. * This class parses HTML code using pure JavaScript and executes various events for each item it finds. It will
  5945. * always execute the events in the right order for tag soup code like <b><p></b></p>. It will also remove elements
  5946. * and attributes that doesn't fit the schema if the validate setting is enabled.
  5947. *
  5948. * @example
  5949. * var parser = new tinymce.html.SaxParser({
  5950. * validate: true,
  5951. *
  5952. * comment: function(text) {
  5953. * console.log('Comment:', text);
  5954. * },
  5955. *
  5956. * cdata: function(text) {
  5957. * console.log('CDATA:', text);
  5958. * },
  5959. *
  5960. * text: function(text, raw) {
  5961. * console.log('Text:', text, 'Raw:', raw);
  5962. * },
  5963. *
  5964. * start: function(name, attrs, empty) {
  5965. * console.log('Start:', name, attrs, empty);
  5966. * },
  5967. *
  5968. * end: function(name) {
  5969. * console.log('End:', name);
  5970. * },
  5971. *
  5972. * pi: function(name, text) {
  5973. * console.log('PI:', name, text);
  5974. * },
  5975. *
  5976. * doctype: function(text) {
  5977. * console.log('DocType:', text);
  5978. * }
  5979. * }, schema);
  5980. * @class tinymce.html.SaxParser
  5981. * @version 3.4
  5982. */
  5983. define("tinymce/html/SaxParser", [
  5984. "tinymce/html/Schema",
  5985. "tinymce/html/Entities",
  5986. "tinymce/util/Tools"
  5987. ], function(Schema, Entities, Tools) {
  5988. var each = Tools.each;
  5989. /**
  5990. * Constructs a new SaxParser instance.
  5991. *
  5992. * @constructor
  5993. * @method SaxParser
  5994. * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks.
  5995. * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing.
  5996. */
  5997. return function(settings, schema) {
  5998. var self = this;
  5999. function noop() {}
  6000. settings = settings || {};
  6001. self.schema = schema = schema || new Schema();
  6002. if (settings.fix_self_closing !== false) {
  6003. settings.fix_self_closing = true;
  6004. }
  6005. // Add handler functions from settings and setup default handlers
  6006. each('comment cdata text start end pi doctype'.split(' '), function(name) {
  6007. if (name) {
  6008. self[name] = settings[name] || noop;
  6009. }
  6010. });
  6011. /**
  6012. * Parses the specified HTML string and executes the callbacks for each item it finds.
  6013. *
  6014. * @example
  6015. * new SaxParser({...}).parse('<b>text</b>');
  6016. * @method parse
  6017. * @param {String} html Html string to sax parse.
  6018. */
  6019. self.parse = function(html) {
  6020. var self = this, matches, index = 0, value, endRegExp, stack = [], attrList, i, text, name;
  6021. var isInternalElement, removeInternalElements, shortEndedElements, fillAttrsMap, isShortEnded;
  6022. var validate, elementRule, isValidElement, attr, attribsValue, validAttributesMap, validAttributePatterns;
  6023. var attributesRequired, attributesDefault, attributesForced;
  6024. var anyAttributesRequired, selfClosing, tokenRegExp, attrRegExp, specialElements, attrValue, idCount = 0;
  6025. var decode = Entities.decode, fixSelfClosing, filteredUrlAttrs = Tools.makeMap('src,href,data,background,formaction,poster');
  6026. var scriptUriRegExp = /((java|vb)script|mhtml):/i, dataUriRegExp = /^data:/i;
  6027. function processEndTag(name) {
  6028. var pos, i;
  6029. // Find position of parent of the same type
  6030. pos = stack.length;
  6031. while (pos--) {
  6032. if (stack[pos].name === name) {
  6033. break;
  6034. }
  6035. }
  6036. // Found parent
  6037. if (pos >= 0) {
  6038. // Close all the open elements
  6039. for (i = stack.length - 1; i >= pos; i--) {
  6040. name = stack[i];
  6041. if (name.valid) {
  6042. self.end(name.name);
  6043. }
  6044. }
  6045. // Remove the open elements from the stack
  6046. stack.length = pos;
  6047. }
  6048. }
  6049. function parseAttribute(match, name, value, val2, val3) {
  6050. var attrRule, i, trimRegExp = /[\s\u0000-\u001F]+/g;
  6051. name = name.toLowerCase();
  6052. value = name in fillAttrsMap ? name : decode(value || val2 || val3 || ''); // Handle boolean attribute than value attribute
  6053. // Validate name and value pass through all data- attributes
  6054. if (validate && !isInternalElement && name.indexOf('data-') !== 0) {
  6055. attrRule = validAttributesMap[name];
  6056. // Find rule by pattern matching
  6057. if (!attrRule && validAttributePatterns) {
  6058. i = validAttributePatterns.length;
  6059. while (i--) {
  6060. attrRule = validAttributePatterns[i];
  6061. if (attrRule.pattern.test(name)) {
  6062. break;
  6063. }
  6064. }
  6065. // No rule matched
  6066. if (i === -1) {
  6067. attrRule = null;
  6068. }
  6069. }
  6070. // No attribute rule found
  6071. if (!attrRule) {
  6072. return;
  6073. }
  6074. // Validate value
  6075. if (attrRule.validValues && !(value in attrRule.validValues)) {
  6076. return;
  6077. }
  6078. }
  6079. // Block any javascript: urls or non image data uris
  6080. if (filteredUrlAttrs[name] && !settings.allow_script_urls) {
  6081. var uri = value.replace(trimRegExp, '');
  6082. try {
  6083. // Might throw malformed URI sequence
  6084. uri = decodeURIComponent(uri);
  6085. } catch (ex) {
  6086. // Fallback to non UTF-8 decoder
  6087. uri = unescape(uri);
  6088. }
  6089. if (scriptUriRegExp.test(uri)) {
  6090. return;
  6091. }
  6092. if (!settings.allow_html_data_urls && dataUriRegExp.test(uri) && !/^data:image\//i.test(uri)) {
  6093. return;
  6094. }
  6095. }
  6096. // Add attribute to list and map
  6097. attrList.map[name] = value;
  6098. attrList.push({
  6099. name: name,
  6100. value: value
  6101. });
  6102. }
  6103. // Precompile RegExps and map objects
  6104. tokenRegExp = new RegExp('<(?:' +
  6105. '(?:!--([\\w\\W]*?)-->)|' + // Comment
  6106. '(?:!\\[CDATA\\[([\\w\\W]*?)\\]\\]>)|' + // CDATA
  6107. '(?:!DOCTYPE([\\w\\W]*?)>)|' + // DOCTYPE
  6108. '(?:\\?([^\\s\\/<>]+) ?([\\w\\W]*?)[?/]>)|' + // PI
  6109. '(?:\\/([^>]+)>)|' + // End element
  6110. '(?:([A-Za-z0-9\\-\\:\\.]+)((?:\\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\\/|\\s+)>)' + // Start element
  6111. ')', 'g');
  6112. attrRegExp = /([\w:\-]+)(?:\s*=\s*(?:(?:\"((?:[^\"])*)\")|(?:\'((?:[^\'])*)\')|([^>\s]+)))?/g;
  6113. // Setup lookup tables for empty elements and boolean attributes
  6114. shortEndedElements = schema.getShortEndedElements();
  6115. selfClosing = settings.self_closing_elements || schema.getSelfClosingElements();
  6116. fillAttrsMap = schema.getBoolAttrs();
  6117. validate = settings.validate;
  6118. removeInternalElements = settings.remove_internals;
  6119. fixSelfClosing = settings.fix_self_closing;
  6120. specialElements = schema.getSpecialElements();
  6121. while ((matches = tokenRegExp.exec(html))) {
  6122. // Text
  6123. if (index < matches.index) {
  6124. self.text(decode(html.substr(index, matches.index - index)));
  6125. }
  6126. if ((value = matches[6])) { // End element
  6127. value = value.toLowerCase();
  6128. // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
  6129. if (value.charAt(0) === ':') {
  6130. value = value.substr(1);
  6131. }
  6132. processEndTag(value);
  6133. } else if ((value = matches[7])) { // Start element
  6134. value = value.toLowerCase();
  6135. // IE will add a ":" in front of elements it doesn't understand like custom elements or HTML5 elements
  6136. if (value.charAt(0) === ':') {
  6137. value = value.substr(1);
  6138. }
  6139. isShortEnded = value in shortEndedElements;
  6140. // Is self closing tag for example an <li> after an open <li>
  6141. if (fixSelfClosing && selfClosing[value] && stack.length > 0 && stack[stack.length - 1].name === value) {
  6142. processEndTag(value);
  6143. }
  6144. // Validate element
  6145. if (!validate || (elementRule = schema.getElementRule(value))) {
  6146. isValidElement = true;
  6147. // Grab attributes map and patters when validation is enabled
  6148. if (validate) {
  6149. validAttributesMap = elementRule.attributes;
  6150. validAttributePatterns = elementRule.attributePatterns;
  6151. }
  6152. // Parse attributes
  6153. if ((attribsValue = matches[8])) {
  6154. isInternalElement = attribsValue.indexOf('data-mce-type') !== -1; // Check if the element is an internal element
  6155. // If the element has internal attributes then remove it if we are told to do so
  6156. if (isInternalElement && removeInternalElements) {
  6157. isValidElement = false;
  6158. }
  6159. attrList = [];
  6160. attrList.map = {};
  6161. attribsValue.replace(attrRegExp, parseAttribute);
  6162. } else {
  6163. attrList = [];
  6164. attrList.map = {};
  6165. }
  6166. // Process attributes if validation is enabled
  6167. if (validate && !isInternalElement) {
  6168. attributesRequired = elementRule.attributesRequired;
  6169. attributesDefault = elementRule.attributesDefault;
  6170. attributesForced = elementRule.attributesForced;
  6171. anyAttributesRequired = elementRule.removeEmptyAttrs;
  6172. // Check if any attribute exists
  6173. if (anyAttributesRequired && !attrList.length) {
  6174. isValidElement = false;
  6175. }
  6176. // Handle forced attributes
  6177. if (attributesForced) {
  6178. i = attributesForced.length;
  6179. while (i--) {
  6180. attr = attributesForced[i];
  6181. name = attr.name;
  6182. attrValue = attr.value;
  6183. if (attrValue === '{$uid}') {
  6184. attrValue = 'mce_' + idCount++;
  6185. }
  6186. attrList.map[name] = attrValue;
  6187. attrList.push({name: name, value: attrValue});
  6188. }
  6189. }
  6190. // Handle default attributes
  6191. if (attributesDefault) {
  6192. i = attributesDefault.length;
  6193. while (i--) {
  6194. attr = attributesDefault[i];
  6195. name = attr.name;
  6196. if (!(name in attrList.map)) {
  6197. attrValue = attr.value;
  6198. if (attrValue === '{$uid}') {
  6199. attrValue = 'mce_' + idCount++;
  6200. }
  6201. attrList.map[name] = attrValue;
  6202. attrList.push({name: name, value: attrValue});
  6203. }
  6204. }
  6205. }
  6206. // Handle required attributes
  6207. if (attributesRequired) {
  6208. i = attributesRequired.length;
  6209. while (i--) {
  6210. if (attributesRequired[i] in attrList.map) {
  6211. break;
  6212. }
  6213. }
  6214. // None of the required attributes where found
  6215. if (i === -1) {
  6216. isValidElement = false;
  6217. }
  6218. }
  6219. // Invalidate element if it's marked as bogus
  6220. if (attrList.map['data-mce-bogus']) {
  6221. isValidElement = false;
  6222. }
  6223. }
  6224. if (isValidElement) {
  6225. self.start(value, attrList, isShortEnded);
  6226. }
  6227. } else {
  6228. isValidElement = false;
  6229. }
  6230. // Treat script, noscript and style a bit different since they may include code that looks like elements
  6231. if ((endRegExp = specialElements[value])) {
  6232. endRegExp.lastIndex = index = matches.index + matches[0].length;
  6233. if ((matches = endRegExp.exec(html))) {
  6234. if (isValidElement) {
  6235. text = html.substr(index, matches.index - index);
  6236. }
  6237. index = matches.index + matches[0].length;
  6238. } else {
  6239. text = html.substr(index);
  6240. index = html.length;
  6241. }
  6242. if (isValidElement) {
  6243. if (text.length > 0) {
  6244. self.text(text, true);
  6245. }
  6246. self.end(value);
  6247. }
  6248. tokenRegExp.lastIndex = index;
  6249. continue;
  6250. }
  6251. // Push value on to stack
  6252. if (!isShortEnded) {
  6253. if (!attribsValue || attribsValue.indexOf('/') != attribsValue.length - 1) {
  6254. stack.push({name: value, valid: isValidElement});
  6255. } else if (isValidElement) {
  6256. self.end(value);
  6257. }
  6258. }
  6259. } else if ((value = matches[1])) { // Comment
  6260. // Padd comment value to avoid browsers from parsing invalid comments as HTML
  6261. if (value.charAt(0) === '>') {
  6262. value = ' ' + value;
  6263. }
  6264. if (!settings.allow_conditional_comments && value.substr(0, 3) === '[if') {
  6265. value = ' ' + value;
  6266. }
  6267. self.comment(value);
  6268. } else if ((value = matches[2])) { // CDATA
  6269. self.cdata(value);
  6270. } else if ((value = matches[3])) { // DOCTYPE
  6271. self.doctype(value);
  6272. } else if ((value = matches[4])) { // PI
  6273. self.pi(value, matches[5]);
  6274. }
  6275. index = matches.index + matches[0].length;
  6276. }
  6277. // Text
  6278. if (index < html.length) {
  6279. self.text(decode(html.substr(index)));
  6280. }
  6281. // Close any open elements
  6282. for (i = stack.length - 1; i >= 0; i--) {
  6283. value = stack[i];
  6284. if (value.valid) {
  6285. self.end(value.name);
  6286. }
  6287. }
  6288. };
  6289. };
  6290. });
  6291. // Included from: js/tinymce/classes/html/DomParser.js
  6292. /**
  6293. * DomParser.js
  6294. *
  6295. * Copyright, Moxiecode Systems AB
  6296. * Released under LGPL License.
  6297. *
  6298. * License: http://www.tinymce.com/license
  6299. * Contributing: http://www.tinymce.com/contributing
  6300. */
  6301. /**
  6302. * This class parses HTML code into a DOM like structure of nodes it will remove redundant whitespace and make
  6303. * sure that the node tree is valid according to the specified schema.
  6304. * So for example: <p>a<p>b</p>c</p> will become <p>a</p><p>b</p><p>c</p>
  6305. *
  6306. * @example
  6307. * var parser = new tinymce.html.DomParser({validate: true}, schema);
  6308. * var rootNode = parser.parse('<h1>content</h1>');
  6309. *
  6310. * @class tinymce.html.DomParser
  6311. * @version 3.4
  6312. */
  6313. define("tinymce/html/DomParser", [
  6314. "tinymce/html/Node",
  6315. "tinymce/html/Schema",
  6316. "tinymce/html/SaxParser",
  6317. "tinymce/util/Tools"
  6318. ], function(Node, Schema, SaxParser, Tools) {
  6319. var makeMap = Tools.makeMap, each = Tools.each, explode = Tools.explode, extend = Tools.extend;
  6320. /**
  6321. * Constructs a new DomParser instance.
  6322. *
  6323. * @constructor
  6324. * @method DomParser
  6325. * @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks.
  6326. * @param {tinymce.html.Schema} schema HTML Schema class to use when parsing.
  6327. */
  6328. return function(settings, schema) {
  6329. var self = this, nodeFilters = {}, attributeFilters = [], matchedNodes = {}, matchedAttributes = {};
  6330. settings = settings || {};
  6331. settings.validate = "validate" in settings ? settings.validate : true;
  6332. settings.root_name = settings.root_name || 'body';
  6333. self.schema = schema = schema || new Schema();
  6334. function fixInvalidChildren(nodes) {
  6335. var ni, node, parent, parents, newParent, currentNode, tempNode, childNode, i;
  6336. var nonEmptyElements, nonSplitableElements, textBlockElements, sibling, nextNode;
  6337. nonSplitableElements = makeMap('tr,td,th,tbody,thead,tfoot,table');
  6338. nonEmptyElements = schema.getNonEmptyElements();
  6339. textBlockElements = schema.getTextBlockElements();
  6340. for (ni = 0; ni < nodes.length; ni++) {
  6341. node = nodes[ni];
  6342. // Already removed or fixed
  6343. if (!node.parent || node.fixed) {
  6344. continue;
  6345. }
  6346. // If the invalid element is a text block and the text block is within a parent LI element
  6347. // Then unwrap the first text block and convert other sibling text blocks to LI elements similar to Word/Open Office
  6348. if (textBlockElements[node.name] && node.parent.name == 'li') {
  6349. // Move sibling text blocks after LI element
  6350. sibling = node.next;
  6351. while (sibling) {
  6352. if (textBlockElements[sibling.name]) {
  6353. sibling.name = 'li';
  6354. sibling.fixed = true;
  6355. node.parent.insert(sibling, node.parent);
  6356. } else {
  6357. break;
  6358. }
  6359. sibling = sibling.next;
  6360. }
  6361. // Unwrap current text block
  6362. node.unwrap(node);
  6363. continue;
  6364. }
  6365. // Get list of all parent nodes until we find a valid parent to stick the child into
  6366. parents = [node];
  6367. for (parent = node.parent; parent && !schema.isValidChild(parent.name, node.name) &&
  6368. !nonSplitableElements[parent.name]; parent = parent.parent) {
  6369. parents.push(parent);
  6370. }
  6371. // Found a suitable parent
  6372. if (parent && parents.length > 1) {
  6373. // Reverse the array since it makes looping easier
  6374. parents.reverse();
  6375. // Clone the related parent and insert that after the moved node
  6376. newParent = currentNode = self.filterNode(parents[0].clone());
  6377. // Start cloning and moving children on the left side of the target node
  6378. for (i = 0; i < parents.length - 1; i++) {
  6379. if (schema.isValidChild(currentNode.name, parents[i].name)) {
  6380. tempNode = self.filterNode(parents[i].clone());
  6381. currentNode.append(tempNode);
  6382. } else {
  6383. tempNode = currentNode;
  6384. }
  6385. for (childNode = parents[i].firstChild; childNode && childNode != parents[i + 1]; ) {
  6386. nextNode = childNode.next;
  6387. tempNode.append(childNode);
  6388. childNode = nextNode;
  6389. }
  6390. currentNode = tempNode;
  6391. }
  6392. if (!newParent.isEmpty(nonEmptyElements)) {
  6393. parent.insert(newParent, parents[0], true);
  6394. parent.insert(node, newParent);
  6395. } else {
  6396. parent.insert(node, parents[0], true);
  6397. }
  6398. // Check if the element is empty by looking through it's contents and special treatment for <p><br /></p>
  6399. parent = parents[0];
  6400. if (parent.isEmpty(nonEmptyElements) || parent.firstChild === parent.lastChild && parent.firstChild.name === 'br') {
  6401. parent.empty().remove();
  6402. }
  6403. } else if (node.parent) {
  6404. // If it's an LI try to find a UL/OL for it or wrap it
  6405. if (node.name === 'li') {
  6406. sibling = node.prev;
  6407. if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
  6408. sibling.append(node);
  6409. continue;
  6410. }
  6411. sibling = node.next;
  6412. if (sibling && (sibling.name === 'ul' || sibling.name === 'ul')) {
  6413. sibling.insert(node, sibling.firstChild, true);
  6414. continue;
  6415. }
  6416. node.wrap(self.filterNode(new Node('ul', 1)));
  6417. continue;
  6418. }
  6419. // Try wrapping the element in a DIV
  6420. if (schema.isValidChild(node.parent.name, 'div') && schema.isValidChild('div', node.name)) {
  6421. node.wrap(self.filterNode(new Node('div', 1)));
  6422. } else {
  6423. // We failed wrapping it, then remove or unwrap it
  6424. if (node.name === 'style' || node.name === 'script') {
  6425. node.empty().remove();
  6426. } else {
  6427. node.unwrap();
  6428. }
  6429. }
  6430. }
  6431. }
  6432. }
  6433. /**
  6434. * Runs the specified node though the element and attributes filters.
  6435. *
  6436. * @method filterNode
  6437. * @param {tinymce.html.Node} Node the node to run filters on.
  6438. * @return {tinymce.html.Node} The passed in node.
  6439. */
  6440. self.filterNode = function(node) {
  6441. var i, name, list;
  6442. // Run element filters
  6443. if (name in nodeFilters) {
  6444. list = matchedNodes[name];
  6445. if (list) {
  6446. list.push(node);
  6447. } else {
  6448. matchedNodes[name] = [node];
  6449. }
  6450. }
  6451. // Run attribute filters
  6452. i = attributeFilters.length;
  6453. while (i--) {
  6454. name = attributeFilters[i].name;
  6455. if (name in node.attributes.map) {
  6456. list = matchedAttributes[name];
  6457. if (list) {
  6458. list.push(node);
  6459. } else {
  6460. matchedAttributes[name] = [node];
  6461. }
  6462. }
  6463. }
  6464. return node;
  6465. };
  6466. /**
  6467. * Adds a node filter function to the parser, the parser will collect the specified nodes by name
  6468. * and then execute the callback ones it has finished parsing the document.
  6469. *
  6470. * @example
  6471. * parser.addNodeFilter('p,h1', function(nodes, name) {
  6472. * for (var i = 0; i < nodes.length; i++) {
  6473. * console.log(nodes[i].name);
  6474. * }
  6475. * });
  6476. * @method addNodeFilter
  6477. * @method {String} name Comma separated list of nodes to collect.
  6478. * @param {function} callback Callback function to execute once it has collected nodes.
  6479. */
  6480. self.addNodeFilter = function(name, callback) {
  6481. each(explode(name), function(name) {
  6482. var list = nodeFilters[name];
  6483. if (!list) {
  6484. nodeFilters[name] = list = [];
  6485. }
  6486. list.push(callback);
  6487. });
  6488. };
  6489. /**
  6490. * Adds a attribute filter function to the parser, the parser will collect nodes that has the specified attributes
  6491. * and then execute the callback ones it has finished parsing the document.
  6492. *
  6493. * @example
  6494. * parser.addAttributeFilter('src,href', function(nodes, name) {
  6495. * for (var i = 0; i < nodes.length; i++) {
  6496. * console.log(nodes[i].name);
  6497. * }
  6498. * });
  6499. * @method addAttributeFilter
  6500. * @method {String} name Comma separated list of nodes to collect.
  6501. * @param {function} callback Callback function to execute once it has collected nodes.
  6502. */
  6503. self.addAttributeFilter = function(name, callback) {
  6504. each(explode(name), function(name) {
  6505. var i;
  6506. for (i = 0; i < attributeFilters.length; i++) {
  6507. if (attributeFilters[i].name === name) {
  6508. attributeFilters[i].callbacks.push(callback);
  6509. return;
  6510. }
  6511. }
  6512. attributeFilters.push({name: name, callbacks: [callback]});
  6513. });
  6514. };
  6515. /**
  6516. * Parses the specified HTML string into a DOM like node tree and returns the result.
  6517. *
  6518. * @example
  6519. * var rootNode = new DomParser({...}).parse('<b>text</b>');
  6520. * @method parse
  6521. * @param {String} html Html string to sax parse.
  6522. * @param {Object} args Optional args object that gets passed to all filter functions.
  6523. * @return {tinymce.html.Node} Root node containing the tree.
  6524. */
  6525. self.parse = function(html, args) {
  6526. var parser, rootNode, node, nodes, i, l, fi, fl, list, name, validate;
  6527. var blockElements, startWhiteSpaceRegExp, invalidChildren = [], isInWhiteSpacePreservedElement;
  6528. var endWhiteSpaceRegExp, allWhiteSpaceRegExp, isAllWhiteSpaceRegExp, whiteSpaceElements;
  6529. var children, nonEmptyElements, rootBlockName;
  6530. args = args || {};
  6531. matchedNodes = {};
  6532. matchedAttributes = {};
  6533. blockElements = extend(makeMap('script,style,head,html,body,title,meta,param'), schema.getBlockElements());
  6534. nonEmptyElements = schema.getNonEmptyElements();
  6535. children = schema.children;
  6536. validate = settings.validate;
  6537. rootBlockName = "forced_root_block" in args ? args.forced_root_block : settings.forced_root_block;
  6538. whiteSpaceElements = schema.getWhiteSpaceElements();
  6539. startWhiteSpaceRegExp = /^[ \t\r\n]+/;
  6540. endWhiteSpaceRegExp = /[ \t\r\n]+$/;
  6541. allWhiteSpaceRegExp = /[ \t\r\n]+/g;
  6542. isAllWhiteSpaceRegExp = /^[ \t\r\n]+$/;
  6543. function addRootBlocks() {
  6544. var node = rootNode.firstChild, next, rootBlockNode;
  6545. // Removes whitespace at beginning and end of block so:
  6546. // <p> x </p> -> <p>x</p>
  6547. function trim(rootBlockNode) {
  6548. if (rootBlockNode) {
  6549. node = rootBlockNode.firstChild;
  6550. if (node && node.type == 3) {
  6551. node.value = node.value.replace(startWhiteSpaceRegExp, '');
  6552. }
  6553. node = rootBlockNode.lastChild;
  6554. if (node && node.type == 3) {
  6555. node.value = node.value.replace(endWhiteSpaceRegExp, '');
  6556. }
  6557. }
  6558. }
  6559. // Check if rootBlock is valid within rootNode for example if P is valid in H1 if H1 is the contentEditabe root
  6560. if (!schema.isValidChild(rootNode.name, rootBlockName.toLowerCase())) {
  6561. return;
  6562. }
  6563. while (node) {
  6564. next = node.next;
  6565. if (node.type == 3 || (node.type == 1 && node.name !== 'p' &&
  6566. !blockElements[node.name] && !node.attr('data-mce-type'))) {
  6567. if (!rootBlockNode) {
  6568. // Create a new root block element
  6569. rootBlockNode = createNode(rootBlockName, 1);
  6570. rootBlockNode.attr(settings.forced_root_block_attrs);
  6571. rootNode.insert(rootBlockNode, node);
  6572. rootBlockNode.append(node);
  6573. } else {
  6574. rootBlockNode.append(node);
  6575. }
  6576. } else {
  6577. trim(rootBlockNode);
  6578. rootBlockNode = null;
  6579. }
  6580. node = next;
  6581. }
  6582. trim(rootBlockNode);
  6583. }
  6584. function createNode(name, type) {
  6585. var node = new Node(name, type), list;
  6586. if (name in nodeFilters) {
  6587. list = matchedNodes[name];
  6588. if (list) {
  6589. list.push(node);
  6590. } else {
  6591. matchedNodes[name] = [node];
  6592. }
  6593. }
  6594. return node;
  6595. }
  6596. function removeWhitespaceBefore(node) {
  6597. var textNode, textVal, sibling;
  6598. for (textNode = node.prev; textNode && textNode.type === 3; ) {
  6599. textVal = textNode.value.replace(endWhiteSpaceRegExp, '');
  6600. if (textVal.length > 0) {
  6601. textNode.value = textVal;
  6602. textNode = textNode.prev;
  6603. } else {
  6604. sibling = textNode.prev;
  6605. textNode.remove();
  6606. textNode = sibling;
  6607. }
  6608. }
  6609. }
  6610. function cloneAndExcludeBlocks(input) {
  6611. var name, output = {};
  6612. for (name in input) {
  6613. if (name !== 'li' && name != 'p') {
  6614. output[name] = input[name];
  6615. }
  6616. }
  6617. return output;
  6618. }
  6619. parser = new SaxParser({
  6620. validate: validate,
  6621. allow_script_urls: settings.allow_script_urls,
  6622. allow_conditional_comments: settings.allow_conditional_comments,
  6623. // Exclude P and LI from DOM parsing since it's treated better by the DOM parser
  6624. self_closing_elements: cloneAndExcludeBlocks(schema.getSelfClosingElements()),
  6625. cdata: function(text) {
  6626. node.append(createNode('#cdata', 4)).value = text;
  6627. },
  6628. text: function(text, raw) {
  6629. var textNode;
  6630. // Trim all redundant whitespace on non white space elements
  6631. if (!isInWhiteSpacePreservedElement) {
  6632. text = text.replace(allWhiteSpaceRegExp, ' ');
  6633. if (node.lastChild && blockElements[node.lastChild.name]) {
  6634. text = text.replace(startWhiteSpaceRegExp, '');
  6635. }
  6636. }
  6637. // Do we need to create the node
  6638. if (text.length !== 0) {
  6639. textNode = createNode('#text', 3);
  6640. textNode.raw = !!raw;
  6641. node.append(textNode).value = text;
  6642. }
  6643. },
  6644. comment: function(text) {
  6645. node.append(createNode('#comment', 8)).value = text;
  6646. },
  6647. pi: function(name, text) {
  6648. node.append(createNode(name, 7)).value = text;
  6649. removeWhitespaceBefore(node);
  6650. },
  6651. doctype: function(text) {
  6652. var newNode;
  6653. newNode = node.append(createNode('#doctype', 10));
  6654. newNode.value = text;
  6655. removeWhitespaceBefore(node);
  6656. },
  6657. start: function(name, attrs, empty) {
  6658. var newNode, attrFiltersLen, elementRule, attrName, parent;
  6659. elementRule = validate ? schema.getElementRule(name) : {};
  6660. if (elementRule) {
  6661. newNode = createNode(elementRule.outputName || name, 1);
  6662. newNode.attributes = attrs;
  6663. newNode.shortEnded = empty;
  6664. node.append(newNode);
  6665. // Check if node is valid child of the parent node is the child is
  6666. // unknown we don't collect it since it's probably a custom element
  6667. parent = children[node.name];
  6668. if (parent && children[newNode.name] && !parent[newNode.name]) {
  6669. invalidChildren.push(newNode);
  6670. }
  6671. attrFiltersLen = attributeFilters.length;
  6672. while (attrFiltersLen--) {
  6673. attrName = attributeFilters[attrFiltersLen].name;
  6674. if (attrName in attrs.map) {
  6675. list = matchedAttributes[attrName];
  6676. if (list) {
  6677. list.push(newNode);
  6678. } else {
  6679. matchedAttributes[attrName] = [newNode];
  6680. }
  6681. }
  6682. }
  6683. // Trim whitespace before block
  6684. if (blockElements[name]) {
  6685. removeWhitespaceBefore(newNode);
  6686. }
  6687. // Change current node if the element wasn't empty i.e not <br /> or <img />
  6688. if (!empty) {
  6689. node = newNode;
  6690. }
  6691. // Check if we are inside a whitespace preserved element
  6692. if (!isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  6693. isInWhiteSpacePreservedElement = true;
  6694. }
  6695. }
  6696. },
  6697. end: function(name) {
  6698. var textNode, elementRule, text, sibling, tempNode;
  6699. elementRule = validate ? schema.getElementRule(name) : {};
  6700. if (elementRule) {
  6701. if (blockElements[name]) {
  6702. if (!isInWhiteSpacePreservedElement) {
  6703. // Trim whitespace of the first node in a block
  6704. textNode = node.firstChild;
  6705. if (textNode && textNode.type === 3) {
  6706. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  6707. // Any characters left after trim or should we remove it
  6708. if (text.length > 0) {
  6709. textNode.value = text;
  6710. textNode = textNode.next;
  6711. } else {
  6712. sibling = textNode.next;
  6713. textNode.remove();
  6714. textNode = sibling;
  6715. // Remove any pure whitespace siblings
  6716. while (textNode && textNode.type === 3) {
  6717. text = textNode.value;
  6718. sibling = textNode.next;
  6719. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  6720. textNode.remove();
  6721. textNode = sibling;
  6722. }
  6723. textNode = sibling;
  6724. }
  6725. }
  6726. }
  6727. // Trim whitespace of the last node in a block
  6728. textNode = node.lastChild;
  6729. if (textNode && textNode.type === 3) {
  6730. text = textNode.value.replace(endWhiteSpaceRegExp, '');
  6731. // Any characters left after trim or should we remove it
  6732. if (text.length > 0) {
  6733. textNode.value = text;
  6734. textNode = textNode.prev;
  6735. } else {
  6736. sibling = textNode.prev;
  6737. textNode.remove();
  6738. textNode = sibling;
  6739. // Remove any pure whitespace siblings
  6740. while (textNode && textNode.type === 3) {
  6741. text = textNode.value;
  6742. sibling = textNode.prev;
  6743. if (text.length === 0 || isAllWhiteSpaceRegExp.test(text)) {
  6744. textNode.remove();
  6745. textNode = sibling;
  6746. }
  6747. textNode = sibling;
  6748. }
  6749. }
  6750. }
  6751. }
  6752. // Trim start white space
  6753. // Removed due to: #5424
  6754. /*textNode = node.prev;
  6755. if (textNode && textNode.type === 3) {
  6756. text = textNode.value.replace(startWhiteSpaceRegExp, '');
  6757. if (text.length > 0)
  6758. textNode.value = text;
  6759. else
  6760. textNode.remove();
  6761. }*/
  6762. }
  6763. // Check if we exited a whitespace preserved element
  6764. if (isInWhiteSpacePreservedElement && whiteSpaceElements[name]) {
  6765. isInWhiteSpacePreservedElement = false;
  6766. }
  6767. // Handle empty nodes
  6768. if (elementRule.removeEmpty || elementRule.paddEmpty) {
  6769. if (node.isEmpty(nonEmptyElements)) {
  6770. if (elementRule.paddEmpty) {
  6771. node.empty().append(new Node('#text', '3')).value = '\u00a0';
  6772. } else {
  6773. // Leave nodes that have a name like <a name="name">
  6774. if (!node.attributes.map.name && !node.attributes.map.id) {
  6775. tempNode = node.parent;
  6776. node.empty().remove();
  6777. node = tempNode;
  6778. return;
  6779. }
  6780. }
  6781. }
  6782. }
  6783. node = node.parent;
  6784. }
  6785. }
  6786. }, schema);
  6787. rootNode = node = new Node(args.context || settings.root_name, 11);
  6788. parser.parse(html);
  6789. // Fix invalid children or report invalid children in a contextual parsing
  6790. if (validate && invalidChildren.length) {
  6791. if (!args.context) {
  6792. fixInvalidChildren(invalidChildren);
  6793. } else {
  6794. args.invalid = true;
  6795. }
  6796. }
  6797. // Wrap nodes in the root into block elements if the root is body
  6798. if (rootBlockName && (rootNode.name == 'body' || args.isRootContent)) {
  6799. addRootBlocks();
  6800. }
  6801. // Run filters only when the contents is valid
  6802. if (!args.invalid) {
  6803. // Run node filters
  6804. for (name in matchedNodes) {
  6805. list = nodeFilters[name];
  6806. nodes = matchedNodes[name];
  6807. // Remove already removed children
  6808. fi = nodes.length;
  6809. while (fi--) {
  6810. if (!nodes[fi].parent) {
  6811. nodes.splice(fi, 1);
  6812. }
  6813. }
  6814. for (i = 0, l = list.length; i < l; i++) {
  6815. list[i](nodes, name, args);
  6816. }
  6817. }
  6818. // Run attribute filters
  6819. for (i = 0, l = attributeFilters.length; i < l; i++) {
  6820. list = attributeFilters[i];
  6821. if (list.name in matchedAttributes) {
  6822. nodes = matchedAttributes[list.name];
  6823. // Remove already removed children
  6824. fi = nodes.length;
  6825. while (fi--) {
  6826. if (!nodes[fi].parent) {
  6827. nodes.splice(fi, 1);
  6828. }
  6829. }
  6830. for (fi = 0, fl = list.callbacks.length; fi < fl; fi++) {
  6831. list.callbacks[fi](nodes, list.name, args);
  6832. }
  6833. }
  6834. }
  6835. }
  6836. return rootNode;
  6837. };
  6838. // Remove <br> at end of block elements Gecko and WebKit injects BR elements to
  6839. // make it possible to place the caret inside empty blocks. This logic tries to remove
  6840. // these elements and keep br elements that where intended to be there intact
  6841. if (settings.remove_trailing_brs) {
  6842. self.addNodeFilter('br', function(nodes) {
  6843. var i, l = nodes.length, node, blockElements = extend({}, schema.getBlockElements());
  6844. var nonEmptyElements = schema.getNonEmptyElements(), parent, lastParent, prev, prevName;
  6845. var elementRule, textNode;
  6846. // Remove brs from body element as well
  6847. blockElements.body = 1;
  6848. // Must loop forwards since it will otherwise remove all brs in <p>a<br><br><br></p>
  6849. for (i = 0; i < l; i++) {
  6850. node = nodes[i];
  6851. parent = node.parent;
  6852. if (blockElements[node.parent.name] && node === parent.lastChild) {
  6853. // Loop all nodes to the left of the current node and check for other BR elements
  6854. // excluding bookmarks since they are invisible
  6855. prev = node.prev;
  6856. while (prev) {
  6857. prevName = prev.name;
  6858. // Ignore bookmarks
  6859. if (prevName !== "span" || prev.attr('data-mce-type') !== 'bookmark') {
  6860. // Found a non BR element
  6861. if (prevName !== "br") {
  6862. break;
  6863. }
  6864. // Found another br it's a <br><br> structure then don't remove anything
  6865. if (prevName === 'br') {
  6866. node = null;
  6867. break;
  6868. }
  6869. }
  6870. prev = prev.prev;
  6871. }
  6872. if (node) {
  6873. node.remove();
  6874. // Is the parent to be considered empty after we removed the BR
  6875. if (parent.isEmpty(nonEmptyElements)) {
  6876. elementRule = schema.getElementRule(parent.name);
  6877. // Remove or padd the element depending on schema rule
  6878. if (elementRule) {
  6879. if (elementRule.removeEmpty) {
  6880. parent.remove();
  6881. } else if (elementRule.paddEmpty) {
  6882. parent.empty().append(new Node('#text', 3)).value = '\u00a0';
  6883. }
  6884. }
  6885. }
  6886. }
  6887. } else {
  6888. // Replaces BR elements inside inline elements like <p><b><i><br></i></b></p>
  6889. // so they become <p><b><i>&nbsp;</i></b></p>
  6890. lastParent = node;
  6891. while (parent && parent.firstChild === lastParent && parent.lastChild === lastParent) {
  6892. lastParent = parent;
  6893. if (blockElements[parent.name]) {
  6894. break;
  6895. }
  6896. parent = parent.parent;
  6897. }
  6898. if (lastParent === parent) {
  6899. textNode = new Node('#text', 3);
  6900. textNode.value = '\u00a0';
  6901. node.replace(textNode);
  6902. }
  6903. }
  6904. }
  6905. });
  6906. }
  6907. // Force anchor names closed, unless the setting "allow_html_in_named_anchor" is explicitly included.
  6908. if (!settings.allow_html_in_named_anchor) {
  6909. self.addAttributeFilter('id,name', function(nodes) {
  6910. var i = nodes.length, sibling, prevSibling, parent, node;
  6911. while (i--) {
  6912. node = nodes[i];
  6913. if (node.name === 'a' && node.firstChild && !node.attr('href')) {
  6914. parent = node.parent;
  6915. // Move children after current node
  6916. sibling = node.lastChild;
  6917. do {
  6918. prevSibling = sibling.prev;
  6919. parent.insert(sibling, node);
  6920. sibling = prevSibling;
  6921. } while (sibling);
  6922. }
  6923. }
  6924. });
  6925. }
  6926. };
  6927. });
  6928. // Included from: js/tinymce/classes/html/Writer.js
  6929. /**
  6930. * Writer.js
  6931. *
  6932. * Copyright, Moxiecode Systems AB
  6933. * Released under LGPL License.
  6934. *
  6935. * License: http://www.tinymce.com/license
  6936. * Contributing: http://www.tinymce.com/contributing
  6937. */
  6938. /**
  6939. * This class is used to write HTML tags out it can be used with the Serializer or the SaxParser.
  6940. *
  6941. * @class tinymce.html.Writer
  6942. * @example
  6943. * var writer = new tinymce.html.Writer({indent: true});
  6944. * var parser = new tinymce.html.SaxParser(writer).parse('<p><br></p>');
  6945. * console.log(writer.getContent());
  6946. *
  6947. * @class tinymce.html.Writer
  6948. * @version 3.4
  6949. */
  6950. define("tinymce/html/Writer", [
  6951. "tinymce/html/Entities",
  6952. "tinymce/util/Tools"
  6953. ], function(Entities, Tools) {
  6954. var makeMap = Tools.makeMap;
  6955. /**
  6956. * Constructs a new Writer instance.
  6957. *
  6958. * @constructor
  6959. * @method Writer
  6960. * @param {Object} settings Name/value settings object.
  6961. */
  6962. return function(settings) {
  6963. var html = [], indent, indentBefore, indentAfter, encode, htmlOutput;
  6964. settings = settings || {};
  6965. indent = settings.indent;
  6966. indentBefore = makeMap(settings.indent_before || '');
  6967. indentAfter = makeMap(settings.indent_after || '');
  6968. encode = Entities.getEncodeFunc(settings.entity_encoding || 'raw', settings.entities);
  6969. htmlOutput = settings.element_format == "html";
  6970. return {
  6971. /**
  6972. * Writes the a start element such as <p id="a">.
  6973. *
  6974. * @method start
  6975. * @param {String} name Name of the element.
  6976. * @param {Array} attrs Optional attribute array or undefined if it hasn't any.
  6977. * @param {Boolean} empty Optional empty state if the tag should end like <br />.
  6978. */
  6979. start: function(name, attrs, empty) {
  6980. var i, l, attr, value;
  6981. if (indent && indentBefore[name] && html.length > 0) {
  6982. value = html[html.length - 1];
  6983. if (value.length > 0 && value !== '\n') {
  6984. html.push('\n');
  6985. }
  6986. }
  6987. html.push('<', name);
  6988. if (attrs) {
  6989. for (i = 0, l = attrs.length; i < l; i++) {
  6990. attr = attrs[i];
  6991. html.push(' ', attr.name, '="', encode(attr.value, true), '"');
  6992. }
  6993. }
  6994. if (!empty || htmlOutput) {
  6995. html[html.length] = '>';
  6996. } else {
  6997. html[html.length] = ' />';
  6998. }
  6999. if (empty && indent && indentAfter[name] && html.length > 0) {
  7000. value = html[html.length - 1];
  7001. if (value.length > 0 && value !== '\n') {
  7002. html.push('\n');
  7003. }
  7004. }
  7005. },
  7006. /**
  7007. * Writes the a end element such as </p>.
  7008. *
  7009. * @method end
  7010. * @param {String} name Name of the element.
  7011. */
  7012. end: function(name) {
  7013. var value;
  7014. /*if (indent && indentBefore[name] && html.length > 0) {
  7015. value = html[html.length - 1];
  7016. if (value.length > 0 && value !== '\n')
  7017. html.push('\n');
  7018. }*/
  7019. html.push('</', name, '>');
  7020. if (indent && indentAfter[name] && html.length > 0) {
  7021. value = html[html.length - 1];
  7022. if (value.length > 0 && value !== '\n') {
  7023. html.push('\n');
  7024. }
  7025. }
  7026. },
  7027. /**
  7028. * Writes a text node.
  7029. *
  7030. * @method text
  7031. * @param {String} text String to write out.
  7032. * @param {Boolean} raw Optional raw state if true the contents wont get encoded.
  7033. */
  7034. text: function(text, raw) {
  7035. if (text.length > 0) {
  7036. html[html.length] = raw ? text : encode(text);
  7037. }
  7038. },
  7039. /**
  7040. * Writes a cdata node such as <![CDATA[data]]>.
  7041. *
  7042. * @method cdata
  7043. * @param {String} text String to write out inside the cdata.
  7044. */
  7045. cdata: function(text) {
  7046. html.push('<![CDATA[', text, ']]>');
  7047. },
  7048. /**
  7049. * Writes a comment node such as <!-- Comment -->.
  7050. *
  7051. * @method cdata
  7052. * @param {String} text String to write out inside the comment.
  7053. */
  7054. comment: function(text) {
  7055. html.push('<!--', text, '-->');
  7056. },
  7057. /**
  7058. * Writes a PI node such as <?xml attr="value" ?>.
  7059. *
  7060. * @method pi
  7061. * @param {String} name Name of the pi.
  7062. * @param {String} text String to write out inside the pi.
  7063. */
  7064. pi: function(name, text) {
  7065. if (text) {
  7066. html.push('<?', name, ' ', text, '?>');
  7067. } else {
  7068. html.push('<?', name, '?>');
  7069. }
  7070. if (indent) {
  7071. html.push('\n');
  7072. }
  7073. },
  7074. /**
  7075. * Writes a doctype node such as <!DOCTYPE data>.
  7076. *
  7077. * @method doctype
  7078. * @param {String} text String to write out inside the doctype.
  7079. */
  7080. doctype: function(text) {
  7081. html.push('<!DOCTYPE', text, '>', indent ? '\n' : '');
  7082. },
  7083. /**
  7084. * Resets the internal buffer if one wants to reuse the writer.
  7085. *
  7086. * @method reset
  7087. */
  7088. reset: function() {
  7089. html.length = 0;
  7090. },
  7091. /**
  7092. * Returns the contents that got serialized.
  7093. *
  7094. * @method getContent
  7095. * @return {String} HTML contents that got written down.
  7096. */
  7097. getContent: function() {
  7098. return html.join('').replace(/\n$/, '');
  7099. }
  7100. };
  7101. };
  7102. });
  7103. // Included from: js/tinymce/classes/html/Serializer.js
  7104. /**
  7105. * Serializer.js
  7106. *
  7107. * Copyright, Moxiecode Systems AB
  7108. * Released under LGPL License.
  7109. *
  7110. * License: http://www.tinymce.com/license
  7111. * Contributing: http://www.tinymce.com/contributing
  7112. */
  7113. /**
  7114. * This class is used to serialize down the DOM tree into a string using a Writer instance.
  7115. *
  7116. *
  7117. * @example
  7118. * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
  7119. * @class tinymce.html.Serializer
  7120. * @version 3.4
  7121. */
  7122. define("tinymce/html/Serializer", [
  7123. "tinymce/html/Writer",
  7124. "tinymce/html/Schema"
  7125. ], function(Writer, Schema) {
  7126. /**
  7127. * Constructs a new Serializer instance.
  7128. *
  7129. * @constructor
  7130. * @method Serializer
  7131. * @param {Object} settings Name/value settings object.
  7132. * @param {tinymce.html.Schema} schema Schema instance to use.
  7133. */
  7134. return function(settings, schema) {
  7135. var self = this, writer = new Writer(settings);
  7136. settings = settings || {};
  7137. settings.validate = "validate" in settings ? settings.validate : true;
  7138. self.schema = schema = schema || new Schema();
  7139. self.writer = writer;
  7140. /**
  7141. * Serializes the specified node into a string.
  7142. *
  7143. * @example
  7144. * new tinymce.html.Serializer().serialize(new tinymce.html.DomParser().parse('<p>text</p>'));
  7145. * @method serialize
  7146. * @param {tinymce.html.Node} node Node instance to serialize.
  7147. * @return {String} String with HTML based on DOM tree.
  7148. */
  7149. self.serialize = function(node) {
  7150. var handlers, validate;
  7151. validate = settings.validate;
  7152. handlers = {
  7153. // #text
  7154. 3: function(node) {
  7155. writer.text(node.value, node.raw);
  7156. },
  7157. // #comment
  7158. 8: function(node) {
  7159. writer.comment(node.value);
  7160. },
  7161. // Processing instruction
  7162. 7: function(node) {
  7163. writer.pi(node.name, node.value);
  7164. },
  7165. // Doctype
  7166. 10: function(node) {
  7167. writer.doctype(node.value);
  7168. },
  7169. // CDATA
  7170. 4: function(node) {
  7171. writer.cdata(node.value);
  7172. },
  7173. // Document fragment
  7174. 11: function(node) {
  7175. if ((node = node.firstChild)) {
  7176. do {
  7177. walk(node);
  7178. } while ((node = node.next));
  7179. }
  7180. }
  7181. };
  7182. writer.reset();
  7183. function walk(node) {
  7184. var handler = handlers[node.type], name, isEmpty, attrs, attrName, attrValue, sortedAttrs, i, l, elementRule;
  7185. if (!handler) {
  7186. name = node.name;
  7187. isEmpty = node.shortEnded;
  7188. attrs = node.attributes;
  7189. // Sort attributes
  7190. if (validate && attrs && attrs.length > 1) {
  7191. sortedAttrs = [];
  7192. sortedAttrs.map = {};
  7193. elementRule = schema.getElementRule(node.name);
  7194. for (i = 0, l = elementRule.attributesOrder.length; i < l; i++) {
  7195. attrName = elementRule.attributesOrder[i];
  7196. if (attrName in attrs.map) {
  7197. attrValue = attrs.map[attrName];
  7198. sortedAttrs.map[attrName] = attrValue;
  7199. sortedAttrs.push({name: attrName, value: attrValue});
  7200. }
  7201. }
  7202. for (i = 0, l = attrs.length; i < l; i++) {
  7203. attrName = attrs[i].name;
  7204. if (!(attrName in sortedAttrs.map)) {
  7205. attrValue = attrs.map[attrName];
  7206. sortedAttrs.map[attrName] = attrValue;
  7207. sortedAttrs.push({name: attrName, value: attrValue});
  7208. }
  7209. }
  7210. attrs = sortedAttrs;
  7211. }
  7212. writer.start(node.name, attrs, isEmpty);
  7213. if (!isEmpty) {
  7214. if ((node = node.firstChild)) {
  7215. do {
  7216. walk(node);
  7217. } while ((node = node.next));
  7218. }
  7219. writer.end(name);
  7220. }
  7221. } else {
  7222. handler(node);
  7223. }
  7224. }
  7225. // Serialize element and treat all non elements as fragments
  7226. if (node.type == 1 && !settings.inner) {
  7227. walk(node);
  7228. } else {
  7229. handlers[11](node);
  7230. }
  7231. return writer.getContent();
  7232. };
  7233. };
  7234. });
  7235. // Included from: js/tinymce/classes/dom/Serializer.js
  7236. /**
  7237. * Serializer.js
  7238. *
  7239. * Copyright, Moxiecode Systems AB
  7240. * Released under LGPL License.
  7241. *
  7242. * License: http://www.tinymce.com/license
  7243. * Contributing: http://www.tinymce.com/contributing
  7244. */
  7245. /**
  7246. * This class is used to serialize DOM trees into a string. Consult the TinyMCE Wiki API for
  7247. * more details and examples on how to use this class.
  7248. *
  7249. * @class tinymce.dom.Serializer
  7250. */
  7251. define("tinymce/dom/Serializer", [
  7252. "tinymce/dom/DOMUtils",
  7253. "tinymce/html/DomParser",
  7254. "tinymce/html/Entities",
  7255. "tinymce/html/Serializer",
  7256. "tinymce/html/Node",
  7257. "tinymce/html/Schema",
  7258. "tinymce/Env",
  7259. "tinymce/util/Tools"
  7260. ], function(DOMUtils, DomParser, Entities, Serializer, Node, Schema, Env, Tools) {
  7261. var each = Tools.each, trim = Tools.trim;
  7262. var DOM = DOMUtils.DOM;
  7263. /**
  7264. * Constructs a new DOM serializer class.
  7265. *
  7266. * @constructor
  7267. * @method Serializer
  7268. * @param {Object} settings Serializer settings object.
  7269. * @param {tinymce.Editor} editor Optional editor to bind events to and get schema/dom from.
  7270. */
  7271. return function(settings, editor) {
  7272. var dom, schema, htmlParser;
  7273. if (editor) {
  7274. dom = editor.dom;
  7275. schema = editor.schema;
  7276. }
  7277. // Default DOM and Schema if they are undefined
  7278. dom = dom || DOM;
  7279. schema = schema || new Schema(settings);
  7280. settings.entity_encoding = settings.entity_encoding || 'named';
  7281. settings.remove_trailing_brs = "remove_trailing_brs" in settings ? settings.remove_trailing_brs : true;
  7282. htmlParser = new DomParser(settings, schema);
  7283. // Convert tabindex back to elements when serializing contents
  7284. htmlParser.addAttributeFilter('data-mce-tabindex', function(nodes, name) {
  7285. var i = nodes.length, node;
  7286. while (i--) {
  7287. node = nodes[i];
  7288. node.attr('tabindex', node.attributes.map['data-mce-tabindex']);
  7289. node.attr(name, null);
  7290. }
  7291. });
  7292. // Convert move data-mce-src, data-mce-href and data-mce-style into nodes or process them if needed
  7293. htmlParser.addAttributeFilter('src,href,style', function(nodes, name) {
  7294. var i = nodes.length, node, value, internalName = 'data-mce-' + name;
  7295. var urlConverter = settings.url_converter, urlConverterScope = settings.url_converter_scope, undef;
  7296. while (i--) {
  7297. node = nodes[i];
  7298. value = node.attributes.map[internalName];
  7299. if (value !== undef) {
  7300. // Set external name to internal value and remove internal
  7301. node.attr(name, value.length > 0 ? value : null);
  7302. node.attr(internalName, null);
  7303. } else {
  7304. // No internal attribute found then convert the value we have in the DOM
  7305. value = node.attributes.map[name];
  7306. if (name === "style") {
  7307. value = dom.serializeStyle(dom.parseStyle(value), node.name);
  7308. } else if (urlConverter) {
  7309. value = urlConverter.call(urlConverterScope, value, name, node.name);
  7310. }
  7311. node.attr(name, value.length > 0 ? value : null);
  7312. }
  7313. }
  7314. });
  7315. // Remove internal classes mceItem<..> or mceSelected
  7316. htmlParser.addAttributeFilter('class', function(nodes) {
  7317. var i = nodes.length, node, value;
  7318. while (i--) {
  7319. node = nodes[i];
  7320. value = node.attr('class').replace(/(?:^|\s)mce-item-\w+(?!\S)/g, '');
  7321. node.attr('class', value.length > 0 ? value : null);
  7322. }
  7323. });
  7324. // Remove bookmark elements
  7325. htmlParser.addAttributeFilter('data-mce-type', function(nodes, name, args) {
  7326. var i = nodes.length, node;
  7327. while (i--) {
  7328. node = nodes[i];
  7329. if (node.attributes.map['data-mce-type'] === 'bookmark' && !args.cleanup) {
  7330. node.remove();
  7331. }
  7332. }
  7333. });
  7334. // Remove expando attributes
  7335. htmlParser.addAttributeFilter('data-mce-expando', function(nodes, name) {
  7336. var i = nodes.length;
  7337. while (i--) {
  7338. nodes[i].attr(name, null);
  7339. }
  7340. });
  7341. htmlParser.addNodeFilter('noscript', function(nodes) {
  7342. var i = nodes.length, node;
  7343. while (i--) {
  7344. node = nodes[i].firstChild;
  7345. if (node) {
  7346. node.value = Entities.decode(node.value);
  7347. }
  7348. }
  7349. });
  7350. // Force script into CDATA sections and remove the mce- prefix also add comments around styles
  7351. htmlParser.addNodeFilter('script,style', function(nodes, name) {
  7352. var i = nodes.length, node, value;
  7353. function trim(value) {
  7354. /*jshint maxlen:255 */
  7355. /*eslint max-len:0 */
  7356. return value.replace(/(<!--\[CDATA\[|\]\]-->)/g, '\n')
  7357. .replace(/^[\r\n]*|[\r\n]*$/g, '')
  7358. .replace(/^\s*((<!--)?(\s*\/\/)?\s*<!\[CDATA\[|(<!--\s*)?\/\*\s*<!\[CDATA\[\s*\*\/|(\/\/)?\s*<!--|\/\*\s*<!--\s*\*\/)\s*[\r\n]*/gi, '')
  7359. .replace(/\s*(\/\*\s*\]\]>\s*\*\/(-->)?|\s*\/\/\s*\]\]>(-->)?|\/\/\s*(-->)?|\]\]>|\/\*\s*-->\s*\*\/|\s*-->\s*)\s*$/g, '');
  7360. }
  7361. while (i--) {
  7362. node = nodes[i];
  7363. value = node.firstChild ? node.firstChild.value : '';
  7364. if (name === "script") {
  7365. // Remove mce- prefix from script elements and remove default text/javascript mime type (HTML5)
  7366. var type = (node.attr('type') || 'text/javascript').replace(/^mce\-/, '');
  7367. node.attr('type', type === 'text/javascript' ? null : type);
  7368. if (value.length > 0) {
  7369. node.firstChild.value = '// <![CDATA[\n' + trim(value) + '\n// ]]>';
  7370. }
  7371. } else {
  7372. if (value.length > 0) {
  7373. node.firstChild.value = '<!--\n' + trim(value) + '\n-->';
  7374. }
  7375. }
  7376. }
  7377. });
  7378. // Convert comments to cdata and handle protected comments
  7379. htmlParser.addNodeFilter('#comment', function(nodes) {
  7380. var i = nodes.length, node;
  7381. while (i--) {
  7382. node = nodes[i];
  7383. if (node.value.indexOf('[CDATA[') === 0) {
  7384. node.name = '#cdata';
  7385. node.type = 4;
  7386. node.value = node.value.replace(/^\[CDATA\[|\]\]$/g, '');
  7387. } else if (node.value.indexOf('mce:protected ') === 0) {
  7388. node.name = "#text";
  7389. node.type = 3;
  7390. node.raw = true;
  7391. node.value = unescape(node.value).substr(14);
  7392. }
  7393. }
  7394. });
  7395. htmlParser.addNodeFilter('xml:namespace,input', function(nodes, name) {
  7396. var i = nodes.length, node;
  7397. while (i--) {
  7398. node = nodes[i];
  7399. if (node.type === 7) {
  7400. node.remove();
  7401. } else if (node.type === 1) {
  7402. if (name === "input" && !("type" in node.attributes.map)) {
  7403. node.attr('type', 'text');
  7404. }
  7405. }
  7406. }
  7407. });
  7408. // Fix list elements, TODO: Replace this later
  7409. if (settings.fix_list_elements) {
  7410. htmlParser.addNodeFilter('ul,ol', function(nodes) {
  7411. var i = nodes.length, node, parentNode;
  7412. while (i--) {
  7413. node = nodes[i];
  7414. parentNode = node.parent;
  7415. if (parentNode.name === 'ul' || parentNode.name === 'ol') {
  7416. if (node.prev && node.prev.name === 'li') {
  7417. node.prev.append(node);
  7418. }
  7419. }
  7420. }
  7421. });
  7422. }
  7423. // Remove internal data attributes
  7424. htmlParser.addAttributeFilter('data-mce-src,data-mce-href,data-mce-style,data-mce-selected', function(nodes, name) {
  7425. var i = nodes.length;
  7426. while (i--) {
  7427. nodes[i].attr(name, null);
  7428. }
  7429. });
  7430. // Return public methods
  7431. return {
  7432. /**
  7433. * Schema instance that was used to when the Serializer was constructed.
  7434. *
  7435. * @field {tinymce.html.Schema} schema
  7436. */
  7437. schema: schema,
  7438. /**
  7439. * Adds a node filter function to the parser used by the serializer, the parser will collect the specified nodes by name
  7440. * and then execute the callback ones it has finished parsing the document.
  7441. *
  7442. * @example
  7443. * parser.addNodeFilter('p,h1', function(nodes, name) {
  7444. * for (var i = 0; i < nodes.length; i++) {
  7445. * console.log(nodes[i].name);
  7446. * }
  7447. * });
  7448. * @method addNodeFilter
  7449. * @method {String} name Comma separated list of nodes to collect.
  7450. * @param {function} callback Callback function to execute once it has collected nodes.
  7451. */
  7452. addNodeFilter: htmlParser.addNodeFilter,
  7453. /**
  7454. * Adds a attribute filter function to the parser used by the serializer, the parser will
  7455. * collect nodes that has the specified attributes
  7456. * and then execute the callback ones it has finished parsing the document.
  7457. *
  7458. * @example
  7459. * parser.addAttributeFilter('src,href', function(nodes, name) {
  7460. * for (var i = 0; i < nodes.length; i++) {
  7461. * console.log(nodes[i].name);
  7462. * }
  7463. * });
  7464. * @method addAttributeFilter
  7465. * @method {String} name Comma separated list of nodes to collect.
  7466. * @param {function} callback Callback function to execute once it has collected nodes.
  7467. */
  7468. addAttributeFilter: htmlParser.addAttributeFilter,
  7469. /**
  7470. * Serializes the specified browser DOM node into a HTML string.
  7471. *
  7472. * @method serialize
  7473. * @param {DOMNode} node DOM node to serialize.
  7474. * @param {Object} args Arguments option that gets passed to event handlers.
  7475. */
  7476. serialize: function(node, args) {
  7477. var self = this, impl, doc, oldDoc, htmlSerializer, content;
  7478. // Explorer won't clone contents of script and style and the
  7479. // selected index of select elements are cleared on a clone operation.
  7480. if (Env.ie && dom.select('script,style,select,map').length > 0) {
  7481. content = node.innerHTML;
  7482. node = node.cloneNode(false);
  7483. dom.setHTML(node, content);
  7484. } else {
  7485. node = node.cloneNode(true);
  7486. }
  7487. // Nodes needs to be attached to something in WebKit/Opera
  7488. // This fix will make DOM ranges and make Sizzle happy!
  7489. impl = node.ownerDocument.implementation;
  7490. if (impl.createHTMLDocument) {
  7491. // Create an empty HTML document
  7492. doc = impl.createHTMLDocument("");
  7493. // Add the element or it's children if it's a body element to the new document
  7494. each(node.nodeName == 'BODY' ? node.childNodes : [node], function(node) {
  7495. doc.body.appendChild(doc.importNode(node, true));
  7496. });
  7497. // Grab first child or body element for serialization
  7498. if (node.nodeName != 'BODY') {
  7499. node = doc.body.firstChild;
  7500. } else {
  7501. node = doc.body;
  7502. }
  7503. // set the new document in DOMUtils so createElement etc works
  7504. oldDoc = dom.doc;
  7505. dom.doc = doc;
  7506. }
  7507. args = args || {};
  7508. args.format = args.format || 'html';
  7509. // Don't wrap content if we want selected html
  7510. if (args.selection) {
  7511. args.forced_root_block = '';
  7512. }
  7513. // Pre process
  7514. if (!args.no_events) {
  7515. args.node = node;
  7516. self.onPreProcess(args);
  7517. }
  7518. // Setup serializer
  7519. htmlSerializer = new Serializer(settings, schema);
  7520. // Parse and serialize HTML
  7521. args.content = htmlSerializer.serialize(
  7522. htmlParser.parse(trim(args.getInner ? node.innerHTML : dom.getOuterHTML(node)), args)
  7523. );
  7524. // Replace all BOM characters for now until we can find a better solution
  7525. if (!args.cleanup) {
  7526. args.content = args.content.replace(/\uFEFF/g, '');
  7527. }
  7528. // Post process
  7529. if (!args.no_events) {
  7530. self.onPostProcess(args);
  7531. }
  7532. // Restore the old document if it was changed
  7533. if (oldDoc) {
  7534. dom.doc = oldDoc;
  7535. }
  7536. args.node = null;
  7537. return args.content;
  7538. },
  7539. /**
  7540. * Adds valid elements rules to the serializers schema instance this enables you to specify things
  7541. * like what elements should be outputted and what attributes specific elements might have.
  7542. * Consult the Wiki for more details on this format.
  7543. *
  7544. * @method addRules
  7545. * @param {String} rules Valid elements rules string to add to schema.
  7546. */
  7547. addRules: function(rules) {
  7548. schema.addValidElements(rules);
  7549. },
  7550. /**
  7551. * Sets the valid elements rules to the serializers schema instance this enables you to specify things
  7552. * like what elements should be outputted and what attributes specific elements might have.
  7553. * Consult the Wiki for more details on this format.
  7554. *
  7555. * @method setRules
  7556. * @param {String} rules Valid elements rules string.
  7557. */
  7558. setRules: function(rules) {
  7559. schema.setValidElements(rules);
  7560. },
  7561. onPreProcess: function(args) {
  7562. if (editor) {
  7563. editor.fire('PreProcess', args);
  7564. }
  7565. },
  7566. onPostProcess: function(args) {
  7567. if (editor) {
  7568. editor.fire('PostProcess', args);
  7569. }
  7570. }
  7571. };
  7572. };
  7573. });
  7574. // Included from: js/tinymce/classes/dom/TridentSelection.js
  7575. /**
  7576. * TridentSelection.js
  7577. *
  7578. * Copyright, Moxiecode Systems AB
  7579. * Released under LGPL License.
  7580. *
  7581. * License: http://www.tinymce.com/license
  7582. * Contributing: http://www.tinymce.com/contributing
  7583. */
  7584. /**
  7585. * Selection class for old explorer versions. This one fakes the
  7586. * native selection object available on modern browsers.
  7587. *
  7588. * @class tinymce.dom.TridentSelection
  7589. */
  7590. define("tinymce/dom/TridentSelection", [], function() {
  7591. function Selection(selection) {
  7592. var self = this, dom = selection.dom, FALSE = false;
  7593. function getPosition(rng, start) {
  7594. var checkRng, startIndex = 0, endIndex, inside,
  7595. children, child, offset, index, position = -1, parent;
  7596. // Setup test range, collapse it and get the parent
  7597. checkRng = rng.duplicate();
  7598. checkRng.collapse(start);
  7599. parent = checkRng.parentElement();
  7600. // Check if the selection is within the right document
  7601. if (parent.ownerDocument !== selection.dom.doc) {
  7602. return;
  7603. }
  7604. // IE will report non editable elements as it's parent so look for an editable one
  7605. while (parent.contentEditable === "false") {
  7606. parent = parent.parentNode;
  7607. }
  7608. // If parent doesn't have any children then return that we are inside the element
  7609. if (!parent.hasChildNodes()) {
  7610. return {node: parent, inside: 1};
  7611. }
  7612. // Setup node list and endIndex
  7613. children = parent.children;
  7614. endIndex = children.length - 1;
  7615. // Perform a binary search for the position
  7616. while (startIndex <= endIndex) {
  7617. index = Math.floor((startIndex + endIndex) / 2);
  7618. // Move selection to node and compare the ranges
  7619. child = children[index];
  7620. checkRng.moveToElementText(child);
  7621. position = checkRng.compareEndPoints(start ? 'StartToStart' : 'EndToEnd', rng);
  7622. // Before/after or an exact match
  7623. if (position > 0) {
  7624. endIndex = index - 1;
  7625. } else if (position < 0) {
  7626. startIndex = index + 1;
  7627. } else {
  7628. return {node: child};
  7629. }
  7630. }
  7631. // Check if child position is before or we didn't find a position
  7632. if (position < 0) {
  7633. // No element child was found use the parent element and the offset inside that
  7634. if (!child) {
  7635. checkRng.moveToElementText(parent);
  7636. checkRng.collapse(true);
  7637. child = parent;
  7638. inside = true;
  7639. } else {
  7640. checkRng.collapse(false);
  7641. }
  7642. // Walk character by character in text node until we hit the selected range endpoint,
  7643. // hit the end of document or parent isn't the right one
  7644. // We need to walk char by char since rng.text or rng.htmlText will trim line endings
  7645. offset = 0;
  7646. while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) {
  7647. if (checkRng.move('character', 1) === 0 || parent != checkRng.parentElement()) {
  7648. break;
  7649. }
  7650. offset++;
  7651. }
  7652. } else {
  7653. // Child position is after the selection endpoint
  7654. checkRng.collapse(true);
  7655. // Walk character by character in text node until we hit the selected range endpoint, hit
  7656. // the end of document or parent isn't the right one
  7657. offset = 0;
  7658. while (checkRng.compareEndPoints(start ? 'StartToStart' : 'StartToEnd', rng) !== 0) {
  7659. if (checkRng.move('character', -1) === 0 || parent != checkRng.parentElement()) {
  7660. break;
  7661. }
  7662. offset++;
  7663. }
  7664. }
  7665. return {node: child, position: position, offset: offset, inside: inside};
  7666. }
  7667. // Returns a W3C DOM compatible range object by using the IE Range API
  7668. function getRange() {
  7669. var ieRange = selection.getRng(), domRange = dom.createRng(), element, collapsed, tmpRange, element2, bookmark;
  7670. // If selection is outside the current document just return an empty range
  7671. element = ieRange.item ? ieRange.item(0) : ieRange.parentElement();
  7672. if (element.ownerDocument != dom.doc) {
  7673. return domRange;
  7674. }
  7675. collapsed = selection.isCollapsed();
  7676. // Handle control selection
  7677. if (ieRange.item) {
  7678. domRange.setStart(element.parentNode, dom.nodeIndex(element));
  7679. domRange.setEnd(domRange.startContainer, domRange.startOffset + 1);
  7680. return domRange;
  7681. }
  7682. function findEndPoint(start) {
  7683. var endPoint = getPosition(ieRange, start), container, offset, textNodeOffset = 0, sibling, undef, nodeValue;
  7684. container = endPoint.node;
  7685. offset = endPoint.offset;
  7686. if (endPoint.inside && !container.hasChildNodes()) {
  7687. domRange[start ? 'setStart' : 'setEnd'](container, 0);
  7688. return;
  7689. }
  7690. if (offset === undef) {
  7691. domRange[start ? 'setStartBefore' : 'setEndAfter'](container);
  7692. return;
  7693. }
  7694. if (endPoint.position < 0) {
  7695. sibling = endPoint.inside ? container.firstChild : container.nextSibling;
  7696. if (!sibling) {
  7697. domRange[start ? 'setStartAfter' : 'setEndAfter'](container);
  7698. return;
  7699. }
  7700. if (!offset) {
  7701. if (sibling.nodeType == 3) {
  7702. domRange[start ? 'setStart' : 'setEnd'](sibling, 0);
  7703. } else {
  7704. domRange[start ? 'setStartBefore' : 'setEndBefore'](sibling);
  7705. }
  7706. return;
  7707. }
  7708. // Find the text node and offset
  7709. while (sibling) {
  7710. nodeValue = sibling.nodeValue;
  7711. textNodeOffset += nodeValue.length;
  7712. // We are at or passed the position we where looking for
  7713. if (textNodeOffset >= offset) {
  7714. container = sibling;
  7715. textNodeOffset -= offset;
  7716. textNodeOffset = nodeValue.length - textNodeOffset;
  7717. break;
  7718. }
  7719. sibling = sibling.nextSibling;
  7720. }
  7721. } else {
  7722. // Find the text node and offset
  7723. sibling = container.previousSibling;
  7724. if (!sibling) {
  7725. return domRange[start ? 'setStartBefore' : 'setEndBefore'](container);
  7726. }
  7727. // If there isn't any text to loop then use the first position
  7728. if (!offset) {
  7729. if (container.nodeType == 3) {
  7730. domRange[start ? 'setStart' : 'setEnd'](sibling, container.nodeValue.length);
  7731. } else {
  7732. domRange[start ? 'setStartAfter' : 'setEndAfter'](sibling);
  7733. }
  7734. return;
  7735. }
  7736. while (sibling) {
  7737. textNodeOffset += sibling.nodeValue.length;
  7738. // We are at or passed the position we where looking for
  7739. if (textNodeOffset >= offset) {
  7740. container = sibling;
  7741. textNodeOffset -= offset;
  7742. break;
  7743. }
  7744. sibling = sibling.previousSibling;
  7745. }
  7746. }
  7747. domRange[start ? 'setStart' : 'setEnd'](container, textNodeOffset);
  7748. }
  7749. try {
  7750. // Find start point
  7751. findEndPoint(true);
  7752. // Find end point if needed
  7753. if (!collapsed) {
  7754. findEndPoint();
  7755. }
  7756. } catch (ex) {
  7757. // IE has a nasty bug where text nodes might throw "invalid argument" when you
  7758. // access the nodeValue or other properties of text nodes. This seems to happend when
  7759. // text nodes are split into two nodes by a delete/backspace call. So lets detect it and try to fix it.
  7760. if (ex.number == -2147024809) {
  7761. // Get the current selection
  7762. bookmark = self.getBookmark(2);
  7763. // Get start element
  7764. tmpRange = ieRange.duplicate();
  7765. tmpRange.collapse(true);
  7766. element = tmpRange.parentElement();
  7767. // Get end element
  7768. if (!collapsed) {
  7769. tmpRange = ieRange.duplicate();
  7770. tmpRange.collapse(false);
  7771. element2 = tmpRange.parentElement();
  7772. element2.innerHTML = element2.innerHTML;
  7773. }
  7774. // Remove the broken elements
  7775. element.innerHTML = element.innerHTML;
  7776. // Restore the selection
  7777. self.moveToBookmark(bookmark);
  7778. // Since the range has moved we need to re-get it
  7779. ieRange = selection.getRng();
  7780. // Find start point
  7781. findEndPoint(true);
  7782. // Find end point if needed
  7783. if (!collapsed) {
  7784. findEndPoint();
  7785. }
  7786. } else {
  7787. throw ex; // Throw other errors
  7788. }
  7789. }
  7790. return domRange;
  7791. }
  7792. this.getBookmark = function(type) {
  7793. var rng = selection.getRng(), bookmark = {};
  7794. function getIndexes(node) {
  7795. var parent, root, children, i, indexes = [];
  7796. parent = node.parentNode;
  7797. root = dom.getRoot().parentNode;
  7798. while (parent != root && parent.nodeType !== 9) {
  7799. children = parent.children;
  7800. i = children.length;
  7801. while (i--) {
  7802. if (node === children[i]) {
  7803. indexes.push(i);
  7804. break;
  7805. }
  7806. }
  7807. node = parent;
  7808. parent = parent.parentNode;
  7809. }
  7810. return indexes;
  7811. }
  7812. function getBookmarkEndPoint(start) {
  7813. var position;
  7814. position = getPosition(rng, start);
  7815. if (position) {
  7816. return {
  7817. position: position.position,
  7818. offset: position.offset,
  7819. indexes: getIndexes(position.node),
  7820. inside: position.inside
  7821. };
  7822. }
  7823. }
  7824. // Non ubstructive bookmark
  7825. if (type === 2) {
  7826. // Handle text selection
  7827. if (!rng.item) {
  7828. bookmark.start = getBookmarkEndPoint(true);
  7829. if (!selection.isCollapsed()) {
  7830. bookmark.end = getBookmarkEndPoint();
  7831. }
  7832. } else {
  7833. bookmark.start = {ctrl: true, indexes: getIndexes(rng.item(0))};
  7834. }
  7835. }
  7836. return bookmark;
  7837. };
  7838. this.moveToBookmark = function(bookmark) {
  7839. var rng, body = dom.doc.body;
  7840. function resolveIndexes(indexes) {
  7841. var node, i, idx, children;
  7842. node = dom.getRoot();
  7843. for (i = indexes.length - 1; i >= 0; i--) {
  7844. children = node.children;
  7845. idx = indexes[i];
  7846. if (idx <= children.length - 1) {
  7847. node = children[idx];
  7848. }
  7849. }
  7850. return node;
  7851. }
  7852. function setBookmarkEndPoint(start) {
  7853. var endPoint = bookmark[start ? 'start' : 'end'], moveLeft, moveRng, undef, offset;
  7854. if (endPoint) {
  7855. moveLeft = endPoint.position > 0;
  7856. moveRng = body.createTextRange();
  7857. moveRng.moveToElementText(resolveIndexes(endPoint.indexes));
  7858. offset = endPoint.offset;
  7859. if (offset !== undef) {
  7860. moveRng.collapse(endPoint.inside || moveLeft);
  7861. moveRng.moveStart('character', moveLeft ? -offset : offset);
  7862. } else {
  7863. moveRng.collapse(start);
  7864. }
  7865. rng.setEndPoint(start ? 'StartToStart' : 'EndToStart', moveRng);
  7866. if (start) {
  7867. rng.collapse(true);
  7868. }
  7869. }
  7870. }
  7871. if (bookmark.start) {
  7872. if (bookmark.start.ctrl) {
  7873. rng = body.createControlRange();
  7874. rng.addElement(resolveIndexes(bookmark.start.indexes));
  7875. rng.select();
  7876. } else {
  7877. rng = body.createTextRange();
  7878. setBookmarkEndPoint(true);
  7879. setBookmarkEndPoint();
  7880. rng.select();
  7881. }
  7882. }
  7883. };
  7884. this.addRange = function(rng) {
  7885. var ieRng, ctrlRng, startContainer, startOffset, endContainer, endOffset, sibling,
  7886. doc = selection.dom.doc, body = doc.body, nativeRng, ctrlElm;
  7887. function setEndPoint(start) {
  7888. var container, offset, marker, tmpRng, nodes;
  7889. marker = dom.create('a');
  7890. container = start ? startContainer : endContainer;
  7891. offset = start ? startOffset : endOffset;
  7892. tmpRng = ieRng.duplicate();
  7893. if (container == doc || container == doc.documentElement) {
  7894. container = body;
  7895. offset = 0;
  7896. }
  7897. if (container.nodeType == 3) {
  7898. container.parentNode.insertBefore(marker, container);
  7899. tmpRng.moveToElementText(marker);
  7900. tmpRng.moveStart('character', offset);
  7901. dom.remove(marker);
  7902. ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
  7903. } else {
  7904. nodes = container.childNodes;
  7905. if (nodes.length) {
  7906. if (offset >= nodes.length) {
  7907. dom.insertAfter(marker, nodes[nodes.length - 1]);
  7908. } else {
  7909. container.insertBefore(marker, nodes[offset]);
  7910. }
  7911. tmpRng.moveToElementText(marker);
  7912. } else if (container.canHaveHTML) {
  7913. // Empty node selection for example <div>|</div>
  7914. // Setting innerHTML with a span marker then remove that marker seems to keep empty block elements open
  7915. container.innerHTML = '<span>&#xFEFF;</span>';
  7916. marker = container.firstChild;
  7917. tmpRng.moveToElementText(marker);
  7918. tmpRng.collapse(FALSE); // Collapse false works better than true for some odd reason
  7919. }
  7920. ieRng.setEndPoint(start ? 'StartToStart' : 'EndToEnd', tmpRng);
  7921. dom.remove(marker);
  7922. }
  7923. }
  7924. // Setup some shorter versions
  7925. startContainer = rng.startContainer;
  7926. startOffset = rng.startOffset;
  7927. endContainer = rng.endContainer;
  7928. endOffset = rng.endOffset;
  7929. ieRng = body.createTextRange();
  7930. // If single element selection then try making a control selection out of it
  7931. if (startContainer == endContainer && startContainer.nodeType == 1) {
  7932. // Trick to place the caret inside an empty block element like <p></p>
  7933. if (startOffset == endOffset && !startContainer.hasChildNodes()) {
  7934. if (startContainer.canHaveHTML) {
  7935. // Check if previous sibling is an empty block if it is then we need to render it
  7936. // IE would otherwise move the caret into the sibling instead of the empty startContainer see: #5236
  7937. // Example this: <p></p><p>|</p> would become this: <p>|</p><p></p>
  7938. sibling = startContainer.previousSibling;
  7939. if (sibling && !sibling.hasChildNodes() && dom.isBlock(sibling)) {
  7940. sibling.innerHTML = '&#xFEFF;';
  7941. } else {
  7942. sibling = null;
  7943. }
  7944. startContainer.innerHTML = '<span>&#xFEFF;</span><span>&#xFEFF;</span>';
  7945. ieRng.moveToElementText(startContainer.lastChild);
  7946. ieRng.select();
  7947. dom.doc.selection.clear();
  7948. startContainer.innerHTML = '';
  7949. if (sibling) {
  7950. sibling.innerHTML = '';
  7951. }
  7952. return;
  7953. } else {
  7954. startOffset = dom.nodeIndex(startContainer);
  7955. startContainer = startContainer.parentNode;
  7956. }
  7957. }
  7958. if (startOffset == endOffset - 1) {
  7959. try {
  7960. ctrlElm = startContainer.childNodes[startOffset];
  7961. ctrlRng = body.createControlRange();
  7962. ctrlRng.addElement(ctrlElm);
  7963. ctrlRng.select();
  7964. // Check if the range produced is on the correct element and is a control range
  7965. // On IE 8 it will select the parent contentEditable container if you select an inner element see: #5398
  7966. nativeRng = selection.getRng();
  7967. if (nativeRng.item && ctrlElm === nativeRng.item(0)) {
  7968. return;
  7969. }
  7970. } catch (ex) {
  7971. // Ignore
  7972. }
  7973. }
  7974. }
  7975. // Set start/end point of selection
  7976. setEndPoint(true);
  7977. setEndPoint();
  7978. // Select the new range and scroll it into view
  7979. ieRng.select();
  7980. };
  7981. // Expose range method
  7982. this.getRangeAt = getRange;
  7983. }
  7984. return Selection;
  7985. });
  7986. // Included from: js/tinymce/classes/util/VK.js
  7987. /**
  7988. * VK.js
  7989. *
  7990. * Copyright, Moxiecode Systems AB
  7991. * Released under LGPL License.
  7992. *
  7993. * License: http://www.tinymce.com/license
  7994. * Contributing: http://www.tinymce.com/contributing
  7995. */
  7996. /**
  7997. * This file exposes a set of the common KeyCodes for use. Please grow it as needed.
  7998. */
  7999. define("tinymce/util/VK", [
  8000. "tinymce/Env"
  8001. ], function(Env) {
  8002. return {
  8003. BACKSPACE: 8,
  8004. DELETE: 46,
  8005. DOWN: 40,
  8006. ENTER: 13,
  8007. LEFT: 37,
  8008. RIGHT: 39,
  8009. SPACEBAR: 32,
  8010. TAB: 9,
  8011. UP: 38,
  8012. modifierPressed: function(e) {
  8013. return e.shiftKey || e.ctrlKey || e.altKey;
  8014. },
  8015. metaKeyPressed: function(e) {
  8016. // Check if ctrl or meta key is pressed also check if alt is false for Polish users
  8017. return (Env.mac ? e.metaKey : e.ctrlKey) && !e.altKey;
  8018. }
  8019. };
  8020. });
  8021. // Included from: js/tinymce/classes/dom/ControlSelection.js
  8022. /**
  8023. * ControlSelection.js
  8024. *
  8025. * Copyright, Moxiecode Systems AB
  8026. * Released under LGPL License.
  8027. *
  8028. * License: http://www.tinymce.com/license
  8029. * Contributing: http://www.tinymce.com/contributing
  8030. */
  8031. /**
  8032. * This class handles control selection of elements. Controls are elements
  8033. * that can be resized and needs to be selected as a whole. It adds custom resize handles
  8034. * to all browser engines that support properly disabling the built in resize logic.
  8035. *
  8036. * @class tinymce.dom.ControlSelection
  8037. */
  8038. define("tinymce/dom/ControlSelection", [
  8039. "tinymce/util/VK",
  8040. "tinymce/util/Tools",
  8041. "tinymce/Env"
  8042. ], function(VK, Tools, Env) {
  8043. return function(selection, editor) {
  8044. var dom = editor.dom, each = Tools.each;
  8045. var selectedElm, selectedElmGhost, resizeHandles, selectedHandle, lastMouseDownEvent;
  8046. var startX, startY, selectedElmX, selectedElmY, startW, startH, ratio, resizeStarted;
  8047. var width, height, editableDoc = editor.getDoc(), rootDocument = document, isIE = Env.ie && Env.ie < 11;
  8048. // Details about each resize handle how to scale etc
  8049. resizeHandles = {
  8050. // Name: x multiplier, y multiplier, delta size x, delta size y
  8051. n: [0.5, 0, 0, -1],
  8052. e: [1, 0.5, 1, 0],
  8053. s: [0.5, 1, 0, 1],
  8054. w: [0, 0.5, -1, 0],
  8055. nw: [0, 0, -1, -1],
  8056. ne: [1, 0, 1, -1],
  8057. se: [1, 1, 1, 1],
  8058. sw: [0, 1, -1, 1]
  8059. };
  8060. // Add CSS for resize handles, cloned element and selected
  8061. var rootClass = '.mce-content-body';
  8062. editor.contentStyles.push(
  8063. rootClass + ' div.mce-resizehandle {' +
  8064. 'position: absolute;' +
  8065. 'border: 1px solid black;' +
  8066. 'background: #FFF;' +
  8067. 'width: 5px;' +
  8068. 'height: 5px;' +
  8069. 'z-index: 10000' +
  8070. '}' +
  8071. rootClass + ' .mce-resizehandle:hover {' +
  8072. 'background: #000' +
  8073. '}' +
  8074. rootClass + ' img[data-mce-selected], hr[data-mce-selected] {' +
  8075. 'outline: 1px solid black;' +
  8076. 'resize: none' + // Have been talks about implementing this in browsers
  8077. '}' +
  8078. rootClass + ' .mce-clonedresizable {' +
  8079. 'position: absolute;' +
  8080. (Env.gecko ? '' : 'outline: 1px dashed black;') + // Gecko produces trails while resizing
  8081. 'opacity: .5;' +
  8082. 'filter: alpha(opacity=50);' +
  8083. 'z-index: 10000' +
  8084. '}'
  8085. );
  8086. function isResizable(elm) {
  8087. var selector = editor.settings.object_resizing;
  8088. if (selector === false || Env.iOS) {
  8089. return false;
  8090. }
  8091. if (typeof selector != 'string') {
  8092. selector = 'table,img,div';
  8093. }
  8094. if (elm.getAttribute('data-mce-resize') === 'false') {
  8095. return false;
  8096. }
  8097. return editor.dom.is(elm, selector);
  8098. }
  8099. function resizeGhostElement(e) {
  8100. var deltaX, deltaY;
  8101. // Calc new width/height
  8102. deltaX = e.screenX - startX;
  8103. deltaY = e.screenY - startY;
  8104. // Calc new size
  8105. width = deltaX * selectedHandle[2] + startW;
  8106. height = deltaY * selectedHandle[3] + startH;
  8107. // Never scale down lower than 5 pixels
  8108. width = width < 5 ? 5 : width;
  8109. height = height < 5 ? 5 : height;
  8110. // Constrain proportions when modifier key is pressed or if the nw, ne, sw, se corners are moved on an image
  8111. if (VK.modifierPressed(e) || (selectedElm.nodeName == "IMG" && selectedHandle[2] * selectedHandle[3] !== 0)) {
  8112. width = Math.round(height / ratio);
  8113. height = Math.round(width * ratio);
  8114. }
  8115. // Update ghost size
  8116. dom.setStyles(selectedElmGhost, {
  8117. width: width,
  8118. height: height
  8119. });
  8120. // Update ghost X position if needed
  8121. if (selectedHandle[2] < 0 && selectedElmGhost.clientWidth <= width) {
  8122. dom.setStyle(selectedElmGhost, 'left', selectedElmX + (startW - width));
  8123. }
  8124. // Update ghost Y position if needed
  8125. if (selectedHandle[3] < 0 && selectedElmGhost.clientHeight <= height) {
  8126. dom.setStyle(selectedElmGhost, 'top', selectedElmY + (startH - height));
  8127. }
  8128. if (!resizeStarted) {
  8129. editor.fire('ObjectResizeStart', {target: selectedElm, width: startW, height: startH});
  8130. resizeStarted = true;
  8131. }
  8132. }
  8133. function endGhostResize() {
  8134. resizeStarted = false;
  8135. function setSizeProp(name, value) {
  8136. if (value) {
  8137. // Resize by using style or attribute
  8138. if (selectedElm.style[name] || !editor.schema.isValid(selectedElm.nodeName.toLowerCase(), name)) {
  8139. dom.setStyle(selectedElm, name, value);
  8140. } else {
  8141. dom.setAttrib(selectedElm, name, value);
  8142. }
  8143. }
  8144. }
  8145. // Set width/height properties
  8146. setSizeProp('width', width);
  8147. setSizeProp('height', height);
  8148. dom.unbind(editableDoc, 'mousemove', resizeGhostElement);
  8149. dom.unbind(editableDoc, 'mouseup', endGhostResize);
  8150. if (rootDocument != editableDoc) {
  8151. dom.unbind(rootDocument, 'mousemove', resizeGhostElement);
  8152. dom.unbind(rootDocument, 'mouseup', endGhostResize);
  8153. }
  8154. // Remove ghost and update resize handle positions
  8155. dom.remove(selectedElmGhost);
  8156. if (!isIE || selectedElm.nodeName == "TABLE") {
  8157. showResizeRect(selectedElm);
  8158. }
  8159. editor.fire('ObjectResized', {target: selectedElm, width: width, height: height});
  8160. editor.nodeChanged();
  8161. }
  8162. function showResizeRect(targetElm, mouseDownHandleName, mouseDownEvent) {
  8163. var position, targetWidth, targetHeight, e, rect, offsetParent = editor.getBody();
  8164. unbindResizeHandleEvents();
  8165. // Get position and size of target
  8166. position = dom.getPos(targetElm, offsetParent);
  8167. selectedElmX = position.x;
  8168. selectedElmY = position.y;
  8169. rect = targetElm.getBoundingClientRect(); // Fix for Gecko offsetHeight for table with caption
  8170. targetWidth = rect.width || (rect.right - rect.left);
  8171. targetHeight = rect.height || (rect.bottom - rect.top);
  8172. // Reset width/height if user selects a new image/table
  8173. if (selectedElm != targetElm) {
  8174. detachResizeStartListener();
  8175. selectedElm = targetElm;
  8176. width = height = 0;
  8177. }
  8178. // Makes it possible to disable resizing
  8179. e = editor.fire('ObjectSelected', {target: targetElm});
  8180. if (isResizable(targetElm) && !e.isDefaultPrevented()) {
  8181. each(resizeHandles, function(handle, name) {
  8182. var handleElm, handlerContainerElm;
  8183. function startDrag(e) {
  8184. startX = e.screenX;
  8185. startY = e.screenY;
  8186. startW = selectedElm.clientWidth;
  8187. startH = selectedElm.clientHeight;
  8188. ratio = startH / startW;
  8189. selectedHandle = handle;
  8190. selectedElmGhost = selectedElm.cloneNode(true);
  8191. dom.addClass(selectedElmGhost, 'mce-clonedresizable');
  8192. selectedElmGhost.contentEditable = false; // Hides IE move layer cursor
  8193. selectedElmGhost.unSelectabe = true;
  8194. dom.setStyles(selectedElmGhost, {
  8195. left: selectedElmX,
  8196. top: selectedElmY,
  8197. margin: 0
  8198. });
  8199. selectedElmGhost.removeAttribute('data-mce-selected');
  8200. editor.getBody().appendChild(selectedElmGhost);
  8201. dom.bind(editableDoc, 'mousemove', resizeGhostElement);
  8202. dom.bind(editableDoc, 'mouseup', endGhostResize);
  8203. if (rootDocument != editableDoc) {
  8204. dom.bind(rootDocument, 'mousemove', resizeGhostElement);
  8205. dom.bind(rootDocument, 'mouseup', endGhostResize);
  8206. }
  8207. }
  8208. if (mouseDownHandleName) {
  8209. // Drag started by IE native resizestart
  8210. if (name == mouseDownHandleName) {
  8211. startDrag(mouseDownEvent);
  8212. }
  8213. return;
  8214. }
  8215. // Get existing or render resize handle
  8216. handleElm = dom.get('mceResizeHandle' + name);
  8217. if (!handleElm) {
  8218. handlerContainerElm = editor.getBody();
  8219. handleElm = dom.add(handlerContainerElm, 'div', {
  8220. id: 'mceResizeHandle' + name,
  8221. 'data-mce-bogus': true,
  8222. 'class': 'mce-resizehandle',
  8223. unselectable: true,
  8224. style: 'cursor:' + name + '-resize; margin:0; padding:0'
  8225. });
  8226. // Hides IE move layer cursor
  8227. // If we set it on Chrome we get this wounderful bug: #6725
  8228. if (Env.ie) {
  8229. handleElm.contentEditable = false;
  8230. }
  8231. } else {
  8232. dom.show(handleElm);
  8233. }
  8234. if (!handle.elm) {
  8235. dom.bind(handleElm, 'mousedown', function(e) {
  8236. e.stopImmediatePropagation();
  8237. e.preventDefault();
  8238. startDrag(e);
  8239. });
  8240. handle.elm = handleElm;
  8241. }
  8242. /*
  8243. var halfHandleW = handleElm.offsetWidth / 2;
  8244. var halfHandleH = handleElm.offsetHeight / 2;
  8245. // Position element
  8246. dom.setStyles(handleElm, {
  8247. left: Math.floor((targetWidth * handle[0] + selectedElmX) - halfHandleW + (handle[2] * halfHandleW)),
  8248. top: Math.floor((targetHeight * handle[1] + selectedElmY) - halfHandleH + (handle[3] * halfHandleH))
  8249. });
  8250. */
  8251. // Position element
  8252. dom.setStyles(handleElm, {
  8253. left: (targetWidth * handle[0] + selectedElmX) - (handleElm.offsetWidth / 2),
  8254. top: (targetHeight * handle[1] + selectedElmY) - (handleElm.offsetHeight / 2)
  8255. });
  8256. });
  8257. } else {
  8258. hideResizeRect();
  8259. }
  8260. selectedElm.setAttribute('data-mce-selected', '1');
  8261. }
  8262. function hideResizeRect() {
  8263. var name, handleElm;
  8264. unbindResizeHandleEvents();
  8265. if (selectedElm) {
  8266. selectedElm.removeAttribute('data-mce-selected');
  8267. }
  8268. for (name in resizeHandles) {
  8269. handleElm = dom.get('mceResizeHandle' + name);
  8270. if (handleElm) {
  8271. dom.unbind(handleElm);
  8272. dom.remove(handleElm);
  8273. }
  8274. }
  8275. }
  8276. function updateResizeRect(e) {
  8277. var controlElm;
  8278. function isChildOrEqual(node, parent) {
  8279. if (node) {
  8280. do {
  8281. if (node === parent) {
  8282. return true;
  8283. }
  8284. } while ((node = node.parentNode));
  8285. }
  8286. }
  8287. // Remove data-mce-selected from all elements since they might have been copied using Ctrl+c/v
  8288. each(dom.select('img[data-mce-selected],hr[data-mce-selected]'), function(img) {
  8289. img.removeAttribute('data-mce-selected');
  8290. });
  8291. controlElm = e.type == 'mousedown' ? e.target : selection.getNode();
  8292. controlElm = dom.getParent(controlElm, isIE ? 'table' : 'table,img,hr');
  8293. if (isChildOrEqual(controlElm, editor.getBody())) {
  8294. disableGeckoResize();
  8295. if (isChildOrEqual(selection.getStart(), controlElm) && isChildOrEqual(selection.getEnd(), controlElm)) {
  8296. if (!isIE || (controlElm != selection.getStart() && selection.getStart().nodeName !== 'IMG')) {
  8297. showResizeRect(controlElm);
  8298. return;
  8299. }
  8300. }
  8301. }
  8302. hideResizeRect();
  8303. }
  8304. function attachEvent(elm, name, func) {
  8305. if (elm && elm.attachEvent) {
  8306. elm.attachEvent('on' + name, func);
  8307. }
  8308. }
  8309. function detachEvent(elm, name, func) {
  8310. if (elm && elm.detachEvent) {
  8311. elm.detachEvent('on' + name, func);
  8312. }
  8313. }
  8314. function resizeNativeStart(e) {
  8315. var target = e.srcElement, pos, name, corner, cornerX, cornerY, relativeX, relativeY;
  8316. pos = target.getBoundingClientRect();
  8317. relativeX = lastMouseDownEvent.clientX - pos.left;
  8318. relativeY = lastMouseDownEvent.clientY - pos.top;
  8319. // Figure out what corner we are draging on
  8320. for (name in resizeHandles) {
  8321. corner = resizeHandles[name];
  8322. cornerX = target.offsetWidth * corner[0];
  8323. cornerY = target.offsetHeight * corner[1];
  8324. if (Math.abs(cornerX - relativeX) < 8 && Math.abs(cornerY - relativeY) < 8) {
  8325. selectedHandle = corner;
  8326. break;
  8327. }
  8328. }
  8329. // Remove native selection and let the magic begin
  8330. resizeStarted = true;
  8331. editor.getDoc().selection.empty();
  8332. showResizeRect(target, name, lastMouseDownEvent);
  8333. }
  8334. function nativeControlSelect(e) {
  8335. var target = e.srcElement;
  8336. if (target != selectedElm) {
  8337. detachResizeStartListener();
  8338. if (target.id.indexOf('mceResizeHandle') === 0) {
  8339. e.returnValue = false;
  8340. return;
  8341. }
  8342. if (target.nodeName == 'IMG' || target.nodeName == 'TABLE') {
  8343. hideResizeRect();
  8344. selectedElm = target;
  8345. attachEvent(target, 'resizestart', resizeNativeStart);
  8346. }
  8347. }
  8348. }
  8349. function detachResizeStartListener() {
  8350. detachEvent(selectedElm, 'resizestart', resizeNativeStart);
  8351. }
  8352. function unbindResizeHandleEvents() {
  8353. for (var name in resizeHandles) {
  8354. var handle = resizeHandles[name];
  8355. if (handle.elm) {
  8356. dom.unbind(handle.elm);
  8357. delete handle.elm;
  8358. }
  8359. }
  8360. }
  8361. function disableGeckoResize() {
  8362. try {
  8363. // Disable object resizing on Gecko
  8364. editor.getDoc().execCommand('enableObjectResizing', false, false);
  8365. } catch (ex) {
  8366. // Ignore
  8367. }
  8368. }
  8369. function controlSelect(elm) {
  8370. var ctrlRng;
  8371. if (!isIE) {
  8372. return;
  8373. }
  8374. ctrlRng = editableDoc.body.createControlRange();
  8375. try {
  8376. ctrlRng.addElement(elm);
  8377. ctrlRng.select();
  8378. return true;
  8379. } catch (ex) {
  8380. // Ignore since the element can't be control selected for example a P tag
  8381. }
  8382. }
  8383. editor.on('init', function() {
  8384. if (isIE) {
  8385. // Hide the resize rect on resize and reselect the image
  8386. editor.on('ObjectResized', function(e) {
  8387. if (e.target.nodeName != 'TABLE') {
  8388. hideResizeRect();
  8389. controlSelect(e.target);
  8390. }
  8391. });
  8392. attachEvent(editor.getBody(), 'controlselect', nativeControlSelect);
  8393. editor.on('mousedown', function(e) {
  8394. lastMouseDownEvent = e;
  8395. });
  8396. } else {
  8397. disableGeckoResize();
  8398. if (Env.ie >= 11) {
  8399. // TODO: Drag/drop doesn't work
  8400. editor.on('mouseup', function(e) {
  8401. var nodeName = e.target.nodeName;
  8402. if (/^(TABLE|IMG|HR)$/.test(nodeName)) {
  8403. editor.selection.select(e.target, nodeName == 'TABLE');
  8404. editor.nodeChanged();
  8405. }
  8406. });
  8407. editor.dom.bind(editor.getBody(), 'mscontrolselect', function(e) {
  8408. if (/^(TABLE|IMG|HR)$/.test(e.target.nodeName)) {
  8409. e.preventDefault();
  8410. // This moves the selection from being a control selection to a text like selection like in WebKit #6753
  8411. // TODO: Fix this the day IE works like other browsers without this nasty native ugly control selections.
  8412. if (e.target.tagName == 'IMG') {
  8413. window.setTimeout(function() {
  8414. editor.selection.select(e.target);
  8415. }, 0);
  8416. }
  8417. }
  8418. });
  8419. }
  8420. }
  8421. editor.on('nodechange mousedown mouseup ResizeEditor', updateResizeRect);
  8422. // Update resize rect while typing in a table
  8423. editor.on('keydown keyup', function(e) {
  8424. if (selectedElm && selectedElm.nodeName == "TABLE") {
  8425. updateResizeRect(e);
  8426. }
  8427. });
  8428. // Hide rect on focusout since it would float on top of windows otherwise
  8429. //editor.on('focusout', hideResizeRect);
  8430. });
  8431. editor.on('remove', unbindResizeHandleEvents);
  8432. function destroy() {
  8433. selectedElm = selectedElmGhost = null;
  8434. if (isIE) {
  8435. detachResizeStartListener();
  8436. detachEvent(editor.getBody(), 'controlselect', nativeControlSelect);
  8437. }
  8438. }
  8439. return {
  8440. isResizable: isResizable,
  8441. showResizeRect: showResizeRect,
  8442. hideResizeRect: hideResizeRect,
  8443. updateResizeRect: updateResizeRect,
  8444. controlSelect: controlSelect,
  8445. destroy: destroy
  8446. };
  8447. };
  8448. });
  8449. // Included from: js/tinymce/classes/dom/RangeUtils.js
  8450. /**
  8451. * Range.js
  8452. *
  8453. * Copyright, Moxiecode Systems AB
  8454. * Released under LGPL License.
  8455. *
  8456. * License: http://www.tinymce.com/license
  8457. * Contributing: http://www.tinymce.com/contributing
  8458. */
  8459. /**
  8460. * RangeUtils
  8461. *
  8462. * @class tinymce.dom.RangeUtils
  8463. * @private
  8464. */
  8465. define("tinymce/dom/RangeUtils", [
  8466. "tinymce/util/Tools",
  8467. "tinymce/dom/TreeWalker"
  8468. ], function(Tools, TreeWalker) {
  8469. var each = Tools.each;
  8470. function RangeUtils(dom) {
  8471. /**
  8472. * Walks the specified range like object and executes the callback for each sibling collection it finds.
  8473. *
  8474. * @method walk
  8475. * @param {Object} rng Range like object.
  8476. * @param {function} callback Callback function to execute for each sibling collection.
  8477. */
  8478. this.walk = function(rng, callback) {
  8479. var startContainer = rng.startContainer,
  8480. startOffset = rng.startOffset,
  8481. endContainer = rng.endContainer,
  8482. endOffset = rng.endOffset,
  8483. ancestor, startPoint,
  8484. endPoint, node, parent, siblings, nodes;
  8485. // Handle table cell selection the table plugin enables
  8486. // you to fake select table cells and perform formatting actions on them
  8487. nodes = dom.select('td.mce-item-selected,th.mce-item-selected');
  8488. if (nodes.length > 0) {
  8489. each(nodes, function(node) {
  8490. callback([node]);
  8491. });
  8492. return;
  8493. }
  8494. /**
  8495. * Excludes start/end text node if they are out side the range
  8496. *
  8497. * @private
  8498. * @param {Array} nodes Nodes to exclude items from.
  8499. * @return {Array} Array with nodes excluding the start/end container if needed.
  8500. */
  8501. function exclude(nodes) {
  8502. var node;
  8503. // First node is excluded
  8504. node = nodes[0];
  8505. if (node.nodeType === 3 && node === startContainer && startOffset >= node.nodeValue.length) {
  8506. nodes.splice(0, 1);
  8507. }
  8508. // Last node is excluded
  8509. node = nodes[nodes.length - 1];
  8510. if (endOffset === 0 && nodes.length > 0 && node === endContainer && node.nodeType === 3) {
  8511. nodes.splice(nodes.length - 1, 1);
  8512. }
  8513. return nodes;
  8514. }
  8515. /**
  8516. * Collects siblings
  8517. *
  8518. * @private
  8519. * @param {Node} node Node to collect siblings from.
  8520. * @param {String} name Name of the sibling to check for.
  8521. * @return {Array} Array of collected siblings.
  8522. */
  8523. function collectSiblings(node, name, end_node) {
  8524. var siblings = [];
  8525. for (; node && node != end_node; node = node[name]) {
  8526. siblings.push(node);
  8527. }
  8528. return siblings;
  8529. }
  8530. /**
  8531. * Find an end point this is the node just before the common ancestor root.
  8532. *
  8533. * @private
  8534. * @param {Node} node Node to start at.
  8535. * @param {Node} root Root/ancestor element to stop just before.
  8536. * @return {Node} Node just before the root element.
  8537. */
  8538. function findEndPoint(node, root) {
  8539. do {
  8540. if (node.parentNode == root) {
  8541. return node;
  8542. }
  8543. node = node.parentNode;
  8544. } while(node);
  8545. }
  8546. function walkBoundary(start_node, end_node, next) {
  8547. var siblingName = next ? 'nextSibling' : 'previousSibling';
  8548. for (node = start_node, parent = node.parentNode; node && node != end_node; node = parent) {
  8549. parent = node.parentNode;
  8550. siblings = collectSiblings(node == start_node ? node : node[siblingName], siblingName);
  8551. if (siblings.length) {
  8552. if (!next) {
  8553. siblings.reverse();
  8554. }
  8555. callback(exclude(siblings));
  8556. }
  8557. }
  8558. }
  8559. // If index based start position then resolve it
  8560. if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) {
  8561. startContainer = startContainer.childNodes[startOffset];
  8562. }
  8563. // If index based end position then resolve it
  8564. if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) {
  8565. endContainer = endContainer.childNodes[Math.min(endOffset - 1, endContainer.childNodes.length - 1)];
  8566. }
  8567. // Same container
  8568. if (startContainer == endContainer) {
  8569. return callback(exclude([startContainer]));
  8570. }
  8571. // Find common ancestor and end points
  8572. ancestor = dom.findCommonAncestor(startContainer, endContainer);
  8573. // Process left side
  8574. for (node = startContainer; node; node = node.parentNode) {
  8575. if (node === endContainer) {
  8576. return walkBoundary(startContainer, ancestor, true);
  8577. }
  8578. if (node === ancestor) {
  8579. break;
  8580. }
  8581. }
  8582. // Process right side
  8583. for (node = endContainer; node; node = node.parentNode) {
  8584. if (node === startContainer) {
  8585. return walkBoundary(endContainer, ancestor);
  8586. }
  8587. if (node === ancestor) {
  8588. break;
  8589. }
  8590. }
  8591. // Find start/end point
  8592. startPoint = findEndPoint(startContainer, ancestor) || startContainer;
  8593. endPoint = findEndPoint(endContainer, ancestor) || endContainer;
  8594. // Walk left leaf
  8595. walkBoundary(startContainer, startPoint, true);
  8596. // Walk the middle from start to end point
  8597. siblings = collectSiblings(
  8598. startPoint == startContainer ? startPoint : startPoint.nextSibling,
  8599. 'nextSibling',
  8600. endPoint == endContainer ? endPoint.nextSibling : endPoint
  8601. );
  8602. if (siblings.length) {
  8603. callback(exclude(siblings));
  8604. }
  8605. // Walk right leaf
  8606. walkBoundary(endContainer, endPoint);
  8607. };
  8608. /**
  8609. * Splits the specified range at it's start/end points.
  8610. *
  8611. * @private
  8612. * @param {Range/RangeObject} rng Range to split.
  8613. * @return {Object} Range position object.
  8614. */
  8615. this.split = function(rng) {
  8616. var startContainer = rng.startContainer,
  8617. startOffset = rng.startOffset,
  8618. endContainer = rng.endContainer,
  8619. endOffset = rng.endOffset;
  8620. function splitText(node, offset) {
  8621. return node.splitText(offset);
  8622. }
  8623. // Handle single text node
  8624. if (startContainer == endContainer && startContainer.nodeType == 3) {
  8625. if (startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  8626. endContainer = splitText(startContainer, startOffset);
  8627. startContainer = endContainer.previousSibling;
  8628. if (endOffset > startOffset) {
  8629. endOffset = endOffset - startOffset;
  8630. startContainer = endContainer = splitText(endContainer, endOffset).previousSibling;
  8631. endOffset = endContainer.nodeValue.length;
  8632. startOffset = 0;
  8633. } else {
  8634. endOffset = 0;
  8635. }
  8636. }
  8637. } else {
  8638. // Split startContainer text node if needed
  8639. if (startContainer.nodeType == 3 && startOffset > 0 && startOffset < startContainer.nodeValue.length) {
  8640. startContainer = splitText(startContainer, startOffset);
  8641. startOffset = 0;
  8642. }
  8643. // Split endContainer text node if needed
  8644. if (endContainer.nodeType == 3 && endOffset > 0 && endOffset < endContainer.nodeValue.length) {
  8645. endContainer = splitText(endContainer, endOffset).previousSibling;
  8646. endOffset = endContainer.nodeValue.length;
  8647. }
  8648. }
  8649. return {
  8650. startContainer: startContainer,
  8651. startOffset: startOffset,
  8652. endContainer: endContainer,
  8653. endOffset: endOffset
  8654. };
  8655. };
  8656. /**
  8657. * Normalizes the specified range by finding the closest best suitable caret location.
  8658. *
  8659. * @private
  8660. * @param {Range} rng Range to normalize.
  8661. * @return {Boolean} True/false if the specified range was normalized or not.
  8662. */
  8663. this.normalize = function(rng) {
  8664. var normalized, collapsed;
  8665. function normalizeEndPoint(start) {
  8666. var container, offset, walker, body = dom.getRoot(), node, nonEmptyElementsMap;
  8667. var directionLeft, isAfterNode;
  8668. function hasBrBeforeAfter(node, left) {
  8669. var walker = new TreeWalker(node, dom.getParent(node.parentNode, dom.isBlock) || body);
  8670. while ((node = walker[left ? 'prev' : 'next']())) {
  8671. if (node.nodeName === "BR") {
  8672. return true;
  8673. }
  8674. }
  8675. }
  8676. function isPrevNode(node, name) {
  8677. return node.previousSibling && node.previousSibling.nodeName == name;
  8678. }
  8679. // Walks the dom left/right to find a suitable text node to move the endpoint into
  8680. // It will only walk within the current parent block or body and will stop if it hits a block or a BR/IMG
  8681. function findTextNodeRelative(left, startNode) {
  8682. var walker, lastInlineElement, parentBlockContainer;
  8683. startNode = startNode || container;
  8684. parentBlockContainer = dom.getParent(startNode.parentNode, dom.isBlock) || body;
  8685. // Lean left before the BR element if it's the only BR within a block element. Gecko bug: #6680
  8686. // This: <p><br>|</p> becomes <p>|<br></p>
  8687. if (left && startNode.nodeName == 'BR' && isAfterNode && dom.isEmpty(parentBlockContainer)) {
  8688. container = startNode.parentNode;
  8689. offset = dom.nodeIndex(startNode);
  8690. normalized = true;
  8691. return;
  8692. }
  8693. // Walk left until we hit a text node we can move to or a block/br/img
  8694. walker = new TreeWalker(startNode, parentBlockContainer);
  8695. while ((node = walker[left ? 'prev' : 'next']())) {
  8696. // Break if we hit a non content editable node
  8697. if (dom.getContentEditableParent(node) === "false") {
  8698. return;
  8699. }
  8700. // Found text node that has a length
  8701. if (node.nodeType === 3 && node.nodeValue.length > 0) {
  8702. container = node;
  8703. offset = left ? node.nodeValue.length : 0;
  8704. normalized = true;
  8705. return;
  8706. }
  8707. // Break if we find a block or a BR/IMG/INPUT etc
  8708. if (dom.isBlock(node) || nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  8709. return;
  8710. }
  8711. lastInlineElement = node;
  8712. }
  8713. // Only fetch the last inline element when in caret mode for now
  8714. if (collapsed && lastInlineElement) {
  8715. container = lastInlineElement;
  8716. normalized = true;
  8717. offset = 0;
  8718. }
  8719. }
  8720. container = rng[(start ? 'start' : 'end') + 'Container'];
  8721. offset = rng[(start ? 'start' : 'end') + 'Offset'];
  8722. isAfterNode = container.nodeType == 1 && offset === container.childNodes.length;
  8723. nonEmptyElementsMap = dom.schema.getNonEmptyElements();
  8724. directionLeft = start;
  8725. if (container.nodeType == 1 && offset > container.childNodes.length - 1) {
  8726. directionLeft = false;
  8727. }
  8728. // If the container is a document move it to the body element
  8729. if (container.nodeType === 9) {
  8730. container = dom.getRoot();
  8731. offset = 0;
  8732. }
  8733. // If the container is body try move it into the closest text node or position
  8734. if (container === body) {
  8735. // If start is before/after a image, table etc
  8736. if (directionLeft) {
  8737. node = container.childNodes[offset > 0 ? offset - 1 : 0];
  8738. if (node) {
  8739. if (nonEmptyElementsMap[node.nodeName] || node.nodeName == "TABLE") {
  8740. return;
  8741. }
  8742. }
  8743. }
  8744. // Resolve the index
  8745. if (container.hasChildNodes()) {
  8746. offset = Math.min(!directionLeft && offset > 0 ? offset - 1 : offset, container.childNodes.length - 1);
  8747. container = container.childNodes[offset];
  8748. offset = 0;
  8749. // Don't walk into elements that doesn't have any child nodes like a IMG
  8750. if (container.hasChildNodes() && !/TABLE/.test(container.nodeName)) {
  8751. // Walk the DOM to find a text node to place the caret at or a BR
  8752. node = container;
  8753. walker = new TreeWalker(container, body);
  8754. do {
  8755. // Found a text node use that position
  8756. if (node.nodeType === 3 && node.nodeValue.length > 0) {
  8757. offset = directionLeft ? 0 : node.nodeValue.length;
  8758. container = node;
  8759. normalized = true;
  8760. break;
  8761. }
  8762. // Found a BR/IMG element that we can place the caret before
  8763. if (nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  8764. offset = dom.nodeIndex(node);
  8765. container = node.parentNode;
  8766. // Put caret after image when moving the end point
  8767. if (node.nodeName == "IMG" && !directionLeft) {
  8768. offset++;
  8769. }
  8770. normalized = true;
  8771. break;
  8772. }
  8773. } while ((node = (directionLeft ? walker.next() : walker.prev())));
  8774. }
  8775. }
  8776. }
  8777. // Lean the caret to the left if possible
  8778. if (collapsed) {
  8779. // So this: <b>x</b><i>|x</i>
  8780. // Becomes: <b>x|</b><i>x</i>
  8781. // Seems that only gecko has issues with this
  8782. if (container.nodeType === 3 && offset === 0) {
  8783. findTextNodeRelative(true);
  8784. }
  8785. // Lean left into empty inline elements when the caret is before a BR
  8786. // So this: <i><b></b><i>|<br></i>
  8787. // Becomes: <i><b>|</b><i><br></i>
  8788. // Seems that only gecko has issues with this.
  8789. // Special edge case for <p><a>x</a>|<br></p> since we don't want <p><a>x|</a><br></p>
  8790. if (container.nodeType === 1) {
  8791. node = container.childNodes[offset];
  8792. // Offset is after the containers last child
  8793. // then use the previous child for normalization
  8794. if (!node) {
  8795. node = container.childNodes[offset - 1];
  8796. }
  8797. if (node && node.nodeName === 'BR' && !isPrevNode(node, 'A') &&
  8798. !hasBrBeforeAfter(node) && !hasBrBeforeAfter(node, true)) {
  8799. findTextNodeRelative(true, node);
  8800. }
  8801. }
  8802. }
  8803. // Lean the start of the selection right if possible
  8804. // So this: x[<b>x]</b>
  8805. // Becomes: x<b>[x]</b>
  8806. if (directionLeft && !collapsed && container.nodeType === 3 && offset === container.nodeValue.length) {
  8807. findTextNodeRelative(false);
  8808. }
  8809. // Set endpoint if it was normalized
  8810. if (normalized) {
  8811. rng['set' + (start ? 'Start' : 'End')](container, offset);
  8812. }
  8813. }
  8814. collapsed = rng.collapsed;
  8815. normalizeEndPoint(true);
  8816. if (!collapsed) {
  8817. normalizeEndPoint();
  8818. }
  8819. // If it was collapsed then make sure it still is
  8820. if (normalized && collapsed) {
  8821. rng.collapse(true);
  8822. }
  8823. return normalized;
  8824. };
  8825. }
  8826. /**
  8827. * Compares two ranges and checks if they are equal.
  8828. *
  8829. * @static
  8830. * @method compareRanges
  8831. * @param {DOMRange} rng1 First range to compare.
  8832. * @param {DOMRange} rng2 First range to compare.
  8833. * @return {Boolean} true/false if the ranges are equal.
  8834. */
  8835. RangeUtils.compareRanges = function(rng1, rng2) {
  8836. if (rng1 && rng2) {
  8837. // Compare native IE ranges
  8838. if (rng1.item || rng1.duplicate) {
  8839. // Both are control ranges and the selected element matches
  8840. if (rng1.item && rng2.item && rng1.item(0) === rng2.item(0)) {
  8841. return true;
  8842. }
  8843. // Both are text ranges and the range matches
  8844. if (rng1.isEqual && rng2.isEqual && rng2.isEqual(rng1)) {
  8845. return true;
  8846. }
  8847. } else {
  8848. // Compare w3c ranges
  8849. return rng1.startContainer == rng2.startContainer && rng1.startOffset == rng2.startOffset;
  8850. }
  8851. }
  8852. return false;
  8853. };
  8854. return RangeUtils;
  8855. });
  8856. // Included from: js/tinymce/classes/dom/Selection.js
  8857. /**
  8858. * Selection.js
  8859. *
  8860. * Copyright, Moxiecode Systems AB
  8861. * Released under LGPL License.
  8862. *
  8863. * License: http://www.tinymce.com/license
  8864. * Contributing: http://www.tinymce.com/contributing
  8865. */
  8866. /**
  8867. * This class handles text and control selection it's an crossbrowser utility class.
  8868. * Consult the TinyMCE Wiki API for more details and examples on how to use this class.
  8869. *
  8870. * @class tinymce.dom.Selection
  8871. * @example
  8872. * // Getting the currently selected node for the active editor
  8873. * alert(tinymce.activeEditor.selection.getNode().nodeName);
  8874. */
  8875. define("tinymce/dom/Selection", [
  8876. "tinymce/dom/TreeWalker",
  8877. "tinymce/dom/TridentSelection",
  8878. "tinymce/dom/ControlSelection",
  8879. "tinymce/dom/RangeUtils",
  8880. "tinymce/Env",
  8881. "tinymce/util/Tools"
  8882. ], function(TreeWalker, TridentSelection, ControlSelection, RangeUtils, Env, Tools) {
  8883. var each = Tools.each, grep = Tools.grep, trim = Tools.trim;
  8884. var isIE = Env.ie, isOpera = Env.opera;
  8885. /**
  8886. * Constructs a new selection instance.
  8887. *
  8888. * @constructor
  8889. * @method Selection
  8890. * @param {tinymce.dom.DOMUtils} dom DOMUtils object reference.
  8891. * @param {Window} win Window to bind the selection object to.
  8892. * @param {tinymce.dom.Serializer} serializer DOM serialization class to use for getContent.
  8893. */
  8894. function Selection(dom, win, serializer, editor) {
  8895. var self = this;
  8896. self.dom = dom;
  8897. self.win = win;
  8898. self.serializer = serializer;
  8899. self.editor = editor;
  8900. self.controlSelection = new ControlSelection(self, editor);
  8901. // No W3C Range support
  8902. if (!self.win.getSelection) {
  8903. self.tridentSel = new TridentSelection(self);
  8904. }
  8905. }
  8906. Selection.prototype = {
  8907. /**
  8908. * Move the selection cursor range to the specified node and offset.
  8909. * If there is no node specified it will move it to the first suitable location within the body.
  8910. *
  8911. * @method setCursorLocation
  8912. * @param {Node} node Optional node to put the cursor in.
  8913. * @param {Number} offset Optional offset from the start of the node to put the cursor at.
  8914. */
  8915. setCursorLocation: function(node, offset) {
  8916. var self = this, rng = self.dom.createRng();
  8917. if (!node) {
  8918. self._moveEndPoint(rng, self.editor.getBody(), true);
  8919. self.setRng(rng);
  8920. } else {
  8921. rng.setStart(node, offset);
  8922. rng.setEnd(node, offset);
  8923. self.setRng(rng);
  8924. self.collapse(false);
  8925. }
  8926. },
  8927. /**
  8928. * Returns the selected contents using the DOM serializer passed in to this class.
  8929. *
  8930. * @method getContent
  8931. * @param {Object} s Optional settings class with for example output format text or html.
  8932. * @return {String} Selected contents in for example HTML format.
  8933. * @example
  8934. * // Alerts the currently selected contents
  8935. * alert(tinymce.activeEditor.selection.getContent());
  8936. *
  8937. * // Alerts the currently selected contents as plain text
  8938. * alert(tinymce.activeEditor.selection.getContent({format: 'text'}));
  8939. */
  8940. getContent: function(args) {
  8941. var self = this, rng = self.getRng(), tmpElm = self.dom.create("body");
  8942. var se = self.getSel(), whiteSpaceBefore, whiteSpaceAfter, fragment;
  8943. args = args || {};
  8944. whiteSpaceBefore = whiteSpaceAfter = '';
  8945. args.get = true;
  8946. args.format = args.format || 'html';
  8947. args.selection = true;
  8948. self.editor.fire('BeforeGetContent', args);
  8949. if (args.format == 'text') {
  8950. return self.isCollapsed() ? '' : (rng.text || (se.toString ? se.toString() : ''));
  8951. }
  8952. if (rng.cloneContents) {
  8953. fragment = rng.cloneContents();
  8954. if (fragment) {
  8955. tmpElm.appendChild(fragment);
  8956. }
  8957. } else if (rng.item !== undefined || rng.htmlText !== undefined) {
  8958. // IE will produce invalid markup if elements are present that
  8959. // it doesn't understand like custom elements or HTML5 elements.
  8960. // Adding a BR in front of the contents and then remoiving it seems to fix it though.
  8961. tmpElm.innerHTML = '<br>' + (rng.item ? rng.item(0).outerHTML : rng.htmlText);
  8962. tmpElm.removeChild(tmpElm.firstChild);
  8963. } else {
  8964. tmpElm.innerHTML = rng.toString();
  8965. }
  8966. // Keep whitespace before and after
  8967. if (/^\s/.test(tmpElm.innerHTML)) {
  8968. whiteSpaceBefore = ' ';
  8969. }
  8970. if (/\s+$/.test(tmpElm.innerHTML)) {
  8971. whiteSpaceAfter = ' ';
  8972. }
  8973. args.getInner = true;
  8974. args.content = self.isCollapsed() ? '' : whiteSpaceBefore + self.serializer.serialize(tmpElm, args) + whiteSpaceAfter;
  8975. self.editor.fire('GetContent', args);
  8976. return args.content;
  8977. },
  8978. /**
  8979. * Sets the current selection to the specified content. If any contents is selected it will be replaced
  8980. * with the contents passed in to this function. If there is no selection the contents will be inserted
  8981. * where the caret is placed in the editor/page.
  8982. *
  8983. * @method setContent
  8984. * @param {String} content HTML contents to set could also be other formats depending on settings.
  8985. * @param {Object} args Optional settings object with for example data format.
  8986. * @example
  8987. * // Inserts some HTML contents at the current selection
  8988. * tinymce.activeEditor.selection.setContent('<strong>Some contents</strong>');
  8989. */
  8990. setContent: function(content, args) {
  8991. var self = this, rng = self.getRng(), caretNode, doc = self.win.document, frag, temp;
  8992. args = args || {format: 'html'};
  8993. args.set = true;
  8994. args.selection = true;
  8995. content = args.content = content;
  8996. // Dispatch before set content event
  8997. if (!args.no_events) {
  8998. self.editor.fire('BeforeSetContent', args);
  8999. }
  9000. content = args.content;
  9001. if (rng.insertNode) {
  9002. // Make caret marker since insertNode places the caret in the beginning of text after insert
  9003. content += '<span id="__caret">_</span>';
  9004. // Delete and insert new node
  9005. if (rng.startContainer == doc && rng.endContainer == doc) {
  9006. // WebKit will fail if the body is empty since the range is then invalid and it can't insert contents
  9007. doc.body.innerHTML = content;
  9008. } else {
  9009. rng.deleteContents();
  9010. if (doc.body.childNodes.length === 0) {
  9011. doc.body.innerHTML = content;
  9012. } else {
  9013. // createContextualFragment doesn't exists in IE 9 DOMRanges
  9014. if (rng.createContextualFragment) {
  9015. rng.insertNode(rng.createContextualFragment(content));
  9016. } else {
  9017. // Fake createContextualFragment call in IE 9
  9018. frag = doc.createDocumentFragment();
  9019. temp = doc.createElement('div');
  9020. frag.appendChild(temp);
  9021. temp.outerHTML = content;
  9022. rng.insertNode(frag);
  9023. }
  9024. }
  9025. }
  9026. // Move to caret marker
  9027. caretNode = self.dom.get('__caret');
  9028. // Make sure we wrap it compleatly, Opera fails with a simple select call
  9029. rng = doc.createRange();
  9030. rng.setStartBefore(caretNode);
  9031. rng.setEndBefore(caretNode);
  9032. self.setRng(rng);
  9033. // Remove the caret position
  9034. self.dom.remove('__caret');
  9035. try {
  9036. self.setRng(rng);
  9037. } catch (ex) {
  9038. // Might fail on Opera for some odd reason
  9039. }
  9040. } else {
  9041. if (rng.item) {
  9042. // Delete content and get caret text selection
  9043. doc.execCommand('Delete', false, null);
  9044. rng = self.getRng();
  9045. }
  9046. // Explorer removes spaces from the beginning of pasted contents
  9047. if (/^\s+/.test(content)) {
  9048. rng.pasteHTML('<span id="__mce_tmp">_</span>' + content);
  9049. self.dom.remove('__mce_tmp');
  9050. } else {
  9051. rng.pasteHTML(content);
  9052. }
  9053. }
  9054. // Dispatch set content event
  9055. if (!args.no_events) {
  9056. self.editor.fire('SetContent', args);
  9057. }
  9058. },
  9059. /**
  9060. * Returns the start element of a selection range. If the start is in a text
  9061. * node the parent element will be returned.
  9062. *
  9063. * @method getStart
  9064. * @return {Element} Start element of selection range.
  9065. */
  9066. getStart: function() {
  9067. var self = this, rng = self.getRng(), startElement, parentElement, checkRng, node;
  9068. if (rng.duplicate || rng.item) {
  9069. // Control selection, return first item
  9070. if (rng.item) {
  9071. return rng.item(0);
  9072. }
  9073. // Get start element
  9074. checkRng = rng.duplicate();
  9075. checkRng.collapse(1);
  9076. startElement = checkRng.parentElement();
  9077. if (startElement.ownerDocument !== self.dom.doc) {
  9078. startElement = self.dom.getRoot();
  9079. }
  9080. // Check if range parent is inside the start element, then return the inner parent element
  9081. // This will fix issues when a single element is selected, IE would otherwise return the wrong start element
  9082. parentElement = node = rng.parentElement();
  9083. while ((node = node.parentNode)) {
  9084. if (node == startElement) {
  9085. startElement = parentElement;
  9086. break;
  9087. }
  9088. }
  9089. return startElement;
  9090. } else {
  9091. startElement = rng.startContainer;
  9092. if (startElement.nodeType == 1 && startElement.hasChildNodes()) {
  9093. startElement = startElement.childNodes[Math.min(startElement.childNodes.length - 1, rng.startOffset)];
  9094. }
  9095. if (startElement && startElement.nodeType == 3) {
  9096. return startElement.parentNode;
  9097. }
  9098. return startElement;
  9099. }
  9100. },
  9101. /**
  9102. * Returns the end element of a selection range. If the end is in a text
  9103. * node the parent element will be returned.
  9104. *
  9105. * @method getEnd
  9106. * @return {Element} End element of selection range.
  9107. */
  9108. getEnd: function() {
  9109. var self = this, rng = self.getRng(), endElement, endOffset;
  9110. if (rng.duplicate || rng.item) {
  9111. if (rng.item) {
  9112. return rng.item(0);
  9113. }
  9114. rng = rng.duplicate();
  9115. rng.collapse(0);
  9116. endElement = rng.parentElement();
  9117. if (endElement.ownerDocument !== self.dom.doc) {
  9118. endElement = self.dom.getRoot();
  9119. }
  9120. if (endElement && endElement.nodeName == 'BODY') {
  9121. return endElement.lastChild || endElement;
  9122. }
  9123. return endElement;
  9124. } else {
  9125. endElement = rng.endContainer;
  9126. endOffset = rng.endOffset;
  9127. if (endElement.nodeType == 1 && endElement.hasChildNodes()) {
  9128. endElement = endElement.childNodes[endOffset > 0 ? endOffset - 1 : endOffset];
  9129. }
  9130. if (endElement && endElement.nodeType == 3) {
  9131. return endElement.parentNode;
  9132. }
  9133. return endElement;
  9134. }
  9135. },
  9136. /**
  9137. * Returns a bookmark location for the current selection. This bookmark object
  9138. * can then be used to restore the selection after some content modification to the document.
  9139. *
  9140. * @method getBookmark
  9141. * @param {Number} type Optional state if the bookmark should be simple or not. Default is complex.
  9142. * @param {Boolean} normalized Optional state that enables you to get a position that it would be after normalization.
  9143. * @return {Object} Bookmark object, use moveToBookmark with this object to restore the selection.
  9144. * @example
  9145. * // Stores a bookmark of the current selection
  9146. * var bm = tinymce.activeEditor.selection.getBookmark();
  9147. *
  9148. * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content');
  9149. *
  9150. * // Restore the selection bookmark
  9151. * tinymce.activeEditor.selection.moveToBookmark(bm);
  9152. */
  9153. getBookmark: function(type, normalized) {
  9154. var self = this, dom = self.dom, rng, rng2, id, collapsed, name, element, chr = '&#xFEFF;', styles;
  9155. function findIndex(name, element) {
  9156. var index = 0;
  9157. each(dom.select(name), function(node, i) {
  9158. if (node == element) {
  9159. index = i;
  9160. }
  9161. });
  9162. return index;
  9163. }
  9164. function normalizeTableCellSelection(rng) {
  9165. function moveEndPoint(start) {
  9166. var container, offset, childNodes, prefix = start ? 'start' : 'end';
  9167. container = rng[prefix + 'Container'];
  9168. offset = rng[prefix + 'Offset'];
  9169. if (container.nodeType == 1 && container.nodeName == "TR") {
  9170. childNodes = container.childNodes;
  9171. container = childNodes[Math.min(start ? offset : offset - 1, childNodes.length - 1)];
  9172. if (container) {
  9173. offset = start ? 0 : container.childNodes.length;
  9174. rng['set' + (start ? 'Start' : 'End')](container, offset);
  9175. }
  9176. }
  9177. }
  9178. moveEndPoint(true);
  9179. moveEndPoint();
  9180. return rng;
  9181. }
  9182. function getLocation() {
  9183. var rng = self.getRng(true), root = dom.getRoot(), bookmark = {};
  9184. function getPoint(rng, start) {
  9185. var container = rng[start ? 'startContainer' : 'endContainer'],
  9186. offset = rng[start ? 'startOffset' : 'endOffset'], point = [], node, childNodes, after = 0;
  9187. if (container.nodeType == 3) {
  9188. if (normalized) {
  9189. for (node = container.previousSibling; node && node.nodeType == 3; node = node.previousSibling) {
  9190. offset += node.nodeValue.length;
  9191. }
  9192. }
  9193. point.push(offset);
  9194. } else {
  9195. childNodes = container.childNodes;
  9196. if (offset >= childNodes.length && childNodes.length) {
  9197. after = 1;
  9198. offset = Math.max(0, childNodes.length - 1);
  9199. }
  9200. point.push(self.dom.nodeIndex(childNodes[offset], normalized) + after);
  9201. }
  9202. for (; container && container != root; container = container.parentNode) {
  9203. point.push(self.dom.nodeIndex(container, normalized));
  9204. }
  9205. return point;
  9206. }
  9207. bookmark.start = getPoint(rng, true);
  9208. if (!self.isCollapsed()) {
  9209. bookmark.end = getPoint(rng);
  9210. }
  9211. return bookmark;
  9212. }
  9213. if (type == 2) {
  9214. element = self.getNode();
  9215. name = element ? element.nodeName : null;
  9216. if (name == 'IMG') {
  9217. return {name: name, index: findIndex(name, element)};
  9218. }
  9219. if (self.tridentSel) {
  9220. return self.tridentSel.getBookmark(type);
  9221. }
  9222. return getLocation();
  9223. }
  9224. // Handle simple range
  9225. if (type) {
  9226. return {rng: self.getRng()};
  9227. }
  9228. rng = self.getRng();
  9229. id = dom.uniqueId();
  9230. collapsed = self.isCollapsed();
  9231. styles = 'overflow:hidden;line-height:0px';
  9232. // Explorer method
  9233. if (rng.duplicate || rng.item) {
  9234. // Text selection
  9235. if (!rng.item) {
  9236. rng2 = rng.duplicate();
  9237. try {
  9238. // Insert start marker
  9239. rng.collapse();
  9240. rng.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_start" style="' + styles + '">' + chr + '</span>');
  9241. // Insert end marker
  9242. if (!collapsed) {
  9243. rng2.collapse(false);
  9244. // Detect the empty space after block elements in IE and move the
  9245. // end back one character <p></p>] becomes <p>]</p>
  9246. rng.moveToElementText(rng2.parentElement());
  9247. if (rng.compareEndPoints('StartToEnd', rng2) === 0) {
  9248. rng2.move('character', -1);
  9249. }
  9250. rng2.pasteHTML('<span data-mce-type="bookmark" id="' + id + '_end" style="' + styles + '">' + chr + '</span>');
  9251. }
  9252. } catch (ex) {
  9253. // IE might throw unspecified error so lets ignore it
  9254. return null;
  9255. }
  9256. } else {
  9257. // Control selection
  9258. element = rng.item(0);
  9259. name = element.nodeName;
  9260. return {name: name, index: findIndex(name, element)};
  9261. }
  9262. } else {
  9263. element = self.getNode();
  9264. name = element.nodeName;
  9265. if (name == 'IMG') {
  9266. return {name: name, index: findIndex(name, element)};
  9267. }
  9268. // W3C method
  9269. rng2 = normalizeTableCellSelection(rng.cloneRange());
  9270. // Insert end marker
  9271. if (!collapsed) {
  9272. rng2.collapse(false);
  9273. rng2.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_end', style: styles}, chr));
  9274. }
  9275. rng = normalizeTableCellSelection(rng);
  9276. rng.collapse(true);
  9277. rng.insertNode(dom.create('span', {'data-mce-type': "bookmark", id: id + '_start', style: styles}, chr));
  9278. }
  9279. self.moveToBookmark({id: id, keep: 1});
  9280. return {id: id};
  9281. },
  9282. /**
  9283. * Restores the selection to the specified bookmark.
  9284. *
  9285. * @method moveToBookmark
  9286. * @param {Object} bookmark Bookmark to restore selection from.
  9287. * @return {Boolean} true/false if it was successful or not.
  9288. * @example
  9289. * // Stores a bookmark of the current selection
  9290. * var bm = tinymce.activeEditor.selection.getBookmark();
  9291. *
  9292. * tinymce.activeEditor.setContent(tinymce.activeEditor.getContent() + 'Some new content');
  9293. *
  9294. * // Restore the selection bookmark
  9295. * tinymce.activeEditor.selection.moveToBookmark(bm);
  9296. */
  9297. moveToBookmark: function(bookmark) {
  9298. var self = this, dom = self.dom, rng, root, startContainer, endContainer, startOffset, endOffset;
  9299. function setEndPoint(start) {
  9300. var point = bookmark[start ? 'start' : 'end'], i, node, offset, children;
  9301. if (point) {
  9302. offset = point[0];
  9303. // Find container node
  9304. for (node = root, i = point.length - 1; i >= 1; i--) {
  9305. children = node.childNodes;
  9306. if (point[i] > children.length - 1) {
  9307. return;
  9308. }
  9309. node = children[point[i]];
  9310. }
  9311. // Move text offset to best suitable location
  9312. if (node.nodeType === 3) {
  9313. offset = Math.min(point[0], node.nodeValue.length);
  9314. }
  9315. // Move element offset to best suitable location
  9316. if (node.nodeType === 1) {
  9317. offset = Math.min(point[0], node.childNodes.length);
  9318. }
  9319. // Set offset within container node
  9320. if (start) {
  9321. rng.setStart(node, offset);
  9322. } else {
  9323. rng.setEnd(node, offset);
  9324. }
  9325. }
  9326. return true;
  9327. }
  9328. function restoreEndPoint(suffix) {
  9329. var marker = dom.get(bookmark.id + '_' + suffix), node, idx, next, prev, keep = bookmark.keep;
  9330. if (marker) {
  9331. node = marker.parentNode;
  9332. if (suffix == 'start') {
  9333. if (!keep) {
  9334. idx = dom.nodeIndex(marker);
  9335. } else {
  9336. node = marker.firstChild;
  9337. idx = 1;
  9338. }
  9339. startContainer = endContainer = node;
  9340. startOffset = endOffset = idx;
  9341. } else {
  9342. if (!keep) {
  9343. idx = dom.nodeIndex(marker);
  9344. } else {
  9345. node = marker.firstChild;
  9346. idx = 1;
  9347. }
  9348. endContainer = node;
  9349. endOffset = idx;
  9350. }
  9351. if (!keep) {
  9352. prev = marker.previousSibling;
  9353. next = marker.nextSibling;
  9354. // Remove all marker text nodes
  9355. each(grep(marker.childNodes), function(node) {
  9356. if (node.nodeType == 3) {
  9357. node.nodeValue = node.nodeValue.replace(/\uFEFF/g, '');
  9358. }
  9359. });
  9360. // Remove marker but keep children if for example contents where inserted into the marker
  9361. // Also remove duplicated instances of the marker for example by a
  9362. // split operation or by WebKit auto split on paste feature
  9363. while ((marker = dom.get(bookmark.id + '_' + suffix))) {
  9364. dom.remove(marker, 1);
  9365. }
  9366. // If siblings are text nodes then merge them unless it's Opera since it some how removes the node
  9367. // and we are sniffing since adding a lot of detection code for a browser with 3% of the market
  9368. // isn't worth the effort. Sorry, Opera but it's just a fact
  9369. if (prev && next && prev.nodeType == next.nodeType && prev.nodeType == 3 && !isOpera) {
  9370. idx = prev.nodeValue.length;
  9371. prev.appendData(next.nodeValue);
  9372. dom.remove(next);
  9373. if (suffix == 'start') {
  9374. startContainer = endContainer = prev;
  9375. startOffset = endOffset = idx;
  9376. } else {
  9377. endContainer = prev;
  9378. endOffset = idx;
  9379. }
  9380. }
  9381. }
  9382. }
  9383. }
  9384. function addBogus(node) {
  9385. // Adds a bogus BR element for empty block elements
  9386. if (dom.isBlock(node) && !node.innerHTML && !isIE) {
  9387. node.innerHTML = '<br data-mce-bogus="1" />';
  9388. }
  9389. return node;
  9390. }
  9391. if (bookmark) {
  9392. if (bookmark.start) {
  9393. rng = dom.createRng();
  9394. root = dom.getRoot();
  9395. if (self.tridentSel) {
  9396. return self.tridentSel.moveToBookmark(bookmark);
  9397. }
  9398. if (setEndPoint(true) && setEndPoint()) {
  9399. self.setRng(rng);
  9400. }
  9401. } else if (bookmark.id) {
  9402. // Restore start/end points
  9403. restoreEndPoint('start');
  9404. restoreEndPoint('end');
  9405. if (startContainer) {
  9406. rng = dom.createRng();
  9407. rng.setStart(addBogus(startContainer), startOffset);
  9408. rng.setEnd(addBogus(endContainer), endOffset);
  9409. self.setRng(rng);
  9410. }
  9411. } else if (bookmark.name) {
  9412. self.select(dom.select(bookmark.name)[bookmark.index]);
  9413. } else if (bookmark.rng) {
  9414. self.setRng(bookmark.rng);
  9415. }
  9416. }
  9417. },
  9418. /**
  9419. * Selects the specified element. This will place the start and end of the selection range around the element.
  9420. *
  9421. * @method select
  9422. * @param {Element} node HMTL DOM element to select.
  9423. * @param {Boolean} content Optional bool state if the contents should be selected or not on non IE browser.
  9424. * @return {Element} Selected element the same element as the one that got passed in.
  9425. * @example
  9426. * // Select the first paragraph in the active editor
  9427. * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]);
  9428. */
  9429. select: function(node, content) {
  9430. var self = this, dom = self.dom, rng = dom.createRng(), idx;
  9431. // Clear stored range set by FocusManager
  9432. self.lastFocusBookmark = null;
  9433. if (node) {
  9434. if (!content && self.controlSelection.controlSelect(node)) {
  9435. return;
  9436. }
  9437. idx = dom.nodeIndex(node);
  9438. rng.setStart(node.parentNode, idx);
  9439. rng.setEnd(node.parentNode, idx + 1);
  9440. // Find first/last text node or BR element
  9441. if (content) {
  9442. self._moveEndPoint(rng, node, true);
  9443. self._moveEndPoint(rng, node);
  9444. }
  9445. self.setRng(rng);
  9446. }
  9447. return node;
  9448. },
  9449. /**
  9450. * Returns true/false if the selection range is collapsed or not. Collapsed means if it's a caret or a larger selection.
  9451. *
  9452. * @method isCollapsed
  9453. * @return {Boolean} true/false state if the selection range is collapsed or not.
  9454. * Collapsed means if it's a caret or a larger selection.
  9455. */
  9456. isCollapsed: function() {
  9457. var self = this, rng = self.getRng(), sel = self.getSel();
  9458. if (!rng || rng.item) {
  9459. return false;
  9460. }
  9461. if (rng.compareEndPoints) {
  9462. return rng.compareEndPoints('StartToEnd', rng) === 0;
  9463. }
  9464. return !sel || rng.collapsed;
  9465. },
  9466. /**
  9467. * Collapse the selection to start or end of range.
  9468. *
  9469. * @method collapse
  9470. * @param {Boolean} to_start Optional boolean state if to collapse to end or not. Defaults to start.
  9471. */
  9472. collapse: function(to_start) {
  9473. var self = this, rng = self.getRng(), node;
  9474. // Control range on IE
  9475. if (rng.item) {
  9476. node = rng.item(0);
  9477. rng = self.win.document.body.createTextRange();
  9478. rng.moveToElementText(node);
  9479. }
  9480. rng.collapse(!!to_start);
  9481. self.setRng(rng);
  9482. },
  9483. /**
  9484. * Returns the browsers internal selection object.
  9485. *
  9486. * @method getSel
  9487. * @return {Selection} Internal browser selection object.
  9488. */
  9489. getSel: function() {
  9490. var win = this.win;
  9491. return win.getSelection ? win.getSelection() : win.document.selection;
  9492. },
  9493. /**
  9494. * Returns the browsers internal range object.
  9495. *
  9496. * @method getRng
  9497. * @param {Boolean} w3c Forces a compatible W3C range on IE.
  9498. * @return {Range} Internal browser range object.
  9499. * @see http://www.quirksmode.org/dom/range_intro.html
  9500. * @see http://www.dotvoid.com/2001/03/using-the-range-object-in-mozilla/
  9501. */
  9502. getRng: function(w3c) {
  9503. var self = this, selection, rng, elm, doc = self.win.document, ieRng;
  9504. function tryCompareBounderyPoints(how, sourceRange, destinationRange) {
  9505. try {
  9506. return sourceRange.compareBoundaryPoints(how, destinationRange);
  9507. } catch (ex) {
  9508. // Gecko throws wrong document exception if the range points
  9509. // to nodes that where removed from the dom #6690
  9510. // Browsers should mutate existing DOMRange instances so that they always point
  9511. // to something in the document this is not the case in Gecko works fine in IE/WebKit/Blink
  9512. // For performance reasons just return -1
  9513. return -1;
  9514. }
  9515. }
  9516. // Use last rng passed from FocusManager if it's available this enables
  9517. // calls to editor.selection.getStart() to work when caret focus is lost on IE
  9518. if (!w3c && self.lastFocusBookmark) {
  9519. var bookmark = self.lastFocusBookmark;
  9520. // Convert bookmark to range IE 11 fix
  9521. if (bookmark.startContainer) {
  9522. rng = doc.createRange();
  9523. rng.setStart(bookmark.startContainer, bookmark.startOffset);
  9524. rng.setEnd(bookmark.endContainer, bookmark.endOffset);
  9525. } else {
  9526. rng = bookmark;
  9527. }
  9528. return rng;
  9529. }
  9530. // Found tridentSel object then we need to use that one
  9531. if (w3c && self.tridentSel) {
  9532. return self.tridentSel.getRangeAt(0);
  9533. }
  9534. try {
  9535. if ((selection = self.getSel())) {
  9536. if (selection.rangeCount > 0) {
  9537. rng = selection.getRangeAt(0);
  9538. } else {
  9539. rng = selection.createRange ? selection.createRange() : doc.createRange();
  9540. }
  9541. }
  9542. } catch (ex) {
  9543. // IE throws unspecified error here if TinyMCE is placed in a frame/iframe
  9544. }
  9545. // We have W3C ranges and it's IE then fake control selection since IE9 doesn't handle that correctly yet
  9546. // IE 11 doesn't support the selection object so we check for that as well
  9547. if (isIE && rng && rng.setStart && doc.selection) {
  9548. try {
  9549. // IE will sometimes throw an exception here
  9550. ieRng = doc.selection.createRange();
  9551. } catch (ex) {
  9552. }
  9553. if (ieRng && ieRng.item) {
  9554. elm = ieRng.item(0);
  9555. rng = doc.createRange();
  9556. rng.setStartBefore(elm);
  9557. rng.setEndAfter(elm);
  9558. }
  9559. }
  9560. // No range found then create an empty one
  9561. // This can occur when the editor is placed in a hidden container element on Gecko
  9562. // Or on IE when there was an exception
  9563. if (!rng) {
  9564. rng = doc.createRange ? doc.createRange() : doc.body.createTextRange();
  9565. }
  9566. // If range is at start of document then move it to start of body
  9567. if (rng.setStart && rng.startContainer.nodeType === 9 && rng.collapsed) {
  9568. elm = self.dom.getRoot();
  9569. rng.setStart(elm, 0);
  9570. rng.setEnd(elm, 0);
  9571. }
  9572. if (self.selectedRange && self.explicitRange) {
  9573. if (tryCompareBounderyPoints(rng.START_TO_START, rng, self.selectedRange) === 0 &&
  9574. tryCompareBounderyPoints(rng.END_TO_END, rng, self.selectedRange) === 0) {
  9575. // Safari, Opera and Chrome only ever select text which causes the range to change.
  9576. // This lets us use the originally set range if the selection hasn't been changed by the user.
  9577. rng = self.explicitRange;
  9578. } else {
  9579. self.selectedRange = null;
  9580. self.explicitRange = null;
  9581. }
  9582. }
  9583. return rng;
  9584. },
  9585. /**
  9586. * Changes the selection to the specified DOM range.
  9587. *
  9588. * @method setRng
  9589. * @param {Range} rng Range to select.
  9590. */
  9591. setRng: function(rng, forward) {
  9592. var self = this, sel;
  9593. // Is IE specific range
  9594. if (rng.select) {
  9595. try {
  9596. rng.select();
  9597. } catch (ex) {
  9598. // Needed for some odd IE bug #1843306
  9599. }
  9600. return;
  9601. }
  9602. if (!self.tridentSel) {
  9603. sel = self.getSel();
  9604. if (sel) {
  9605. self.explicitRange = rng;
  9606. try {
  9607. sel.removeAllRanges();
  9608. sel.addRange(rng);
  9609. } catch (ex) {
  9610. // IE might throw errors here if the editor is within a hidden container and selection is changed
  9611. }
  9612. // Forward is set to false and we have an extend function
  9613. if (forward === false && sel.extend) {
  9614. sel.collapse(rng.endContainer, rng.endOffset);
  9615. sel.extend(rng.startContainer, rng.startOffset);
  9616. }
  9617. // adding range isn't always successful so we need to check range count otherwise an exception can occur
  9618. self.selectedRange = sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
  9619. }
  9620. } else {
  9621. // Is W3C Range fake range on IE
  9622. if (rng.cloneRange) {
  9623. try {
  9624. self.tridentSel.addRange(rng);
  9625. return;
  9626. } catch (ex) {
  9627. //IE9 throws an error here if called before selection is placed in the editor
  9628. }
  9629. }
  9630. }
  9631. },
  9632. /**
  9633. * Sets the current selection to the specified DOM element.
  9634. *
  9635. * @method setNode
  9636. * @param {Element} elm Element to set as the contents of the selection.
  9637. * @return {Element} Returns the element that got passed in.
  9638. * @example
  9639. * // Inserts a DOM node at current selection/caret location
  9640. * tinymce.activeEditor.selection.setNode(tinymce.activeEditor.dom.create('img', {src: 'some.gif', title: 'some title'}));
  9641. */
  9642. setNode: function(elm) {
  9643. var self = this;
  9644. self.setContent(self.dom.getOuterHTML(elm));
  9645. return elm;
  9646. },
  9647. /**
  9648. * Returns the currently selected element or the common ancestor element for both start and end of the selection.
  9649. *
  9650. * @method getNode
  9651. * @return {Element} Currently selected element or common ancestor element.
  9652. * @example
  9653. * // Alerts the currently selected elements node name
  9654. * alert(tinymce.activeEditor.selection.getNode().nodeName);
  9655. */
  9656. getNode: function() {
  9657. var self = this, rng = self.getRng(), elm;
  9658. var startContainer = rng.startContainer, endContainer = rng.endContainer;
  9659. var startOffset = rng.startOffset, endOffset = rng.endOffset, root = self.dom.getRoot();
  9660. function skipEmptyTextNodes(node, forwards) {
  9661. var orig = node;
  9662. while (node && node.nodeType === 3 && node.length === 0) {
  9663. node = forwards ? node.nextSibling : node.previousSibling;
  9664. }
  9665. return node || orig;
  9666. }
  9667. // Range maybe lost after the editor is made visible again
  9668. if (!rng) {
  9669. return root;
  9670. }
  9671. if (rng.setStart) {
  9672. elm = rng.commonAncestorContainer;
  9673. // Handle selection a image or other control like element such as anchors
  9674. if (!rng.collapsed) {
  9675. if (startContainer == endContainer) {
  9676. if (endOffset - startOffset < 2) {
  9677. if (startContainer.hasChildNodes()) {
  9678. elm = startContainer.childNodes[startOffset];
  9679. }
  9680. }
  9681. }
  9682. // If the anchor node is a element instead of a text node then return this element
  9683. //if (tinymce.isWebKit && sel.anchorNode && sel.anchorNode.nodeType == 1)
  9684. // return sel.anchorNode.childNodes[sel.anchorOffset];
  9685. // Handle cases where the selection is immediately wrapped around a node and return that node instead of it's parent.
  9686. // This happens when you double click an underlined word in FireFox.
  9687. if (startContainer.nodeType === 3 && endContainer.nodeType === 3) {
  9688. if (startContainer.length === startOffset) {
  9689. startContainer = skipEmptyTextNodes(startContainer.nextSibling, true);
  9690. } else {
  9691. startContainer = startContainer.parentNode;
  9692. }
  9693. if (endOffset === 0) {
  9694. endContainer = skipEmptyTextNodes(endContainer.previousSibling, false);
  9695. } else {
  9696. endContainer = endContainer.parentNode;
  9697. }
  9698. if (startContainer && startContainer === endContainer) {
  9699. return startContainer;
  9700. }
  9701. }
  9702. }
  9703. if (elm && elm.nodeType == 3) {
  9704. return elm.parentNode;
  9705. }
  9706. return elm;
  9707. }
  9708. elm = rng.item ? rng.item(0) : rng.parentElement();
  9709. // IE 7 might return elements outside the iframe
  9710. if (elm.ownerDocument !== self.win.document) {
  9711. elm = root;
  9712. }
  9713. return elm;
  9714. },
  9715. getSelectedBlocks: function(startElm, endElm) {
  9716. var self = this, dom = self.dom, node, root, selectedBlocks = [];
  9717. root = dom.getRoot();
  9718. startElm = dom.getParent(startElm || self.getStart(), dom.isBlock);
  9719. endElm = dom.getParent(endElm || self.getEnd(), dom.isBlock);
  9720. if (startElm && startElm != root) {
  9721. selectedBlocks.push(startElm);
  9722. }
  9723. if (startElm && endElm && startElm != endElm) {
  9724. node = startElm;
  9725. var walker = new TreeWalker(startElm, root);
  9726. while ((node = walker.next()) && node != endElm) {
  9727. if (dom.isBlock(node)) {
  9728. selectedBlocks.push(node);
  9729. }
  9730. }
  9731. }
  9732. if (endElm && startElm != endElm && endElm != root) {
  9733. selectedBlocks.push(endElm);
  9734. }
  9735. return selectedBlocks;
  9736. },
  9737. isForward: function() {
  9738. var dom = this.dom, sel = this.getSel(), anchorRange, focusRange;
  9739. // No support for selection direction then always return true
  9740. if (!sel || !sel.anchorNode || !sel.focusNode) {
  9741. return true;
  9742. }
  9743. anchorRange = dom.createRng();
  9744. anchorRange.setStart(sel.anchorNode, sel.anchorOffset);
  9745. anchorRange.collapse(true);
  9746. focusRange = dom.createRng();
  9747. focusRange.setStart(sel.focusNode, sel.focusOffset);
  9748. focusRange.collapse(true);
  9749. return anchorRange.compareBoundaryPoints(anchorRange.START_TO_START, focusRange) <= 0;
  9750. },
  9751. normalize: function() {
  9752. var self = this, rng = self.getRng();
  9753. if (!isIE && new RangeUtils(self.dom).normalize(rng)) {
  9754. self.setRng(rng, self.isForward());
  9755. }
  9756. return rng;
  9757. },
  9758. /**
  9759. * Executes callback of the current selection matches the specified selector or not and passes the state and args to the callback.
  9760. *
  9761. * @method selectorChanged
  9762. * @param {String} selector CSS selector to check for.
  9763. * @param {function} callback Callback with state and args when the selector is matches or not.
  9764. */
  9765. selectorChanged: function(selector, callback) {
  9766. var self = this, currentSelectors;
  9767. if (!self.selectorChangedData) {
  9768. self.selectorChangedData = {};
  9769. currentSelectors = {};
  9770. self.editor.on('NodeChange', function(e) {
  9771. var node = e.element, dom = self.dom, parents = dom.getParents(node, null, dom.getRoot()), matchedSelectors = {};
  9772. // Check for new matching selectors
  9773. each(self.selectorChangedData, function(callbacks, selector) {
  9774. each(parents, function(node) {
  9775. if (dom.is(node, selector)) {
  9776. if (!currentSelectors[selector]) {
  9777. // Execute callbacks
  9778. each(callbacks, function(callback) {
  9779. callback(true, {node: node, selector: selector, parents: parents});
  9780. });
  9781. currentSelectors[selector] = callbacks;
  9782. }
  9783. matchedSelectors[selector] = callbacks;
  9784. return false;
  9785. }
  9786. });
  9787. });
  9788. // Check if current selectors still match
  9789. each(currentSelectors, function(callbacks, selector) {
  9790. if (!matchedSelectors[selector]) {
  9791. delete currentSelectors[selector];
  9792. each(callbacks, function(callback) {
  9793. callback(false, {node: node, selector: selector, parents: parents});
  9794. });
  9795. }
  9796. });
  9797. });
  9798. }
  9799. // Add selector listeners
  9800. if (!self.selectorChangedData[selector]) {
  9801. self.selectorChangedData[selector] = [];
  9802. }
  9803. self.selectorChangedData[selector].push(callback);
  9804. return self;
  9805. },
  9806. getScrollContainer: function() {
  9807. var scrollContainer, node = this.dom.getRoot();
  9808. while (node && node.nodeName != 'BODY') {
  9809. if (node.scrollHeight > node.clientHeight) {
  9810. scrollContainer = node;
  9811. break;
  9812. }
  9813. node = node.parentNode;
  9814. }
  9815. return scrollContainer;
  9816. },
  9817. scrollIntoView: function(elm) {
  9818. var y, viewPort, self = this, dom = self.dom, root = dom.getRoot(), viewPortY, viewPortH;
  9819. function getPos(elm) {
  9820. var x = 0, y = 0;
  9821. var offsetParent = elm;
  9822. while (offsetParent && offsetParent.nodeType) {
  9823. x += offsetParent.offsetLeft || 0;
  9824. y += offsetParent.offsetTop || 0;
  9825. offsetParent = offsetParent.offsetParent;
  9826. }
  9827. return {x: x, y: y};
  9828. }
  9829. if (root.nodeName != 'BODY') {
  9830. var scrollContainer = self.getScrollContainer();
  9831. if (scrollContainer) {
  9832. y = getPos(elm).y - getPos(scrollContainer).y;
  9833. viewPortH = scrollContainer.clientHeight;
  9834. viewPortY = scrollContainer.scrollTop;
  9835. if (y < viewPortY || y + 25 > viewPortY + viewPortH) {
  9836. scrollContainer.scrollTop = y < viewPortY ? y : y - viewPortH + 25;
  9837. }
  9838. return;
  9839. }
  9840. }
  9841. viewPort = dom.getViewPort(self.editor.getWin());
  9842. y = dom.getPos(elm).y;
  9843. viewPortY = viewPort.y;
  9844. viewPortH = viewPort.h;
  9845. if (y < viewPort.y || y + 25 > viewPortY + viewPortH) {
  9846. self.editor.getWin().scrollTo(0, y < viewPortY ? y : y - viewPortH + 25);
  9847. }
  9848. },
  9849. _moveEndPoint: function(rng, node, start) {
  9850. var root = node, walker = new TreeWalker(node, root);
  9851. var nonEmptyElementsMap = this.dom.schema.getNonEmptyElements();
  9852. do {
  9853. // Text node
  9854. if (node.nodeType == 3 && trim(node.nodeValue).length !== 0) {
  9855. if (start) {
  9856. rng.setStart(node, 0);
  9857. } else {
  9858. rng.setEnd(node, node.nodeValue.length);
  9859. }
  9860. return;
  9861. }
  9862. // BR/IMG/INPUT elements
  9863. if (nonEmptyElementsMap[node.nodeName]) {
  9864. if (start) {
  9865. rng.setStartBefore(node);
  9866. } else {
  9867. if (node.nodeName == 'BR') {
  9868. rng.setEndBefore(node);
  9869. } else {
  9870. rng.setEndAfter(node);
  9871. }
  9872. }
  9873. return;
  9874. }
  9875. // Found empty text block old IE can place the selection inside those
  9876. if (Env.ie && Env.ie < 11 && this.dom.isBlock(node) && this.dom.isEmpty(node)) {
  9877. if (start) {
  9878. rng.setStart(node, 0);
  9879. } else {
  9880. rng.setEnd(node, 0);
  9881. }
  9882. return;
  9883. }
  9884. } while ((node = (start ? walker.next() : walker.prev())));
  9885. // Failed to find any text node or other suitable location then move to the root of body
  9886. if (root.nodeName == 'BODY') {
  9887. if (start) {
  9888. rng.setStart(root, 0);
  9889. } else {
  9890. rng.setEnd(root, root.childNodes.length);
  9891. }
  9892. }
  9893. },
  9894. destroy: function() {
  9895. this.win = null;
  9896. this.controlSelection.destroy();
  9897. }
  9898. };
  9899. return Selection;
  9900. });
  9901. // Included from: js/tinymce/classes/fmt/Preview.js
  9902. /**
  9903. * Preview.js
  9904. *
  9905. * Copyright, Moxiecode Systems AB
  9906. * Released under LGPL License.
  9907. *
  9908. * License: http://www.tinymce.com/license
  9909. * Contributing: http://www.tinymce.com/contributing
  9910. */
  9911. /**
  9912. * Internal class for generating previews styles for formats.
  9913. *
  9914. * Example:
  9915. * Preview.getCssText(editor, 'bold');
  9916. *
  9917. * @class tinymce.fmt.Preview
  9918. * @private
  9919. */
  9920. define("tinymce/fmt/Preview", [
  9921. "tinymce/util/Tools"
  9922. ], function(Tools) {
  9923. var each = Tools.each;
  9924. function getCssText(editor, format) {
  9925. var name, previewElm, dom = editor.dom;
  9926. var previewCss = '', parentFontSize, previewStyles;
  9927. previewStyles = editor.settings.preview_styles;
  9928. // No preview forced
  9929. if (previewStyles === false) {
  9930. return '';
  9931. }
  9932. // Default preview
  9933. if (!previewStyles) {
  9934. previewStyles = 'font-family font-size font-weight font-style text-decoration ' +
  9935. 'text-transform color background-color border border-radius outline text-shadow';
  9936. }
  9937. // Removes any variables since these can't be previewed
  9938. function removeVars(val) {
  9939. return val.replace(/%(\w+)/g, '');
  9940. }
  9941. // Create block/inline element to use for preview
  9942. if (typeof(format) == "string") {
  9943. format = editor.formatter.get(format);
  9944. if (!format) {
  9945. return;
  9946. }
  9947. format = format[0];
  9948. }
  9949. name = format.block || format.inline || 'span';
  9950. previewElm = dom.create(name);
  9951. // Add format styles to preview element
  9952. each(format.styles, function(value, name) {
  9953. value = removeVars(value);
  9954. if (value) {
  9955. dom.setStyle(previewElm, name, value);
  9956. }
  9957. });
  9958. // Add attributes to preview element
  9959. each(format.attributes, function(value, name) {
  9960. value = removeVars(value);
  9961. if (value) {
  9962. dom.setAttrib(previewElm, name, value);
  9963. }
  9964. });
  9965. // Add classes to preview element
  9966. each(format.classes, function(value) {
  9967. value = removeVars(value);
  9968. if (!dom.hasClass(previewElm, value)) {
  9969. dom.addClass(previewElm, value);
  9970. }
  9971. });
  9972. editor.fire('PreviewFormats');
  9973. // Add the previewElm outside the visual area
  9974. dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF});
  9975. editor.getBody().appendChild(previewElm);
  9976. // Get parent container font size so we can compute px values out of em/% for older IE:s
  9977. parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true);
  9978. parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0;
  9979. each(previewStyles.split(' '), function(name) {
  9980. var value = dom.getStyle(previewElm, name, true);
  9981. // If background is transparent then check if the body has a background color we can use
  9982. if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) {
  9983. value = dom.getStyle(editor.getBody(), name, true);
  9984. // Ignore white since it's the default color, not the nicest fix
  9985. // TODO: Fix this by detecting runtime style
  9986. if (dom.toHex(value).toLowerCase() == '#ffffff') {
  9987. return;
  9988. }
  9989. }
  9990. if (name == 'color') {
  9991. // Ignore black since it's the default color, not the nicest fix
  9992. // TODO: Fix this by detecting runtime style
  9993. if (dom.toHex(value).toLowerCase() == '#000000') {
  9994. return;
  9995. }
  9996. }
  9997. // Old IE won't calculate the font size so we need to do that manually
  9998. if (name == 'font-size') {
  9999. if (/em|%$/.test(value)) {
  10000. if (parentFontSize === 0) {
  10001. return;
  10002. }
  10003. // Convert font size from em/% to px
  10004. value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1);
  10005. value = (value * parentFontSize) + 'px';
  10006. }
  10007. }
  10008. if (name == "border" && value) {
  10009. previewCss += 'padding:0 2px;';
  10010. }
  10011. previewCss += name + ':' + value + ';';
  10012. });
  10013. editor.fire('AfterPreviewFormats');
  10014. //previewCss += 'line-height:normal';
  10015. dom.remove(previewElm);
  10016. return previewCss;
  10017. }
  10018. return {
  10019. getCssText: getCssText
  10020. };
  10021. });
  10022. // Included from: js/tinymce/classes/Formatter.js
  10023. /**
  10024. * Formatter.js
  10025. *
  10026. * Copyright, Moxiecode Systems AB
  10027. * Released under LGPL License.
  10028. *
  10029. * License: http://www.tinymce.com/license
  10030. * Contributing: http://www.tinymce.com/contributing
  10031. */
  10032. /**
  10033. * Text formatter engine class. This class is used to apply formats like bold, italic, font size
  10034. * etc to the current selection or specific nodes. This engine was build to replace the browsers
  10035. * default formatting logic for execCommand due to it's inconsistent and buggy behavior.
  10036. *
  10037. * @class tinymce.Formatter
  10038. * @example
  10039. * tinymce.activeEditor.formatter.register('mycustomformat', {
  10040. * inline: 'span',
  10041. * styles: {color: '#ff0000'}
  10042. * });
  10043. *
  10044. * tinymce.activeEditor.formatter.apply('mycustomformat');
  10045. */
  10046. define("tinymce/Formatter", [
  10047. "tinymce/dom/TreeWalker",
  10048. "tinymce/dom/RangeUtils",
  10049. "tinymce/util/Tools",
  10050. "tinymce/fmt/Preview"
  10051. ], function(TreeWalker, RangeUtils, Tools, Preview) {
  10052. /**
  10053. * Constructs a new formatter instance.
  10054. *
  10055. * @constructor Formatter
  10056. * @param {tinymce.Editor} ed Editor instance to construct the formatter engine to.
  10057. */
  10058. return function(ed) {
  10059. var formats = {},
  10060. dom = ed.dom,
  10061. selection = ed.selection,
  10062. rangeUtils = new RangeUtils(dom),
  10063. isValid = ed.schema.isValidChild,
  10064. isBlock = dom.isBlock,
  10065. forcedRootBlock = ed.settings.forced_root_block,
  10066. nodeIndex = dom.nodeIndex,
  10067. INVISIBLE_CHAR = '\uFEFF',
  10068. MCE_ATTR_RE = /^(src|href|style)$/,
  10069. FALSE = false,
  10070. TRUE = true,
  10071. formatChangeData,
  10072. undef,
  10073. getContentEditable = dom.getContentEditable,
  10074. disableCaretContainer,
  10075. markCaretContainersBogus;
  10076. var each = Tools.each,
  10077. grep = Tools.grep,
  10078. walk = Tools.walk,
  10079. extend = Tools.extend;
  10080. function isTextBlock(name) {
  10081. if (name.nodeType) {
  10082. name = name.nodeName;
  10083. }
  10084. return !!ed.schema.getTextBlockElements()[name.toLowerCase()];
  10085. }
  10086. function getParents(node, selector) {
  10087. return dom.getParents(node, selector, dom.getRoot());
  10088. }
  10089. function isCaretNode(node) {
  10090. return node.nodeType === 1 && node.id === '_mce_caret';
  10091. }
  10092. function defaultFormats() {
  10093. register({
  10094. valigntop: [
  10095. {selector: 'td,th', styles: {'verticalAlign': 'top'}}
  10096. ],
  10097. valignmiddle: [
  10098. {selector: 'td,th', styles: {'verticalAlign': 'middle'}}
  10099. ],
  10100. valignbottom: [
  10101. {selector: 'td,th', styles: {'verticalAlign': 'bottom'}}
  10102. ],
  10103. alignleft: [
  10104. {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'left'}, defaultBlock: 'div'},
  10105. {selector: 'img,table', collapsed: false, styles: {'float': 'left'}}
  10106. ],
  10107. aligncenter: [
  10108. {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'center'}, defaultBlock: 'div'},
  10109. {selector: 'img', collapsed: false, styles: {display: 'block', marginLeft: 'auto', marginRight: 'auto'}},
  10110. {selector: 'table', collapsed: false, styles: {marginLeft: 'auto', marginRight: 'auto'}}
  10111. ],
  10112. alignright: [
  10113. {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'right'}, defaultBlock: 'div'},
  10114. {selector: 'img,table', collapsed: false, styles: {'float': 'right'}}
  10115. ],
  10116. alignjustify: [
  10117. {selector: 'figure,p,h1,h2,h3,h4,h5,h6,td,th,tr,div,ul,ol,li', styles: {textAlign: 'justify'}, defaultBlock: 'div'}
  10118. ],
  10119. bold: [
  10120. {inline: 'strong', remove: 'all'},
  10121. {inline: 'span', styles: {fontWeight: 'bold'}},
  10122. {inline: 'b', remove: 'all'}
  10123. ],
  10124. italic: [
  10125. {inline: 'em', remove: 'all'},
  10126. {inline: 'span', styles: {fontStyle: 'italic'}},
  10127. {inline: 'i', remove: 'all'}
  10128. ],
  10129. underline: [
  10130. {inline: 'span', styles: {textDecoration: 'underline'}, exact: true},
  10131. {inline: 'u', remove: 'all'}
  10132. ],
  10133. strikethrough: [
  10134. {inline: 'span', styles: {textDecoration: 'line-through'}, exact: true},
  10135. {inline: 'strike', remove: 'all'}
  10136. ],
  10137. forecolor: {inline: 'span', styles: {color: '%value'}, wrap_links: false},
  10138. hilitecolor: {inline: 'span', styles: {backgroundColor: '%value'}, wrap_links: false},
  10139. fontname: {inline: 'span', styles: {fontFamily: '%value'}},
  10140. fontsize: {inline: 'span', styles: {fontSize: '%value'}},
  10141. fontsize_class: {inline: 'span', attributes: {'class': '%value'}},
  10142. blockquote: {block: 'blockquote', wrapper: 1, remove: 'all'},
  10143. subscript: {inline: 'sub'},
  10144. superscript: {inline: 'sup'},
  10145. code: {inline: 'code'},
  10146. link: {inline: 'a', selector: 'a', remove: 'all', split: true, deep: true,
  10147. onmatch: function() {
  10148. return true;
  10149. },
  10150. onformat: function(elm, fmt, vars) {
  10151. each(vars, function(value, key) {
  10152. dom.setAttrib(elm, key, value);
  10153. });
  10154. }
  10155. },
  10156. removeformat: [
  10157. {
  10158. selector: 'b,strong,em,i,font,u,strike,sub,sup,dfn,code,samp,kbd,var,cite,mark,q',
  10159. remove: 'all',
  10160. split: true,
  10161. expand: false,
  10162. block_expand: true,
  10163. deep: true
  10164. },
  10165. {selector: 'span', attributes: ['style', 'class'], remove: 'empty', split: true, expand: false, deep: true},
  10166. {selector: '*', attributes: ['style', 'class'], split: false, expand: false, deep: true}
  10167. ]
  10168. });
  10169. // Register default block formats
  10170. each('p h1 h2 h3 h4 h5 h6 div address pre div dt dd samp'.split(/\s/), function(name) {
  10171. register(name, {block: name, remove: 'all'});
  10172. });
  10173. // Register user defined formats
  10174. register(ed.settings.formats);
  10175. }
  10176. function addKeyboardShortcuts() {
  10177. // Add some inline shortcuts
  10178. ed.addShortcut('ctrl+b', 'bold_desc', 'Bold');
  10179. ed.addShortcut('ctrl+i', 'italic_desc', 'Italic');
  10180. ed.addShortcut('ctrl+u', 'underline_desc', 'Underline');
  10181. // BlockFormat shortcuts keys
  10182. for (var i = 1; i <= 6; i++) {
  10183. ed.addShortcut('ctrl+' + i, '', ['FormatBlock', false, 'h' + i]);
  10184. }
  10185. ed.addShortcut('ctrl+7', '', ['FormatBlock', false, 'p']);
  10186. ed.addShortcut('ctrl+8', '', ['FormatBlock', false, 'div']);
  10187. ed.addShortcut('ctrl+9', '', ['FormatBlock', false, 'address']);
  10188. }
  10189. // Public functions
  10190. /**
  10191. * Returns the format by name or all formats if no name is specified.
  10192. *
  10193. * @method get
  10194. * @param {String} name Optional name to retrive by.
  10195. * @return {Array/Object} Array/Object with all registred formats or a specific format.
  10196. */
  10197. function get(name) {
  10198. return name ? formats[name] : formats;
  10199. }
  10200. /**
  10201. * Registers a specific format by name.
  10202. *
  10203. * @method register
  10204. * @param {Object/String} name Name of the format for example "bold".
  10205. * @param {Object/Array} format Optional format object or array of format variants
  10206. * can only be omitted if the first arg is an object.
  10207. */
  10208. function register(name, format) {
  10209. if (name) {
  10210. if (typeof(name) !== 'string') {
  10211. each(name, function(format, name) {
  10212. register(name, format);
  10213. });
  10214. } else {
  10215. // Force format into array and add it to internal collection
  10216. format = format.length ? format : [format];
  10217. each(format, function(format) {
  10218. // Set deep to false by default on selector formats this to avoid removing
  10219. // alignment on images inside paragraphs when alignment is changed on paragraphs
  10220. if (format.deep === undef) {
  10221. format.deep = !format.selector;
  10222. }
  10223. // Default to true
  10224. if (format.split === undef) {
  10225. format.split = !format.selector || format.inline;
  10226. }
  10227. // Default to true
  10228. if (format.remove === undef && format.selector && !format.inline) {
  10229. format.remove = 'none';
  10230. }
  10231. // Mark format as a mixed format inline + block level
  10232. if (format.selector && format.inline) {
  10233. format.mixed = true;
  10234. format.block_expand = true;
  10235. }
  10236. // Split classes if needed
  10237. if (typeof(format.classes) === 'string') {
  10238. format.classes = format.classes.split(/\s+/);
  10239. }
  10240. });
  10241. formats[name] = format;
  10242. }
  10243. }
  10244. }
  10245. function getTextDecoration(node) {
  10246. var decoration;
  10247. ed.dom.getParent(node, function(n) {
  10248. decoration = ed.dom.getStyle(n, 'text-decoration');
  10249. return decoration && decoration !== 'none';
  10250. });
  10251. return decoration;
  10252. }
  10253. function processUnderlineAndColor(node) {
  10254. var textDecoration;
  10255. if (node.nodeType === 1 && node.parentNode && node.parentNode.nodeType === 1) {
  10256. textDecoration = getTextDecoration(node.parentNode);
  10257. if (ed.dom.getStyle(node, 'color') && textDecoration) {
  10258. ed.dom.setStyle(node, 'text-decoration', textDecoration);
  10259. } else if (ed.dom.getStyle(node, 'textdecoration') === textDecoration) {
  10260. ed.dom.setStyle(node, 'text-decoration', null);
  10261. }
  10262. }
  10263. }
  10264. /**
  10265. * Applies the specified format to the current selection or specified node.
  10266. *
  10267. * @method apply
  10268. * @param {String} name Name of format to apply.
  10269. * @param {Object} vars Optional list of variables to replace within format before applying it.
  10270. * @param {Node} node Optional node to apply the format to defaults to current selection.
  10271. */
  10272. function apply(name, vars, node) {
  10273. var formatList = get(name), format = formatList[0], bookmark, rng, isCollapsed = !node && selection.isCollapsed();
  10274. function setElementFormat(elm, fmt) {
  10275. fmt = fmt || format;
  10276. if (elm) {
  10277. if (fmt.onformat) {
  10278. fmt.onformat(elm, fmt, vars, node);
  10279. }
  10280. each(fmt.styles, function(value, name) {
  10281. dom.setStyle(elm, name, replaceVars(value, vars));
  10282. });
  10283. // Needed for the WebKit span spam bug
  10284. // TODO: Remove this once WebKit/Blink fixes this
  10285. if (fmt.styles) {
  10286. var styleVal = dom.getAttrib(elm, 'style');
  10287. if (styleVal) {
  10288. elm.setAttribute('data-mce-style', styleVal);
  10289. }
  10290. }
  10291. each(fmt.attributes, function(value, name) {
  10292. dom.setAttrib(elm, name, replaceVars(value, vars));
  10293. });
  10294. each(fmt.classes, function(value) {
  10295. value = replaceVars(value, vars);
  10296. if (!dom.hasClass(elm, value)) {
  10297. dom.addClass(elm, value);
  10298. }
  10299. });
  10300. }
  10301. }
  10302. function adjustSelectionToVisibleSelection() {
  10303. function findSelectionEnd(start, end) {
  10304. var walker = new TreeWalker(end);
  10305. for (node = walker.current(); node; node = walker.prev()) {
  10306. if (node.childNodes.length > 1 || node == start || node.tagName == 'BR') {
  10307. return node;
  10308. }
  10309. }
  10310. }
  10311. // Adjust selection so that a end container with a end offset of zero is not included in the selection
  10312. // as this isn't visible to the user.
  10313. var rng = ed.selection.getRng();
  10314. var start = rng.startContainer;
  10315. var end = rng.endContainer;
  10316. if (start != end && rng.endOffset === 0) {
  10317. var newEnd = findSelectionEnd(start, end);
  10318. var endOffset = newEnd.nodeType == 3 ? newEnd.length : newEnd.childNodes.length;
  10319. rng.setEnd(newEnd, endOffset);
  10320. }
  10321. return rng;
  10322. }
  10323. function applyStyleToList(node, bookmark, wrapElm, newWrappers, process){
  10324. var nodes = [], listIndex = -1, list, startIndex = -1, endIndex = -1, currentWrapElm;
  10325. // find the index of the first child list.
  10326. each(node.childNodes, function(n, index) {
  10327. if (n.nodeName === "UL" || n.nodeName === "OL") {
  10328. listIndex = index;
  10329. list = n;
  10330. return false;
  10331. }
  10332. });
  10333. // get the index of the bookmarks
  10334. each(node.childNodes, function(n, index) {
  10335. if (n.nodeName === "SPAN" && dom.getAttrib(n, "data-mce-type") == "bookmark") {
  10336. if (n.id == bookmark.id + "_start") {
  10337. startIndex = index;
  10338. } else if (n.id == bookmark.id + "_end") {
  10339. endIndex = index;
  10340. }
  10341. }
  10342. });
  10343. // if the selection spans across an embedded list, or there isn't an embedded list - handle processing normally
  10344. if (listIndex <= 0 || (startIndex < listIndex && endIndex > listIndex)) {
  10345. each(grep(node.childNodes), process);
  10346. return 0;
  10347. } else {
  10348. currentWrapElm = dom.clone(wrapElm, FALSE);
  10349. // create a list of the nodes on the same side of the list as the selection
  10350. each(grep(node.childNodes), function(n, index) {
  10351. if ((startIndex < listIndex && index < listIndex) || (startIndex > listIndex && index > listIndex)) {
  10352. nodes.push(n);
  10353. n.parentNode.removeChild(n);
  10354. }
  10355. });
  10356. // insert the wrapping element either before or after the list.
  10357. if (startIndex < listIndex) {
  10358. node.insertBefore(currentWrapElm, list);
  10359. } else if (startIndex > listIndex) {
  10360. node.insertBefore(currentWrapElm, list.nextSibling);
  10361. }
  10362. // add the new nodes to the list.
  10363. newWrappers.push(currentWrapElm);
  10364. each(nodes, function(node) {
  10365. currentWrapElm.appendChild(node);
  10366. });
  10367. return currentWrapElm;
  10368. }
  10369. }
  10370. function applyRngStyle(rng, bookmark, node_specific) {
  10371. var newWrappers = [], wrapName, wrapElm, contentEditable = true;
  10372. // Setup wrapper element
  10373. wrapName = format.inline || format.block;
  10374. wrapElm = dom.create(wrapName);
  10375. setElementFormat(wrapElm);
  10376. rangeUtils.walk(rng, function(nodes) {
  10377. var currentWrapElm;
  10378. /**
  10379. * Process a list of nodes wrap them.
  10380. */
  10381. function process(node) {
  10382. var nodeName, parentName, found, hasContentEditableState, lastContentEditable;
  10383. lastContentEditable = contentEditable;
  10384. nodeName = node.nodeName.toLowerCase();
  10385. parentName = node.parentNode.nodeName.toLowerCase();
  10386. // Node has a contentEditable value
  10387. if (node.nodeType === 1 && getContentEditable(node)) {
  10388. lastContentEditable = contentEditable;
  10389. contentEditable = getContentEditable(node) === "true";
  10390. hasContentEditableState = true; // We don't want to wrap the container only it's children
  10391. }
  10392. // Stop wrapping on br elements
  10393. if (isEq(nodeName, 'br')) {
  10394. currentWrapElm = 0;
  10395. // Remove any br elements when we wrap things
  10396. if (format.block) {
  10397. dom.remove(node);
  10398. }
  10399. return;
  10400. }
  10401. // If node is wrapper type
  10402. if (format.wrapper && matchNode(node, name, vars)) {
  10403. currentWrapElm = 0;
  10404. return;
  10405. }
  10406. // Can we rename the block
  10407. // TODO: Break this if up, too complex
  10408. if (contentEditable && !hasContentEditableState && format.block &&
  10409. !format.wrapper && isTextBlock(nodeName) && isValid(parentName, wrapName)) {
  10410. node = dom.rename(node, wrapName);
  10411. setElementFormat(node);
  10412. newWrappers.push(node);
  10413. currentWrapElm = 0;
  10414. return;
  10415. }
  10416. // Handle selector patterns
  10417. if (format.selector) {
  10418. // Look for matching formats
  10419. each(formatList, function(format) {
  10420. // Check collapsed state if it exists
  10421. if ('collapsed' in format && format.collapsed !== isCollapsed) {
  10422. return;
  10423. }
  10424. if (dom.is(node, format.selector) && !isCaretNode(node)) {
  10425. setElementFormat(node, format);
  10426. found = true;
  10427. }
  10428. });
  10429. // Continue processing if a selector match wasn't found and a inline element is defined
  10430. if (!format.inline || found) {
  10431. currentWrapElm = 0;
  10432. return;
  10433. }
  10434. }
  10435. // Is it valid to wrap this item
  10436. // TODO: Break this if up, too complex
  10437. if (contentEditable && !hasContentEditableState && isValid(wrapName, nodeName) && isValid(parentName, wrapName) &&
  10438. !(!node_specific && node.nodeType === 3 &&
  10439. node.nodeValue.length === 1 &&
  10440. node.nodeValue.charCodeAt(0) === 65279) &&
  10441. !isCaretNode(node) &&
  10442. (!format.inline || !isBlock(node))) {
  10443. // Start wrapping
  10444. if (!currentWrapElm) {
  10445. // Wrap the node
  10446. currentWrapElm = dom.clone(wrapElm, FALSE);
  10447. node.parentNode.insertBefore(currentWrapElm, node);
  10448. newWrappers.push(currentWrapElm);
  10449. }
  10450. currentWrapElm.appendChild(node);
  10451. } else if (nodeName == 'li' && bookmark) {
  10452. // Start wrapping - if we are in a list node and have a bookmark, then
  10453. // we will always begin by wrapping in a new element.
  10454. currentWrapElm = applyStyleToList(node, bookmark, wrapElm, newWrappers, process);
  10455. } else {
  10456. // Start a new wrapper for possible children
  10457. currentWrapElm = 0;
  10458. each(grep(node.childNodes), process);
  10459. if (hasContentEditableState) {
  10460. contentEditable = lastContentEditable; // Restore last contentEditable state from stack
  10461. }
  10462. // End the last wrapper
  10463. currentWrapElm = 0;
  10464. }
  10465. }
  10466. // Process siblings from range
  10467. each(nodes, process);
  10468. });
  10469. // Wrap links inside as well, for example color inside a link when the wrapper is around the link
  10470. if (format.wrap_links === false) {
  10471. each(newWrappers, function(node) {
  10472. function process(node) {
  10473. var i, currentWrapElm, children;
  10474. if (node.nodeName === 'A') {
  10475. currentWrapElm = dom.clone(wrapElm, FALSE);
  10476. newWrappers.push(currentWrapElm);
  10477. children = grep(node.childNodes);
  10478. for (i = 0; i < children.length; i++) {
  10479. currentWrapElm.appendChild(children[i]);
  10480. }
  10481. node.appendChild(currentWrapElm);
  10482. }
  10483. each(grep(node.childNodes), process);
  10484. }
  10485. process(node);
  10486. });
  10487. }
  10488. // Cleanup
  10489. each(newWrappers, function(node) {
  10490. var childCount;
  10491. function getChildCount(node) {
  10492. var count = 0;
  10493. each(node.childNodes, function(node) {
  10494. if (!isWhiteSpaceNode(node) && !isBookmarkNode(node)) {
  10495. count++;
  10496. }
  10497. });
  10498. return count;
  10499. }
  10500. function mergeStyles(node) {
  10501. var child, clone;
  10502. each(node.childNodes, function(node) {
  10503. if (node.nodeType == 1 && !isBookmarkNode(node) && !isCaretNode(node)) {
  10504. child = node;
  10505. return FALSE; // break loop
  10506. }
  10507. });
  10508. // If child was found and of the same type as the current node
  10509. if (child && !isBookmarkNode(child) && matchName(child, format)) {
  10510. clone = dom.clone(child, FALSE);
  10511. setElementFormat(clone);
  10512. dom.replace(clone, node, TRUE);
  10513. dom.remove(child, 1);
  10514. }
  10515. return clone || node;
  10516. }
  10517. childCount = getChildCount(node);
  10518. // Remove empty nodes but only if there is multiple wrappers and they are not block
  10519. // elements so never remove single <h1></h1> since that would remove the
  10520. // currrent empty block element where the caret is at
  10521. if ((newWrappers.length > 1 || !isBlock(node)) && childCount === 0) {
  10522. dom.remove(node, 1);
  10523. return;
  10524. }
  10525. if (format.inline || format.wrapper) {
  10526. // Merges the current node with it's children of similar type to reduce the number of elements
  10527. if (!format.exact && childCount === 1) {
  10528. node = mergeStyles(node);
  10529. }
  10530. // Remove/merge children
  10531. each(formatList, function(format) {
  10532. // Merge all children of similar type will move styles from child to parent
  10533. // this: <span style="color:red"><b><span style="color:red; font-size:10px">text</span></b></span>
  10534. // will become: <span style="color:red"><b><span style="font-size:10px">text</span></b></span>
  10535. each(dom.select(format.inline, node), function(child) {
  10536. var parent;
  10537. if (isBookmarkNode(child)) {
  10538. return;
  10539. }
  10540. // When wrap_links is set to false we don't want
  10541. // to remove the format on children within links
  10542. if (format.wrap_links === false) {
  10543. parent = child.parentNode;
  10544. do {
  10545. if (parent.nodeName === 'A') {
  10546. return;
  10547. }
  10548. } while ((parent = parent.parentNode));
  10549. }
  10550. removeFormat(format, vars, child, format.exact ? child : null);
  10551. });
  10552. });
  10553. // Remove child if direct parent is of same type
  10554. if (matchNode(node.parentNode, name, vars)) {
  10555. dom.remove(node, 1);
  10556. node = 0;
  10557. return TRUE;
  10558. }
  10559. // Look for parent with similar style format
  10560. if (format.merge_with_parents) {
  10561. dom.getParent(node.parentNode, function(parent) {
  10562. if (matchNode(parent, name, vars)) {
  10563. dom.remove(node, 1);
  10564. node = 0;
  10565. return TRUE;
  10566. }
  10567. });
  10568. }
  10569. // Merge next and previous siblings if they are similar <b>text</b><b>text</b> becomes <b>texttext</b>
  10570. if (node && format.merge_siblings !== false) {
  10571. node = mergeSiblings(getNonWhiteSpaceSibling(node), node);
  10572. node = mergeSiblings(node, getNonWhiteSpaceSibling(node, TRUE));
  10573. }
  10574. }
  10575. });
  10576. }
  10577. if (format) {
  10578. if (node) {
  10579. if (node.nodeType) {
  10580. rng = dom.createRng();
  10581. rng.setStartBefore(node);
  10582. rng.setEndAfter(node);
  10583. applyRngStyle(expandRng(rng, formatList), null, true);
  10584. } else {
  10585. applyRngStyle(node, null, true);
  10586. }
  10587. } else {
  10588. if (!isCollapsed || !format.inline || dom.select('td.mce-item-selected,th.mce-item-selected').length) {
  10589. // Obtain selection node before selection is unselected by applyRngStyle()
  10590. var curSelNode = ed.selection.getNode();
  10591. // If the formats have a default block and we can't find a parent block then
  10592. // start wrapping it with a DIV this is for forced_root_blocks: false
  10593. // It's kind of a hack but people should be using the default block type P since all desktop editors work that way
  10594. if (!forcedRootBlock && formatList[0].defaultBlock && !dom.getParent(curSelNode, dom.isBlock)) {
  10595. apply(formatList[0].defaultBlock);
  10596. }
  10597. // Apply formatting to selection
  10598. ed.selection.setRng(adjustSelectionToVisibleSelection());
  10599. bookmark = selection.getBookmark();
  10600. applyRngStyle(expandRng(selection.getRng(TRUE), formatList), bookmark);
  10601. // Colored nodes should be underlined so that the color of the underline matches the text color.
  10602. if (format.styles && (format.styles.color || format.styles.textDecoration)) {
  10603. walk(curSelNode, processUnderlineAndColor, 'childNodes');
  10604. processUnderlineAndColor(curSelNode);
  10605. }
  10606. selection.moveToBookmark(bookmark);
  10607. moveStart(selection.getRng(TRUE));
  10608. ed.nodeChanged();
  10609. } else {
  10610. performCaretAction('apply', name, vars);
  10611. }
  10612. }
  10613. }
  10614. }
  10615. /**
  10616. * Removes the specified format from the current selection or specified node.
  10617. *
  10618. * @method remove
  10619. * @param {String} name Name of format to remove.
  10620. * @param {Object} vars Optional list of variables to replace within format before removing it.
  10621. * @param {Node/Range} node Optional node or DOM range to remove the format from defaults to current selection.
  10622. */
  10623. function remove(name, vars, node) {
  10624. var formatList = get(name), format = formatList[0], bookmark, rng, contentEditable = true;
  10625. // Merges the styles for each node
  10626. function process(node) {
  10627. var children, i, l, lastContentEditable, hasContentEditableState;
  10628. // Node has a contentEditable value
  10629. if (node.nodeType === 1 && getContentEditable(node)) {
  10630. lastContentEditable = contentEditable;
  10631. contentEditable = getContentEditable(node) === "true";
  10632. hasContentEditableState = true; // We don't want to wrap the container only it's children
  10633. }
  10634. // Grab the children first since the nodelist might be changed
  10635. children = grep(node.childNodes);
  10636. // Process current node
  10637. if (contentEditable && !hasContentEditableState) {
  10638. for (i = 0, l = formatList.length; i < l; i++) {
  10639. if (removeFormat(formatList[i], vars, node, node)) {
  10640. break;
  10641. }
  10642. }
  10643. }
  10644. // Process the children
  10645. if (format.deep) {
  10646. if (children.length) {
  10647. for (i = 0, l = children.length; i < l; i++) {
  10648. process(children[i]);
  10649. }
  10650. if (hasContentEditableState) {
  10651. contentEditable = lastContentEditable; // Restore last contentEditable state from stack
  10652. }
  10653. }
  10654. }
  10655. }
  10656. function findFormatRoot(container) {
  10657. var formatRoot;
  10658. // Find format root
  10659. each(getParents(container.parentNode).reverse(), function(parent) {
  10660. var format;
  10661. // Find format root element
  10662. if (!formatRoot && parent.id != '_start' && parent.id != '_end') {
  10663. // Is the node matching the format we are looking for
  10664. format = matchNode(parent, name, vars);
  10665. if (format && format.split !== false) {
  10666. formatRoot = parent;
  10667. }
  10668. }
  10669. });
  10670. return formatRoot;
  10671. }
  10672. function wrapAndSplit(format_root, container, target, split) {
  10673. var parent, clone, lastClone, firstClone, i, formatRootParent;
  10674. // Format root found then clone formats and split it
  10675. if (format_root) {
  10676. formatRootParent = format_root.parentNode;
  10677. for (parent = container.parentNode; parent && parent != formatRootParent; parent = parent.parentNode) {
  10678. clone = dom.clone(parent, FALSE);
  10679. for (i = 0; i < formatList.length; i++) {
  10680. if (removeFormat(formatList[i], vars, clone, clone)) {
  10681. clone = 0;
  10682. break;
  10683. }
  10684. }
  10685. // Build wrapper node
  10686. if (clone) {
  10687. if (lastClone) {
  10688. clone.appendChild(lastClone);
  10689. }
  10690. if (!firstClone) {
  10691. firstClone = clone;
  10692. }
  10693. lastClone = clone;
  10694. }
  10695. }
  10696. // Never split block elements if the format is mixed
  10697. if (split && (!format.mixed || !isBlock(format_root))) {
  10698. container = dom.split(format_root, container);
  10699. }
  10700. // Wrap container in cloned formats
  10701. if (lastClone) {
  10702. target.parentNode.insertBefore(lastClone, target);
  10703. firstClone.appendChild(target);
  10704. }
  10705. }
  10706. return container;
  10707. }
  10708. function splitToFormatRoot(container) {
  10709. return wrapAndSplit(findFormatRoot(container), container, container, true);
  10710. }
  10711. function unwrap(start) {
  10712. var node = dom.get(start ? '_start' : '_end'),
  10713. out = node[start ? 'firstChild' : 'lastChild'];
  10714. // If the end is placed within the start the result will be removed
  10715. // So this checks if the out node is a bookmark node if it is it
  10716. // checks for another more suitable node
  10717. if (isBookmarkNode(out)) {
  10718. out = out[start ? 'firstChild' : 'lastChild'];
  10719. }
  10720. dom.remove(node, true);
  10721. return out;
  10722. }
  10723. function removeRngStyle(rng) {
  10724. var startContainer, endContainer;
  10725. var commonAncestorContainer = rng.commonAncestorContainer;
  10726. rng = expandRng(rng, formatList, TRUE);
  10727. if (format.split) {
  10728. startContainer = getContainer(rng, TRUE);
  10729. endContainer = getContainer(rng);
  10730. if (startContainer != endContainer) {
  10731. // WebKit will render the table incorrectly if we wrap a TH or TD in a SPAN
  10732. // so let's see if we can use the first child instead
  10733. // This will happen if you triple click a table cell and use remove formatting
  10734. if (/^(TR|TH|TD)$/.test(startContainer.nodeName) && startContainer.firstChild) {
  10735. if (startContainer.nodeName == "TR") {
  10736. startContainer = startContainer.firstChild.firstChild || startContainer;
  10737. } else {
  10738. startContainer = startContainer.firstChild || startContainer;
  10739. }
  10740. }
  10741. // Try to adjust endContainer as well if cells on the same row were selected - bug #6410
  10742. if (commonAncestorContainer &&
  10743. /^T(HEAD|BODY|FOOT|R)$/.test(commonAncestorContainer.nodeName) &&
  10744. /^(TH|TD)$/.test(endContainer.nodeName) && endContainer.firstChild) {
  10745. endContainer = endContainer.firstChild || endContainer;
  10746. }
  10747. // Wrap start/end nodes in span element since these might be cloned/moved
  10748. startContainer = wrap(startContainer, 'span', {id: '_start', 'data-mce-type': 'bookmark'});
  10749. endContainer = wrap(endContainer, 'span', {id: '_end', 'data-mce-type': 'bookmark'});
  10750. // Split start/end
  10751. splitToFormatRoot(startContainer);
  10752. splitToFormatRoot(endContainer);
  10753. // Unwrap start/end to get real elements again
  10754. startContainer = unwrap(TRUE);
  10755. endContainer = unwrap();
  10756. } else {
  10757. startContainer = endContainer = splitToFormatRoot(startContainer);
  10758. }
  10759. // Update range positions since they might have changed after the split operations
  10760. rng.startContainer = startContainer.parentNode;
  10761. rng.startOffset = nodeIndex(startContainer);
  10762. rng.endContainer = endContainer.parentNode;
  10763. rng.endOffset = nodeIndex(endContainer) + 1;
  10764. }
  10765. // Remove items between start/end
  10766. rangeUtils.walk(rng, function(nodes) {
  10767. each(nodes, function(node) {
  10768. process(node);
  10769. // Remove parent span if it only contains text-decoration: underline, yet a parent node is also underlined.
  10770. if (node.nodeType === 1 && ed.dom.getStyle(node, 'text-decoration') === 'underline' &&
  10771. node.parentNode && getTextDecoration(node.parentNode) === 'underline') {
  10772. removeFormat({
  10773. 'deep': false,
  10774. 'exact': true,
  10775. 'inline': 'span',
  10776. 'styles': {
  10777. 'textDecoration': 'underline'
  10778. }
  10779. }, null, node);
  10780. }
  10781. });
  10782. });
  10783. }
  10784. // Handle node
  10785. if (node) {
  10786. if (node.nodeType) {
  10787. rng = dom.createRng();
  10788. rng.setStartBefore(node);
  10789. rng.setEndAfter(node);
  10790. removeRngStyle(rng);
  10791. } else {
  10792. removeRngStyle(node);
  10793. }
  10794. return;
  10795. }
  10796. if (!selection.isCollapsed() || !format.inline || dom.select('td.mce-item-selected,th.mce-item-selected').length) {
  10797. bookmark = selection.getBookmark();
  10798. removeRngStyle(selection.getRng(TRUE));
  10799. selection.moveToBookmark(bookmark);
  10800. // Check if start element still has formatting then we are at: "<b>text|</b>text"
  10801. // and need to move the start into the next text node
  10802. if (format.inline && match(name, vars, selection.getStart())) {
  10803. moveStart(selection.getRng(true));
  10804. }
  10805. ed.nodeChanged();
  10806. } else {
  10807. performCaretAction('remove', name, vars);
  10808. }
  10809. }
  10810. /**
  10811. * Toggles the specified format on/off.
  10812. *
  10813. * @method toggle
  10814. * @param {String} name Name of format to apply/remove.
  10815. * @param {Object} vars Optional list of variables to replace within format before applying/removing it.
  10816. * @param {Node} node Optional node to apply the format to or remove from. Defaults to current selection.
  10817. */
  10818. function toggle(name, vars, node) {
  10819. var fmt = get(name);
  10820. if (match(name, vars, node) && (!('toggle' in fmt[0]) || fmt[0].toggle)) {
  10821. remove(name, vars, node);
  10822. } else {
  10823. apply(name, vars, node);
  10824. }
  10825. }
  10826. /**
  10827. * Return true/false if the specified node has the specified format.
  10828. *
  10829. * @method matchNode
  10830. * @param {Node} node Node to check the format on.
  10831. * @param {String} name Format name to check.
  10832. * @param {Object} vars Optional list of variables to replace before checking it.
  10833. * @param {Boolean} similar Match format that has similar properties.
  10834. * @return {Object} Returns the format object it matches or undefined if it doesn't match.
  10835. */
  10836. function matchNode(node, name, vars, similar) {
  10837. var formatList = get(name), format, i, classes;
  10838. function matchItems(node, format, item_name) {
  10839. var key, value, items = format[item_name], i;
  10840. // Custom match
  10841. if (format.onmatch) {
  10842. return format.onmatch(node, format, item_name);
  10843. }
  10844. // Check all items
  10845. if (items) {
  10846. // Non indexed object
  10847. if (items.length === undef) {
  10848. for (key in items) {
  10849. if (items.hasOwnProperty(key)) {
  10850. if (item_name === 'attributes') {
  10851. value = dom.getAttrib(node, key);
  10852. } else {
  10853. value = getStyle(node, key);
  10854. }
  10855. if (similar && !value && !format.exact) {
  10856. return;
  10857. }
  10858. if ((!similar || format.exact) && !isEq(value, normalizeStyleValue(replaceVars(items[key], vars), key))) {
  10859. return;
  10860. }
  10861. }
  10862. }
  10863. } else {
  10864. // Only one match needed for indexed arrays
  10865. for (i = 0; i < items.length; i++) {
  10866. if (item_name === 'attributes' ? dom.getAttrib(node, items[i]) : getStyle(node, items[i])) {
  10867. return format;
  10868. }
  10869. }
  10870. }
  10871. }
  10872. return format;
  10873. }
  10874. if (formatList && node) {
  10875. // Check each format in list
  10876. for (i = 0; i < formatList.length; i++) {
  10877. format = formatList[i];
  10878. // Name name, attributes, styles and classes
  10879. if (matchName(node, format) && matchItems(node, format, 'attributes') && matchItems(node, format, 'styles')) {
  10880. // Match classes
  10881. if ((classes = format.classes)) {
  10882. for (i = 0; i < classes.length; i++) {
  10883. if (!dom.hasClass(node, classes[i])) {
  10884. return;
  10885. }
  10886. }
  10887. }
  10888. return format;
  10889. }
  10890. }
  10891. }
  10892. }
  10893. /**
  10894. * Matches the current selection or specified node against the specified format name.
  10895. *
  10896. * @method match
  10897. * @param {String} name Name of format to match.
  10898. * @param {Object} vars Optional list of variables to replace before checking it.
  10899. * @param {Node} node Optional node to check.
  10900. * @return {boolean} true/false if the specified selection/node matches the format.
  10901. */
  10902. function match(name, vars, node) {
  10903. var startNode;
  10904. function matchParents(node) {
  10905. var root = dom.getRoot();
  10906. if (node === root) {
  10907. return false;
  10908. }
  10909. // Find first node with similar format settings
  10910. node = dom.getParent(node, function(node) {
  10911. return node.parentNode === root || !!matchNode(node, name, vars, true);
  10912. });
  10913. // Do an exact check on the similar format element
  10914. return matchNode(node, name, vars);
  10915. }
  10916. // Check specified node
  10917. if (node) {
  10918. return matchParents(node);
  10919. }
  10920. // Check selected node
  10921. node = selection.getNode();
  10922. if (matchParents(node)) {
  10923. return TRUE;
  10924. }
  10925. // Check start node if it's different
  10926. startNode = selection.getStart();
  10927. if (startNode != node) {
  10928. if (matchParents(startNode)) {
  10929. return TRUE;
  10930. }
  10931. }
  10932. return FALSE;
  10933. }
  10934. /**
  10935. * Matches the current selection against the array of formats and returns a new array with matching formats.
  10936. *
  10937. * @method matchAll
  10938. * @param {Array} names Name of format to match.
  10939. * @param {Object} vars Optional list of variables to replace before checking it.
  10940. * @return {Array} Array with matched formats.
  10941. */
  10942. function matchAll(names, vars) {
  10943. var startElement, matchedFormatNames = [], checkedMap = {};
  10944. // Check start of selection for formats
  10945. startElement = selection.getStart();
  10946. dom.getParent(startElement, function(node) {
  10947. var i, name;
  10948. for (i = 0; i < names.length; i++) {
  10949. name = names[i];
  10950. if (!checkedMap[name] && matchNode(node, name, vars)) {
  10951. checkedMap[name] = true;
  10952. matchedFormatNames.push(name);
  10953. }
  10954. }
  10955. }, dom.getRoot());
  10956. return matchedFormatNames;
  10957. }
  10958. /**
  10959. * Returns true/false if the specified format can be applied to the current selection or not. It
  10960. * will currently only check the state for selector formats, it returns true on all other format types.
  10961. *
  10962. * @method canApply
  10963. * @param {String} name Name of format to check.
  10964. * @return {boolean} true/false if the specified format can be applied to the current selection/node.
  10965. */
  10966. function canApply(name) {
  10967. var formatList = get(name), startNode, parents, i, x, selector;
  10968. if (formatList) {
  10969. startNode = selection.getStart();
  10970. parents = getParents(startNode);
  10971. for (x = formatList.length - 1; x >= 0; x--) {
  10972. selector = formatList[x].selector;
  10973. // Format is not selector based then always return TRUE
  10974. // Is it has a defaultBlock then it's likely it can be applied for example align on a non block element line
  10975. if (!selector || formatList[x].defaultBlock) {
  10976. return TRUE;
  10977. }
  10978. for (i = parents.length - 1; i >= 0; i--) {
  10979. if (dom.is(parents[i], selector)) {
  10980. return TRUE;
  10981. }
  10982. }
  10983. }
  10984. }
  10985. return FALSE;
  10986. }
  10987. /**
  10988. * Executes the specified callback when the current selection matches the formats or not.
  10989. *
  10990. * @method formatChanged
  10991. * @param {String} formats Comma separated list of formats to check for.
  10992. * @param {function} callback Callback with state and args when the format is changed/toggled on/off.
  10993. * @param {Boolean} similar True/false state if the match should handle similar or exact formats.
  10994. */
  10995. function formatChanged(formats, callback, similar) {
  10996. var currentFormats;
  10997. // Setup format node change logic
  10998. if (!formatChangeData) {
  10999. formatChangeData = {};
  11000. currentFormats = {};
  11001. ed.on('NodeChange', function(e) {
  11002. var parents = getParents(e.element), matchedFormats = {};
  11003. // Check for new formats
  11004. each(formatChangeData, function(callbacks, format) {
  11005. each(parents, function(node) {
  11006. if (matchNode(node, format, {}, callbacks.similar)) {
  11007. if (!currentFormats[format]) {
  11008. // Execute callbacks
  11009. each(callbacks, function(callback) {
  11010. callback(true, {node: node, format: format, parents: parents});
  11011. });
  11012. currentFormats[format] = callbacks;
  11013. }
  11014. matchedFormats[format] = callbacks;
  11015. return false;
  11016. }
  11017. });
  11018. });
  11019. // Check if current formats still match
  11020. each(currentFormats, function(callbacks, format) {
  11021. if (!matchedFormats[format]) {
  11022. delete currentFormats[format];
  11023. each(callbacks, function(callback) {
  11024. callback(false, {node: e.element, format: format, parents: parents});
  11025. });
  11026. }
  11027. });
  11028. });
  11029. }
  11030. // Add format listeners
  11031. each(formats.split(','), function(format) {
  11032. if (!formatChangeData[format]) {
  11033. formatChangeData[format] = [];
  11034. formatChangeData[format].similar = similar;
  11035. }
  11036. formatChangeData[format].push(callback);
  11037. });
  11038. return this;
  11039. }
  11040. /**
  11041. * Returns a preview css text for the specified format.
  11042. *
  11043. * @method getCssText
  11044. * @param {String/Object} format Format to generate preview css text for.
  11045. * @return {String} Css text for the specified format.
  11046. * @example
  11047. * var cssText1 = editor.formatter.getCssText('bold');
  11048. * var cssText2 = editor.formatter.getCssText({inline: 'b'});
  11049. */
  11050. function getCssText(format) {
  11051. return Preview.getCssText(ed, format);
  11052. }
  11053. // Expose to public
  11054. extend(this, {
  11055. get: get,
  11056. register: register,
  11057. apply: apply,
  11058. remove: remove,
  11059. toggle: toggle,
  11060. match: match,
  11061. matchAll: matchAll,
  11062. matchNode: matchNode,
  11063. canApply: canApply,
  11064. formatChanged: formatChanged,
  11065. getCssText: getCssText
  11066. });
  11067. // Initialize
  11068. defaultFormats();
  11069. addKeyboardShortcuts();
  11070. ed.on('BeforeGetContent', function() {
  11071. if (markCaretContainersBogus) {
  11072. markCaretContainersBogus();
  11073. }
  11074. });
  11075. ed.on('mouseup keydown', function(e) {
  11076. if (disableCaretContainer) {
  11077. disableCaretContainer(e);
  11078. }
  11079. });
  11080. // Private functions
  11081. /**
  11082. * Checks if the specified nodes name matches the format inline/block or selector.
  11083. *
  11084. * @private
  11085. * @param {Node} node Node to match against the specified format.
  11086. * @param {Object} format Format object o match with.
  11087. * @return {boolean} true/false if the format matches.
  11088. */
  11089. function matchName(node, format) {
  11090. // Check for inline match
  11091. if (isEq(node, format.inline)) {
  11092. return TRUE;
  11093. }
  11094. // Check for block match
  11095. if (isEq(node, format.block)) {
  11096. return TRUE;
  11097. }
  11098. // Check for selector match
  11099. if (format.selector) {
  11100. return node.nodeType == 1 && dom.is(node, format.selector);
  11101. }
  11102. }
  11103. /**
  11104. * Compares two string/nodes regardless of their case.
  11105. *
  11106. * @private
  11107. * @param {String/Node} Node or string to compare.
  11108. * @param {String/Node} Node or string to compare.
  11109. * @return {boolean} True/false if they match.
  11110. */
  11111. function isEq(str1, str2) {
  11112. str1 = str1 || '';
  11113. str2 = str2 || '';
  11114. str1 = '' + (str1.nodeName || str1);
  11115. str2 = '' + (str2.nodeName || str2);
  11116. return str1.toLowerCase() == str2.toLowerCase();
  11117. }
  11118. /**
  11119. * Returns the style by name on the specified node. This method modifies the style
  11120. * contents to make it more easy to match. This will resolve a few browser issues.
  11121. *
  11122. * @private
  11123. * @param {Node} node to get style from.
  11124. * @param {String} name Style name to get.
  11125. * @return {String} Style item value.
  11126. */
  11127. function getStyle(node, name) {
  11128. return normalizeStyleValue(dom.getStyle(node, name), name);
  11129. }
  11130. /**
  11131. * Normalize style value by name. This method modifies the style contents
  11132. * to make it more easy to match. This will resolve a few browser issues.
  11133. *
  11134. * @private
  11135. * @param {Node} node to get style from.
  11136. * @param {String} name Style name to get.
  11137. * @return {String} Style item value.
  11138. */
  11139. function normalizeStyleValue(value, name) {
  11140. // Force the format to hex
  11141. if (name == 'color' || name == 'backgroundColor') {
  11142. value = dom.toHex(value);
  11143. }
  11144. // Opera will return bold as 700
  11145. if (name == 'fontWeight' && value == 700) {
  11146. value = 'bold';
  11147. }
  11148. // Normalize fontFamily so "'Font name', Font" becomes: "Font name,Font"
  11149. if (name == 'fontFamily') {
  11150. value = value.replace(/[\'\"]/g, '').replace(/,\s+/g, ',');
  11151. }
  11152. return '' + value;
  11153. }
  11154. /**
  11155. * Replaces variables in the value. The variable format is %var.
  11156. *
  11157. * @private
  11158. * @param {String} value Value to replace variables in.
  11159. * @param {Object} vars Name/value array with variables to replace.
  11160. * @return {String} New value with replaced variables.
  11161. */
  11162. function replaceVars(value, vars) {
  11163. if (typeof(value) != "string") {
  11164. value = value(vars);
  11165. } else if (vars) {
  11166. value = value.replace(/%(\w+)/g, function(str, name) {
  11167. return vars[name] || str;
  11168. });
  11169. }
  11170. return value;
  11171. }
  11172. function isWhiteSpaceNode(node) {
  11173. return node && node.nodeType === 3 && /^([\t \r\n]+|)$/.test(node.nodeValue);
  11174. }
  11175. function wrap(node, name, attrs) {
  11176. var wrapper = dom.create(name, attrs);
  11177. node.parentNode.insertBefore(wrapper, node);
  11178. wrapper.appendChild(node);
  11179. return wrapper;
  11180. }
  11181. /**
  11182. * Expands the specified range like object to depending on format.
  11183. *
  11184. * For example on block formats it will move the start/end position
  11185. * to the beginning of the current block.
  11186. *
  11187. * @private
  11188. * @param {Object} rng Range like object.
  11189. * @param {Array} formats Array with formats to expand by.
  11190. * @return {Object} Expanded range like object.
  11191. */
  11192. function expandRng(rng, format, remove) {
  11193. var lastIdx, leaf, endPoint,
  11194. startContainer = rng.startContainer,
  11195. startOffset = rng.startOffset,
  11196. endContainer = rng.endContainer,
  11197. endOffset = rng.endOffset;
  11198. // This function walks up the tree if there is no siblings before/after the node
  11199. function findParentContainer(start) {
  11200. var container, parent, sibling, siblingName, root;
  11201. container = parent = start ? startContainer : endContainer;
  11202. siblingName = start ? 'previousSibling' : 'nextSibling';
  11203. root = dom.getRoot();
  11204. function isBogusBr(node) {
  11205. return node.nodeName == "BR" && node.getAttribute('data-mce-bogus') && !node.nextSibling;
  11206. }
  11207. // If it's a text node and the offset is inside the text
  11208. if (container.nodeType == 3 && !isWhiteSpaceNode(container)) {
  11209. if (start ? startOffset > 0 : endOffset < container.nodeValue.length) {
  11210. return container;
  11211. }
  11212. }
  11213. /*eslint no-constant-condition:0 */
  11214. while (true) {
  11215. // Stop expanding on block elements
  11216. if (!format[0].block_expand && isBlock(parent)) {
  11217. return parent;
  11218. }
  11219. // Walk left/right
  11220. for (sibling = parent[siblingName]; sibling; sibling = sibling[siblingName]) {
  11221. if (!isBookmarkNode(sibling) && !isWhiteSpaceNode(sibling) && !isBogusBr(sibling)) {
  11222. return parent;
  11223. }
  11224. }
  11225. // Check if we can move up are we at root level or body level
  11226. if (parent.parentNode == root) {
  11227. container = parent;
  11228. break;
  11229. }
  11230. parent = parent.parentNode;
  11231. }
  11232. return container;
  11233. }
  11234. // This function walks down the tree to find the leaf at the selection.
  11235. // The offset is also returned as if node initially a leaf, the offset may be in the middle of the text node.
  11236. function findLeaf(node, offset) {
  11237. if (offset === undef) {
  11238. offset = node.nodeType === 3 ? node.length : node.childNodes.length;
  11239. }
  11240. while (node && node.hasChildNodes()) {
  11241. node = node.childNodes[offset];
  11242. if (node) {
  11243. offset = node.nodeType === 3 ? node.length : node.childNodes.length;
  11244. }
  11245. }
  11246. return { node: node, offset: offset };
  11247. }
  11248. // If index based start position then resolve it
  11249. if (startContainer.nodeType == 1 && startContainer.hasChildNodes()) {
  11250. lastIdx = startContainer.childNodes.length - 1;
  11251. startContainer = startContainer.childNodes[startOffset > lastIdx ? lastIdx : startOffset];
  11252. if (startContainer.nodeType == 3) {
  11253. startOffset = 0;
  11254. }
  11255. }
  11256. // If index based end position then resolve it
  11257. if (endContainer.nodeType == 1 && endContainer.hasChildNodes()) {
  11258. lastIdx = endContainer.childNodes.length - 1;
  11259. endContainer = endContainer.childNodes[endOffset > lastIdx ? lastIdx : endOffset - 1];
  11260. if (endContainer.nodeType == 3) {
  11261. endOffset = endContainer.nodeValue.length;
  11262. }
  11263. }
  11264. // Expands the node to the closes contentEditable false element if it exists
  11265. function findParentContentEditable(node) {
  11266. var parent = node;
  11267. while (parent) {
  11268. if (parent.nodeType === 1 && getContentEditable(parent)) {
  11269. return getContentEditable(parent) === "false" ? parent : node;
  11270. }
  11271. parent = parent.parentNode;
  11272. }
  11273. return node;
  11274. }
  11275. function findWordEndPoint(container, offset, start) {
  11276. var walker, node, pos, lastTextNode;
  11277. function findSpace(node, offset) {
  11278. var pos, pos2, str = node.nodeValue;
  11279. if (typeof(offset) == "undefined") {
  11280. offset = start ? str.length : 0;
  11281. }
  11282. if (start) {
  11283. pos = str.lastIndexOf(' ', offset);
  11284. pos2 = str.lastIndexOf('\u00a0', offset);
  11285. pos = pos > pos2 ? pos : pos2;
  11286. // Include the space on remove to avoid tag soup
  11287. if (pos !== -1 && !remove) {
  11288. pos++;
  11289. }
  11290. } else {
  11291. pos = str.indexOf(' ', offset);
  11292. pos2 = str.indexOf('\u00a0', offset);
  11293. pos = pos !== -1 && (pos2 === -1 || pos < pos2) ? pos : pos2;
  11294. }
  11295. return pos;
  11296. }
  11297. if (container.nodeType === 3) {
  11298. pos = findSpace(container, offset);
  11299. if (pos !== -1) {
  11300. return {container: container, offset: pos};
  11301. }
  11302. lastTextNode = container;
  11303. }
  11304. // Walk the nodes inside the block
  11305. walker = new TreeWalker(container, dom.getParent(container, isBlock) || ed.getBody());
  11306. while ((node = walker[start ? 'prev' : 'next']())) {
  11307. if (node.nodeType === 3) {
  11308. lastTextNode = node;
  11309. pos = findSpace(node);
  11310. if (pos !== -1) {
  11311. return {container: node, offset: pos};
  11312. }
  11313. } else if (isBlock(node)) {
  11314. break;
  11315. }
  11316. }
  11317. if (lastTextNode) {
  11318. if (start) {
  11319. offset = 0;
  11320. } else {
  11321. offset = lastTextNode.length;
  11322. }
  11323. return {container: lastTextNode, offset: offset};
  11324. }
  11325. }
  11326. function findSelectorEndPoint(container, sibling_name) {
  11327. var parents, i, y, curFormat;
  11328. if (container.nodeType == 3 && container.nodeValue.length === 0 && container[sibling_name]) {
  11329. container = container[sibling_name];
  11330. }
  11331. parents = getParents(container);
  11332. for (i = 0; i < parents.length; i++) {
  11333. for (y = 0; y < format.length; y++) {
  11334. curFormat = format[y];
  11335. // If collapsed state is set then skip formats that doesn't match that
  11336. if ("collapsed" in curFormat && curFormat.collapsed !== rng.collapsed) {
  11337. continue;
  11338. }
  11339. if (dom.is(parents[i], curFormat.selector)) {
  11340. return parents[i];
  11341. }
  11342. }
  11343. }
  11344. return container;
  11345. }
  11346. function findBlockEndPoint(container, sibling_name) {
  11347. var node, root = dom.getRoot();
  11348. // Expand to block of similar type
  11349. if (!format[0].wrapper) {
  11350. node = dom.getParent(container, format[0].block, root);
  11351. }
  11352. // Expand to first wrappable block element or any block element
  11353. if (!node) {
  11354. node = dom.getParent(container.nodeType == 3 ? container.parentNode : container, function(node) {
  11355. // Fixes #6183 where it would expand to editable parent element in inline mode
  11356. return node != root && isTextBlock(node);
  11357. });
  11358. }
  11359. // Exclude inner lists from wrapping
  11360. if (node && format[0].wrapper) {
  11361. node = getParents(node, 'ul,ol').reverse()[0] || node;
  11362. }
  11363. // Didn't find a block element look for first/last wrappable element
  11364. if (!node) {
  11365. node = container;
  11366. while (node[sibling_name] && !isBlock(node[sibling_name])) {
  11367. node = node[sibling_name];
  11368. // Break on BR but include it will be removed later on
  11369. // we can't remove it now since we need to check if it can be wrapped
  11370. if (isEq(node, 'br')) {
  11371. break;
  11372. }
  11373. }
  11374. }
  11375. return node || container;
  11376. }
  11377. // Expand to closest contentEditable element
  11378. startContainer = findParentContentEditable(startContainer);
  11379. endContainer = findParentContentEditable(endContainer);
  11380. // Exclude bookmark nodes if possible
  11381. if (isBookmarkNode(startContainer.parentNode) || isBookmarkNode(startContainer)) {
  11382. startContainer = isBookmarkNode(startContainer) ? startContainer : startContainer.parentNode;
  11383. startContainer = startContainer.nextSibling || startContainer;
  11384. if (startContainer.nodeType == 3) {
  11385. startOffset = 0;
  11386. }
  11387. }
  11388. if (isBookmarkNode(endContainer.parentNode) || isBookmarkNode(endContainer)) {
  11389. endContainer = isBookmarkNode(endContainer) ? endContainer : endContainer.parentNode;
  11390. endContainer = endContainer.previousSibling || endContainer;
  11391. if (endContainer.nodeType == 3) {
  11392. endOffset = endContainer.length;
  11393. }
  11394. }
  11395. if (format[0].inline) {
  11396. if (rng.collapsed) {
  11397. // Expand left to closest word boundary
  11398. endPoint = findWordEndPoint(startContainer, startOffset, true);
  11399. if (endPoint) {
  11400. startContainer = endPoint.container;
  11401. startOffset = endPoint.offset;
  11402. }
  11403. // Expand right to closest word boundary
  11404. endPoint = findWordEndPoint(endContainer, endOffset);
  11405. if (endPoint) {
  11406. endContainer = endPoint.container;
  11407. endOffset = endPoint.offset;
  11408. }
  11409. }
  11410. // Avoid applying formatting to a trailing space.
  11411. leaf = findLeaf(endContainer, endOffset);
  11412. if (leaf.node) {
  11413. while (leaf.node && leaf.offset === 0 && leaf.node.previousSibling) {
  11414. leaf = findLeaf(leaf.node.previousSibling);
  11415. }
  11416. if (leaf.node && leaf.offset > 0 && leaf.node.nodeType === 3 &&
  11417. leaf.node.nodeValue.charAt(leaf.offset - 1) === ' ') {
  11418. if (leaf.offset > 1) {
  11419. endContainer = leaf.node;
  11420. endContainer.splitText(leaf.offset - 1);
  11421. }
  11422. }
  11423. }
  11424. }
  11425. // Move start/end point up the tree if the leaves are sharp and if we are in different containers
  11426. // Example * becomes !: !<p><b><i>*text</i><i>text*</i></b></p>!
  11427. // This will reduce the number of wrapper elements that needs to be created
  11428. // Move start point up the tree
  11429. if (format[0].inline || format[0].block_expand) {
  11430. if (!format[0].inline || (startContainer.nodeType != 3 || startOffset === 0)) {
  11431. startContainer = findParentContainer(true);
  11432. }
  11433. if (!format[0].inline || (endContainer.nodeType != 3 || endOffset === endContainer.nodeValue.length)) {
  11434. endContainer = findParentContainer();
  11435. }
  11436. }
  11437. // Expand start/end container to matching selector
  11438. if (format[0].selector && format[0].expand !== FALSE && !format[0].inline) {
  11439. // Find new startContainer/endContainer if there is better one
  11440. startContainer = findSelectorEndPoint(startContainer, 'previousSibling');
  11441. endContainer = findSelectorEndPoint(endContainer, 'nextSibling');
  11442. }
  11443. // Expand start/end container to matching block element or text node
  11444. if (format[0].block || format[0].selector) {
  11445. // Find new startContainer/endContainer if there is better one
  11446. startContainer = findBlockEndPoint(startContainer, 'previousSibling');
  11447. endContainer = findBlockEndPoint(endContainer, 'nextSibling');
  11448. // Non block element then try to expand up the leaf
  11449. if (format[0].block) {
  11450. if (!isBlock(startContainer)) {
  11451. startContainer = findParentContainer(true);
  11452. }
  11453. if (!isBlock(endContainer)) {
  11454. endContainer = findParentContainer();
  11455. }
  11456. }
  11457. }
  11458. // Setup index for startContainer
  11459. if (startContainer.nodeType == 1) {
  11460. startOffset = nodeIndex(startContainer);
  11461. startContainer = startContainer.parentNode;
  11462. }
  11463. // Setup index for endContainer
  11464. if (endContainer.nodeType == 1) {
  11465. endOffset = nodeIndex(endContainer) + 1;
  11466. endContainer = endContainer.parentNode;
  11467. }
  11468. // Return new range like object
  11469. return {
  11470. startContainer: startContainer,
  11471. startOffset: startOffset,
  11472. endContainer: endContainer,
  11473. endOffset: endOffset
  11474. };
  11475. }
  11476. /**
  11477. * Removes the specified format for the specified node. It will also remove the node if it doesn't have
  11478. * any attributes if the format specifies it to do so.
  11479. *
  11480. * @private
  11481. * @param {Object} format Format object with items to remove from node.
  11482. * @param {Object} vars Name/value object with variables to apply to format.
  11483. * @param {Node} node Node to remove the format styles on.
  11484. * @param {Node} compare_node Optional compare node, if specified the styles will be compared to that node.
  11485. * @return {Boolean} True/false if the node was removed or not.
  11486. */
  11487. function removeFormat(format, vars, node, compare_node) {
  11488. var i, attrs, stylesModified;
  11489. // Check if node matches format
  11490. if (!matchName(node, format)) {
  11491. return FALSE;
  11492. }
  11493. // Should we compare with format attribs and styles
  11494. if (format.remove != 'all') {
  11495. // Remove styles
  11496. each(format.styles, function(value, name) {
  11497. value = normalizeStyleValue(replaceVars(value, vars), name);
  11498. // Indexed array
  11499. if (typeof(name) === 'number') {
  11500. name = value;
  11501. compare_node = 0;
  11502. }
  11503. if (!compare_node || isEq(getStyle(compare_node, name), value)) {
  11504. dom.setStyle(node, name, '');
  11505. }
  11506. stylesModified = 1;
  11507. });
  11508. // Remove style attribute if it's empty
  11509. if (stylesModified && dom.getAttrib(node, 'style') === '') {
  11510. node.removeAttribute('style');
  11511. node.removeAttribute('data-mce-style');
  11512. }
  11513. // Remove attributes
  11514. each(format.attributes, function(value, name) {
  11515. var valueOut;
  11516. value = replaceVars(value, vars);
  11517. // Indexed array
  11518. if (typeof(name) === 'number') {
  11519. name = value;
  11520. compare_node = 0;
  11521. }
  11522. if (!compare_node || isEq(dom.getAttrib(compare_node, name), value)) {
  11523. // Keep internal classes
  11524. if (name == 'class') {
  11525. value = dom.getAttrib(node, name);
  11526. if (value) {
  11527. // Build new class value where everything is removed except the internal prefixed classes
  11528. valueOut = '';
  11529. each(value.split(/\s+/), function(cls) {
  11530. if (/mce\w+/.test(cls)) {
  11531. valueOut += (valueOut ? ' ' : '') + cls;
  11532. }
  11533. });
  11534. // We got some internal classes left
  11535. if (valueOut) {
  11536. dom.setAttrib(node, name, valueOut);
  11537. return;
  11538. }
  11539. }
  11540. }
  11541. // IE6 has a bug where the attribute doesn't get removed correctly
  11542. if (name == "class") {
  11543. node.removeAttribute('className');
  11544. }
  11545. // Remove mce prefixed attributes
  11546. if (MCE_ATTR_RE.test(name)) {
  11547. node.removeAttribute('data-mce-' + name);
  11548. }
  11549. node.removeAttribute(name);
  11550. }
  11551. });
  11552. // Remove classes
  11553. each(format.classes, function(value) {
  11554. value = replaceVars(value, vars);
  11555. if (!compare_node || dom.hasClass(compare_node, value)) {
  11556. dom.removeClass(node, value);
  11557. }
  11558. });
  11559. // Check for non internal attributes
  11560. attrs = dom.getAttribs(node);
  11561. for (i = 0; i < attrs.length; i++) {
  11562. if (attrs[i].nodeName.indexOf('_') !== 0) {
  11563. return FALSE;
  11564. }
  11565. }
  11566. }
  11567. // Remove the inline child if it's empty for example <b> or <span>
  11568. if (format.remove != 'none') {
  11569. removeNode(node, format);
  11570. return TRUE;
  11571. }
  11572. }
  11573. /**
  11574. * Removes the node and wrap it's children in paragraphs before doing so or
  11575. * appends BR elements to the beginning/end of the block element if forcedRootBlocks is disabled.
  11576. *
  11577. * If the div in the node below gets removed:
  11578. * text<div>text</div>text
  11579. *
  11580. * Output becomes:
  11581. * text<div><br />text<br /></div>text
  11582. *
  11583. * So when the div is removed the result is:
  11584. * text<br />text<br />text
  11585. *
  11586. * @private
  11587. * @param {Node} node Node to remove + apply BR/P elements to.
  11588. * @param {Object} format Format rule.
  11589. * @return {Node} Input node.
  11590. */
  11591. function removeNode(node, format) {
  11592. var parentNode = node.parentNode, rootBlockElm;
  11593. function find(node, next, inc) {
  11594. node = getNonWhiteSpaceSibling(node, next, inc);
  11595. return !node || (node.nodeName == 'BR' || isBlock(node));
  11596. }
  11597. if (format.block) {
  11598. if (!forcedRootBlock) {
  11599. // Append BR elements if needed before we remove the block
  11600. if (isBlock(node) && !isBlock(parentNode)) {
  11601. if (!find(node, FALSE) && !find(node.firstChild, TRUE, 1)) {
  11602. node.insertBefore(dom.create('br'), node.firstChild);
  11603. }
  11604. if (!find(node, TRUE) && !find(node.lastChild, FALSE, 1)) {
  11605. node.appendChild(dom.create('br'));
  11606. }
  11607. }
  11608. } else {
  11609. // Wrap the block in a forcedRootBlock if we are at the root of document
  11610. if (parentNode == dom.getRoot()) {
  11611. if (!format.list_block || !isEq(node, format.list_block)) {
  11612. each(grep(node.childNodes), function(node) {
  11613. if (isValid(forcedRootBlock, node.nodeName.toLowerCase())) {
  11614. if (!rootBlockElm) {
  11615. rootBlockElm = wrap(node, forcedRootBlock);
  11616. dom.setAttribs(rootBlockElm, ed.settings.forced_root_block_attrs);
  11617. } else {
  11618. rootBlockElm.appendChild(node);
  11619. }
  11620. } else {
  11621. rootBlockElm = 0;
  11622. }
  11623. });
  11624. }
  11625. }
  11626. }
  11627. }
  11628. // Never remove nodes that isn't the specified inline element if a selector is specified too
  11629. if (format.selector && format.inline && !isEq(format.inline, node)) {
  11630. return;
  11631. }
  11632. dom.remove(node, 1);
  11633. }
  11634. /**
  11635. * Returns the next/previous non whitespace node.
  11636. *
  11637. * @private
  11638. * @param {Node} node Node to start at.
  11639. * @param {boolean} next (Optional) Include next or previous node defaults to previous.
  11640. * @param {boolean} inc (Optional) Include the current node in checking. Defaults to false.
  11641. * @return {Node} Next or previous node or undefined if it wasn't found.
  11642. */
  11643. function getNonWhiteSpaceSibling(node, next, inc) {
  11644. if (node) {
  11645. next = next ? 'nextSibling' : 'previousSibling';
  11646. for (node = inc ? node : node[next]; node; node = node[next]) {
  11647. if (node.nodeType == 1 || !isWhiteSpaceNode(node)) {
  11648. return node;
  11649. }
  11650. }
  11651. }
  11652. }
  11653. /**
  11654. * Checks if the specified node is a bookmark node or not.
  11655. *
  11656. * @private
  11657. * @param {Node} node Node to check if it's a bookmark node or not.
  11658. * @return {Boolean} true/false if the node is a bookmark node.
  11659. */
  11660. function isBookmarkNode(node) {
  11661. return node && node.nodeType == 1 && node.getAttribute('data-mce-type') == 'bookmark';
  11662. }
  11663. /**
  11664. * Merges the next/previous sibling element if they match.
  11665. *
  11666. * @private
  11667. * @param {Node} prev Previous node to compare/merge.
  11668. * @param {Node} next Next node to compare/merge.
  11669. * @return {Node} Next node if we didn't merge and prev node if we did.
  11670. */
  11671. function mergeSiblings(prev, next) {
  11672. var sibling, tmpSibling;
  11673. /**
  11674. * Compares two nodes and checks if it's attributes and styles matches.
  11675. * This doesn't compare classes as items since their order is significant.
  11676. *
  11677. * @private
  11678. * @param {Node} node1 First node to compare with.
  11679. * @param {Node} node2 Second node to compare with.
  11680. * @return {boolean} True/false if the nodes are the same or not.
  11681. */
  11682. function compareElements(node1, node2) {
  11683. // Not the same name
  11684. if (node1.nodeName != node2.nodeName) {
  11685. return FALSE;
  11686. }
  11687. /**
  11688. * Returns all the nodes attributes excluding internal ones, styles and classes.
  11689. *
  11690. * @private
  11691. * @param {Node} node Node to get attributes from.
  11692. * @return {Object} Name/value object with attributes and attribute values.
  11693. */
  11694. function getAttribs(node) {
  11695. var attribs = {};
  11696. each(dom.getAttribs(node), function(attr) {
  11697. var name = attr.nodeName.toLowerCase();
  11698. // Don't compare internal attributes or style
  11699. if (name.indexOf('_') !== 0 && name !== 'style' && name !== 'data-mce-style') {
  11700. attribs[name] = dom.getAttrib(node, name);
  11701. }
  11702. });
  11703. return attribs;
  11704. }
  11705. /**
  11706. * Compares two objects checks if it's key + value exists in the other one.
  11707. *
  11708. * @private
  11709. * @param {Object} obj1 First object to compare.
  11710. * @param {Object} obj2 Second object to compare.
  11711. * @return {boolean} True/false if the objects matches or not.
  11712. */
  11713. function compareObjects(obj1, obj2) {
  11714. var value, name;
  11715. for (name in obj1) {
  11716. // Obj1 has item obj2 doesn't have
  11717. if (obj1.hasOwnProperty(name)) {
  11718. value = obj2[name];
  11719. // Obj2 doesn't have obj1 item
  11720. if (value === undef) {
  11721. return FALSE;
  11722. }
  11723. // Obj2 item has a different value
  11724. if (obj1[name] != value) {
  11725. return FALSE;
  11726. }
  11727. // Delete similar value
  11728. delete obj2[name];
  11729. }
  11730. }
  11731. // Check if obj 2 has something obj 1 doesn't have
  11732. for (name in obj2) {
  11733. // Obj2 has item obj1 doesn't have
  11734. if (obj2.hasOwnProperty(name)) {
  11735. return FALSE;
  11736. }
  11737. }
  11738. return TRUE;
  11739. }
  11740. // Attribs are not the same
  11741. if (!compareObjects(getAttribs(node1), getAttribs(node2))) {
  11742. return FALSE;
  11743. }
  11744. // Styles are not the same
  11745. if (!compareObjects(dom.parseStyle(dom.getAttrib(node1, 'style')), dom.parseStyle(dom.getAttrib(node2, 'style')))) {
  11746. return FALSE;
  11747. }
  11748. return !isBookmarkNode(node1) && !isBookmarkNode(node2);
  11749. }
  11750. function findElementSibling(node, sibling_name) {
  11751. for (sibling = node; sibling; sibling = sibling[sibling_name]) {
  11752. if (sibling.nodeType == 3 && sibling.nodeValue.length !== 0) {
  11753. return node;
  11754. }
  11755. if (sibling.nodeType == 1 && !isBookmarkNode(sibling)) {
  11756. return sibling;
  11757. }
  11758. }
  11759. return node;
  11760. }
  11761. // Check if next/prev exists and that they are elements
  11762. if (prev && next) {
  11763. // If previous sibling is empty then jump over it
  11764. prev = findElementSibling(prev, 'previousSibling');
  11765. next = findElementSibling(next, 'nextSibling');
  11766. // Compare next and previous nodes
  11767. if (compareElements(prev, next)) {
  11768. // Append nodes between
  11769. for (sibling = prev.nextSibling; sibling && sibling != next;) {
  11770. tmpSibling = sibling;
  11771. sibling = sibling.nextSibling;
  11772. prev.appendChild(tmpSibling);
  11773. }
  11774. // Remove next node
  11775. dom.remove(next);
  11776. // Move children into prev node
  11777. each(grep(next.childNodes), function(node) {
  11778. prev.appendChild(node);
  11779. });
  11780. return prev;
  11781. }
  11782. }
  11783. return next;
  11784. }
  11785. function getContainer(rng, start) {
  11786. var container, offset, lastIdx;
  11787. container = rng[start ? 'startContainer' : 'endContainer'];
  11788. offset = rng[start ? 'startOffset' : 'endOffset'];
  11789. if (container.nodeType == 1) {
  11790. lastIdx = container.childNodes.length - 1;
  11791. if (!start && offset) {
  11792. offset--;
  11793. }
  11794. container = container.childNodes[offset > lastIdx ? lastIdx : offset];
  11795. }
  11796. // If start text node is excluded then walk to the next node
  11797. if (container.nodeType === 3 && start && offset >= container.nodeValue.length) {
  11798. container = new TreeWalker(container, ed.getBody()).next() || container;
  11799. }
  11800. // If end text node is excluded then walk to the previous node
  11801. if (container.nodeType === 3 && !start && offset === 0) {
  11802. container = new TreeWalker(container, ed.getBody()).prev() || container;
  11803. }
  11804. return container;
  11805. }
  11806. function performCaretAction(type, name, vars) {
  11807. var caretContainerId = '_mce_caret', debug = ed.settings.caret_debug;
  11808. // Creates a caret container bogus element
  11809. function createCaretContainer(fill) {
  11810. var caretContainer = dom.create('span', {id: caretContainerId, 'data-mce-bogus': true, style: debug ? 'color:red' : ''});
  11811. if (fill) {
  11812. caretContainer.appendChild(ed.getDoc().createTextNode(INVISIBLE_CHAR));
  11813. }
  11814. return caretContainer;
  11815. }
  11816. function isCaretContainerEmpty(node, nodes) {
  11817. while (node) {
  11818. if ((node.nodeType === 3 && node.nodeValue !== INVISIBLE_CHAR) || node.childNodes.length > 1) {
  11819. return false;
  11820. }
  11821. // Collect nodes
  11822. if (nodes && node.nodeType === 1) {
  11823. nodes.push(node);
  11824. }
  11825. node = node.firstChild;
  11826. }
  11827. return true;
  11828. }
  11829. // Returns any parent caret container element
  11830. function getParentCaretContainer(node) {
  11831. while (node) {
  11832. if (node.id === caretContainerId) {
  11833. return node;
  11834. }
  11835. node = node.parentNode;
  11836. }
  11837. }
  11838. // Finds the first text node in the specified node
  11839. function findFirstTextNode(node) {
  11840. var walker;
  11841. if (node) {
  11842. walker = new TreeWalker(node, node);
  11843. for (node = walker.current(); node; node = walker.next()) {
  11844. if (node.nodeType === 3) {
  11845. return node;
  11846. }
  11847. }
  11848. }
  11849. }
  11850. // Removes the caret container for the specified node or all on the current document
  11851. function removeCaretContainer(node, move_caret) {
  11852. var child, rng;
  11853. if (!node) {
  11854. node = getParentCaretContainer(selection.getStart());
  11855. if (!node) {
  11856. while ((node = dom.get(caretContainerId))) {
  11857. removeCaretContainer(node, false);
  11858. }
  11859. }
  11860. } else {
  11861. rng = selection.getRng(true);
  11862. if (isCaretContainerEmpty(node)) {
  11863. if (move_caret !== false) {
  11864. rng.setStartBefore(node);
  11865. rng.setEndBefore(node);
  11866. }
  11867. dom.remove(node);
  11868. } else {
  11869. child = findFirstTextNode(node);
  11870. if (child.nodeValue.charAt(0) === INVISIBLE_CHAR) {
  11871. child = child.deleteData(0, 1);
  11872. }
  11873. dom.remove(node, 1);
  11874. }
  11875. selection.setRng(rng);
  11876. }
  11877. }
  11878. // Applies formatting to the caret postion
  11879. function applyCaretFormat() {
  11880. var rng, caretContainer, textNode, offset, bookmark, container, text;
  11881. rng = selection.getRng(true);
  11882. offset = rng.startOffset;
  11883. container = rng.startContainer;
  11884. text = container.nodeValue;
  11885. caretContainer = getParentCaretContainer(selection.getStart());
  11886. if (caretContainer) {
  11887. textNode = findFirstTextNode(caretContainer);
  11888. }
  11889. // Expand to word is caret is in the middle of a text node and the char before/after is a alpha numeric character
  11890. if (text && offset > 0 && offset < text.length && /\w/.test(text.charAt(offset)) && /\w/.test(text.charAt(offset - 1))) {
  11891. // Get bookmark of caret position
  11892. bookmark = selection.getBookmark();
  11893. // Collapse bookmark range (WebKit)
  11894. rng.collapse(true);
  11895. // Expand the range to the closest word and split it at those points
  11896. rng = expandRng(rng, get(name));
  11897. rng = rangeUtils.split(rng);
  11898. // Apply the format to the range
  11899. apply(name, vars, rng);
  11900. // Move selection back to caret position
  11901. selection.moveToBookmark(bookmark);
  11902. } else {
  11903. if (!caretContainer || textNode.nodeValue !== INVISIBLE_CHAR) {
  11904. caretContainer = createCaretContainer(true);
  11905. textNode = caretContainer.firstChild;
  11906. rng.insertNode(caretContainer);
  11907. offset = 1;
  11908. apply(name, vars, caretContainer);
  11909. } else {
  11910. apply(name, vars, caretContainer);
  11911. }
  11912. // Move selection to text node
  11913. selection.setCursorLocation(textNode, offset);
  11914. }
  11915. }
  11916. function removeCaretFormat() {
  11917. var rng = selection.getRng(true), container, offset, bookmark,
  11918. hasContentAfter, node, formatNode, parents = [], i, caretContainer;
  11919. container = rng.startContainer;
  11920. offset = rng.startOffset;
  11921. node = container;
  11922. if (container.nodeType == 3) {
  11923. if (offset != container.nodeValue.length || container.nodeValue === INVISIBLE_CHAR) {
  11924. hasContentAfter = true;
  11925. }
  11926. node = node.parentNode;
  11927. }
  11928. while (node) {
  11929. if (matchNode(node, name, vars)) {
  11930. formatNode = node;
  11931. break;
  11932. }
  11933. if (node.nextSibling) {
  11934. hasContentAfter = true;
  11935. }
  11936. parents.push(node);
  11937. node = node.parentNode;
  11938. }
  11939. // Node doesn't have the specified format
  11940. if (!formatNode) {
  11941. return;
  11942. }
  11943. // Is there contents after the caret then remove the format on the element
  11944. if (hasContentAfter) {
  11945. // Get bookmark of caret position
  11946. bookmark = selection.getBookmark();
  11947. // Collapse bookmark range (WebKit)
  11948. rng.collapse(true);
  11949. // Expand the range to the closest word and split it at those points
  11950. rng = expandRng(rng, get(name), true);
  11951. rng = rangeUtils.split(rng);
  11952. // Remove the format from the range
  11953. remove(name, vars, rng);
  11954. // Move selection back to caret position
  11955. selection.moveToBookmark(bookmark);
  11956. } else {
  11957. caretContainer = createCaretContainer();
  11958. node = caretContainer;
  11959. for (i = parents.length - 1; i >= 0; i--) {
  11960. node.appendChild(dom.clone(parents[i], false));
  11961. node = node.firstChild;
  11962. }
  11963. // Insert invisible character into inner most format element
  11964. node.appendChild(dom.doc.createTextNode(INVISIBLE_CHAR));
  11965. node = node.firstChild;
  11966. var block = dom.getParent(formatNode, isTextBlock);
  11967. if (block && dom.isEmpty(block)) {
  11968. // Replace formatNode with caretContainer when removing format from empty block like <p><b>|</b></p>
  11969. formatNode.parentNode.replaceChild(caretContainer, formatNode);
  11970. } else {
  11971. // Insert caret container after the formated node
  11972. dom.insertAfter(caretContainer, formatNode);
  11973. }
  11974. // Move selection to text node
  11975. selection.setCursorLocation(node, 1);
  11976. // If the formatNode is empty, we can remove it safely.
  11977. if (dom.isEmpty(formatNode)) {
  11978. dom.remove(formatNode);
  11979. }
  11980. }
  11981. }
  11982. // Checks if the parent caret container node isn't empty if that is the case it
  11983. // will remove the bogus state on all children that isn't empty
  11984. function unmarkBogusCaretParents() {
  11985. var caretContainer;
  11986. caretContainer = getParentCaretContainer(selection.getStart());
  11987. if (caretContainer && !dom.isEmpty(caretContainer)) {
  11988. walk(caretContainer, function(node) {
  11989. if (node.nodeType == 1 && node.id !== caretContainerId && !dom.isEmpty(node)) {
  11990. dom.setAttrib(node, 'data-mce-bogus', null);
  11991. }
  11992. }, 'childNodes');
  11993. }
  11994. }
  11995. // Only bind the caret events once
  11996. if (!ed._hasCaretEvents) {
  11997. // Mark current caret container elements as bogus when getting the contents so we don't end up with empty elements
  11998. markCaretContainersBogus = function() {
  11999. var nodes = [], i;
  12000. if (isCaretContainerEmpty(getParentCaretContainer(selection.getStart()), nodes)) {
  12001. // Mark children
  12002. i = nodes.length;
  12003. while (i--) {
  12004. dom.setAttrib(nodes[i], 'data-mce-bogus', '1');
  12005. }
  12006. }
  12007. };
  12008. disableCaretContainer = function(e) {
  12009. var keyCode = e.keyCode;
  12010. removeCaretContainer();
  12011. // Remove caret container on keydown and it's a backspace, enter or left/right arrow keys
  12012. if (keyCode == 8 || keyCode == 37 || keyCode == 39) {
  12013. removeCaretContainer(getParentCaretContainer(selection.getStart()));
  12014. }
  12015. unmarkBogusCaretParents();
  12016. };
  12017. // Remove bogus state if they got filled by contents using editor.selection.setContent
  12018. ed.on('SetContent', function(e) {
  12019. if (e.selection) {
  12020. unmarkBogusCaretParents();
  12021. }
  12022. });
  12023. ed._hasCaretEvents = true;
  12024. }
  12025. // Do apply or remove caret format
  12026. if (type == "apply") {
  12027. applyCaretFormat();
  12028. } else {
  12029. removeCaretFormat();
  12030. }
  12031. }
  12032. /**
  12033. * Moves the start to the first suitable text node.
  12034. */
  12035. function moveStart(rng) {
  12036. var container = rng.startContainer,
  12037. offset = rng.startOffset, isAtEndOfText,
  12038. walker, node, nodes, tmpNode;
  12039. // Convert text node into index if possible
  12040. if (container.nodeType == 3 && offset >= container.nodeValue.length) {
  12041. // Get the parent container location and walk from there
  12042. offset = nodeIndex(container);
  12043. container = container.parentNode;
  12044. isAtEndOfText = true;
  12045. }
  12046. // Move startContainer/startOffset in to a suitable node
  12047. if (container.nodeType == 1) {
  12048. nodes = container.childNodes;
  12049. container = nodes[Math.min(offset, nodes.length - 1)];
  12050. walker = new TreeWalker(container, dom.getParent(container, dom.isBlock));
  12051. // If offset is at end of the parent node walk to the next one
  12052. if (offset > nodes.length - 1 || isAtEndOfText) {
  12053. walker.next();
  12054. }
  12055. for (node = walker.current(); node; node = walker.next()) {
  12056. if (node.nodeType == 3 && !isWhiteSpaceNode(node)) {
  12057. // IE has a "neat" feature where it moves the start node into the closest element
  12058. // we can avoid this by inserting an element before it and then remove it after we set the selection
  12059. tmpNode = dom.create('a', null, INVISIBLE_CHAR);
  12060. node.parentNode.insertBefore(tmpNode, node);
  12061. // Set selection and remove tmpNode
  12062. rng.setStart(node, 0);
  12063. selection.setRng(rng);
  12064. dom.remove(tmpNode);
  12065. return;
  12066. }
  12067. }
  12068. }
  12069. }
  12070. };
  12071. });
  12072. // Included from: js/tinymce/classes/UndoManager.js
  12073. /**
  12074. * UndoManager.js
  12075. *
  12076. * Copyright, Moxiecode Systems AB
  12077. * Released under LGPL License.
  12078. *
  12079. * License: http://www.tinymce.com/license
  12080. * Contributing: http://www.tinymce.com/contributing
  12081. */
  12082. /**
  12083. * This class handles the undo/redo history levels for the editor. Since the build in undo/redo has major drawbacks a custom one was needed.
  12084. *
  12085. * @class tinymce.UndoManager
  12086. */
  12087. define("tinymce/UndoManager", [
  12088. "tinymce/Env",
  12089. "tinymce/util/Tools"
  12090. ], function(Env, Tools) {
  12091. var trim = Tools.trim, trimContentRegExp;
  12092. trimContentRegExp = new RegExp([
  12093. '<span[^>]+data-mce-bogus[^>]+>[\u200B\uFEFF]+<\\/span>', // Trim bogus spans like caret containers
  12094. '<div[^>]+data-mce-bogus[^>]+><\\/div>', // Trim bogus divs like resize handles
  12095. '\\s?data-mce-selected="[^"]+"' // Trim temporaty data-mce prefixed attributes like data-mce-selected
  12096. ].join('|'), 'gi');
  12097. return function(editor) {
  12098. var self = this, index = 0, data = [], beforeBookmark, isFirstTypedCharacter, locks = 0;
  12099. // Returns a trimmed version of the current editor contents
  12100. function getContent() {
  12101. return trim(editor.getContent({format: 'raw', no_events: 1}).replace(trimContentRegExp, ''));
  12102. }
  12103. function addNonTypingUndoLevel(e) {
  12104. self.typing = false;
  12105. self.add({}, e);
  12106. }
  12107. // Add initial undo level when the editor is initialized
  12108. editor.on('init', function() {
  12109. self.add();
  12110. });
  12111. // Get position before an execCommand is processed
  12112. editor.on('BeforeExecCommand', function(e) {
  12113. var cmd = e.command;
  12114. if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') {
  12115. self.beforeChange();
  12116. }
  12117. });
  12118. // Add undo level after an execCommand call was made
  12119. editor.on('ExecCommand', function(e) {
  12120. var cmd = e.command;
  12121. if (cmd != 'Undo' && cmd != 'Redo' && cmd != 'mceRepaint') {
  12122. addNonTypingUndoLevel(e);
  12123. }
  12124. });
  12125. editor.on('ObjectResizeStart', function() {
  12126. self.beforeChange();
  12127. });
  12128. editor.on('SaveContent ObjectResized blur', addNonTypingUndoLevel);
  12129. editor.dom.bind(editor.dom.getRoot(), 'dragend', addNonTypingUndoLevel);
  12130. editor.on('KeyUp', function(e) {
  12131. var keyCode = e.keyCode;
  12132. if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45 || keyCode == 13 || e.ctrlKey) {
  12133. addNonTypingUndoLevel();
  12134. editor.nodeChanged();
  12135. }
  12136. if (keyCode == 46 || keyCode == 8 || (Env.mac && (keyCode == 91 || keyCode == 93))) {
  12137. editor.nodeChanged();
  12138. }
  12139. // Fire a TypingUndo event on the first character entered
  12140. if (isFirstTypedCharacter && self.typing) {
  12141. // Make the it dirty if the content was changed after typing the first character
  12142. if (!editor.isDirty()) {
  12143. editor.isNotDirty = !data[0] || getContent() == data[0].content;
  12144. // Fire initial change event
  12145. if (!editor.isNotDirty) {
  12146. editor.fire('change', {level: data[0], lastLevel: null});
  12147. }
  12148. }
  12149. editor.fire('TypingUndo');
  12150. isFirstTypedCharacter = false;
  12151. editor.nodeChanged();
  12152. }
  12153. });
  12154. editor.on('KeyDown', function(e) {
  12155. var keyCode = e.keyCode;
  12156. // Is caracter positon keys left,right,up,down,home,end,pgdown,pgup,enter
  12157. if ((keyCode >= 33 && keyCode <= 36) || (keyCode >= 37 && keyCode <= 40) || keyCode == 45) {
  12158. if (self.typing) {
  12159. addNonTypingUndoLevel(e);
  12160. }
  12161. return;
  12162. }
  12163. // If key isn't shift,ctrl,alt,capslock,metakey
  12164. if ((keyCode < 16 || keyCode > 20) && keyCode != 224 && keyCode != 91 && !self.typing) {
  12165. self.beforeChange();
  12166. self.typing = true;
  12167. self.add({}, e);
  12168. isFirstTypedCharacter = true;
  12169. }
  12170. });
  12171. editor.on('MouseDown', function(e) {
  12172. if (self.typing) {
  12173. addNonTypingUndoLevel(e);
  12174. }
  12175. });
  12176. // Add keyboard shortcuts for undo/redo keys
  12177. editor.addShortcut('ctrl+z', '', 'Undo');
  12178. editor.addShortcut('ctrl+y,ctrl+shift+z', '', 'Redo');
  12179. editor.on('AddUndo Undo Redo ClearUndos MouseUp', function(e) {
  12180. if (!e.isDefaultPrevented()) {
  12181. editor.nodeChanged();
  12182. }
  12183. });
  12184. self = {
  12185. // Explose for debugging reasons
  12186. data: data,
  12187. /**
  12188. * State if the user is currently typing or not. This will add a typing operation into one undo
  12189. * level instead of one new level for each keystroke.
  12190. *
  12191. * @field {Boolean} typing
  12192. */
  12193. typing: false,
  12194. /**
  12195. * Stores away a bookmark to be used when performing an undo action so that the selection is before
  12196. * the change has been made.
  12197. *
  12198. * @method beforeChange
  12199. */
  12200. beforeChange: function() {
  12201. if (!locks) {
  12202. beforeBookmark = editor.selection.getBookmark(2, true);
  12203. }
  12204. },
  12205. /**
  12206. * Adds a new undo level/snapshot to the undo list.
  12207. *
  12208. * @method add
  12209. * @param {Object} level Optional undo level object to add.
  12210. * @param {DOMEvent} Event Optional event responsible for the creation of the undo level.
  12211. * @return {Object} Undo level that got added or null it a level wasn't needed.
  12212. */
  12213. add: function(level, event) {
  12214. var i, settings = editor.settings, lastLevel;
  12215. level = level || {};
  12216. level.content = getContent();
  12217. if (locks || editor.removed) {
  12218. return null;
  12219. }
  12220. lastLevel = data[index];
  12221. if (editor.fire('BeforeAddUndo', {level: level, lastLevel: lastLevel, originalEvent: event}).isDefaultPrevented()) {
  12222. return null;
  12223. }
  12224. // Add undo level if needed
  12225. if (lastLevel && lastLevel.content == level.content) {
  12226. return null;
  12227. }
  12228. // Set before bookmark on previous level
  12229. if (data[index]) {
  12230. data[index].beforeBookmark = beforeBookmark;
  12231. }
  12232. // Time to compress
  12233. if (settings.custom_undo_redo_levels) {
  12234. if (data.length > settings.custom_undo_redo_levels) {
  12235. for (i = 0; i < data.length - 1; i++) {
  12236. data[i] = data[i + 1];
  12237. }
  12238. data.length--;
  12239. index = data.length;
  12240. }
  12241. }
  12242. // Get a non intrusive normalized bookmark
  12243. level.bookmark = editor.selection.getBookmark(2, true);
  12244. // Crop array if needed
  12245. if (index < data.length - 1) {
  12246. data.length = index + 1;
  12247. }
  12248. data.push(level);
  12249. index = data.length - 1;
  12250. var args = {level: level, lastLevel: lastLevel, originalEvent: event};
  12251. editor.fire('AddUndo', args);
  12252. if (index > 0) {
  12253. editor.isNotDirty = false;
  12254. editor.fire('change', args);
  12255. }
  12256. return level;
  12257. },
  12258. /**
  12259. * Undoes the last action.
  12260. *
  12261. * @method undo
  12262. * @return {Object} Undo level or null if no undo was performed.
  12263. */
  12264. undo: function() {
  12265. var level;
  12266. if (self.typing) {
  12267. self.add();
  12268. self.typing = false;
  12269. }
  12270. if (index > 0) {
  12271. level = data[--index];
  12272. // Undo to first index then set dirty state to false
  12273. if (index === 0) {
  12274. editor.isNotDirty = true;
  12275. }
  12276. editor.setContent(level.content, {format: 'raw'});
  12277. editor.selection.moveToBookmark(level.beforeBookmark);
  12278. editor.fire('undo', {level: level});
  12279. }
  12280. return level;
  12281. },
  12282. /**
  12283. * Redoes the last action.
  12284. *
  12285. * @method redo
  12286. * @return {Object} Redo level or null if no redo was performed.
  12287. */
  12288. redo: function() {
  12289. var level;
  12290. if (index < data.length - 1) {
  12291. level = data[++index];
  12292. editor.setContent(level.content, {format: 'raw'});
  12293. editor.selection.moveToBookmark(level.bookmark);
  12294. editor.fire('redo', {level: level});
  12295. }
  12296. return level;
  12297. },
  12298. /**
  12299. * Removes all undo levels.
  12300. *
  12301. * @method clear
  12302. */
  12303. clear: function() {
  12304. data = [];
  12305. index = 0;
  12306. self.typing = false;
  12307. editor.fire('ClearUndos');
  12308. },
  12309. /**
  12310. * Returns true/false if the undo manager has any undo levels.
  12311. *
  12312. * @method hasUndo
  12313. * @return {Boolean} true/false if the undo manager has any undo levels.
  12314. */
  12315. hasUndo: function() {
  12316. // Has undo levels or typing and content isn't the same as the initial level
  12317. return index > 0 || (self.typing && data[0] && getContent() != data[0].content);
  12318. },
  12319. /**
  12320. * Returns true/false if the undo manager has any redo levels.
  12321. *
  12322. * @method hasRedo
  12323. * @return {Boolean} true/false if the undo manager has any redo levels.
  12324. */
  12325. hasRedo: function() {
  12326. return index < data.length - 1 && !this.typing;
  12327. },
  12328. /**
  12329. * Executes the specified function in an undo transation. The selection
  12330. * before the modification will be stored to the undo stack and if the DOM changes
  12331. * it will add a new undo level. Any methods within the transation that adds undo levels will
  12332. * be ignored. So a transation can include calls to execCommand or editor.insertContent.
  12333. *
  12334. * @method transact
  12335. * @param {function} callback Function to execute dom manipulation logic in.
  12336. */
  12337. transact: function(callback) {
  12338. self.beforeChange();
  12339. try {
  12340. locks++;
  12341. callback();
  12342. } finally {
  12343. locks--;
  12344. }
  12345. self.add();
  12346. }
  12347. };
  12348. return self;
  12349. };
  12350. });
  12351. // Included from: js/tinymce/classes/EnterKey.js
  12352. /**
  12353. * EnterKey.js
  12354. *
  12355. * Copyright, Moxiecode Systems AB
  12356. * Released under LGPL License.
  12357. *
  12358. * License: http://www.tinymce.com/license
  12359. * Contributing: http://www.tinymce.com/contributing
  12360. */
  12361. /**
  12362. * Contains logic for handling the enter key to split/generate block elements.
  12363. */
  12364. define("tinymce/EnterKey", [
  12365. "tinymce/dom/TreeWalker",
  12366. "tinymce/dom/RangeUtils",
  12367. "tinymce/Env"
  12368. ], function(TreeWalker, RangeUtils, Env) {
  12369. var isIE = Env.ie && Env.ie < 11;
  12370. return function(editor) {
  12371. var dom = editor.dom, selection = editor.selection, settings = editor.settings;
  12372. var undoManager = editor.undoManager, schema = editor.schema, nonEmptyElementsMap = schema.getNonEmptyElements();
  12373. function handleEnterKey(evt) {
  12374. var rng, tmpRng, editableRoot, container, offset, parentBlock, documentMode, shiftKey,
  12375. newBlock, fragment, containerBlock, parentBlockName, containerBlockName, newBlockName, isAfterLastNodeInContainer;
  12376. // Returns true if the block can be split into two blocks or not
  12377. function canSplitBlock(node) {
  12378. return node &&
  12379. dom.isBlock(node) &&
  12380. !/^(TD|TH|CAPTION|FORM)$/.test(node.nodeName) &&
  12381. !/^(fixed|absolute)/i.test(node.style.position) &&
  12382. dom.getContentEditable(node) !== "true";
  12383. }
  12384. // Renders empty block on IE
  12385. function renderBlockOnIE(block) {
  12386. var oldRng;
  12387. if (dom.isBlock(block)) {
  12388. oldRng = selection.getRng();
  12389. block.appendChild(dom.create('span', null, '\u00a0'));
  12390. selection.select(block);
  12391. block.lastChild.outerHTML = '';
  12392. selection.setRng(oldRng);
  12393. }
  12394. }
  12395. // Remove the first empty inline element of the block so this: <p><b><em></em></b>x</p> becomes this: <p>x</p>
  12396. function trimInlineElementsOnLeftSideOfBlock(block) {
  12397. var node = block, firstChilds = [], i;
  12398. // Find inner most first child ex: <p><i><b>*</b></i></p>
  12399. while ((node = node.firstChild)) {
  12400. if (dom.isBlock(node)) {
  12401. return;
  12402. }
  12403. if (node.nodeType == 1 && !nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  12404. firstChilds.push(node);
  12405. }
  12406. }
  12407. i = firstChilds.length;
  12408. while (i--) {
  12409. node = firstChilds[i];
  12410. if (!node.hasChildNodes() || (node.firstChild == node.lastChild && node.firstChild.nodeValue === '')) {
  12411. dom.remove(node);
  12412. } else {
  12413. // Remove <a> </a> see #5381
  12414. if (node.nodeName == "A" && (node.innerText || node.textContent) === ' ') {
  12415. dom.remove(node);
  12416. }
  12417. }
  12418. }
  12419. }
  12420. // Moves the caret to a suitable position within the root for example in the first non
  12421. // pure whitespace text node or before an image
  12422. function moveToCaretPosition(root) {
  12423. var walker, node, rng, lastNode = root, tempElm;
  12424. function firstNonWhiteSpaceNodeSibling(node) {
  12425. while (node) {
  12426. if (node.nodeType == 1 || (node.nodeType == 3 && node.data && /[\r\n\s]/.test(node.data))) {
  12427. return node;
  12428. }
  12429. node = node.nextSibling;
  12430. }
  12431. }
  12432. // Old IE versions doesn't properly render blocks with br elements in them
  12433. // For example <p><br></p> wont be rendered correctly in a contentEditable area
  12434. // until you remove the br producing <p></p>
  12435. if (Env.ie && Env.ie < 9 && parentBlock && parentBlock.firstChild) {
  12436. if (parentBlock.firstChild == parentBlock.lastChild && parentBlock.firstChild.tagName == 'BR') {
  12437. dom.remove(parentBlock.firstChild);
  12438. }
  12439. }
  12440. if (root.nodeName == 'LI') {
  12441. var firstChild = firstNonWhiteSpaceNodeSibling(root.firstChild);
  12442. if (firstChild && /^(UL|OL)$/.test(firstChild.nodeName)) {
  12443. root.insertBefore(dom.doc.createTextNode('\u00a0'), root.firstChild);
  12444. }
  12445. }
  12446. rng = dom.createRng();
  12447. if (root.hasChildNodes()) {
  12448. walker = new TreeWalker(root, root);
  12449. while ((node = walker.current())) {
  12450. if (node.nodeType == 3) {
  12451. rng.setStart(node, 0);
  12452. rng.setEnd(node, 0);
  12453. break;
  12454. }
  12455. if (nonEmptyElementsMap[node.nodeName.toLowerCase()]) {
  12456. rng.setStartBefore(node);
  12457. rng.setEndBefore(node);
  12458. break;
  12459. }
  12460. lastNode = node;
  12461. node = walker.next();
  12462. }
  12463. if (!node) {
  12464. rng.setStart(lastNode, 0);
  12465. rng.setEnd(lastNode, 0);
  12466. }
  12467. } else {
  12468. if (root.nodeName == 'BR') {
  12469. if (root.nextSibling && dom.isBlock(root.nextSibling)) {
  12470. // Trick on older IE versions to render the caret before the BR between two lists
  12471. if (!documentMode || documentMode < 9) {
  12472. tempElm = dom.create('br');
  12473. root.parentNode.insertBefore(tempElm, root);
  12474. }
  12475. rng.setStartBefore(root);
  12476. rng.setEndBefore(root);
  12477. } else {
  12478. rng.setStartAfter(root);
  12479. rng.setEndAfter(root);
  12480. }
  12481. } else {
  12482. rng.setStart(root, 0);
  12483. rng.setEnd(root, 0);
  12484. }
  12485. }
  12486. selection.setRng(rng);
  12487. // Remove tempElm created for old IE:s
  12488. dom.remove(tempElm);
  12489. selection.scrollIntoView(root);
  12490. }
  12491. function setForcedBlockAttrs(node) {
  12492. var forcedRootBlockName = settings.forced_root_block;
  12493. if (forcedRootBlockName && forcedRootBlockName.toLowerCase() === node.tagName.toLowerCase()) {
  12494. dom.setAttribs(node, settings.forced_root_block_attrs);
  12495. }
  12496. }
  12497. // Creates a new block element by cloning the current one or creating a new one if the name is specified
  12498. // This function will also copy any text formatting from the parent block and add it to the new one
  12499. function createNewBlock(name) {
  12500. var node = container, block, clonedNode, caretNode;
  12501. if (name || parentBlockName == "TABLE") {
  12502. block = dom.create(name || newBlockName);
  12503. setForcedBlockAttrs(block);
  12504. } else {
  12505. block = parentBlock.cloneNode(false);
  12506. }
  12507. caretNode = block;
  12508. // Clone any parent styles
  12509. if (settings.keep_styles !== false) {
  12510. do {
  12511. if (/^(SPAN|STRONG|B|EM|I|FONT|STRIKE|U|VAR|CITE|DFN|CODE|MARK|Q|SUP|SUB|SAMP)$/.test(node.nodeName)) {
  12512. // Never clone a caret containers
  12513. if (node.id == '_mce_caret') {
  12514. continue;
  12515. }
  12516. clonedNode = node.cloneNode(false);
  12517. dom.setAttrib(clonedNode, 'id', ''); // Remove ID since it needs to be document unique
  12518. if (block.hasChildNodes()) {
  12519. clonedNode.appendChild(block.firstChild);
  12520. block.appendChild(clonedNode);
  12521. } else {
  12522. caretNode = clonedNode;
  12523. block.appendChild(clonedNode);
  12524. }
  12525. }
  12526. } while ((node = node.parentNode));
  12527. }
  12528. // BR is needed in empty blocks on non IE browsers
  12529. if (!isIE) {
  12530. caretNode.innerHTML = '<br data-mce-bogus="1">';
  12531. }
  12532. return block;
  12533. }
  12534. // Returns true/false if the caret is at the start/end of the parent block element
  12535. function isCaretAtStartOrEndOfBlock(start) {
  12536. var walker, node, name;
  12537. // Caret is in the middle of a text node like "a|b"
  12538. if (container.nodeType == 3 && (start ? offset > 0 : offset < container.nodeValue.length)) {
  12539. return false;
  12540. }
  12541. // If after the last element in block node edge case for #5091
  12542. if (container.parentNode == parentBlock && isAfterLastNodeInContainer && !start) {
  12543. return true;
  12544. }
  12545. // If the caret if before the first element in parentBlock
  12546. if (start && container.nodeType == 1 && container == parentBlock.firstChild) {
  12547. return true;
  12548. }
  12549. // Caret can be before/after a table
  12550. if (container.nodeName === "TABLE" || (container.previousSibling && container.previousSibling.nodeName == "TABLE")) {
  12551. return (isAfterLastNodeInContainer && !start) || (!isAfterLastNodeInContainer && start);
  12552. }
  12553. // Walk the DOM and look for text nodes or non empty elements
  12554. walker = new TreeWalker(container, parentBlock);
  12555. // If caret is in beginning or end of a text block then jump to the next/previous node
  12556. if (container.nodeType == 3) {
  12557. if (start && offset === 0) {
  12558. walker.prev();
  12559. } else if (!start && offset == container.nodeValue.length) {
  12560. walker.next();
  12561. }
  12562. }
  12563. while ((node = walker.current())) {
  12564. if (node.nodeType === 1) {
  12565. // Ignore bogus elements
  12566. if (!node.getAttribute('data-mce-bogus')) {
  12567. // Keep empty elements like <img /> <input /> but not trailing br:s like <p>text|<br></p>
  12568. name = node.nodeName.toLowerCase();
  12569. if (nonEmptyElementsMap[name] && name !== 'br') {
  12570. return false;
  12571. }
  12572. }
  12573. } else if (node.nodeType === 3 && !/^[ \t\r\n]*$/.test(node.nodeValue)) {
  12574. return false;
  12575. }
  12576. if (start) {
  12577. walker.prev();
  12578. } else {
  12579. walker.next();
  12580. }
  12581. }
  12582. return true;
  12583. }
  12584. // Wraps any text nodes or inline elements in the specified forced root block name
  12585. function wrapSelfAndSiblingsInDefaultBlock(container, offset) {
  12586. var newBlock, parentBlock, startNode, node, next, rootBlockName, blockName = newBlockName || 'P';
  12587. // Not in a block element or in a table cell or caption
  12588. parentBlock = dom.getParent(container, dom.isBlock);
  12589. rootBlockName = editor.getBody().nodeName.toLowerCase();
  12590. if (!parentBlock || !canSplitBlock(parentBlock)) {
  12591. parentBlock = parentBlock || editableRoot;
  12592. if (!parentBlock.hasChildNodes()) {
  12593. newBlock = dom.create(blockName);
  12594. setForcedBlockAttrs(newBlock);
  12595. parentBlock.appendChild(newBlock);
  12596. rng.setStart(newBlock, 0);
  12597. rng.setEnd(newBlock, 0);
  12598. return newBlock;
  12599. }
  12600. // Find parent that is the first child of parentBlock
  12601. node = container;
  12602. while (node.parentNode != parentBlock) {
  12603. node = node.parentNode;
  12604. }
  12605. // Loop left to find start node start wrapping at
  12606. while (node && !dom.isBlock(node)) {
  12607. startNode = node;
  12608. node = node.previousSibling;
  12609. }
  12610. if (startNode && schema.isValidChild(rootBlockName, blockName.toLowerCase())) {
  12611. newBlock = dom.create(blockName);
  12612. setForcedBlockAttrs(newBlock);
  12613. startNode.parentNode.insertBefore(newBlock, startNode);
  12614. // Start wrapping until we hit a block
  12615. node = startNode;
  12616. while (node && !dom.isBlock(node)) {
  12617. next = node.nextSibling;
  12618. newBlock.appendChild(node);
  12619. node = next;
  12620. }
  12621. // Restore range to it's past location
  12622. rng.setStart(container, offset);
  12623. rng.setEnd(container, offset);
  12624. }
  12625. }
  12626. return container;
  12627. }
  12628. // Inserts a block or br before/after or in the middle of a split list of the LI is empty
  12629. function handleEmptyListItem() {
  12630. function isFirstOrLastLi(first) {
  12631. var node = containerBlock[first ? 'firstChild' : 'lastChild'];
  12632. // Find first/last element since there might be whitespace there
  12633. while (node) {
  12634. if (node.nodeType == 1) {
  12635. break;
  12636. }
  12637. node = node[first ? 'nextSibling' : 'previousSibling'];
  12638. }
  12639. return node === parentBlock;
  12640. }
  12641. function getContainerBlock() {
  12642. var containerBlockParent = containerBlock.parentNode;
  12643. if (containerBlockParent.nodeName == 'LI') {
  12644. return containerBlockParent;
  12645. }
  12646. return containerBlock;
  12647. }
  12648. // Check if we are in an nested list
  12649. var containerBlockParentName = containerBlock.parentNode.nodeName;
  12650. if (/^(OL|UL|LI)$/.test(containerBlockParentName)) {
  12651. newBlockName = 'LI';
  12652. }
  12653. newBlock = newBlockName ? createNewBlock(newBlockName) : dom.create('BR');
  12654. if (isFirstOrLastLi(true) && isFirstOrLastLi()) {
  12655. if (containerBlockParentName == 'LI') {
  12656. // Nested list is inside a LI
  12657. dom.insertAfter(newBlock, getContainerBlock());
  12658. } else {
  12659. // Is first and last list item then replace the OL/UL with a text block
  12660. dom.replace(newBlock, containerBlock);
  12661. }
  12662. } else if (isFirstOrLastLi(true)) {
  12663. if (containerBlockParentName == 'LI') {
  12664. // List nested in an LI then move the list to a new sibling LI
  12665. dom.insertAfter(newBlock, getContainerBlock());
  12666. newBlock.appendChild(dom.doc.createTextNode(' ')); // Needed for IE so the caret can be placed
  12667. newBlock.appendChild(containerBlock);
  12668. } else {
  12669. // First LI in list then remove LI and add text block before list
  12670. containerBlock.parentNode.insertBefore(newBlock, containerBlock);
  12671. }
  12672. } else if (isFirstOrLastLi()) {
  12673. // Last LI in list then remove LI and add text block after list
  12674. dom.insertAfter(newBlock, getContainerBlock());
  12675. renderBlockOnIE(newBlock);
  12676. } else {
  12677. // Middle LI in list the split the list and insert a text block in the middle
  12678. // Extract after fragment and insert it after the current block
  12679. containerBlock = getContainerBlock();
  12680. tmpRng = rng.cloneRange();
  12681. tmpRng.setStartAfter(parentBlock);
  12682. tmpRng.setEndAfter(containerBlock);
  12683. fragment = tmpRng.extractContents();
  12684. if (newBlockName == 'LI' && fragment.firstChild.nodeName == 'LI') {
  12685. newBlock = fragment.firstChild;
  12686. dom.insertAfter(fragment, containerBlock);
  12687. } else {
  12688. dom.insertAfter(fragment, containerBlock);
  12689. dom.insertAfter(newBlock, containerBlock);
  12690. }
  12691. }
  12692. dom.remove(parentBlock);
  12693. moveToCaretPosition(newBlock);
  12694. undoManager.add();
  12695. }
  12696. // Walks the parent block to the right and look for BR elements
  12697. function hasRightSideContent() {
  12698. var walker = new TreeWalker(container, parentBlock), node;
  12699. while ((node = walker.next())) {
  12700. if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) {
  12701. return true;
  12702. }
  12703. }
  12704. }
  12705. // Inserts a BR element if the forced_root_block option is set to false or empty string
  12706. function insertBr() {
  12707. var brElm, extraBr, marker;
  12708. if (container && container.nodeType == 3 && offset >= container.nodeValue.length) {
  12709. // Insert extra BR element at the end block elements
  12710. if (!isIE && !hasRightSideContent()) {
  12711. brElm = dom.create('br');
  12712. rng.insertNode(brElm);
  12713. rng.setStartAfter(brElm);
  12714. rng.setEndAfter(brElm);
  12715. extraBr = true;
  12716. }
  12717. }
  12718. brElm = dom.create('br');
  12719. rng.insertNode(brElm);
  12720. // Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it
  12721. if (isIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) {
  12722. brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm);
  12723. }
  12724. // Insert temp marker and scroll to that
  12725. marker = dom.create('span', {}, '&nbsp;');
  12726. brElm.parentNode.insertBefore(marker, brElm);
  12727. selection.scrollIntoView(marker);
  12728. dom.remove(marker);
  12729. if (!extraBr) {
  12730. rng.setStartAfter(brElm);
  12731. rng.setEndAfter(brElm);
  12732. } else {
  12733. rng.setStartBefore(brElm);
  12734. rng.setEndBefore(brElm);
  12735. }
  12736. selection.setRng(rng);
  12737. undoManager.add();
  12738. }
  12739. // Trims any linebreaks at the beginning of node user for example when pressing enter in a PRE element
  12740. function trimLeadingLineBreaks(node) {
  12741. do {
  12742. if (node.nodeType === 3) {
  12743. node.nodeValue = node.nodeValue.replace(/^[\r\n]+/, '');
  12744. }
  12745. node = node.firstChild;
  12746. } while (node);
  12747. }
  12748. function getEditableRoot(node) {
  12749. var root = dom.getRoot(), parent, editableRoot;
  12750. // Get all parents until we hit a non editable parent or the root
  12751. parent = node;
  12752. while (parent !== root && dom.getContentEditable(parent) !== "false") {
  12753. if (dom.getContentEditable(parent) === "true") {
  12754. editableRoot = parent;
  12755. }
  12756. parent = parent.parentNode;
  12757. }
  12758. return parent !== root ? editableRoot : root;
  12759. }
  12760. // Adds a BR at the end of blocks that only contains an IMG or INPUT since
  12761. // these might be floated and then they won't expand the block
  12762. function addBrToBlockIfNeeded(block) {
  12763. var lastChild;
  12764. // IE will render the blocks correctly other browsers needs a BR
  12765. if (!isIE) {
  12766. block.normalize(); // Remove empty text nodes that got left behind by the extract
  12767. // Check if the block is empty or contains a floated last child
  12768. lastChild = block.lastChild;
  12769. if (!lastChild || (/^(left|right)$/gi.test(dom.getStyle(lastChild, 'float', true)))) {
  12770. dom.add(block, 'br');
  12771. }
  12772. }
  12773. }
  12774. rng = selection.getRng(true);
  12775. // Event is blocked by some other handler for example the lists plugin
  12776. if (evt.isDefaultPrevented()) {
  12777. return;
  12778. }
  12779. // Delete any selected contents
  12780. if (!rng.collapsed) {
  12781. editor.execCommand('Delete');
  12782. return;
  12783. }
  12784. // Setup range items and newBlockName
  12785. new RangeUtils(dom).normalize(rng);
  12786. container = rng.startContainer;
  12787. offset = rng.startOffset;
  12788. newBlockName = (settings.force_p_newlines ? 'p' : '') || settings.forced_root_block;
  12789. newBlockName = newBlockName ? newBlockName.toUpperCase() : '';
  12790. documentMode = dom.doc.documentMode;
  12791. shiftKey = evt.shiftKey;
  12792. // Resolve node index
  12793. if (container.nodeType == 1 && container.hasChildNodes()) {
  12794. isAfterLastNodeInContainer = offset > container.childNodes.length - 1;
  12795. container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container;
  12796. if (isAfterLastNodeInContainer && container.nodeType == 3) {
  12797. offset = container.nodeValue.length;
  12798. } else {
  12799. offset = 0;
  12800. }
  12801. }
  12802. // Get editable root node normaly the body element but sometimes a div or span
  12803. editableRoot = getEditableRoot(container);
  12804. // If there is no editable root then enter is done inside a contentEditable false element
  12805. if (!editableRoot) {
  12806. return;
  12807. }
  12808. undoManager.beforeChange();
  12809. // If editable root isn't block nor the root of the editor
  12810. if (!dom.isBlock(editableRoot) && editableRoot != dom.getRoot()) {
  12811. if (!newBlockName || shiftKey) {
  12812. insertBr();
  12813. }
  12814. return;
  12815. }
  12816. // Wrap the current node and it's sibling in a default block if it's needed.
  12817. // for example this <td>text|<b>text2</b></td> will become this <td><p>text|<b>text2</p></b></td>
  12818. // This won't happen if root blocks are disabled or the shiftKey is pressed
  12819. if ((newBlockName && !shiftKey) || (!newBlockName && shiftKey)) {
  12820. container = wrapSelfAndSiblingsInDefaultBlock(container, offset);
  12821. }
  12822. // Find parent block and setup empty block paddings
  12823. parentBlock = dom.getParent(container, dom.isBlock);
  12824. containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null;
  12825. // Setup block names
  12826. parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
  12827. containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5
  12828. // Enter inside block contained within a LI then split or insert before/after LI
  12829. if (containerBlockName == 'LI' && !evt.ctrlKey) {
  12830. parentBlock = containerBlock;
  12831. parentBlockName = containerBlockName;
  12832. }
  12833. // Handle enter in LI
  12834. if (parentBlockName == 'LI') {
  12835. if (!newBlockName && shiftKey) {
  12836. insertBr();
  12837. return;
  12838. }
  12839. // Handle enter inside an empty list item
  12840. if (dom.isEmpty(parentBlock)) {
  12841. handleEmptyListItem();
  12842. return;
  12843. }
  12844. }
  12845. // Don't split PRE tags but insert a BR instead easier when writing code samples etc
  12846. if (parentBlockName == 'PRE' && settings.br_in_pre !== false) {
  12847. if (!shiftKey) {
  12848. insertBr();
  12849. return;
  12850. }
  12851. } else {
  12852. // If no root block is configured then insert a BR by default or if the shiftKey is pressed
  12853. if ((!newBlockName && !shiftKey && parentBlockName != 'LI') || (newBlockName && shiftKey)) {
  12854. insertBr();
  12855. return;
  12856. }
  12857. }
  12858. // If parent block is root then never insert new blocks
  12859. if (newBlockName && parentBlock === editor.getBody()) {
  12860. return;
  12861. }
  12862. // Default block name if it's not configured
  12863. newBlockName = newBlockName || 'P';
  12864. // Insert new block before/after the parent block depending on caret location
  12865. if (isCaretAtStartOrEndOfBlock()) {
  12866. // If the caret is at the end of a header we produce a P tag after it similar to Word unless we are in a hgroup
  12867. if (/^(H[1-6]|PRE|FIGURE)$/.test(parentBlockName) && containerBlockName != 'HGROUP') {
  12868. newBlock = createNewBlock(newBlockName);
  12869. } else {
  12870. newBlock = createNewBlock();
  12871. }
  12872. // Split the current container block element if enter is pressed inside an empty inner block element
  12873. if (settings.end_container_on_empty_block && canSplitBlock(containerBlock) && dom.isEmpty(parentBlock)) {
  12874. // Split container block for example a BLOCKQUOTE at the current blockParent location for example a P
  12875. newBlock = dom.split(containerBlock, parentBlock);
  12876. } else {
  12877. dom.insertAfter(newBlock, parentBlock);
  12878. }
  12879. moveToCaretPosition(newBlock);
  12880. } else if (isCaretAtStartOrEndOfBlock(true)) {
  12881. // Insert new block before
  12882. newBlock = parentBlock.parentNode.insertBefore(createNewBlock(), parentBlock);
  12883. renderBlockOnIE(newBlock);
  12884. moveToCaretPosition(parentBlock);
  12885. } else {
  12886. // Extract after fragment and insert it after the current block
  12887. tmpRng = rng.cloneRange();
  12888. tmpRng.setEndAfter(parentBlock);
  12889. fragment = tmpRng.extractContents();
  12890. trimLeadingLineBreaks(fragment);
  12891. newBlock = fragment.firstChild;
  12892. dom.insertAfter(fragment, parentBlock);
  12893. trimInlineElementsOnLeftSideOfBlock(newBlock);
  12894. addBrToBlockIfNeeded(parentBlock);
  12895. moveToCaretPosition(newBlock);
  12896. }
  12897. dom.setAttrib(newBlock, 'id', ''); // Remove ID since it needs to be document unique
  12898. // Allow custom handling of new blocks
  12899. editor.fire('NewBlock', { newBlock: newBlock });
  12900. undoManager.add();
  12901. }
  12902. editor.on('keydown', function(evt) {
  12903. if (evt.keyCode == 13) {
  12904. if (handleEnterKey(evt) !== false) {
  12905. evt.preventDefault();
  12906. }
  12907. }
  12908. });
  12909. };
  12910. });
  12911. // Included from: js/tinymce/classes/ForceBlocks.js
  12912. /**
  12913. * ForceBlocks.js
  12914. *
  12915. * Copyright, Moxiecode Systems AB
  12916. * Released under LGPL License.
  12917. *
  12918. * License: http://www.tinymce.com/license
  12919. * Contributing: http://www.tinymce.com/contributing
  12920. */
  12921. define("tinymce/ForceBlocks", [], function() {
  12922. return function(editor) {
  12923. var settings = editor.settings, dom = editor.dom, selection = editor.selection;
  12924. var schema = editor.schema, blockElements = schema.getBlockElements();
  12925. function addRootBlocks() {
  12926. var node = selection.getStart(), rootNode = editor.getBody(), rng;
  12927. var startContainer, startOffset, endContainer, endOffset, rootBlockNode;
  12928. var tempNode, offset = -0xFFFFFF, wrapped, restoreSelection;
  12929. var tmpRng, rootNodeName, forcedRootBlock;
  12930. forcedRootBlock = settings.forced_root_block;
  12931. if (!node || node.nodeType !== 1 || !forcedRootBlock) {
  12932. return;
  12933. }
  12934. // Check if node is wrapped in block
  12935. while (node && node != rootNode) {
  12936. if (blockElements[node.nodeName]) {
  12937. return;
  12938. }
  12939. node = node.parentNode;
  12940. }
  12941. // Get current selection
  12942. rng = selection.getRng();
  12943. if (rng.setStart) {
  12944. startContainer = rng.startContainer;
  12945. startOffset = rng.startOffset;
  12946. endContainer = rng.endContainer;
  12947. endOffset = rng.endOffset;
  12948. try {
  12949. restoreSelection = editor.getDoc().activeElement === rootNode;
  12950. } catch (ex) {
  12951. // IE throws unspecified error here sometimes
  12952. }
  12953. } else {
  12954. // Force control range into text range
  12955. if (rng.item) {
  12956. node = rng.item(0);
  12957. rng = editor.getDoc().body.createTextRange();
  12958. rng.moveToElementText(node);
  12959. }
  12960. restoreSelection = rng.parentElement().ownerDocument === editor.getDoc();
  12961. tmpRng = rng.duplicate();
  12962. tmpRng.collapse(true);
  12963. startOffset = tmpRng.move('character', offset) * -1;
  12964. if (!tmpRng.collapsed) {
  12965. tmpRng = rng.duplicate();
  12966. tmpRng.collapse(false);
  12967. endOffset = (tmpRng.move('character', offset) * -1) - startOffset;
  12968. }
  12969. }
  12970. // Wrap non block elements and text nodes
  12971. node = rootNode.firstChild;
  12972. rootNodeName = rootNode.nodeName.toLowerCase();
  12973. while (node) {
  12974. // TODO: Break this up, too complex
  12975. if (((node.nodeType === 3 || (node.nodeType == 1 && !blockElements[node.nodeName]))) &&
  12976. schema.isValidChild(rootNodeName, forcedRootBlock.toLowerCase())) {
  12977. // Remove empty text nodes
  12978. if (node.nodeType === 3 && node.nodeValue.length === 0) {
  12979. tempNode = node;
  12980. node = node.nextSibling;
  12981. dom.remove(tempNode);
  12982. continue;
  12983. }
  12984. if (!rootBlockNode) {
  12985. rootBlockNode = dom.create(forcedRootBlock, editor.settings.forced_root_block_attrs);
  12986. node.parentNode.insertBefore(rootBlockNode, node);
  12987. wrapped = true;
  12988. }
  12989. tempNode = node;
  12990. node = node.nextSibling;
  12991. rootBlockNode.appendChild(tempNode);
  12992. } else {
  12993. rootBlockNode = null;
  12994. node = node.nextSibling;
  12995. }
  12996. }
  12997. if (wrapped && restoreSelection) {
  12998. if (rng.setStart) {
  12999. rng.setStart(startContainer, startOffset);
  13000. rng.setEnd(endContainer, endOffset);
  13001. selection.setRng(rng);
  13002. } else {
  13003. // Only select if the previous selection was inside the document to prevent auto focus in quirks mode
  13004. try {
  13005. rng = editor.getDoc().body.createTextRange();
  13006. rng.moveToElementText(rootNode);
  13007. rng.collapse(true);
  13008. rng.moveStart('character', startOffset);
  13009. if (endOffset > 0) {
  13010. rng.moveEnd('character', endOffset);
  13011. }
  13012. rng.select();
  13013. } catch (ex) {
  13014. // Ignore
  13015. }
  13016. }
  13017. editor.nodeChanged();
  13018. }
  13019. }
  13020. // Force root blocks
  13021. if (settings.forced_root_block) {
  13022. editor.on('NodeChange', addRootBlocks);
  13023. }
  13024. };
  13025. });
  13026. // Included from: js/tinymce/classes/EditorCommands.js
  13027. /**
  13028. * EditorCommands.js
  13029. *
  13030. * Copyright, Moxiecode Systems AB
  13031. * Released under LGPL License.
  13032. *
  13033. * License: http://www.tinymce.com/license
  13034. * Contributing: http://www.tinymce.com/contributing
  13035. */
  13036. /**
  13037. * This class enables you to add custom editor commands and it contains
  13038. * overrides for native browser commands to address various bugs and issues.
  13039. *
  13040. * @class tinymce.EditorCommands
  13041. */
  13042. define("tinymce/EditorCommands", [
  13043. "tinymce/html/Serializer",
  13044. "tinymce/Env",
  13045. "tinymce/util/Tools"
  13046. ], function(Serializer, Env, Tools) {
  13047. // Added for compression purposes
  13048. var each = Tools.each, extend = Tools.extend;
  13049. var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode;
  13050. var isGecko = Env.gecko, isIE = Env.ie;
  13051. var TRUE = true, FALSE = false;
  13052. return function(editor) {
  13053. var dom = editor.dom,
  13054. selection = editor.selection,
  13055. commands = {state: {}, exec: {}, value: {}},
  13056. settings = editor.settings,
  13057. formatter = editor.formatter,
  13058. bookmark;
  13059. /**
  13060. * Executes the specified command.
  13061. *
  13062. * @method execCommand
  13063. * @param {String} command Command to execute.
  13064. * @param {Boolean} ui Optional user interface state.
  13065. * @param {Object} value Optional value for command.
  13066. * @return {Boolean} true/false if the command was found or not.
  13067. */
  13068. function execCommand(command, ui, value) {
  13069. var func;
  13070. command = command.toLowerCase();
  13071. if ((func = commands.exec[command])) {
  13072. func(command, ui, value);
  13073. return TRUE;
  13074. }
  13075. return FALSE;
  13076. }
  13077. /**
  13078. * Queries the current state for a command for example if the current selection is "bold".
  13079. *
  13080. * @method queryCommandState
  13081. * @param {String} command Command to check the state of.
  13082. * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found.
  13083. */
  13084. function queryCommandState(command) {
  13085. var func;
  13086. command = command.toLowerCase();
  13087. if ((func = commands.state[command])) {
  13088. return func(command);
  13089. }
  13090. return -1;
  13091. }
  13092. /**
  13093. * Queries the command value for example the current fontsize.
  13094. *
  13095. * @method queryCommandValue
  13096. * @param {String} command Command to check the value of.
  13097. * @return {Object} Command value of false if it's not found.
  13098. */
  13099. function queryCommandValue(command) {
  13100. var func;
  13101. command = command.toLowerCase();
  13102. if ((func = commands.value[command])) {
  13103. return func(command);
  13104. }
  13105. return FALSE;
  13106. }
  13107. /**
  13108. * Adds commands to the command collection.
  13109. *
  13110. * @method addCommands
  13111. * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated.
  13112. * @param {String} type Optional type to add, defaults to exec. Can be value or state as well.
  13113. */
  13114. function addCommands(command_list, type) {
  13115. type = type || 'exec';
  13116. each(command_list, function(callback, command) {
  13117. each(command.toLowerCase().split(','), function(command) {
  13118. commands[type][command] = callback;
  13119. });
  13120. });
  13121. }
  13122. // Expose public methods
  13123. extend(this, {
  13124. execCommand: execCommand,
  13125. queryCommandState: queryCommandState,
  13126. queryCommandValue: queryCommandValue,
  13127. addCommands: addCommands
  13128. });
  13129. // Private methods
  13130. function execNativeCommand(command, ui, value) {
  13131. if (ui === undefined) {
  13132. ui = FALSE;
  13133. }
  13134. if (value === undefined) {
  13135. value = null;
  13136. }
  13137. return editor.getDoc().execCommand(command, ui, value);
  13138. }
  13139. function isFormatMatch(name) {
  13140. return formatter.match(name);
  13141. }
  13142. function toggleFormat(name, value) {
  13143. formatter.toggle(name, value ? {value: value} : undefined);
  13144. editor.nodeChanged();
  13145. }
  13146. function storeSelection(type) {
  13147. bookmark = selection.getBookmark(type);
  13148. }
  13149. function restoreSelection() {
  13150. selection.moveToBookmark(bookmark);
  13151. }
  13152. // Add execCommand overrides
  13153. addCommands({
  13154. // Ignore these, added for compatibility
  13155. 'mceResetDesignMode,mceBeginUndoLevel': function() {},
  13156. // Add undo manager logic
  13157. 'mceEndUndoLevel,mceAddUndoLevel': function() {
  13158. editor.undoManager.add();
  13159. },
  13160. 'Cut,Copy,Paste': function(command) {
  13161. var doc = editor.getDoc(), failed;
  13162. // Try executing the native command
  13163. try {
  13164. execNativeCommand(command);
  13165. } catch (ex) {
  13166. // Command failed
  13167. failed = TRUE;
  13168. }
  13169. // Present alert message about clipboard access not being available
  13170. if (failed || !doc.queryCommandSupported(command)) {
  13171. var msg = editor.translate(
  13172. "Your browser doesn't support direct access to the clipboard. " +
  13173. "Please use the Ctrl+X/C/V keyboard shortcuts instead."
  13174. );
  13175. if (Env.mac) {
  13176. msg = msg.replace(/Ctrl\+/g, '\u2318+');
  13177. }
  13178. editor.windowManager.alert(msg);
  13179. }
  13180. },
  13181. // Override unlink command
  13182. unlink: function() {
  13183. if (selection.isCollapsed()) {
  13184. var elm = selection.getNode();
  13185. if (elm.tagName == 'A') {
  13186. editor.dom.remove(elm, true);
  13187. }
  13188. return;
  13189. }
  13190. formatter.remove("link");
  13191. },
  13192. // Override justify commands to use the text formatter engine
  13193. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) {
  13194. var align = command.substring(7);
  13195. if (align == 'full') {
  13196. align = 'justify';
  13197. }
  13198. // Remove all other alignments first
  13199. each('left,center,right,justify'.split(','), function(name) {
  13200. if (align != name) {
  13201. formatter.remove('align' + name);
  13202. }
  13203. });
  13204. toggleFormat('align' + align);
  13205. execCommand('mceRepaint');
  13206. },
  13207. // Override list commands to fix WebKit bug
  13208. 'InsertUnorderedList,InsertOrderedList': function(command) {
  13209. var listElm, listParent;
  13210. execNativeCommand(command);
  13211. // WebKit produces lists within block elements so we need to split them
  13212. // we will replace the native list creation logic to custom logic later on
  13213. // TODO: Remove this when the list creation logic is removed
  13214. listElm = dom.getParent(selection.getNode(), 'ol,ul');
  13215. if (listElm) {
  13216. listParent = listElm.parentNode;
  13217. // If list is within a text block then split that block
  13218. if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
  13219. storeSelection();
  13220. dom.split(listParent, listElm);
  13221. restoreSelection();
  13222. }
  13223. }
  13224. },
  13225. // Override commands to use the text formatter engine
  13226. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
  13227. toggleFormat(command);
  13228. },
  13229. // Override commands to use the text formatter engine
  13230. 'ForeColor,HiliteColor,FontName': function(command, ui, value) {
  13231. toggleFormat(command, value);
  13232. },
  13233. FontSize: function(command, ui, value) {
  13234. var fontClasses, fontSizes;
  13235. // Convert font size 1-7 to styles
  13236. if (value >= 1 && value <= 7) {
  13237. fontSizes = explode(settings.font_size_style_values);
  13238. fontClasses = explode(settings.font_size_classes);
  13239. if (fontClasses) {
  13240. value = fontClasses[value - 1] || value;
  13241. } else {
  13242. value = fontSizes[value - 1] || value;
  13243. }
  13244. }
  13245. toggleFormat(command, value);
  13246. },
  13247. RemoveFormat: function(command) {
  13248. formatter.remove(command);
  13249. },
  13250. mceBlockQuote: function() {
  13251. toggleFormat('blockquote');
  13252. },
  13253. FormatBlock: function(command, ui, value) {
  13254. return toggleFormat(value || 'p');
  13255. },
  13256. mceCleanup: function() {
  13257. var bookmark = selection.getBookmark();
  13258. editor.setContent(editor.getContent({cleanup: TRUE}), {cleanup: TRUE});
  13259. selection.moveToBookmark(bookmark);
  13260. },
  13261. mceRemoveNode: function(command, ui, value) {
  13262. var node = value || selection.getNode();
  13263. // Make sure that the body node isn't removed
  13264. if (node != editor.getBody()) {
  13265. storeSelection();
  13266. editor.dom.remove(node, TRUE);
  13267. restoreSelection();
  13268. }
  13269. },
  13270. mceSelectNodeDepth: function(command, ui, value) {
  13271. var counter = 0;
  13272. dom.getParent(selection.getNode(), function(node) {
  13273. if (node.nodeType == 1 && counter++ == value) {
  13274. selection.select(node);
  13275. return FALSE;
  13276. }
  13277. }, editor.getBody());
  13278. },
  13279. mceSelectNode: function(command, ui, value) {
  13280. selection.select(value);
  13281. },
  13282. mceInsertContent: function(command, ui, value) {
  13283. var parser, serializer, parentNode, rootNode, fragment, args;
  13284. var marker, rng, node, node2, bookmarkHtml;
  13285. function trimOrPaddLeftRight(html) {
  13286. var rng, container, offset;
  13287. rng = selection.getRng(true);
  13288. container = rng.startContainer;
  13289. offset = rng.startOffset;
  13290. function hasSiblingText(siblingName) {
  13291. return container[siblingName] && container[siblingName].nodeType == 3;
  13292. }
  13293. if (container.nodeType == 3) {
  13294. if (offset > 0) {
  13295. html = html.replace(/^&nbsp;/, ' ');
  13296. } else if (!hasSiblingText('previousSibling')) {
  13297. html = html.replace(/^ /, '&nbsp;');
  13298. }
  13299. if (offset < container.length) {
  13300. html = html.replace(/&nbsp;(<br>|)$/, ' ');
  13301. } else if (!hasSiblingText('nextSibling')) {
  13302. html = html.replace(/(&nbsp;| )(<br>|)$/, '&nbsp;');
  13303. }
  13304. }
  13305. return html;
  13306. }
  13307. // Check for whitespace before/after value
  13308. if (/^ | $/.test(value)) {
  13309. value = trimOrPaddLeftRight(value);
  13310. }
  13311. // Setup parser and serializer
  13312. parser = editor.parser;
  13313. serializer = new Serializer({}, editor.schema);
  13314. bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;&#200B;</span>';
  13315. // Run beforeSetContent handlers on the HTML to be inserted
  13316. args = {content: value, format: 'html', selection: true};
  13317. editor.fire('BeforeSetContent', args);
  13318. value = args.content;
  13319. // Add caret at end of contents if it's missing
  13320. if (value.indexOf('{$caret}') == -1) {
  13321. value += '{$caret}';
  13322. }
  13323. // Replace the caret marker with a span bookmark element
  13324. value = value.replace(/\{\$caret\}/, bookmarkHtml);
  13325. // If selection is at <body>|<p></p> then move it into <body><p>|</p>
  13326. rng = selection.getRng();
  13327. var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null);
  13328. var body = editor.getBody();
  13329. if (caretElement === body && selection.isCollapsed()) {
  13330. if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) {
  13331. rng = dom.createRng();
  13332. rng.setStart(body.firstChild, 0);
  13333. rng.setEnd(body.firstChild, 0);
  13334. selection.setRng(rng);
  13335. }
  13336. }
  13337. // Insert node maker where we will insert the new HTML and get it's parent
  13338. if (!selection.isCollapsed()) {
  13339. editor.getDoc().execCommand('Delete', false, null);
  13340. }
  13341. parentNode = selection.getNode();
  13342. // Parse the fragment within the context of the parent node
  13343. var parserArgs = {context: parentNode.nodeName.toLowerCase()};
  13344. fragment = parser.parse(value, parserArgs);
  13345. // Move the caret to a more suitable location
  13346. node = fragment.lastChild;
  13347. if (node.attr('id') == 'mce_marker') {
  13348. marker = node;
  13349. for (node = node.prev; node; node = node.walk(true)) {
  13350. if (node.type == 3 || !dom.isBlock(node.name)) {
  13351. node.parent.insert(marker, node, node.name === 'br');
  13352. break;
  13353. }
  13354. }
  13355. }
  13356. // If parser says valid we can insert the contents into that parent
  13357. if (!parserArgs.invalid) {
  13358. value = serializer.serialize(fragment);
  13359. // Check if parent is empty or only has one BR element then set the innerHTML of that parent
  13360. node = parentNode.firstChild;
  13361. node2 = parentNode.lastChild;
  13362. if (!node || (node === node2 && node.nodeName === 'BR')) {
  13363. dom.setHTML(parentNode, value);
  13364. } else {
  13365. selection.setContent(value);
  13366. }
  13367. } else {
  13368. // If the fragment was invalid within that context then we need
  13369. // to parse and process the parent it's inserted into
  13370. // Insert bookmark node and get the parent
  13371. selection.setContent(bookmarkHtml);
  13372. parentNode = selection.getNode();
  13373. rootNode = editor.getBody();
  13374. // Opera will return the document node when selection is in root
  13375. if (parentNode.nodeType == 9) {
  13376. parentNode = node = rootNode;
  13377. } else {
  13378. node = parentNode;
  13379. }
  13380. // Find the ancestor just before the root element
  13381. while (node !== rootNode) {
  13382. parentNode = node;
  13383. node = node.parentNode;
  13384. }
  13385. // Get the outer/inner HTML depending on if we are in the root and parser and serialize that
  13386. value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode);
  13387. value = serializer.serialize(
  13388. parser.parse(
  13389. // Need to replace by using a function since $ in the contents would otherwise be a problem
  13390. value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() {
  13391. return serializer.serialize(fragment);
  13392. })
  13393. )
  13394. );
  13395. // Set the inner/outer HTML depending on if we are in the root or not
  13396. if (parentNode == rootNode) {
  13397. dom.setHTML(rootNode, value);
  13398. } else {
  13399. dom.setOuterHTML(parentNode, value);
  13400. }
  13401. }
  13402. marker = dom.get('mce_marker');
  13403. selection.scrollIntoView(marker);
  13404. // Move selection before marker and remove it
  13405. rng = dom.createRng();
  13406. // If previous sibling is a text node set the selection to the end of that node
  13407. node = marker.previousSibling;
  13408. if (node && node.nodeType == 3) {
  13409. rng.setStart(node, node.nodeValue.length);
  13410. // TODO: Why can't we normalize on IE
  13411. if (!isIE) {
  13412. node2 = marker.nextSibling;
  13413. if (node2 && node2.nodeType == 3) {
  13414. node.appendData(node2.data);
  13415. node2.parentNode.removeChild(node2);
  13416. }
  13417. }
  13418. } else {
  13419. // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node
  13420. rng.setStartBefore(marker);
  13421. rng.setEndBefore(marker);
  13422. }
  13423. // Remove the marker node and set the new range
  13424. dom.remove(marker);
  13425. selection.setRng(rng);
  13426. // Dispatch after event and add any visual elements needed
  13427. editor.fire('SetContent', args);
  13428. editor.addVisual();
  13429. },
  13430. mceInsertRawHTML: function(command, ui, value) {
  13431. selection.setContent('tiny_mce_marker');
  13432. editor.setContent(
  13433. editor.getContent().replace(/tiny_mce_marker/g, function() {
  13434. return value;
  13435. })
  13436. );
  13437. },
  13438. mceToggleFormat: function(command, ui, value) {
  13439. toggleFormat(value);
  13440. },
  13441. mceSetContent: function(command, ui, value) {
  13442. editor.setContent(value);
  13443. },
  13444. 'Indent,Outdent': function(command) {
  13445. var intentValue, indentUnit, value;
  13446. // Setup indent level
  13447. intentValue = settings.indentation;
  13448. indentUnit = /[a-z%]+$/i.exec(intentValue);
  13449. intentValue = parseInt(intentValue, 10);
  13450. if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) {
  13451. // If forced_root_blocks is set to false we don't have a block to indent so lets create a div
  13452. if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) {
  13453. formatter.apply('div');
  13454. }
  13455. each(selection.getSelectedBlocks(), function(element) {
  13456. if (element.nodeName != "LI") {
  13457. var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding';
  13458. indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left';
  13459. if (command == 'outdent') {
  13460. value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue);
  13461. dom.setStyle(element, indentStyleName, value ? value + indentUnit : '');
  13462. } else {
  13463. value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit;
  13464. dom.setStyle(element, indentStyleName, value);
  13465. }
  13466. }
  13467. });
  13468. } else {
  13469. execNativeCommand(command);
  13470. }
  13471. },
  13472. mceRepaint: function() {
  13473. if (isGecko) {
  13474. try {
  13475. storeSelection(TRUE);
  13476. if (selection.getSel()) {
  13477. selection.getSel().selectAllChildren(editor.getBody());
  13478. }
  13479. selection.collapse(TRUE);
  13480. restoreSelection();
  13481. } catch (ex) {
  13482. // Ignore
  13483. }
  13484. }
  13485. },
  13486. InsertHorizontalRule: function() {
  13487. editor.execCommand('mceInsertContent', false, '<hr />');
  13488. },
  13489. mceToggleVisualAid: function() {
  13490. editor.hasVisual = !editor.hasVisual;
  13491. editor.addVisual();
  13492. },
  13493. mceReplaceContent: function(command, ui, value) {
  13494. editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format: 'text'})));
  13495. },
  13496. mceInsertLink: function(command, ui, value) {
  13497. var anchor;
  13498. if (typeof(value) == 'string') {
  13499. value = {href: value};
  13500. }
  13501. anchor = dom.getParent(selection.getNode(), 'a');
  13502. // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here.
  13503. value.href = value.href.replace(' ', '%20');
  13504. // Remove existing links if there could be child links or that the href isn't specified
  13505. if (!anchor || !value.href) {
  13506. formatter.remove('link');
  13507. }
  13508. // Apply new link to selection
  13509. if (value.href) {
  13510. formatter.apply('link', value, anchor);
  13511. }
  13512. },
  13513. selectAll: function() {
  13514. var root = dom.getRoot(), rng;
  13515. if (selection.getRng().setStart) {
  13516. rng = dom.createRng();
  13517. rng.setStart(root, 0);
  13518. rng.setEnd(root, root.childNodes.length);
  13519. selection.setRng(rng);
  13520. } else {
  13521. // IE will render it's own root level block elements and sometimes
  13522. // even put font elements in them when the user starts typing. So we need to
  13523. // move the selection to a more suitable element from this:
  13524. // <body>|<p></p></body> to this: <body><p>|</p></body>
  13525. rng = selection.getRng();
  13526. if (!rng.item) {
  13527. rng.moveToElementText(root);
  13528. rng.select();
  13529. }
  13530. }
  13531. },
  13532. "delete": function() {
  13533. execNativeCommand("Delete");
  13534. // Check if body is empty after the delete call if so then set the contents
  13535. // to an empty string and move the caret to any block produced by that operation
  13536. // this fixes the issue with root blocks not being properly produced after a delete call on IE
  13537. var body = editor.getBody();
  13538. if (dom.isEmpty(body)) {
  13539. editor.setContent('');
  13540. if (body.firstChild && dom.isBlock(body.firstChild)) {
  13541. editor.selection.setCursorLocation(body.firstChild, 0);
  13542. } else {
  13543. editor.selection.setCursorLocation(body, 0);
  13544. }
  13545. }
  13546. },
  13547. mceNewDocument: function() {
  13548. editor.setContent('');
  13549. }
  13550. });
  13551. // Add queryCommandState overrides
  13552. addCommands({
  13553. // Override justify commands
  13554. 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) {
  13555. var name = 'align' + command.substring(7);
  13556. var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks();
  13557. var matches = map(nodes, function(node) {
  13558. return !!formatter.matchNode(node, name);
  13559. });
  13560. return inArray(matches, TRUE) !== -1;
  13561. },
  13562. 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
  13563. return isFormatMatch(command);
  13564. },
  13565. mceBlockQuote: function() {
  13566. return isFormatMatch('blockquote');
  13567. },
  13568. Outdent: function() {
  13569. var node;
  13570. if (settings.inline_styles) {
  13571. if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
  13572. return TRUE;
  13573. }
  13574. if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) {
  13575. return TRUE;
  13576. }
  13577. }
  13578. return (
  13579. queryCommandState('InsertUnorderedList') ||
  13580. queryCommandState('InsertOrderedList') ||
  13581. (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE'))
  13582. );
  13583. },
  13584. 'InsertUnorderedList,InsertOrderedList': function(command) {
  13585. var list = dom.getParent(selection.getNode(), 'ul,ol');
  13586. return list &&
  13587. (
  13588. command === 'insertunorderedlist' && list.tagName === 'UL' ||
  13589. command === 'insertorderedlist' && list.tagName === 'OL'
  13590. );
  13591. }
  13592. }, 'state');
  13593. // Add queryCommandValue overrides
  13594. addCommands({
  13595. 'FontSize,FontName': function(command) {
  13596. var value = 0, parent;
  13597. if ((parent = dom.getParent(selection.getNode(), 'span'))) {
  13598. if (command == 'fontsize') {
  13599. value = parent.style.fontSize;
  13600. } else {
  13601. value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase();
  13602. }
  13603. }
  13604. return value;
  13605. }
  13606. }, 'value');
  13607. // Add undo manager logic
  13608. addCommands({
  13609. Undo: function() {
  13610. editor.undoManager.undo();
  13611. },
  13612. Redo: function() {
  13613. editor.undoManager.redo();
  13614. }
  13615. });
  13616. };
  13617. });
  13618. // Included from: js/tinymce/classes/util/URI.js
  13619. /**
  13620. * URI.js
  13621. *
  13622. * Copyright, Moxiecode Systems AB
  13623. * Released under LGPL License.
  13624. *
  13625. * License: http://www.tinymce.com/license
  13626. * Contributing: http://www.tinymce.com/contributing
  13627. */
  13628. /**
  13629. * This class handles parsing, modification and serialization of URI/URL strings.
  13630. * @class tinymce.util.URI
  13631. */
  13632. define("tinymce/util/URI", [
  13633. "tinymce/util/Tools"
  13634. ], function(Tools) {
  13635. var each = Tools.each, trim = Tools.trim,
  13636. DEFAULT_PORTS = {
  13637. 'ftp': 21,
  13638. 'http': 80,
  13639. 'https': 443,
  13640. 'mailto': 25
  13641. };
  13642. /**
  13643. * Constructs a new URI instance.
  13644. *
  13645. * @constructor
  13646. * @method URI
  13647. * @param {String} url URI string to parse.
  13648. * @param {Object} settings Optional settings object.
  13649. */
  13650. function URI(url, settings) {
  13651. var self = this, baseUri, base_url;
  13652. // Trim whitespace
  13653. url = trim(url);
  13654. // Default settings
  13655. settings = self.settings = settings || {};
  13656. // Strange app protocol that isn't http/https or local anchor
  13657. // For example: mailto,skype,tel etc.
  13658. if (/^([\w\-]+):([^\/]{2})/i.test(url) || /^\s*#/.test(url)) {
  13659. self.source = url;
  13660. return;
  13661. }
  13662. var isProtocolRelative = url.indexOf('//') === 0;
  13663. // Absolute path with no host, fake host and protocol
  13664. if (url.indexOf('/') === 0 && !isProtocolRelative) {
  13665. url = (settings.base_uri ? settings.base_uri.protocol || 'http' : 'http') + '://mce_host' + url;
  13666. }
  13667. // Relative path http:// or protocol relative //path
  13668. if (!/^[\w\-]*:?\/\//.test(url)) {
  13669. base_url = settings.base_uri ? settings.base_uri.path : new URI(location.href).directory;
  13670. if (settings.base_uri.protocol === "") {
  13671. url = '//mce_host' + self.toAbsPath(base_url, url);
  13672. } else {
  13673. url = ((settings.base_uri && settings.base_uri.protocol) || 'http') + '://mce_host' + self.toAbsPath(base_url, url);
  13674. }
  13675. }
  13676. // Parse URL (Credits goes to Steave, http://blog.stevenlevithan.com/archives/parseuri)
  13677. url = url.replace(/@@/g, '(mce_at)'); // Zope 3 workaround, they use @@something
  13678. /*jshint maxlen: 255 */
  13679. /*eslint max-len: 0 */
  13680. url = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@\/]*):?([^:@\/]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/.exec(url);
  13681. each(["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], function(v, i) {
  13682. var part = url[i];
  13683. // Zope 3 workaround, they use @@something
  13684. if (part) {
  13685. part = part.replace(/\(mce_at\)/g, '@@');
  13686. }
  13687. self[v] = part;
  13688. });
  13689. baseUri = settings.base_uri;
  13690. if (baseUri) {
  13691. if (!self.protocol) {
  13692. self.protocol = baseUri.protocol;
  13693. }
  13694. if (!self.userInfo) {
  13695. self.userInfo = baseUri.userInfo;
  13696. }
  13697. if (!self.port && self.host === 'mce_host') {
  13698. self.port = baseUri.port;
  13699. }
  13700. if (!self.host || self.host === 'mce_host') {
  13701. self.host = baseUri.host;
  13702. }
  13703. self.source = '';
  13704. }
  13705. if (isProtocolRelative) {
  13706. self.protocol = '';
  13707. }
  13708. //t.path = t.path || '/';
  13709. }
  13710. URI.prototype = {
  13711. /**
  13712. * Sets the internal path part of the URI.
  13713. *
  13714. * @method setPath
  13715. * @param {string} path Path string to set.
  13716. */
  13717. setPath: function(path) {
  13718. var self = this;
  13719. path = /^(.*?)\/?(\w+)?$/.exec(path);
  13720. // Update path parts
  13721. self.path = path[0];
  13722. self.directory = path[1];
  13723. self.file = path[2];
  13724. // Rebuild source
  13725. self.source = '';
  13726. self.getURI();
  13727. },
  13728. /**
  13729. * Converts the specified URI into a relative URI based on the current URI instance location.
  13730. *
  13731. * @method toRelative
  13732. * @param {String} uri URI to convert into a relative path/URI.
  13733. * @return {String} Relative URI from the point specified in the current URI instance.
  13734. * @example
  13735. * // Converts an absolute URL to an relative URL url will be somedir/somefile.htm
  13736. * var url = new tinymce.util.URI('http://www.site.com/dir/').toRelative('http://www.site.com/dir/somedir/somefile.htm');
  13737. */
  13738. toRelative: function(uri) {
  13739. var self = this, output;
  13740. if (uri === "./") {
  13741. return uri;
  13742. }
  13743. uri = new URI(uri, {base_uri: self});
  13744. // Not on same domain/port or protocol
  13745. if ((uri.host != 'mce_host' && self.host != uri.host && uri.host) || self.port != uri.port ||
  13746. (self.protocol != uri.protocol && uri.protocol !== "")) {
  13747. return uri.getURI();
  13748. }
  13749. var tu = self.getURI(), uu = uri.getURI();
  13750. // Allow usage of the base_uri when relative_urls = true
  13751. if (tu == uu || (tu.charAt(tu.length - 1) == "/" && tu.substr(0, tu.length - 1) == uu)) {
  13752. return tu;
  13753. }
  13754. output = self.toRelPath(self.path, uri.path);
  13755. // Add query
  13756. if (uri.query) {
  13757. output += '?' + uri.query;
  13758. }
  13759. // Add anchor
  13760. if (uri.anchor) {
  13761. output += '#' + uri.anchor;
  13762. }
  13763. return output;
  13764. },
  13765. /**
  13766. * Converts the specified URI into a absolute URI based on the current URI instance location.
  13767. *
  13768. * @method toAbsolute
  13769. * @param {String} uri URI to convert into a relative path/URI.
  13770. * @param {Boolean} noHost No host and protocol prefix.
  13771. * @return {String} Absolute URI from the point specified in the current URI instance.
  13772. * @example
  13773. * // Converts an relative URL to an absolute URL url will be http://www.site.com/dir/somedir/somefile.htm
  13774. * var url = new tinymce.util.URI('http://www.site.com/dir/').toAbsolute('somedir/somefile.htm');
  13775. */
  13776. toAbsolute: function(uri, noHost) {
  13777. uri = new URI(uri, {base_uri: this});
  13778. return uri.getURI(noHost && this.isSameOrigin(uri));
  13779. },
  13780. /**
  13781. * Determine whether the given URI has the same origin as this URI. Based on RFC-6454.
  13782. * Supports default ports for protocols listed in DEFAULT_PORTS. Unsupported protocols will fail safe: they
  13783. * won't match, if the port specifications differ.
  13784. *
  13785. * @method isSameOrigin
  13786. * @param {tinymce.util.URI} uri Uri instance to compare.
  13787. * @returns {Boolean} True if the origins are the same.
  13788. */
  13789. isSameOrigin: function(uri) {
  13790. if (this.host == uri.host && this.protocol == uri.protocol){
  13791. if (this.port == uri.port) {
  13792. return true;
  13793. }
  13794. var defaultPort = DEFAULT_PORTS[this.protocol];
  13795. if (defaultPort && ((this.port || defaultPort) == (uri.port || defaultPort))) {
  13796. return true;
  13797. }
  13798. }
  13799. return false;
  13800. },
  13801. /**
  13802. * Converts a absolute path into a relative path.
  13803. *
  13804. * @method toRelPath
  13805. * @param {String} base Base point to convert the path from.
  13806. * @param {String} path Absolute path to convert into a relative path.
  13807. */
  13808. toRelPath: function(base, path) {
  13809. var items, breakPoint = 0, out = '', i, l;
  13810. // Split the paths
  13811. base = base.substring(0, base.lastIndexOf('/'));
  13812. base = base.split('/');
  13813. items = path.split('/');
  13814. if (base.length >= items.length) {
  13815. for (i = 0, l = base.length; i < l; i++) {
  13816. if (i >= items.length || base[i] != items[i]) {
  13817. breakPoint = i + 1;
  13818. break;
  13819. }
  13820. }
  13821. }
  13822. if (base.length < items.length) {
  13823. for (i = 0, l = items.length; i < l; i++) {
  13824. if (i >= base.length || base[i] != items[i]) {
  13825. breakPoint = i + 1;
  13826. break;
  13827. }
  13828. }
  13829. }
  13830. if (breakPoint === 1) {
  13831. return path;
  13832. }
  13833. for (i = 0, l = base.length - (breakPoint - 1); i < l; i++) {
  13834. out += "../";
  13835. }
  13836. for (i = breakPoint - 1, l = items.length; i < l; i++) {
  13837. if (i != breakPoint - 1) {
  13838. out += "/" + items[i];
  13839. } else {
  13840. out += items[i];
  13841. }
  13842. }
  13843. return out;
  13844. },
  13845. /**
  13846. * Converts a relative path into a absolute path.
  13847. *
  13848. * @method toAbsPath
  13849. * @param {String} base Base point to convert the path from.
  13850. * @param {String} path Relative path to convert into an absolute path.
  13851. */
  13852. toAbsPath: function(base, path) {
  13853. var i, nb = 0, o = [], tr, outPath;
  13854. // Split paths
  13855. tr = /\/$/.test(path) ? '/' : '';
  13856. base = base.split('/');
  13857. path = path.split('/');
  13858. // Remove empty chunks
  13859. each(base, function(k) {
  13860. if (k) {
  13861. o.push(k);
  13862. }
  13863. });
  13864. base = o;
  13865. // Merge relURLParts chunks
  13866. for (i = path.length - 1, o = []; i >= 0; i--) {
  13867. // Ignore empty or .
  13868. if (path[i].length === 0 || path[i] === ".") {
  13869. continue;
  13870. }
  13871. // Is parent
  13872. if (path[i] === '..') {
  13873. nb++;
  13874. continue;
  13875. }
  13876. // Move up
  13877. if (nb > 0) {
  13878. nb--;
  13879. continue;
  13880. }
  13881. o.push(path[i]);
  13882. }
  13883. i = base.length - nb;
  13884. // If /a/b/c or /
  13885. if (i <= 0) {
  13886. outPath = o.reverse().join('/');
  13887. } else {
  13888. outPath = base.slice(0, i).join('/') + '/' + o.reverse().join('/');
  13889. }
  13890. // Add front / if it's needed
  13891. if (outPath.indexOf('/') !== 0) {
  13892. outPath = '/' + outPath;
  13893. }
  13894. // Add traling / if it's needed
  13895. if (tr && outPath.lastIndexOf('/') !== outPath.length - 1) {
  13896. outPath += tr;
  13897. }
  13898. return outPath;
  13899. },
  13900. /**
  13901. * Returns the full URI of the internal structure.
  13902. *
  13903. * @method getURI
  13904. * @param {Boolean} noProtoHost Optional no host and protocol part. Defaults to false.
  13905. */
  13906. getURI: function(noProtoHost) {
  13907. var s, self = this;
  13908. // Rebuild source
  13909. if (!self.source || noProtoHost) {
  13910. s = '';
  13911. if (!noProtoHost) {
  13912. if (self.protocol) {
  13913. s += self.protocol + '://';
  13914. } else {
  13915. s += '//';
  13916. }
  13917. if (self.userInfo) {
  13918. s += self.userInfo + '@';
  13919. }
  13920. if (self.host) {
  13921. s += self.host;
  13922. }
  13923. if (self.port) {
  13924. s += ':' + self.port;
  13925. }
  13926. }
  13927. if (self.path) {
  13928. s += self.path;
  13929. }
  13930. if (self.query) {
  13931. s += '?' + self.query;
  13932. }
  13933. if (self.anchor) {
  13934. s += '#' + self.anchor;
  13935. }
  13936. self.source = s;
  13937. }
  13938. return self.source;
  13939. }
  13940. };
  13941. return URI;
  13942. });
  13943. // Included from: js/tinymce/classes/util/Class.js
  13944. /**
  13945. * Class.js
  13946. *
  13947. * Copyright 2003-2012, Moxiecode Systems AB, All rights reserved.
  13948. */
  13949. /**
  13950. * This utilitiy class is used for easier inheritage.
  13951. *
  13952. * Features:
  13953. * * Exposed super functions: this._super();
  13954. * * Mixins
  13955. * * Dummy functions
  13956. * * Property functions: var value = object.value(); and object.value(newValue);
  13957. * * Static functions
  13958. * * Defaults settings
  13959. */
  13960. define("tinymce/util/Class", [
  13961. "tinymce/util/Tools"
  13962. ], function(Tools) {
  13963. var each = Tools.each, extend = Tools.extend;
  13964. var extendClass, initializing;
  13965. function Class() {
  13966. }
  13967. // Provides classical inheritance, based on code made by John Resig
  13968. Class.extend = extendClass = function(prop) {
  13969. var self = this, _super = self.prototype, prototype, name, member;
  13970. // The dummy class constructor
  13971. function Class() {
  13972. var i, mixins, mixin, self = this;
  13973. // All construction is actually done in the init method
  13974. if (!initializing) {
  13975. // Run class constuctor
  13976. if (self.init) {
  13977. self.init.apply(self, arguments);
  13978. }
  13979. // Run mixin constructors
  13980. mixins = self.Mixins;
  13981. if (mixins) {
  13982. i = mixins.length;
  13983. while (i--) {
  13984. mixin = mixins[i];
  13985. if (mixin.init) {
  13986. mixin.init.apply(self, arguments);
  13987. }
  13988. }
  13989. }
  13990. }
  13991. }
  13992. // Dummy function, needs to be extended in order to provide functionality
  13993. function dummy() {
  13994. return this;
  13995. }
  13996. // Creates a overloaded method for the class
  13997. // this enables you to use this._super(); to call the super function
  13998. function createMethod(name, fn) {
  13999. return function(){
  14000. var self = this, tmp = self._super, ret;
  14001. self._super = _super[name];
  14002. ret = fn.apply(self, arguments);
  14003. self._super = tmp;
  14004. return ret;
  14005. };
  14006. }
  14007. // Instantiate a base class (but only create the instance,
  14008. // don't run the init constructor)
  14009. initializing = true;
  14010. /*eslint new-cap:0 */
  14011. prototype = new self();
  14012. initializing = false;
  14013. // Add mixins
  14014. if (prop.Mixins) {
  14015. each(prop.Mixins, function(mixin) {
  14016. mixin = mixin;
  14017. for (var name in mixin) {
  14018. if (name !== "init") {
  14019. prop[name] = mixin[name];
  14020. }
  14021. }
  14022. });
  14023. if (_super.Mixins) {
  14024. prop.Mixins = _super.Mixins.concat(prop.Mixins);
  14025. }
  14026. }
  14027. // Generate dummy methods
  14028. if (prop.Methods) {
  14029. each(prop.Methods.split(','), function(name) {
  14030. prop[name] = dummy;
  14031. });
  14032. }
  14033. // Generate property methods
  14034. if (prop.Properties) {
  14035. each(prop.Properties.split(','), function(name) {
  14036. var fieldName = '_' + name;
  14037. prop[name] = function(value) {
  14038. var self = this, undef;
  14039. // Set value
  14040. if (value !== undef) {
  14041. self[fieldName] = value;
  14042. return self;
  14043. }
  14044. // Get value
  14045. return self[fieldName];
  14046. };
  14047. });
  14048. }
  14049. // Static functions
  14050. if (prop.Statics) {
  14051. each(prop.Statics, function(func, name) {
  14052. Class[name] = func;
  14053. });
  14054. }
  14055. // Default settings
  14056. if (prop.Defaults && _super.Defaults) {
  14057. prop.Defaults = extend({}, _super.Defaults, prop.Defaults);
  14058. }
  14059. // Copy the properties over onto the new prototype
  14060. for (name in prop) {
  14061. member = prop[name];
  14062. if (typeof member == "function" && _super[name]) {
  14063. prototype[name] = createMethod(name, member);
  14064. } else {
  14065. prototype[name] = member;
  14066. }
  14067. }
  14068. // Populate our constructed prototype object
  14069. Class.prototype = prototype;
  14070. // Enforce the constructor to be what we expect
  14071. Class.constructor = Class;
  14072. // And make this class extendible
  14073. Class.extend = extendClass;
  14074. return Class;
  14075. };
  14076. return Class;
  14077. });
  14078. // Included from: js/tinymce/classes/ui/Selector.js
  14079. /**
  14080. * Selector.js
  14081. *
  14082. * Copyright, Moxiecode Systems AB
  14083. * Released under LGPL License.
  14084. *
  14085. * License: http://www.tinymce.com/license
  14086. * Contributing: http://www.tinymce.com/contributing
  14087. */
  14088. /*eslint no-nested-ternary:0 */
  14089. /**
  14090. * Selector engine, enables you to select controls by using CSS like expressions.
  14091. * We currently only support basic CSS expressions to reduce the size of the core
  14092. * and the ones we support should be enough for most cases.
  14093. *
  14094. * @example
  14095. * Supported expressions:
  14096. * element
  14097. * element#name
  14098. * element.class
  14099. * element[attr]
  14100. * element[attr*=value]
  14101. * element[attr~=value]
  14102. * element[attr!=value]
  14103. * element[attr^=value]
  14104. * element[attr$=value]
  14105. * element:<state>
  14106. * element:not(<expression>)
  14107. * element:first
  14108. * element:last
  14109. * element:odd
  14110. * element:even
  14111. * element element
  14112. * element > element
  14113. *
  14114. * @class tinymce.ui.Selector
  14115. */
  14116. define("tinymce/ui/Selector", [
  14117. "tinymce/util/Class"
  14118. ], function(Class) {
  14119. "use strict";
  14120. /**
  14121. * Produces an array with a unique set of objects. It will not compare the values
  14122. * but the references of the objects.
  14123. *
  14124. * @private
  14125. * @method unqiue
  14126. * @param {Array} array Array to make into an array with unique items.
  14127. * @return {Array} Array with unique items.
  14128. */
  14129. function unique(array) {
  14130. var uniqueItems = [], i = array.length, item;
  14131. while (i--) {
  14132. item = array[i];
  14133. if (!item.__checked) {
  14134. uniqueItems.push(item);
  14135. item.__checked = 1;
  14136. }
  14137. }
  14138. i = uniqueItems.length;
  14139. while (i--) {
  14140. delete uniqueItems[i].__checked;
  14141. }
  14142. return uniqueItems;
  14143. }
  14144. var expression = /^([\w\\*]+)?(?:#([\w\\]+))?(?:\.([\w\\\.]+))?(?:\[\@?([\w\\]+)([\^\$\*!~]?=)([\w\\]+)\])?(?:\:(.+))?/i;
  14145. /*jshint maxlen:255 */
  14146. /*eslint max-len:0 */
  14147. var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
  14148. whiteSpace = /^\s*|\s*$/g,
  14149. Collection;
  14150. var Selector = Class.extend({
  14151. /**
  14152. * Constructs a new Selector instance.
  14153. *
  14154. * @constructor
  14155. * @method init
  14156. * @param {String} selector CSS like selector expression.
  14157. */
  14158. init: function(selector) {
  14159. var match = this.match;
  14160. function compileNameFilter(name) {
  14161. if (name) {
  14162. name = name.toLowerCase();
  14163. return function(item) {
  14164. return name === '*' || item.type === name;
  14165. };
  14166. }
  14167. }
  14168. function compileIdFilter(id) {
  14169. if (id) {
  14170. return function(item) {
  14171. return item._name === id;
  14172. };
  14173. }
  14174. }
  14175. function compileClassesFilter(classes) {
  14176. if (classes) {
  14177. classes = classes.split('.');
  14178. return function(item) {
  14179. var i = classes.length;
  14180. while (i--) {
  14181. if (!item.hasClass(classes[i])) {
  14182. return false;
  14183. }
  14184. }
  14185. return true;
  14186. };
  14187. }
  14188. }
  14189. function compileAttrFilter(name, cmp, check) {
  14190. if (name) {
  14191. return function(item) {
  14192. var value = item[name] ? item[name]() : '';
  14193. return !cmp ? !!check :
  14194. cmp === "=" ? value === check :
  14195. cmp === "*=" ? value.indexOf(check) >= 0 :
  14196. cmp === "~=" ? (" " + value + " ").indexOf(" " + check + " ") >= 0 :
  14197. cmp === "!=" ? value != check :
  14198. cmp === "^=" ? value.indexOf(check) === 0 :
  14199. cmp === "$=" ? value.substr(value.length - check.length) === check :
  14200. false;
  14201. };
  14202. }
  14203. }
  14204. function compilePsuedoFilter(name) {
  14205. var notSelectors;
  14206. if (name) {
  14207. name = /(?:not\((.+)\))|(.+)/i.exec(name);
  14208. if (!name[1]) {
  14209. name = name[2];
  14210. return function(item, index, length) {
  14211. return name === 'first' ? index === 0 :
  14212. name === 'last' ? index === length - 1 :
  14213. name === 'even' ? index % 2 === 0 :
  14214. name === 'odd' ? index % 2 === 1 :
  14215. item[name] ? item[name]() :
  14216. false;
  14217. };
  14218. } else {
  14219. // Compile not expression
  14220. notSelectors = parseChunks(name[1], []);
  14221. return function(item) {
  14222. return !match(item, notSelectors);
  14223. };
  14224. }
  14225. }
  14226. }
  14227. function compile(selector, filters, direct) {
  14228. var parts;
  14229. function add(filter) {
  14230. if (filter) {
  14231. filters.push(filter);
  14232. }
  14233. }
  14234. // Parse expression into parts
  14235. parts = expression.exec(selector.replace(whiteSpace, ''));
  14236. add(compileNameFilter(parts[1]));
  14237. add(compileIdFilter(parts[2]));
  14238. add(compileClassesFilter(parts[3]));
  14239. add(compileAttrFilter(parts[4], parts[5], parts[6]));
  14240. add(compilePsuedoFilter(parts[7]));
  14241. // Mark the filter with psuedo for performance
  14242. filters.psuedo = !!parts[7];
  14243. filters.direct = direct;
  14244. return filters;
  14245. }
  14246. // Parser logic based on Sizzle by John Resig
  14247. function parseChunks(selector, selectors) {
  14248. var parts = [], extra, matches, i;
  14249. do {
  14250. chunker.exec("");
  14251. matches = chunker.exec(selector);
  14252. if (matches) {
  14253. selector = matches[3];
  14254. parts.push(matches[1]);
  14255. if (matches[2]) {
  14256. extra = matches[3];
  14257. break;
  14258. }
  14259. }
  14260. } while (matches);
  14261. if (extra) {
  14262. parseChunks(extra, selectors);
  14263. }
  14264. selector = [];
  14265. for (i = 0; i < parts.length; i++) {
  14266. if (parts[i] != '>') {
  14267. selector.push(compile(parts[i], [], parts[i - 1] === '>'));
  14268. }
  14269. }
  14270. selectors.push(selector);
  14271. return selectors;
  14272. }
  14273. this._selectors = parseChunks(selector, []);
  14274. },
  14275. /**
  14276. * Returns true/false if the selector matches the specified control.
  14277. *
  14278. * @method match
  14279. * @param {tinymce.ui.Control} control Control to match agains the selector.
  14280. * @param {Array} selectors Optional array of selectors, mostly used internally.
  14281. * @return {Boolean} true/false state if the control matches or not.
  14282. */
  14283. match: function(control, selectors) {
  14284. var i, l, si, sl, selector, fi, fl, filters, index, length, siblings, count, item;
  14285. selectors = selectors || this._selectors;
  14286. for (i = 0, l = selectors.length; i < l; i++) {
  14287. selector = selectors[i];
  14288. sl = selector.length;
  14289. item = control;
  14290. count = 0;
  14291. for (si = sl - 1; si >= 0; si--) {
  14292. filters = selector[si];
  14293. while (item) {
  14294. // Find the index and length since a psuedo filter like :first needs it
  14295. if (filters.psuedo) {
  14296. siblings = item.parent().items();
  14297. index = length = siblings.length;
  14298. while (index--) {
  14299. if (siblings[index] === item) {
  14300. break;
  14301. }
  14302. }
  14303. }
  14304. for (fi = 0, fl = filters.length; fi < fl; fi++) {
  14305. if (!filters[fi](item, index, length)) {
  14306. fi = fl + 1;
  14307. break;
  14308. }
  14309. }
  14310. if (fi === fl) {
  14311. count++;
  14312. break;
  14313. } else {
  14314. // If it didn't match the right most expression then
  14315. // break since it's no point looking at the parents
  14316. if (si === sl - 1) {
  14317. break;
  14318. }
  14319. }
  14320. item = item.parent();
  14321. }
  14322. }
  14323. // If we found all selectors then return true otherwise continue looking
  14324. if (count === sl) {
  14325. return true;
  14326. }
  14327. }
  14328. return false;
  14329. },
  14330. /**
  14331. * Returns a tinymce.ui.Collection with matches of the specified selector inside the specified container.
  14332. *
  14333. * @method find
  14334. * @param {tinymce.ui.Control} container Container to look for items in.
  14335. * @return {tinymce.ui.Collection} Collection with matched elements.
  14336. */
  14337. find: function(container) {
  14338. var matches = [], i, l, selectors = this._selectors;
  14339. function collect(items, selector, index) {
  14340. var i, l, fi, fl, item, filters = selector[index];
  14341. for (i = 0, l = items.length; i < l; i++) {
  14342. item = items[i];
  14343. // Run each filter agains the item
  14344. for (fi = 0, fl = filters.length; fi < fl; fi++) {
  14345. if (!filters[fi](item, i, l)) {
  14346. fi = fl + 1;
  14347. break;
  14348. }
  14349. }
  14350. // All filters matched the item
  14351. if (fi === fl) {
  14352. // Matched item is on the last expression like: panel toolbar [button]
  14353. if (index == selector.length - 1) {
  14354. matches.push(item);
  14355. } else {
  14356. // Collect next expression type
  14357. if (item.items) {
  14358. collect(item.items(), selector, index + 1);
  14359. }
  14360. }
  14361. } else if (filters.direct) {
  14362. return;
  14363. }
  14364. // Collect child items
  14365. if (item.items) {
  14366. collect(item.items(), selector, index);
  14367. }
  14368. }
  14369. }
  14370. if (container.items) {
  14371. for (i = 0, l = selectors.length; i < l; i++) {
  14372. collect(container.items(), selectors[i], 0);
  14373. }
  14374. // Unique the matches if needed
  14375. if (l > 1) {
  14376. matches = unique(matches);
  14377. }
  14378. }
  14379. // Fix for circular reference
  14380. if (!Collection) {
  14381. // TODO: Fix me!
  14382. Collection = Selector.Collection;
  14383. }
  14384. return new Collection(matches);
  14385. }
  14386. });
  14387. return Selector;
  14388. });
  14389. // Included from: js/tinymce/classes/ui/Collection.js
  14390. /**
  14391. * Collection.js
  14392. *
  14393. * Copyright, Moxiecode Systems AB
  14394. * Released under LGPL License.
  14395. *
  14396. * License: http://www.tinymce.com/license
  14397. * Contributing: http://www.tinymce.com/contributing
  14398. */
  14399. /**
  14400. * Control collection, this class contains control instances and it enables you to
  14401. * perform actions on all the contained items. This is very similar to how jQuery works.
  14402. *
  14403. * @example
  14404. * someCollection.show().disabled(true);
  14405. *
  14406. * @class tinymce.ui.Collection
  14407. */
  14408. define("tinymce/ui/Collection", [
  14409. "tinymce/util/Tools",
  14410. "tinymce/ui/Selector",
  14411. "tinymce/util/Class"
  14412. ], function(Tools, Selector, Class) {
  14413. "use strict";
  14414. var Collection, proto, push = Array.prototype.push, slice = Array.prototype.slice;
  14415. proto = {
  14416. /**
  14417. * Current number of contained control instances.
  14418. *
  14419. * @field length
  14420. * @type Number
  14421. */
  14422. length: 0,
  14423. /**
  14424. * Constructor for the collection.
  14425. *
  14426. * @constructor
  14427. * @method init
  14428. * @param {Array} items Optional array with items to add.
  14429. */
  14430. init: function(items) {
  14431. if (items) {
  14432. this.add(items);
  14433. }
  14434. },
  14435. /**
  14436. * Adds new items to the control collection.
  14437. *
  14438. * @method add
  14439. * @param {Array} items Array if items to add to collection.
  14440. * @return {tinymce.ui.Collection} Current collection instance.
  14441. */
  14442. add: function(items) {
  14443. var self = this;
  14444. // Force single item into array
  14445. if (!Tools.isArray(items)) {
  14446. if (items instanceof Collection) {
  14447. self.add(items.toArray());
  14448. } else {
  14449. push.call(self, items);
  14450. }
  14451. } else {
  14452. push.apply(self, items);
  14453. }
  14454. return self;
  14455. },
  14456. /**
  14457. * Sets the contents of the collection. This will remove any existing items
  14458. * and replace them with the ones specified in the input array.
  14459. *
  14460. * @method set
  14461. * @param {Array} items Array with items to set into the Collection.
  14462. * @return {tinymce.ui.Collection} Collection instance.
  14463. */
  14464. set: function(items) {
  14465. var self = this, len = self.length, i;
  14466. self.length = 0;
  14467. self.add(items);
  14468. // Remove old entries
  14469. for (i = self.length; i < len; i++) {
  14470. delete self[i];
  14471. }
  14472. return self;
  14473. },
  14474. /**
  14475. * Filters the collection item based on the specified selector expression or selector function.
  14476. *
  14477. * @method filter
  14478. * @param {String} selector Selector expression to filter items by.
  14479. * @return {tinymce.ui.Collection} Collection containing the filtered items.
  14480. */
  14481. filter: function(selector) {
  14482. var self = this, i, l, matches = [], item, match;
  14483. // Compile string into selector expression
  14484. if (typeof(selector) === "string") {
  14485. selector = new Selector(selector);
  14486. match = function(item) {
  14487. return selector.match(item);
  14488. };
  14489. } else {
  14490. // Use selector as matching function
  14491. match = selector;
  14492. }
  14493. for (i = 0, l = self.length; i < l; i++) {
  14494. item = self[i];
  14495. if (match(item)) {
  14496. matches.push(item);
  14497. }
  14498. }
  14499. return new Collection(matches);
  14500. },
  14501. /**
  14502. * Slices the items within the collection.
  14503. *
  14504. * @method slice
  14505. * @param {Number} index Index to slice at.
  14506. * @param {Number} len Optional length to slice.
  14507. * @return {tinymce.ui.Collection} Current collection.
  14508. */
  14509. slice: function() {
  14510. return new Collection(slice.apply(this, arguments));
  14511. },
  14512. /**
  14513. * Makes the current collection equal to the specified index.
  14514. *
  14515. * @method eq
  14516. * @param {Number} index Index of the item to set the collection to.
  14517. * @return {tinymce.ui.Collection} Current collection.
  14518. */
  14519. eq: function(index) {
  14520. return index === -1 ? this.slice(index) : this.slice(index, +index + 1);
  14521. },
  14522. /**
  14523. * Executes the specified callback on each item in collection.
  14524. *
  14525. * @method each
  14526. * @param {function} callback Callback to execute for each item in collection.
  14527. * @return {tinymce.ui.Collection} Current collection instance.
  14528. */
  14529. each: function(callback) {
  14530. Tools.each(this, callback);
  14531. return this;
  14532. },
  14533. /**
  14534. * Returns an JavaScript array object of the contents inside the collection.
  14535. *
  14536. * @method toArray
  14537. * @return {Array} Array with all items from collection.
  14538. */
  14539. toArray: function() {
  14540. return Tools.toArray(this);
  14541. },
  14542. /**
  14543. * Finds the index of the specified control or return -1 if it isn't in the collection.
  14544. *
  14545. * @method indexOf
  14546. * @param {Control} ctrl Control instance to look for.
  14547. * @return {Number} Index of the specified control or -1.
  14548. */
  14549. indexOf: function(ctrl) {
  14550. var self = this, i = self.length;
  14551. while (i--) {
  14552. if (self[i] === ctrl) {
  14553. break;
  14554. }
  14555. }
  14556. return i;
  14557. },
  14558. /**
  14559. * Returns a new collection of the contents in reverse order.
  14560. *
  14561. * @method reverse
  14562. * @return {tinymce.ui.Collection} Collection instance with reversed items.
  14563. */
  14564. reverse: function() {
  14565. return new Collection(Tools.toArray(this).reverse());
  14566. },
  14567. /**
  14568. * Returns true/false if the class exists or not.
  14569. *
  14570. * @method hasClass
  14571. * @param {String} cls Class to check for.
  14572. * @return {Boolean} true/false state if the class exists or not.
  14573. */
  14574. hasClass: function(cls) {
  14575. return this[0] ? this[0].hasClass(cls) : false;
  14576. },
  14577. /**
  14578. * Sets/gets the specific property on the items in the collection. The same as executing control.<property>(<value>);
  14579. *
  14580. * @method prop
  14581. * @param {String} name Property name to get/set.
  14582. * @param {Object} value Optional object value to set.
  14583. * @return {tinymce.ui.Collection} Current collection instance or value of the first item on a get operation.
  14584. */
  14585. prop: function(name, value) {
  14586. var self = this, undef, item;
  14587. if (value !== undef) {
  14588. self.each(function(item) {
  14589. if (item[name]) {
  14590. item[name](value);
  14591. }
  14592. });
  14593. return self;
  14594. }
  14595. item = self[0];
  14596. if (item && item[name]) {
  14597. return item[name]();
  14598. }
  14599. },
  14600. /**
  14601. * Executes the specific function name with optional arguments an all items in collection if it exists.
  14602. *
  14603. * @example collection.exec("myMethod", arg1, arg2, arg3);
  14604. * @method exec
  14605. * @param {String} name Name of the function to execute.
  14606. * @param {Object} ... Multiple arguments to pass to each function.
  14607. * @return {tinymce.ui.Collection} Current collection.
  14608. */
  14609. exec: function(name) {
  14610. var self = this, args = Tools.toArray(arguments).slice(1);
  14611. self.each(function(item) {
  14612. if (item[name]) {
  14613. item[name].apply(item, args);
  14614. }
  14615. });
  14616. return self;
  14617. },
  14618. /**
  14619. * Remove all items from collection and DOM.
  14620. *
  14621. * @method remove
  14622. * @return {tinymce.ui.Collection} Current collection.
  14623. */
  14624. remove: function() {
  14625. var i = this.length;
  14626. while (i--) {
  14627. this[i].remove();
  14628. }
  14629. return this;
  14630. }
  14631. /**
  14632. * Fires the specified event by name and arguments on the control. This will execute all
  14633. * bound event handlers.
  14634. *
  14635. * @method fire
  14636. * @param {String} name Name of the event to fire.
  14637. * @param {Object} args Optional arguments to pass to the event.
  14638. * @return {tinymce.ui.Collection} Current collection instance.
  14639. */
  14640. // fire: function(event, args) {}, -- Generated by code below
  14641. /**
  14642. * Binds a callback to the specified event. This event can both be
  14643. * native browser events like "click" or custom ones like PostRender.
  14644. *
  14645. * The callback function will have two parameters the first one being the control that received the event
  14646. * the second one will be the event object either the browsers native event object or a custom JS object.
  14647. *
  14648. * @method on
  14649. * @param {String} name Name of the event to bind. For example "click".
  14650. * @param {String/function} callback Callback function to execute ones the event occurs.
  14651. * @return {tinymce.ui.Collection} Current collection instance.
  14652. */
  14653. // on: function(name, callback) {}, -- Generated by code below
  14654. /**
  14655. * Unbinds the specified event and optionally a specific callback. If you omit the name
  14656. * parameter all event handlers will be removed. If you omit the callback all event handles
  14657. * by the specified name will be removed.
  14658. *
  14659. * @method off
  14660. * @param {String} name Optional name for the event to unbind.
  14661. * @param {function} callback Optional callback function to unbind.
  14662. * @return {tinymce.ui.Collection} Current collection instance.
  14663. */
  14664. // off: function(name, callback) {}, -- Generated by code below
  14665. /**
  14666. * Shows the items in the current collection.
  14667. *
  14668. * @method show
  14669. * @return {tinymce.ui.Collection} Current collection instance.
  14670. */
  14671. // show: function() {}, -- Generated by code below
  14672. /**
  14673. * Hides the items in the current collection.
  14674. *
  14675. * @method hide
  14676. * @return {tinymce.ui.Collection} Current collection instance.
  14677. */
  14678. // hide: function() {}, -- Generated by code below
  14679. /**
  14680. * Sets/gets the text contents of the items in the current collection.
  14681. *
  14682. * @method text
  14683. * @return {tinymce.ui.Collection} Current collection instance or text value of the first item on a get operation.
  14684. */
  14685. // text: function(value) {}, -- Generated by code below
  14686. /**
  14687. * Sets/gets the name contents of the items in the current collection.
  14688. *
  14689. * @method name
  14690. * @return {tinymce.ui.Collection} Current collection instance or name value of the first item on a get operation.
  14691. */
  14692. // name: function(value) {}, -- Generated by code below
  14693. /**
  14694. * Sets/gets the disabled state on the items in the current collection.
  14695. *
  14696. * @method disabled
  14697. * @return {tinymce.ui.Collection} Current collection instance or disabled state of the first item on a get operation.
  14698. */
  14699. // disabled: function(state) {}, -- Generated by code below
  14700. /**
  14701. * Sets/gets the active state on the items in the current collection.
  14702. *
  14703. * @method active
  14704. * @return {tinymce.ui.Collection} Current collection instance or active state of the first item on a get operation.
  14705. */
  14706. // active: function(state) {}, -- Generated by code below
  14707. /**
  14708. * Sets/gets the selected state on the items in the current collection.
  14709. *
  14710. * @method selected
  14711. * @return {tinymce.ui.Collection} Current collection instance or selected state of the first item on a get operation.
  14712. */
  14713. // selected: function(state) {}, -- Generated by code below
  14714. /**
  14715. * Sets/gets the selected state on the items in the current collection.
  14716. *
  14717. * @method visible
  14718. * @return {tinymce.ui.Collection} Current collection instance or visible state of the first item on a get operation.
  14719. */
  14720. // visible: function(state) {}, -- Generated by code below
  14721. /**
  14722. * Adds a class to all items in the collection.
  14723. *
  14724. * @method addClass
  14725. * @param {String} cls Class to add to each item.
  14726. * @return {tinymce.ui.Collection} Current collection instance.
  14727. */
  14728. // addClass: function(cls) {}, -- Generated by code below
  14729. /**
  14730. * Removes the specified class from all items in collection.
  14731. *
  14732. * @method removeClass
  14733. * @param {String} cls Class to remove from each item.
  14734. * @return {tinymce.ui.Collection} Current collection instance.
  14735. */
  14736. // removeClass: function(cls) {}, -- Generated by code below
  14737. };
  14738. // Extend tinymce.ui.Collection prototype with some generated control specific methods
  14739. Tools.each('fire on off show hide addClass removeClass append prepend before after reflow'.split(' '), function(name) {
  14740. proto[name] = function() {
  14741. var args = Tools.toArray(arguments);
  14742. this.each(function(ctrl) {
  14743. if (name in ctrl) {
  14744. ctrl[name].apply(ctrl, args);
  14745. }
  14746. });
  14747. return this;
  14748. };
  14749. });
  14750. // Extend tinymce.ui.Collection prototype with some property methods
  14751. Tools.each('text name disabled active selected checked visible parent value data'.split(' '), function(name) {
  14752. proto[name] = function(value) {
  14753. return this.prop(name, value);
  14754. };
  14755. });
  14756. // Create class based on the new prototype
  14757. Collection = Class.extend(proto);
  14758. // Stick Collection into Selector to prevent circual references
  14759. Selector.Collection = Collection;
  14760. return Collection;
  14761. });
  14762. // Included from: js/tinymce/classes/ui/DomUtils.js
  14763. /**
  14764. * DOMUtils.js
  14765. *
  14766. * Copyright, Moxiecode Systems AB
  14767. * Released under LGPL License.
  14768. *
  14769. * License: http://www.tinymce.com/license
  14770. * Contributing: http://www.tinymce.com/contributing
  14771. */
  14772. define("tinymce/ui/DomUtils", [
  14773. "tinymce/util/Tools",
  14774. "tinymce/dom/DOMUtils"
  14775. ], function(Tools, DOMUtils) {
  14776. "use strict";
  14777. return {
  14778. id: function() {
  14779. return DOMUtils.DOM.uniqueId();
  14780. },
  14781. createFragment: function(html) {
  14782. return DOMUtils.DOM.createFragment(html);
  14783. },
  14784. getWindowSize: function() {
  14785. return DOMUtils.DOM.getViewPort();
  14786. },
  14787. getSize: function(elm) {
  14788. var width, height;
  14789. if (elm.getBoundingClientRect) {
  14790. var rect = elm.getBoundingClientRect();
  14791. width = Math.max(rect.width || (rect.right - rect.left), elm.offsetWidth);
  14792. height = Math.max(rect.height || (rect.bottom - rect.bottom), elm.offsetHeight);
  14793. } else {
  14794. width = elm.offsetWidth;
  14795. height = elm.offsetHeight;
  14796. }
  14797. return {width: width, height: height};
  14798. },
  14799. getPos: function(elm, root) {
  14800. return DOMUtils.DOM.getPos(elm, root);
  14801. },
  14802. getViewPort: function(win) {
  14803. return DOMUtils.DOM.getViewPort(win);
  14804. },
  14805. get: function(id) {
  14806. return document.getElementById(id);
  14807. },
  14808. addClass : function(elm, cls) {
  14809. return DOMUtils.DOM.addClass(elm, cls);
  14810. },
  14811. removeClass : function(elm, cls) {
  14812. return DOMUtils.DOM.removeClass(elm, cls);
  14813. },
  14814. hasClass : function(elm, cls) {
  14815. return DOMUtils.DOM.hasClass(elm, cls);
  14816. },
  14817. toggleClass: function(elm, cls, state) {
  14818. return DOMUtils.DOM.toggleClass(elm, cls, state);
  14819. },
  14820. css: function(elm, name, value) {
  14821. return DOMUtils.DOM.setStyle(elm, name, value);
  14822. },
  14823. on: function(target, name, callback, scope) {
  14824. return DOMUtils.DOM.bind(target, name, callback, scope);
  14825. },
  14826. off: function(target, name, callback) {
  14827. return DOMUtils.DOM.unbind(target, name, callback);
  14828. },
  14829. fire: function(target, name, args) {
  14830. return DOMUtils.DOM.fire(target, name, args);
  14831. },
  14832. innerHtml: function(elm, html) {
  14833. // Workaround for <div> in <p> bug on IE 8 #6178
  14834. DOMUtils.DOM.setHTML(elm, html);
  14835. }
  14836. };
  14837. });
  14838. // Included from: js/tinymce/classes/ui/Control.js
  14839. /**
  14840. * Control.js
  14841. *
  14842. * Copyright, Moxiecode Systems AB
  14843. * Released under LGPL License.
  14844. *
  14845. * License: http://www.tinymce.com/license
  14846. * Contributing: http://www.tinymce.com/contributing
  14847. */
  14848. /*eslint consistent-this:0 */
  14849. /**
  14850. * This is the base class for all controls and containers. All UI control instances inherit
  14851. * from this one as it has the base logic needed by all of them.
  14852. *
  14853. * @class tinymce.ui.Control
  14854. */
  14855. define("tinymce/ui/Control", [
  14856. "tinymce/util/Class",
  14857. "tinymce/util/Tools",
  14858. "tinymce/ui/Collection",
  14859. "tinymce/ui/DomUtils"
  14860. ], function(Class, Tools, Collection, DomUtils) {
  14861. "use strict";
  14862. var nativeEvents = Tools.makeMap("focusin focusout scroll click dblclick mousedown mouseup mousemove mouseover" +
  14863. " mouseout mouseenter mouseleave wheel keydown keypress input keyup contextmenu", " ");
  14864. var elementIdCache = {};
  14865. var hasMouseWheelEventSupport = "onmousewheel" in document;
  14866. var hasWheelEventSupport = false;
  14867. var classPrefix = "mce-";
  14868. var Control = Class.extend({
  14869. Statics: {
  14870. elementIdCache: elementIdCache,
  14871. classPrefix: classPrefix
  14872. },
  14873. isRtl: function() {
  14874. return Control.rtl;
  14875. },
  14876. /**
  14877. * Class/id prefix to use for all controls.
  14878. *
  14879. * @final
  14880. * @field {String} classPrefix
  14881. */
  14882. classPrefix: classPrefix,
  14883. /**
  14884. * Constructs a new control instance with the specified settings.
  14885. *
  14886. * @constructor
  14887. * @param {Object} settings Name/value object with settings.
  14888. * @setting {String} style Style CSS properties to add.
  14889. * @setting {String} border Border box values example: 1 1 1 1
  14890. * @setting {String} padding Padding box values example: 1 1 1 1
  14891. * @setting {String} margin Margin box values example: 1 1 1 1
  14892. * @setting {Number} minWidth Minimal width for the control.
  14893. * @setting {Number} minHeight Minimal height for the control.
  14894. * @setting {String} classes Space separated list of classes to add.
  14895. * @setting {String} role WAI-ARIA role to use for control.
  14896. * @setting {Boolean} hidden Is the control hidden by default.
  14897. * @setting {Boolean} disabled Is the control disabled by default.
  14898. * @setting {String} name Name of the control instance.
  14899. */
  14900. init: function(settings) {
  14901. var self = this, classes, i;
  14902. self.settings = settings = Tools.extend({}, self.Defaults, settings);
  14903. // Initial states
  14904. self._id = settings.id || DomUtils.id();
  14905. self._text = self._name = '';
  14906. self._width = self._height = 0;
  14907. self._aria = {role: settings.role};
  14908. // Setup classes
  14909. classes = settings.classes;
  14910. if (classes) {
  14911. classes = classes.split(' ');
  14912. classes.map = {};
  14913. i = classes.length;
  14914. while (i--) {
  14915. classes.map[classes[i]] = true;
  14916. }
  14917. }
  14918. self._classes = classes || [];
  14919. self.visible(true);
  14920. // Set some properties
  14921. Tools.each('title text width height name classes visible disabled active value'.split(' '), function(name) {
  14922. var value = settings[name], undef;
  14923. if (value !== undef) {
  14924. self[name](value);
  14925. } else if (self['_' + name] === undef) {
  14926. self['_' + name] = false;
  14927. }
  14928. });
  14929. self.on('click', function() {
  14930. if (self.disabled()) {
  14931. return false;
  14932. }
  14933. });
  14934. // TODO: Is this needed duplicate code see above?
  14935. if (settings.classes) {
  14936. Tools.each(settings.classes.split(' '), function(cls) {
  14937. self.addClass(cls);
  14938. });
  14939. }
  14940. /**
  14941. * Name/value object with settings for the current control.
  14942. *
  14943. * @field {Object} settings
  14944. */
  14945. self.settings = settings;
  14946. self._borderBox = self.parseBox(settings.border);
  14947. self._paddingBox = self.parseBox(settings.padding);
  14948. self._marginBox = self.parseBox(settings.margin);
  14949. if (settings.hidden) {
  14950. self.hide();
  14951. }
  14952. },
  14953. // Will generate getter/setter methods for these properties
  14954. Properties: 'parent,title,text,width,height,disabled,active,name,value',
  14955. // Will generate empty dummy functions for these
  14956. Methods: 'renderHtml',
  14957. /**
  14958. * Returns the root element to render controls into.
  14959. *
  14960. * @method getContainerElm
  14961. * @return {Element} HTML DOM element to render into.
  14962. */
  14963. getContainerElm: function() {
  14964. return document.body;
  14965. },
  14966. /**
  14967. * Returns a control instance for the current DOM element.
  14968. *
  14969. * @method getParentCtrl
  14970. * @param {Element} elm HTML dom element to get parent control from.
  14971. * @return {tinymce.ui.Control} Control instance or undefined.
  14972. */
  14973. getParentCtrl: function(elm) {
  14974. var ctrl, lookup = this.getRoot().controlIdLookup;
  14975. while (elm && lookup) {
  14976. ctrl = lookup[elm.id];
  14977. if (ctrl) {
  14978. break;
  14979. }
  14980. elm = elm.parentNode;
  14981. }
  14982. return ctrl;
  14983. },
  14984. /**
  14985. * Parses the specified box value. A box value contains 1-4 properties in clockwise order.
  14986. *
  14987. * @method parseBox
  14988. * @param {String/Number} value Box value "0 1 2 3" or "0" etc.
  14989. * @return {Object} Object with top/right/bottom/left properties.
  14990. * @private
  14991. */
  14992. parseBox: function(value) {
  14993. var len, radix = 10;
  14994. if (!value) {
  14995. return;
  14996. }
  14997. if (typeof(value) === "number") {
  14998. value = value || 0;
  14999. return {
  15000. top: value,
  15001. left: value,
  15002. bottom: value,
  15003. right: value
  15004. };
  15005. }
  15006. value = value.split(' ');
  15007. len = value.length;
  15008. if (len === 1) {
  15009. value[1] = value[2] = value[3] = value[0];
  15010. } else if (len === 2) {
  15011. value[2] = value[0];
  15012. value[3] = value[1];
  15013. } else if (len === 3) {
  15014. value[3] = value[1];
  15015. }
  15016. return {
  15017. top: parseInt(value[0], radix) || 0,
  15018. right: parseInt(value[1], radix) || 0,
  15019. bottom: parseInt(value[2], radix) || 0,
  15020. left: parseInt(value[3], radix) || 0
  15021. };
  15022. },
  15023. borderBox: function() {
  15024. return this._borderBox;
  15025. },
  15026. paddingBox: function() {
  15027. return this._paddingBox;
  15028. },
  15029. marginBox: function() {
  15030. return this._marginBox;
  15031. },
  15032. measureBox: function(elm, prefix) {
  15033. function getStyle(name) {
  15034. var defaultView = document.defaultView;
  15035. if (defaultView) {
  15036. // Remove camelcase
  15037. name = name.replace(/[A-Z]/g, function(a) {
  15038. return '-' + a;
  15039. });
  15040. return defaultView.getComputedStyle(elm, null).getPropertyValue(name);
  15041. }
  15042. return elm.currentStyle[name];
  15043. }
  15044. function getSide(name) {
  15045. var val = parseFloat(getStyle(name), 10);
  15046. return isNaN(val) ? 0 : val;
  15047. }
  15048. return {
  15049. top: getSide(prefix + "TopWidth"),
  15050. right: getSide(prefix + "RightWidth"),
  15051. bottom: getSide(prefix + "BottomWidth"),
  15052. left: getSide(prefix + "LeftWidth")
  15053. };
  15054. },
  15055. /**
  15056. * Initializes the current controls layout rect.
  15057. * This will be executed by the layout managers to determine the
  15058. * default minWidth/minHeight etc.
  15059. *
  15060. * @method initLayoutRect
  15061. * @return {Object} Layout rect instance.
  15062. */
  15063. initLayoutRect: function() {
  15064. var self = this, settings = self.settings, borderBox, layoutRect;
  15065. var elm = self.getEl(), width, height, minWidth, minHeight, autoResize;
  15066. var startMinWidth, startMinHeight, initialSize;
  15067. // Measure the current element
  15068. borderBox = self._borderBox = self._borderBox || self.measureBox(elm, 'border');
  15069. self._paddingBox = self._paddingBox || self.measureBox(elm, 'padding');
  15070. self._marginBox = self._marginBox || self.measureBox(elm, 'margin');
  15071. initialSize = DomUtils.getSize(elm);
  15072. // Setup minWidth/minHeight and width/height
  15073. startMinWidth = settings.minWidth;
  15074. startMinHeight = settings.minHeight;
  15075. minWidth = startMinWidth || initialSize.width;
  15076. minHeight = startMinHeight || initialSize.height;
  15077. width = settings.width;
  15078. height = settings.height;
  15079. autoResize = settings.autoResize;
  15080. autoResize = typeof(autoResize) != "undefined" ? autoResize : !width && !height;
  15081. width = width || minWidth;
  15082. height = height || minHeight;
  15083. var deltaW = borderBox.left + borderBox.right;
  15084. var deltaH = borderBox.top + borderBox.bottom;
  15085. var maxW = settings.maxWidth || 0xFFFF;
  15086. var maxH = settings.maxHeight || 0xFFFF;
  15087. // Setup initial layout rect
  15088. self._layoutRect = layoutRect = {
  15089. x: settings.x || 0,
  15090. y: settings.y || 0,
  15091. w: width,
  15092. h: height,
  15093. deltaW: deltaW,
  15094. deltaH: deltaH,
  15095. contentW: width - deltaW,
  15096. contentH: height - deltaH,
  15097. innerW: width - deltaW,
  15098. innerH: height - deltaH,
  15099. startMinWidth: startMinWidth || 0,
  15100. startMinHeight: startMinHeight || 0,
  15101. minW: Math.min(minWidth, maxW),
  15102. minH: Math.min(minHeight, maxH),
  15103. maxW: maxW,
  15104. maxH: maxH,
  15105. autoResize: autoResize,
  15106. scrollW: 0
  15107. };
  15108. self._lastLayoutRect = {};
  15109. return layoutRect;
  15110. },
  15111. /**
  15112. * Getter/setter for the current layout rect.
  15113. *
  15114. * @method layoutRect
  15115. * @param {Object} [newRect] Optional new layout rect.
  15116. * @return {tinymce.ui.Control/Object} Current control or rect object.
  15117. */
  15118. layoutRect: function(newRect) {
  15119. var self = this, curRect = self._layoutRect, lastLayoutRect, size, deltaWidth, deltaHeight, undef, repaintControls;
  15120. // Initialize default layout rect
  15121. if (!curRect) {
  15122. curRect = self.initLayoutRect();
  15123. }
  15124. // Set new rect values
  15125. if (newRect) {
  15126. // Calc deltas between inner and outer sizes
  15127. deltaWidth = curRect.deltaW;
  15128. deltaHeight = curRect.deltaH;
  15129. // Set x position
  15130. if (newRect.x !== undef) {
  15131. curRect.x = newRect.x;
  15132. }
  15133. // Set y position
  15134. if (newRect.y !== undef) {
  15135. curRect.y = newRect.y;
  15136. }
  15137. // Set minW
  15138. if (newRect.minW !== undef) {
  15139. curRect.minW = newRect.minW;
  15140. }
  15141. // Set minH
  15142. if (newRect.minH !== undef) {
  15143. curRect.minH = newRect.minH;
  15144. }
  15145. // Set new width and calculate inner width
  15146. size = newRect.w;
  15147. if (size !== undef) {
  15148. size = size < curRect.minW ? curRect.minW : size;
  15149. size = size > curRect.maxW ? curRect.maxW : size;
  15150. curRect.w = size;
  15151. curRect.innerW = size - deltaWidth;
  15152. }
  15153. // Set new height and calculate inner height
  15154. size = newRect.h;
  15155. if (size !== undef) {
  15156. size = size < curRect.minH ? curRect.minH : size;
  15157. size = size > curRect.maxH ? curRect.maxH : size;
  15158. curRect.h = size;
  15159. curRect.innerH = size - deltaHeight;
  15160. }
  15161. // Set new inner width and calculate width
  15162. size = newRect.innerW;
  15163. if (size !== undef) {
  15164. size = size < curRect.minW - deltaWidth ? curRect.minW - deltaWidth : size;
  15165. size = size > curRect.maxW - deltaWidth ? curRect.maxW - deltaWidth : size;
  15166. curRect.innerW = size;
  15167. curRect.w = size + deltaWidth;
  15168. }
  15169. // Set new height and calculate inner height
  15170. size = newRect.innerH;
  15171. if (size !== undef) {
  15172. size = size < curRect.minH - deltaHeight ? curRect.minH - deltaHeight : size;
  15173. size = size > curRect.maxH - deltaHeight ? curRect.maxH - deltaHeight : size;
  15174. curRect.innerH = size;
  15175. curRect.h = size + deltaHeight;
  15176. }
  15177. // Set new contentW
  15178. if (newRect.contentW !== undef) {
  15179. curRect.contentW = newRect.contentW;
  15180. }
  15181. // Set new contentH
  15182. if (newRect.contentH !== undef) {
  15183. curRect.contentH = newRect.contentH;
  15184. }
  15185. // Compare last layout rect with the current one to see if we need to repaint or not
  15186. lastLayoutRect = self._lastLayoutRect;
  15187. if (lastLayoutRect.x !== curRect.x || lastLayoutRect.y !== curRect.y ||
  15188. lastLayoutRect.w !== curRect.w || lastLayoutRect.h !== curRect.h) {
  15189. repaintControls = Control.repaintControls;
  15190. if (repaintControls) {
  15191. if (repaintControls.map && !repaintControls.map[self._id]) {
  15192. repaintControls.push(self);
  15193. repaintControls.map[self._id] = true;
  15194. }
  15195. }
  15196. lastLayoutRect.x = curRect.x;
  15197. lastLayoutRect.y = curRect.y;
  15198. lastLayoutRect.w = curRect.w;
  15199. lastLayoutRect.h = curRect.h;
  15200. }
  15201. return self;
  15202. }
  15203. return curRect;
  15204. },
  15205. /**
  15206. * Repaints the control after a layout operation.
  15207. *
  15208. * @method repaint
  15209. */
  15210. repaint: function() {
  15211. var self = this, style, bodyStyle, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect, round;
  15212. // Use Math.round on all values on IE < 9
  15213. round = !document.createRange ? Math.round : function(value) {
  15214. return value;
  15215. };
  15216. style = self.getEl().style;
  15217. rect = self._layoutRect;
  15218. lastRepaintRect = self._lastRepaintRect || {};
  15219. borderBox = self._borderBox;
  15220. borderW = borderBox.left + borderBox.right;
  15221. borderH = borderBox.top + borderBox.bottom;
  15222. if (rect.x !== lastRepaintRect.x) {
  15223. style.left = round(rect.x) + 'px';
  15224. lastRepaintRect.x = rect.x;
  15225. }
  15226. if (rect.y !== lastRepaintRect.y) {
  15227. style.top = round(rect.y) + 'px';
  15228. lastRepaintRect.y = rect.y;
  15229. }
  15230. if (rect.w !== lastRepaintRect.w) {
  15231. style.width = round(rect.w - borderW) + 'px';
  15232. lastRepaintRect.w = rect.w;
  15233. }
  15234. if (rect.h !== lastRepaintRect.h) {
  15235. style.height = round(rect.h - borderH) + 'px';
  15236. lastRepaintRect.h = rect.h;
  15237. }
  15238. // Update body if needed
  15239. if (self._hasBody && rect.innerW !== lastRepaintRect.innerW) {
  15240. bodyStyle = self.getEl('body').style;
  15241. bodyStyle.width = round(rect.innerW) + 'px';
  15242. lastRepaintRect.innerW = rect.innerW;
  15243. }
  15244. if (self._hasBody && rect.innerH !== lastRepaintRect.innerH) {
  15245. bodyStyle = bodyStyle || self.getEl('body').style;
  15246. bodyStyle.height = round(rect.innerH) + 'px';
  15247. lastRepaintRect.innerH = rect.innerH;
  15248. }
  15249. self._lastRepaintRect = lastRepaintRect;
  15250. self.fire('repaint', {}, false);
  15251. },
  15252. /**
  15253. * Binds a callback to the specified event. This event can both be
  15254. * native browser events like "click" or custom ones like PostRender.
  15255. *
  15256. * The callback function will be passed a DOM event like object that enables yout do stop propagation.
  15257. *
  15258. * @method on
  15259. * @param {String} name Name of the event to bind. For example "click".
  15260. * @param {String/function} callback Callback function to execute ones the event occurs.
  15261. * @return {tinymce.ui.Control} Current control object.
  15262. */
  15263. on: function(name, callback) {
  15264. var self = this, bindings, handlers, names, i;
  15265. function resolveCallbackName(name) {
  15266. var callback, scope;
  15267. return function(e) {
  15268. if (!callback) {
  15269. self.parentsAndSelf().each(function(ctrl) {
  15270. var callbacks = ctrl.settings.callbacks;
  15271. if (callbacks && (callback = callbacks[name])) {
  15272. scope = ctrl;
  15273. return false;
  15274. }
  15275. });
  15276. }
  15277. return callback.call(scope, e);
  15278. };
  15279. }
  15280. if (callback) {
  15281. if (typeof(callback) == 'string') {
  15282. callback = resolveCallbackName(callback);
  15283. }
  15284. names = name.toLowerCase().split(' ');
  15285. i = names.length;
  15286. while (i--) {
  15287. name = names[i];
  15288. bindings = self._bindings;
  15289. if (!bindings) {
  15290. bindings = self._bindings = {};
  15291. }
  15292. handlers = bindings[name];
  15293. if (!handlers) {
  15294. handlers = bindings[name] = [];
  15295. }
  15296. handlers.push(callback);
  15297. if (nativeEvents[name]) {
  15298. if (!self._nativeEvents) {
  15299. self._nativeEvents = {};
  15300. }
  15301. self._nativeEvents[name] = true;
  15302. if (self._rendered) {
  15303. self.bindPendingEvents();
  15304. }
  15305. }
  15306. }
  15307. }
  15308. return self;
  15309. },
  15310. /**
  15311. * Unbinds the specified event and optionally a specific callback. If you omit the name
  15312. * parameter all event handlers will be removed. If you omit the callback all event handles
  15313. * by the specified name will be removed.
  15314. *
  15315. * @method off
  15316. * @param {String} [name] Name for the event to unbind.
  15317. * @param {function} [callback] Callback function to unbind.
  15318. * @return {mxex.ui.Control} Current control object.
  15319. */
  15320. off: function(name, callback) {
  15321. var self = this, i, bindings = self._bindings, handlers, bindingName, names, hi;
  15322. if (bindings) {
  15323. if (name) {
  15324. names = name.toLowerCase().split(' ');
  15325. i = names.length;
  15326. while (i--) {
  15327. name = names[i];
  15328. handlers = bindings[name];
  15329. // Unbind all handlers
  15330. if (!name) {
  15331. for (bindingName in bindings) {
  15332. bindings[bindingName].length = 0;
  15333. }
  15334. return self;
  15335. }
  15336. if (handlers) {
  15337. // Unbind all by name
  15338. if (!callback) {
  15339. handlers.length = 0;
  15340. } else {
  15341. // Unbind specific ones
  15342. hi = handlers.length;
  15343. while (hi--) {
  15344. if (handlers[hi] === callback) {
  15345. handlers.splice(hi, 1);
  15346. }
  15347. }
  15348. }
  15349. }
  15350. }
  15351. } else {
  15352. self._bindings = [];
  15353. }
  15354. }
  15355. return self;
  15356. },
  15357. /**
  15358. * Fires the specified event by name and arguments on the control. This will execute all
  15359. * bound event handlers.
  15360. *
  15361. * @method fire
  15362. * @param {String} name Name of the event to fire.
  15363. * @param {Object} [args] Arguments to pass to the event.
  15364. * @param {Boolean} [bubble] Value to control bubbeling. Defaults to true.
  15365. * @return {Object} Current arguments object.
  15366. */
  15367. fire: function(name, args, bubble) {
  15368. var self = this, i, l, handlers, parentCtrl;
  15369. name = name.toLowerCase();
  15370. // Dummy function that gets replaced on the delegation state functions
  15371. function returnFalse() {
  15372. return false;
  15373. }
  15374. // Dummy function that gets replaced on the delegation state functions
  15375. function returnTrue() {
  15376. return true;
  15377. }
  15378. // Setup empty object if args is omited
  15379. args = args || {};
  15380. // Stick type into event object
  15381. if (!args.type) {
  15382. args.type = name;
  15383. }
  15384. // Stick control into event
  15385. if (!args.control) {
  15386. args.control = self;
  15387. }
  15388. // Add event delegation methods if they are missing
  15389. if (!args.preventDefault) {
  15390. // Add preventDefault method
  15391. args.preventDefault = function() {
  15392. args.isDefaultPrevented = returnTrue;
  15393. };
  15394. // Add stopPropagation
  15395. args.stopPropagation = function() {
  15396. args.isPropagationStopped = returnTrue;
  15397. };
  15398. // Add stopImmediatePropagation
  15399. args.stopImmediatePropagation = function() {
  15400. args.isImmediatePropagationStopped = returnTrue;
  15401. };
  15402. // Add event delegation states
  15403. args.isDefaultPrevented = returnFalse;
  15404. args.isPropagationStopped = returnFalse;
  15405. args.isImmediatePropagationStopped = returnFalse;
  15406. }
  15407. if (self._bindings) {
  15408. handlers = self._bindings[name];
  15409. if (handlers) {
  15410. for (i = 0, l = handlers.length; i < l; i++) {
  15411. // Execute callback and break if the callback returns a false
  15412. if (!args.isImmediatePropagationStopped() && handlers[i].call(self, args) === false) {
  15413. break;
  15414. }
  15415. }
  15416. }
  15417. }
  15418. // Bubble event up to parent controls
  15419. if (bubble !== false) {
  15420. parentCtrl = self.parent();
  15421. while (parentCtrl && !args.isPropagationStopped()) {
  15422. parentCtrl.fire(name, args, false);
  15423. parentCtrl = parentCtrl.parent();
  15424. }
  15425. }
  15426. return args;
  15427. },
  15428. /**
  15429. * Returns true/false if the specified event has any listeners.
  15430. *
  15431. * @method hasEventListeners
  15432. * @param {String} name Name of the event to check for.
  15433. * @return {Boolean} True/false state if the event has listeners.
  15434. */
  15435. hasEventListeners: function(name) {
  15436. return name in this._bindings;
  15437. },
  15438. /**
  15439. * Returns a control collection with all parent controls.
  15440. *
  15441. * @method parents
  15442. * @param {String} selector Optional selector expression to find parents.
  15443. * @return {tinymce.ui.Collection} Collection with all parent controls.
  15444. */
  15445. parents: function(selector) {
  15446. var self = this, ctrl, parents = new Collection();
  15447. // Add each parent to collection
  15448. for (ctrl = self.parent(); ctrl; ctrl = ctrl.parent()) {
  15449. parents.add(ctrl);
  15450. }
  15451. // Filter away everything that doesn't match the selector
  15452. if (selector) {
  15453. parents = parents.filter(selector);
  15454. }
  15455. return parents;
  15456. },
  15457. /**
  15458. * Returns the current control and it's parents.
  15459. *
  15460. * @method parentsAndSelf
  15461. * @param {String} selector Optional selector expression to find parents.
  15462. * @return {tinymce.ui.Collection} Collection with all parent controls.
  15463. */
  15464. parentsAndSelf: function(selector) {
  15465. return new Collection(this).add(this.parents(selector));
  15466. },
  15467. /**
  15468. * Returns the control next to the current control.
  15469. *
  15470. * @method next
  15471. * @return {tinymce.ui.Control} Next control instance.
  15472. */
  15473. next: function() {
  15474. var parentControls = this.parent().items();
  15475. return parentControls[parentControls.indexOf(this) + 1];
  15476. },
  15477. /**
  15478. * Returns the control previous to the current control.
  15479. *
  15480. * @method prev
  15481. * @return {tinymce.ui.Control} Previous control instance.
  15482. */
  15483. prev: function() {
  15484. var parentControls = this.parent().items();
  15485. return parentControls[parentControls.indexOf(this) - 1];
  15486. },
  15487. /**
  15488. * Find the common ancestor for two control instances.
  15489. *
  15490. * @method findCommonAncestor
  15491. * @param {tinymce.ui.Control} ctrl1 First control.
  15492. * @param {tinymce.ui.Control} ctrl2 Second control.
  15493. * @return {tinymce.ui.Control} Ancestor control instance.
  15494. */
  15495. findCommonAncestor: function(ctrl1, ctrl2) {
  15496. var parentCtrl;
  15497. while (ctrl1) {
  15498. parentCtrl = ctrl2;
  15499. while (parentCtrl && ctrl1 != parentCtrl) {
  15500. parentCtrl = parentCtrl.parent();
  15501. }
  15502. if (ctrl1 == parentCtrl) {
  15503. break;
  15504. }
  15505. ctrl1 = ctrl1.parent();
  15506. }
  15507. return ctrl1;
  15508. },
  15509. /**
  15510. * Returns true/false if the specific control has the specific class.
  15511. *
  15512. * @method hasClass
  15513. * @param {String} cls Class to check for.
  15514. * @param {String} [group] Sub element group name.
  15515. * @return {Boolean} True/false if the control has the specified class.
  15516. */
  15517. hasClass: function(cls, group) {
  15518. var classes = this._classes[group || 'control'];
  15519. cls = this.classPrefix + cls;
  15520. return classes && !!classes.map[cls];
  15521. },
  15522. /**
  15523. * Adds the specified class to the control
  15524. *
  15525. * @method addClass
  15526. * @param {String} cls Class to check for.
  15527. * @param {String} [group] Sub element group name.
  15528. * @return {tinymce.ui.Control} Current control object.
  15529. */
  15530. addClass: function(cls, group) {
  15531. var self = this, classes, elm;
  15532. cls = this.classPrefix + cls;
  15533. classes = self._classes[group || 'control'];
  15534. if (!classes) {
  15535. classes = [];
  15536. classes.map = {};
  15537. self._classes[group || 'control'] = classes;
  15538. }
  15539. if (!classes.map[cls]) {
  15540. classes.map[cls] = cls;
  15541. classes.push(cls);
  15542. if (self._rendered) {
  15543. elm = self.getEl(group);
  15544. if (elm) {
  15545. elm.className = classes.join(' ');
  15546. }
  15547. }
  15548. }
  15549. return self;
  15550. },
  15551. /**
  15552. * Removes the specified class from the control.
  15553. *
  15554. * @method removeClass
  15555. * @param {String} cls Class to remove.
  15556. * @param {String} [group] Sub element group name.
  15557. * @return {tinymce.ui.Control} Current control object.
  15558. */
  15559. removeClass: function(cls, group) {
  15560. var self = this, classes, i, elm;
  15561. cls = this.classPrefix + cls;
  15562. classes = self._classes[group || 'control'];
  15563. if (classes && classes.map[cls]) {
  15564. delete classes.map[cls];
  15565. i = classes.length;
  15566. while (i--) {
  15567. if (classes[i] === cls) {
  15568. classes.splice(i, 1);
  15569. }
  15570. }
  15571. }
  15572. if (self._rendered) {
  15573. elm = self.getEl(group);
  15574. if (elm) {
  15575. elm.className = classes.join(' ');
  15576. }
  15577. }
  15578. return self;
  15579. },
  15580. /**
  15581. * Toggles the specified class on the control.
  15582. *
  15583. * @method toggleClass
  15584. * @param {String} cls Class to remove.
  15585. * @param {Boolean} state True/false state to add/remove class.
  15586. * @param {String} [group] Sub element group name.
  15587. * @return {tinymce.ui.Control} Current control object.
  15588. */
  15589. toggleClass: function(cls, state, group) {
  15590. var self = this;
  15591. if (state) {
  15592. self.addClass(cls, group);
  15593. } else {
  15594. self.removeClass(cls, group);
  15595. }
  15596. return self;
  15597. },
  15598. /**
  15599. * Returns the class string for the specified group name.
  15600. *
  15601. * @method classes
  15602. * @param {String} [group] Group to get clases by.
  15603. * @return {String} Classes for the specified group.
  15604. */
  15605. classes: function(group) {
  15606. var classes = this._classes[group || 'control'];
  15607. return classes ? classes.join(' ') : '';
  15608. },
  15609. /**
  15610. * Sets the inner HTML of the control element.
  15611. *
  15612. * @method innerHtml
  15613. * @param {String} html Html string to set as inner html.
  15614. * @return {tinymce.ui.Control} Current control object.
  15615. */
  15616. innerHtml: function(html) {
  15617. DomUtils.innerHtml(this.getEl(), html);
  15618. return this;
  15619. },
  15620. /**
  15621. * Returns the control DOM element or sub element.
  15622. *
  15623. * @method getEl
  15624. * @param {String} [suffix] Suffix to get element by.
  15625. * @param {Boolean} [dropCache] True if the cache for the element should be dropped.
  15626. * @return {Element} HTML DOM element for the current control or it's children.
  15627. */
  15628. getEl: function(suffix, dropCache) {
  15629. var elm, id = suffix ? this._id + '-' + suffix : this._id;
  15630. elm = elementIdCache[id] = (dropCache === true ? null : elementIdCache[id]) || DomUtils.get(id);
  15631. return elm;
  15632. },
  15633. /**
  15634. * Sets/gets the visible for the control.
  15635. *
  15636. * @method visible
  15637. * @param {Boolean} state Value to set to control.
  15638. * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get.
  15639. */
  15640. visible: function(state) {
  15641. var self = this, parentCtrl;
  15642. if (typeof(state) !== "undefined") {
  15643. if (self._visible !== state) {
  15644. if (self._rendered) {
  15645. self.getEl().style.display = state ? '' : 'none';
  15646. }
  15647. self._visible = state;
  15648. // Parent container needs to reflow
  15649. parentCtrl = self.parent();
  15650. if (parentCtrl) {
  15651. parentCtrl._lastRect = null;
  15652. }
  15653. self.fire(state ? 'show' : 'hide');
  15654. }
  15655. return self;
  15656. }
  15657. return self._visible;
  15658. },
  15659. /**
  15660. * Sets the visible state to true.
  15661. *
  15662. * @method show
  15663. * @return {tinymce.ui.Control} Current control instance.
  15664. */
  15665. show: function() {
  15666. return this.visible(true);
  15667. },
  15668. /**
  15669. * Sets the visible state to false.
  15670. *
  15671. * @method hide
  15672. * @return {tinymce.ui.Control} Current control instance.
  15673. */
  15674. hide: function() {
  15675. return this.visible(false);
  15676. },
  15677. /**
  15678. * Focuses the current control.
  15679. *
  15680. * @method focus
  15681. * @return {tinymce.ui.Control} Current control instance.
  15682. */
  15683. focus: function() {
  15684. try {
  15685. this.getEl().focus();
  15686. } catch (ex) {
  15687. // Ignore IE error
  15688. }
  15689. return this;
  15690. },
  15691. /**
  15692. * Blurs the current control.
  15693. *
  15694. * @method blur
  15695. * @return {tinymce.ui.Control} Current control instance.
  15696. */
  15697. blur: function() {
  15698. this.getEl().blur();
  15699. return this;
  15700. },
  15701. /**
  15702. * Sets the specified aria property.
  15703. *
  15704. * @method aria
  15705. * @param {String} name Name of the aria property to set.
  15706. * @param {String} value Value of the aria property.
  15707. * @return {tinymce.ui.Control} Current control instance.
  15708. */
  15709. aria: function(name, value) {
  15710. var self = this, elm = self.getEl(self.ariaTarget);
  15711. if (typeof(value) === "undefined") {
  15712. return self._aria[name];
  15713. } else {
  15714. self._aria[name] = value;
  15715. }
  15716. if (self._rendered) {
  15717. elm.setAttribute(name == 'role' ? name : 'aria-' + name, value);
  15718. }
  15719. return self;
  15720. },
  15721. /**
  15722. * Encodes the specified string with HTML entities. It will also
  15723. * translate the string to different languages.
  15724. *
  15725. * @method encode
  15726. * @param {String/Object/Array} text Text to entity encode.
  15727. * @param {Boolean} [translate=true] False if the contents shouldn't be translated.
  15728. * @return {String} Encoded and possible traslated string.
  15729. */
  15730. encode: function(text, translate) {
  15731. if (translate !== false) {
  15732. text = this.translate(text);
  15733. }
  15734. return (text || '').replace(/[&<>"]/g, function(match) {
  15735. return '&#' + match.charCodeAt(0) + ';';
  15736. });
  15737. },
  15738. /**
  15739. * Returns the translated string.
  15740. *
  15741. * @method translate
  15742. * @param {String} text Text to translate.
  15743. * @return {String} Translated string or the same as the input.
  15744. */
  15745. translate: function(text) {
  15746. return Control.translate ? Control.translate(text) : text;
  15747. },
  15748. /**
  15749. * Adds items before the current control.
  15750. *
  15751. * @method before
  15752. * @param {Array/tinymce.ui.Collection} items Array of items to prepend before this control.
  15753. * @return {tinymce.ui.Control} Current control instance.
  15754. */
  15755. before: function(items) {
  15756. var self = this, parent = self.parent();
  15757. if (parent) {
  15758. parent.insert(items, parent.items().indexOf(self), true);
  15759. }
  15760. return self;
  15761. },
  15762. /**
  15763. * Adds items after the current control.
  15764. *
  15765. * @method after
  15766. * @param {Array/tinymce.ui.Collection} items Array of items to append after this control.
  15767. * @return {tinymce.ui.Control} Current control instance.
  15768. */
  15769. after: function(items) {
  15770. var self = this, parent = self.parent();
  15771. if (parent) {
  15772. parent.insert(items, parent.items().indexOf(self));
  15773. }
  15774. return self;
  15775. },
  15776. /**
  15777. * Removes the current control from DOM and from UI collections.
  15778. *
  15779. * @method remove
  15780. * @return {tinymce.ui.Control} Current control instance.
  15781. */
  15782. remove: function() {
  15783. var self = this, elm = self.getEl(), parent = self.parent(), newItems, i;
  15784. if (self.items) {
  15785. var controls = self.items().toArray();
  15786. i = controls.length;
  15787. while (i--) {
  15788. controls[i].remove();
  15789. }
  15790. }
  15791. if (parent && parent.items) {
  15792. newItems = [];
  15793. parent.items().each(function(item) {
  15794. if (item !== self) {
  15795. newItems.push(item);
  15796. }
  15797. });
  15798. parent.items().set(newItems);
  15799. parent._lastRect = null;
  15800. }
  15801. if (self._eventsRoot && self._eventsRoot == self) {
  15802. DomUtils.off(elm);
  15803. }
  15804. var lookup = self.getRoot().controlIdLookup;
  15805. if (lookup) {
  15806. delete lookup[self._id];
  15807. }
  15808. delete elementIdCache[self._id];
  15809. if (elm && elm.parentNode) {
  15810. var nodes = elm.getElementsByTagName('*');
  15811. i = nodes.length;
  15812. while (i--) {
  15813. delete elementIdCache[nodes[i].id];
  15814. }
  15815. elm.parentNode.removeChild(elm);
  15816. }
  15817. self._rendered = false;
  15818. return self;
  15819. },
  15820. /**
  15821. * Renders the control before the specified element.
  15822. *
  15823. * @method renderBefore
  15824. * @param {Element} elm Element to render before.
  15825. * @return {tinymce.ui.Control} Current control instance.
  15826. */
  15827. renderBefore: function(elm) {
  15828. var self = this;
  15829. elm.parentNode.insertBefore(DomUtils.createFragment(self.renderHtml()), elm);
  15830. self.postRender();
  15831. return self;
  15832. },
  15833. /**
  15834. * Renders the control to the specified element.
  15835. *
  15836. * @method renderBefore
  15837. * @param {Element} elm Element to render to.
  15838. * @return {tinymce.ui.Control} Current control instance.
  15839. */
  15840. renderTo: function(elm) {
  15841. var self = this;
  15842. elm = elm || self.getContainerElm();
  15843. elm.appendChild(DomUtils.createFragment(self.renderHtml()));
  15844. self.postRender();
  15845. return self;
  15846. },
  15847. /**
  15848. * Post render method. Called after the control has been rendered to the target.
  15849. *
  15850. * @method postRender
  15851. * @return {tinymce.ui.Control} Current control instance.
  15852. */
  15853. postRender: function() {
  15854. var self = this, settings = self.settings, elm, box, parent, name, parentEventsRoot;
  15855. // Bind on<event> settings
  15856. for (name in settings) {
  15857. if (name.indexOf("on") === 0) {
  15858. self.on(name.substr(2), settings[name]);
  15859. }
  15860. }
  15861. if (self._eventsRoot) {
  15862. for (parent = self.parent(); !parentEventsRoot && parent; parent = parent.parent()) {
  15863. parentEventsRoot = parent._eventsRoot;
  15864. }
  15865. if (parentEventsRoot) {
  15866. for (name in parentEventsRoot._nativeEvents) {
  15867. self._nativeEvents[name] = true;
  15868. }
  15869. }
  15870. }
  15871. self.bindPendingEvents();
  15872. if (settings.style) {
  15873. elm = self.getEl();
  15874. if (elm) {
  15875. elm.setAttribute('style', settings.style);
  15876. elm.style.cssText = settings.style;
  15877. }
  15878. }
  15879. if (!self._visible) {
  15880. DomUtils.css(self.getEl(), 'display', 'none');
  15881. }
  15882. if (self.settings.border) {
  15883. box = self.borderBox();
  15884. DomUtils.css(self.getEl(), {
  15885. 'border-top-width': box.top,
  15886. 'border-right-width': box.right,
  15887. 'border-bottom-width': box.bottom,
  15888. 'border-left-width': box.left
  15889. });
  15890. }
  15891. // Add instance to lookup
  15892. var root = self.getRoot();
  15893. if (!root.controlIdLookup) {
  15894. root.controlIdLookup = {};
  15895. }
  15896. root.controlIdLookup[self._id] = self;
  15897. for (var key in self._aria) {
  15898. self.aria(key, self._aria[key]);
  15899. }
  15900. self.fire('postrender', {}, false);
  15901. },
  15902. /**
  15903. * Scrolls the current control into view.
  15904. *
  15905. * @method scrollIntoView
  15906. * @param {String} align Alignment in view top|center|bottom.
  15907. * @return {tinymce.ui.Control} Current control instance.
  15908. */
  15909. scrollIntoView: function(align) {
  15910. function getOffset(elm, rootElm) {
  15911. var x, y, parent = elm;
  15912. x = y = 0;
  15913. while (parent && parent != rootElm && parent.nodeType) {
  15914. x += parent.offsetLeft || 0;
  15915. y += parent.offsetTop || 0;
  15916. parent = parent.offsetParent;
  15917. }
  15918. return {x: x, y: y};
  15919. }
  15920. var elm = this.getEl(), parentElm = elm.parentNode;
  15921. var x, y, width, height, parentWidth, parentHeight;
  15922. var pos = getOffset(elm, parentElm);
  15923. x = pos.x;
  15924. y = pos.y;
  15925. width = elm.offsetWidth;
  15926. height = elm.offsetHeight;
  15927. parentWidth = parentElm.clientWidth;
  15928. parentHeight = parentElm.clientHeight;
  15929. if (align == "end") {
  15930. x -= parentWidth - width;
  15931. y -= parentHeight - height;
  15932. } else if (align == "center") {
  15933. x -= (parentWidth / 2) - (width / 2);
  15934. y -= (parentHeight / 2) - (height / 2);
  15935. }
  15936. parentElm.scrollLeft = x;
  15937. parentElm.scrollTop = y;
  15938. return this;
  15939. },
  15940. /**
  15941. * Binds pending DOM events.
  15942. *
  15943. * @private
  15944. */
  15945. bindPendingEvents: function() {
  15946. var self = this, i, l, parents, eventRootCtrl, nativeEvents, name;
  15947. function delegate(e) {
  15948. var control = self.getParentCtrl(e.target);
  15949. if (control) {
  15950. control.fire(e.type, e);
  15951. }
  15952. }
  15953. function mouseLeaveHandler() {
  15954. var ctrl = eventRootCtrl._lastHoverCtrl;
  15955. if (ctrl) {
  15956. ctrl.fire("mouseleave", {target: ctrl.getEl()});
  15957. ctrl.parents().each(function(ctrl) {
  15958. ctrl.fire("mouseleave", {target: ctrl.getEl()});
  15959. });
  15960. eventRootCtrl._lastHoverCtrl = null;
  15961. }
  15962. }
  15963. function mouseEnterHandler(e) {
  15964. var ctrl = self.getParentCtrl(e.target), lastCtrl = eventRootCtrl._lastHoverCtrl, idx = 0, i, parents, lastParents;
  15965. // Over on a new control
  15966. if (ctrl !== lastCtrl) {
  15967. eventRootCtrl._lastHoverCtrl = ctrl;
  15968. parents = ctrl.parents().toArray().reverse();
  15969. parents.push(ctrl);
  15970. if (lastCtrl) {
  15971. lastParents = lastCtrl.parents().toArray().reverse();
  15972. lastParents.push(lastCtrl);
  15973. for (idx = 0; idx < lastParents.length; idx++) {
  15974. if (parents[idx] !== lastParents[idx]) {
  15975. break;
  15976. }
  15977. }
  15978. for (i = lastParents.length - 1; i >= idx; i--) {
  15979. lastCtrl = lastParents[i];
  15980. lastCtrl.fire("mouseleave", {
  15981. target : lastCtrl.getEl()
  15982. });
  15983. }
  15984. }
  15985. for (i = idx; i < parents.length; i++) {
  15986. ctrl = parents[i];
  15987. ctrl.fire("mouseenter", {
  15988. target : ctrl.getEl()
  15989. });
  15990. }
  15991. }
  15992. }
  15993. function fixWheelEvent(e) {
  15994. e.preventDefault();
  15995. if (e.type == "mousewheel") {
  15996. e.deltaY = -1 / 40 * e.wheelDelta;
  15997. if (e.wheelDeltaX) {
  15998. e.deltaX = -1 / 40 * e.wheelDeltaX;
  15999. }
  16000. } else {
  16001. e.deltaX = 0;
  16002. e.deltaY = e.detail;
  16003. }
  16004. e = self.fire("wheel", e);
  16005. }
  16006. self._rendered = true;
  16007. nativeEvents = self._nativeEvents;
  16008. if (nativeEvents) {
  16009. // Find event root element if it exists
  16010. parents = self.parents().toArray();
  16011. parents.unshift(self);
  16012. for (i = 0, l = parents.length; !eventRootCtrl && i < l; i++) {
  16013. eventRootCtrl = parents[i]._eventsRoot;
  16014. }
  16015. // Event root wasn't found the use the root control
  16016. if (!eventRootCtrl) {
  16017. eventRootCtrl = parents[parents.length - 1] || self;
  16018. }
  16019. // Set the eventsRoot property on children that didn't have it
  16020. self._eventsRoot = eventRootCtrl;
  16021. for (l = i, i = 0; i < l; i++) {
  16022. parents[i]._eventsRoot = eventRootCtrl;
  16023. }
  16024. var eventRootDelegates = eventRootCtrl._delegates;
  16025. if (!eventRootDelegates) {
  16026. eventRootDelegates = eventRootCtrl._delegates = {};
  16027. }
  16028. // Bind native event delegates
  16029. for (name in nativeEvents) {
  16030. if (!nativeEvents) {
  16031. return false;
  16032. }
  16033. if (name === "wheel" && !hasWheelEventSupport) {
  16034. if (hasMouseWheelEventSupport) {
  16035. DomUtils.on(self.getEl(), "mousewheel", fixWheelEvent);
  16036. } else {
  16037. DomUtils.on(self.getEl(), "DOMMouseScroll", fixWheelEvent);
  16038. }
  16039. continue;
  16040. }
  16041. // Special treatment for mousenter/mouseleave since these doesn't bubble
  16042. if (name === "mouseenter" || name === "mouseleave") {
  16043. // Fake mousenter/mouseleave
  16044. if (!eventRootCtrl._hasMouseEnter) {
  16045. DomUtils.on(eventRootCtrl.getEl(), "mouseleave", mouseLeaveHandler);
  16046. DomUtils.on(eventRootCtrl.getEl(), "mouseover", mouseEnterHandler);
  16047. eventRootCtrl._hasMouseEnter = 1;
  16048. }
  16049. } else if (!eventRootDelegates[name]) {
  16050. DomUtils.on(eventRootCtrl.getEl(), name, delegate);
  16051. eventRootDelegates[name] = true;
  16052. }
  16053. // Remove the event once it's bound
  16054. nativeEvents[name] = false;
  16055. }
  16056. }
  16057. },
  16058. getRoot: function() {
  16059. var ctrl = this, rootControl, parents = [];
  16060. while (ctrl) {
  16061. if (ctrl.rootControl) {
  16062. rootControl = ctrl.rootControl;
  16063. break;
  16064. }
  16065. parents.push(ctrl);
  16066. rootControl = ctrl;
  16067. ctrl = ctrl.parent();
  16068. }
  16069. if (!rootControl) {
  16070. rootControl = this;
  16071. }
  16072. var i = parents.length;
  16073. while (i--) {
  16074. parents[i].rootControl = rootControl;
  16075. }
  16076. return rootControl;
  16077. },
  16078. /**
  16079. * Reflows the current control and it's parents.
  16080. * This should be used after you for example append children to the current control so
  16081. * that the layout managers know that they need to reposition everything.
  16082. *
  16083. * @example
  16084. * container.append({type: 'button', text: 'My button'}).reflow();
  16085. *
  16086. * @method reflow
  16087. * @return {tinymce.ui.Control} Current control instance.
  16088. */
  16089. reflow: function() {
  16090. this.repaint();
  16091. return this;
  16092. }
  16093. /**
  16094. * Sets/gets the parent container for the control.
  16095. *
  16096. * @method parent
  16097. * @param {tinymce.ui.Container} parent Optional parent to set.
  16098. * @return {tinymce.ui.Control} Parent control or the current control on a set action.
  16099. */
  16100. // parent: function(parent) {} -- Generated
  16101. /**
  16102. * Sets/gets the text for the control.
  16103. *
  16104. * @method text
  16105. * @param {String} value Value to set to control.
  16106. * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get.
  16107. */
  16108. // text: function(value) {} -- Generated
  16109. /**
  16110. * Sets/gets the width for the control.
  16111. *
  16112. * @method width
  16113. * @param {Number} value Value to set to control.
  16114. * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get.
  16115. */
  16116. // width: function(value) {} -- Generated
  16117. /**
  16118. * Sets/gets the height for the control.
  16119. *
  16120. * @method height
  16121. * @param {Number} value Value to set to control.
  16122. * @return {Number/tinymce.ui.Control} Current control on a set operation or current value on a get.
  16123. */
  16124. // height: function(value) {} -- Generated
  16125. /**
  16126. * Sets/gets the disabled state on the control.
  16127. *
  16128. * @method disabled
  16129. * @param {Boolean} state Value to set to control.
  16130. * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get.
  16131. */
  16132. // disabled: function(state) {} -- Generated
  16133. /**
  16134. * Sets/gets the active for the control.
  16135. *
  16136. * @method active
  16137. * @param {Boolean} state Value to set to control.
  16138. * @return {Boolean/tinymce.ui.Control} Current control on a set operation or current state on a get.
  16139. */
  16140. // active: function(state) {} -- Generated
  16141. /**
  16142. * Sets/gets the name for the control.
  16143. *
  16144. * @method name
  16145. * @param {String} value Value to set to control.
  16146. * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get.
  16147. */
  16148. // name: function(value) {} -- Generated
  16149. /**
  16150. * Sets/gets the title for the control.
  16151. *
  16152. * @method title
  16153. * @param {String} value Value to set to control.
  16154. * @return {String/tinymce.ui.Control} Current control on a set operation or current value on a get.
  16155. */
  16156. // title: function(value) {} -- Generated
  16157. });
  16158. return Control;
  16159. });
  16160. // Included from: js/tinymce/classes/ui/Factory.js
  16161. /**
  16162. * Factory.js
  16163. *
  16164. * Copyright, Moxiecode Systems AB
  16165. * Released under LGPL License.
  16166. *
  16167. * License: http://www.tinymce.com/license
  16168. * Contributing: http://www.tinymce.com/contributing
  16169. */
  16170. /*global tinymce:true */
  16171. /**
  16172. * This class is a factory for control instances. This enables you
  16173. * to create instances of controls without having to require the UI controls directly.
  16174. *
  16175. * It also allow you to override or add new control types.
  16176. *
  16177. * @class tinymce.ui.Factory
  16178. */
  16179. define("tinymce/ui/Factory", [], function() {
  16180. "use strict";
  16181. var types = {}, namespaceInit;
  16182. return {
  16183. /**
  16184. * Adds a new control instance type to the factory.
  16185. *
  16186. * @method add
  16187. * @param {String} type Type name for example "button".
  16188. * @param {function} typeClass Class type function.
  16189. */
  16190. add: function(type, typeClass) {
  16191. types[type.toLowerCase()] = typeClass;
  16192. },
  16193. /**
  16194. * Returns true/false if the specified type exists or not.
  16195. *
  16196. * @method has
  16197. * @param {String} type Type to look for.
  16198. * @return {Boolean} true/false if the control by name exists.
  16199. */
  16200. has: function(type) {
  16201. return !!types[type.toLowerCase()];
  16202. },
  16203. /**
  16204. * Creates a new control instance based on the settings provided. The instance created will be
  16205. * based on the specified type property it can also create whole structures of components out of
  16206. * the specified JSON object.
  16207. *
  16208. * @example
  16209. * tinymce.ui.Factory.create({
  16210. * type: 'button',
  16211. * text: 'Hello world!'
  16212. * });
  16213. *
  16214. * @method create
  16215. * @param {Object/String} settings Name/Value object with items used to create the type.
  16216. * @return {tinymce.ui.Control} Control instance based on the specified type.
  16217. */
  16218. create: function(type, settings) {
  16219. var ControlType, name, namespace;
  16220. // Build type lookup
  16221. if (!namespaceInit) {
  16222. namespace = tinymce.ui;
  16223. for (name in namespace) {
  16224. types[name.toLowerCase()] = namespace[name];
  16225. }
  16226. namespaceInit = true;
  16227. }
  16228. // If string is specified then use it as the type
  16229. if (typeof(type) == 'string') {
  16230. settings = settings || {};
  16231. settings.type = type;
  16232. } else {
  16233. settings = type;
  16234. type = settings.type;
  16235. }
  16236. // Find control type
  16237. type = type.toLowerCase();
  16238. ControlType = types[type];
  16239. // #if debug
  16240. if (!ControlType) {
  16241. throw new Error("Could not find control by type: " + type);
  16242. }
  16243. // #endif
  16244. ControlType = new ControlType(settings);
  16245. ControlType.type = type; // Set the type on the instance, this will be used by the Selector engine
  16246. return ControlType;
  16247. }
  16248. };
  16249. });
  16250. // Included from: js/tinymce/classes/ui/KeyboardNavigation.js
  16251. /**
  16252. * KeyboardNavigation.js
  16253. *
  16254. * Copyright, Moxiecode Systems AB
  16255. * Released under LGPL License.
  16256. *
  16257. * License: http://www.tinymce.com/license
  16258. * Contributing: http://www.tinymce.com/contributing
  16259. */
  16260. /**
  16261. * This class handles keyboard navigation of controls and elements.
  16262. *
  16263. * @class tinymce.ui.KeyboardNavigation
  16264. */
  16265. define("tinymce/ui/KeyboardNavigation", [
  16266. ], function() {
  16267. "use strict";
  16268. /**
  16269. * This class handles all keyboard navigation for WAI-ARIA support. Each root container
  16270. * gets an instance of this class.
  16271. *
  16272. * @constructor
  16273. */
  16274. return function(settings) {
  16275. var root = settings.root, focusedElement, focusedControl;
  16276. focusedElement = document.activeElement;
  16277. focusedControl = root.getParentCtrl(focusedElement);
  16278. /**
  16279. * Returns the currently focused elements wai aria role of the currently
  16280. * focused element or specified element.
  16281. *
  16282. * @private
  16283. * @param {Element} elm Optional element to get role from.
  16284. * @return {String} Role of specified element.
  16285. */
  16286. function getRole(elm) {
  16287. elm = elm || focusedElement;
  16288. return elm && elm.getAttribute('role');
  16289. }
  16290. /**
  16291. * Returns the wai role of the parent element of the currently
  16292. * focused element or specified element.
  16293. *
  16294. * @private
  16295. * @param {Element} elm Optional element to get parent role from.
  16296. * @return {String} Role of the first parent that has a role.
  16297. */
  16298. function getParentRole(elm) {
  16299. var role, parent = elm || focusedElement;
  16300. while ((parent = parent.parentNode)) {
  16301. if ((role = getRole(parent))) {
  16302. return role;
  16303. }
  16304. }
  16305. }
  16306. /**
  16307. * Returns a wai aria property by name for example aria-selected.
  16308. *
  16309. * @private
  16310. * @param {String} name Name of the aria property to get for example "disabled".
  16311. * @return {String} Aria property value.
  16312. */
  16313. function getAriaProp(name) {
  16314. var elm = focusedElement;
  16315. if (elm) {
  16316. return elm.getAttribute('aria-' + name);
  16317. }
  16318. }
  16319. /**
  16320. * Is the element a text input element or not.
  16321. *
  16322. * @private
  16323. * @param {Element} elm Element to check if it's an text input element or not.
  16324. * @return {Boolean} True/false if the element is a text element or not.
  16325. */
  16326. function isTextInputElement(elm) {
  16327. var tagName = elm.tagName.toUpperCase();
  16328. // Notice: since type can be "email" etc we don't check the type
  16329. // So all input elements gets treated as text input elements
  16330. return tagName == "INPUT" || tagName == "TEXTAREA";
  16331. }
  16332. /**
  16333. * Returns true/false if the specified element can be focused or not.
  16334. *
  16335. * @private
  16336. * @param {Element} elm DOM element to check if it can be focused or not.
  16337. * @return {Boolean} True/false if the element can have focus.
  16338. */
  16339. function canFocus(elm) {
  16340. if (isTextInputElement(elm) && !elm.hidden) {
  16341. return true;
  16342. }
  16343. if (/^(button|menuitem|checkbox|tab|menuitemcheckbox|option|gridcell)$/.test(getRole(elm))) {
  16344. return true;
  16345. }
  16346. return false;
  16347. }
  16348. /**
  16349. * Returns an array of focusable visible elements within the specified container element.
  16350. *
  16351. * @private
  16352. * @param {Element} elm DOM element to find focusable elements within.
  16353. * @return {Array} Array of focusable elements.
  16354. */
  16355. function getFocusElements(elm) {
  16356. var elements = [];
  16357. function collect(elm) {
  16358. if (elm.nodeType != 1 || elm.style.display == 'none') {
  16359. return;
  16360. }
  16361. if (canFocus(elm)) {
  16362. elements.push(elm);
  16363. }
  16364. for (var i = 0; i < elm.childNodes.length; i++) {
  16365. collect(elm.childNodes[i]);
  16366. }
  16367. }
  16368. collect(elm || root.getEl());
  16369. return elements;
  16370. }
  16371. /**
  16372. * Returns the navigation root control for the specified control. The navigation root
  16373. * is the control that the keyboard navigation gets scoped to for example a menubar or toolbar group.
  16374. * It will look for parents of the specified target control or the currenty focused control if this option is omitted.
  16375. *
  16376. * @private
  16377. * @param {tinymce.ui.Control} targetControl Optional target control to find root of.
  16378. * @return {tinymce.ui.Control} Navigation root control.
  16379. */
  16380. function getNavigationRoot(targetControl) {
  16381. var navigationRoot, controls;
  16382. targetControl = targetControl || focusedControl;
  16383. controls = targetControl.parents().toArray();
  16384. controls.unshift(targetControl);
  16385. for (var i = 0; i < controls.length; i++) {
  16386. navigationRoot = controls[i];
  16387. if (navigationRoot.settings.ariaRoot) {
  16388. break;
  16389. }
  16390. }
  16391. return navigationRoot;
  16392. }
  16393. /**
  16394. * Focuses the first item in the specified targetControl element or the last aria index if the
  16395. * navigation root has the ariaRemember option enabled.
  16396. *
  16397. * @private
  16398. * @param {tinymce.ui.Control} targetControl Target control to focus the first item in.
  16399. */
  16400. function focusFirst(targetControl) {
  16401. var navigationRoot = getNavigationRoot(targetControl);
  16402. var focusElements = getFocusElements(navigationRoot.getEl());
  16403. if (navigationRoot.settings.ariaRemember && "lastAriaIndex" in navigationRoot) {
  16404. moveFocusToIndex(navigationRoot.lastAriaIndex, focusElements);
  16405. } else {
  16406. moveFocusToIndex(0, focusElements);
  16407. }
  16408. }
  16409. /**
  16410. * Moves the focus to the specified index within the elements list.
  16411. * This will scope the index to the size of the element list if it changed.
  16412. *
  16413. * @private
  16414. * @param {Number} idx Specified index to move to.
  16415. * @param {Array} elements Array with dom elements to move focus within.
  16416. * @return {Number} Input index or a changed index if it was out of range.
  16417. */
  16418. function moveFocusToIndex(idx, elements) {
  16419. if (idx < 0) {
  16420. idx = elements.length - 1;
  16421. } else if (idx >= elements.length) {
  16422. idx = 0;
  16423. }
  16424. if (elements[idx]) {
  16425. elements[idx].focus();
  16426. }
  16427. return idx;
  16428. }
  16429. /**
  16430. * Moves the focus forwards or backwards.
  16431. *
  16432. * @private
  16433. * @param {Number} dir Direction to move in positive means forward, negative means backwards.
  16434. * @param {Array} elements Optional array of elements to move within defaults to the current navigation roots elements.
  16435. */
  16436. function moveFocus(dir, elements) {
  16437. var idx = -1, navigationRoot = getNavigationRoot();
  16438. elements = elements || getFocusElements(navigationRoot.getEl());
  16439. for (var i = 0; i < elements.length; i++) {
  16440. if (elements[i] === focusedElement) {
  16441. idx = i;
  16442. }
  16443. }
  16444. idx += dir;
  16445. navigationRoot.lastAriaIndex = moveFocusToIndex(idx, elements);
  16446. }
  16447. /**
  16448. * Moves the focus to the left this is called by the left key.
  16449. *
  16450. * @private
  16451. */
  16452. function left() {
  16453. var parentRole = getParentRole();
  16454. if (parentRole == "tablist") {
  16455. moveFocus(-1, getFocusElements(focusedElement.parentNode));
  16456. } else if (focusedControl.parent().submenu) {
  16457. cancel();
  16458. } else {
  16459. moveFocus(-1);
  16460. }
  16461. }
  16462. /**
  16463. * Moves the focus to the right this is called by the right key.
  16464. *
  16465. * @private
  16466. */
  16467. function right() {
  16468. var role = getRole(), parentRole = getParentRole();
  16469. if (parentRole == "tablist") {
  16470. moveFocus(1, getFocusElements(focusedElement.parentNode));
  16471. } else if (role == "menuitem" && parentRole == "menu" && getAriaProp('haspopup')) {
  16472. enter();
  16473. } else {
  16474. moveFocus(1);
  16475. }
  16476. }
  16477. /**
  16478. * Moves the focus to the up this is called by the up key.
  16479. *
  16480. * @private
  16481. */
  16482. function up() {
  16483. moveFocus(-1);
  16484. }
  16485. /**
  16486. * Moves the focus to the up this is called by the down key.
  16487. *
  16488. * @private
  16489. */
  16490. function down() {
  16491. var role = getRole(), parentRole = getParentRole();
  16492. if (role == "menuitem" && parentRole == "menubar") {
  16493. enter();
  16494. } else if (role == "button" && getAriaProp('haspopup')) {
  16495. enter({key: 'down'});
  16496. } else {
  16497. moveFocus(1);
  16498. }
  16499. }
  16500. /**
  16501. * Moves the focus to the next item or previous item depending on shift key.
  16502. *
  16503. * @private
  16504. * @param {DOMEvent} e DOM event object.
  16505. */
  16506. function tab(e) {
  16507. var parentRole = getParentRole();
  16508. if (parentRole == "tablist") {
  16509. var elm = getFocusElements(focusedControl.getEl('body'))[0];
  16510. if (elm) {
  16511. elm.focus();
  16512. }
  16513. } else {
  16514. moveFocus(e.shiftKey ? -1 : 1);
  16515. }
  16516. }
  16517. /**
  16518. * Calls the cancel event on the currently focused control. This is normally done using the Esc key.
  16519. *
  16520. * @private
  16521. */
  16522. function cancel() {
  16523. focusedControl.fire('cancel');
  16524. }
  16525. /**
  16526. * Calls the click event on the currently focused control. This is normally done using the Enter/Space keys.
  16527. *
  16528. * @private
  16529. * @param {Object} aria Optional aria data to pass along with the enter event.
  16530. */
  16531. function enter(aria) {
  16532. aria = aria || {};
  16533. focusedControl.fire('click', {target: focusedElement, aria: aria});
  16534. }
  16535. root.on('keydown', function(e) {
  16536. function handleNonTabOrEscEvent(e, handler) {
  16537. // Ignore non tab keys for text elements
  16538. if (isTextInputElement(focusedElement)) {
  16539. return;
  16540. }
  16541. if (handler(e) !== false) {
  16542. e.preventDefault();
  16543. }
  16544. }
  16545. if (e.isDefaultPrevented()) {
  16546. return;
  16547. }
  16548. switch (e.keyCode) {
  16549. case 37: // DOM_VK_LEFT
  16550. handleNonTabOrEscEvent(e, left);
  16551. break;
  16552. case 39: // DOM_VK_RIGHT
  16553. handleNonTabOrEscEvent(e, right);
  16554. break;
  16555. case 38: // DOM_VK_UP
  16556. handleNonTabOrEscEvent(e, up);
  16557. break;
  16558. case 40: // DOM_VK_DOWN
  16559. handleNonTabOrEscEvent(e, down);
  16560. break;
  16561. case 27: // DOM_VK_ESCAPE
  16562. cancel();
  16563. break;
  16564. case 14: // DOM_VK_ENTER
  16565. case 13: // DOM_VK_RETURN
  16566. case 32: // DOM_VK_SPACE
  16567. handleNonTabOrEscEvent(e, enter);
  16568. break;
  16569. case 9: // DOM_VK_TAB
  16570. if (tab(e) !== false) {
  16571. e.preventDefault();
  16572. }
  16573. break;
  16574. }
  16575. });
  16576. root.on('focusin', function(e) {
  16577. focusedElement = e.target;
  16578. focusedControl = e.control;
  16579. });
  16580. return {
  16581. focusFirst: focusFirst
  16582. };
  16583. };
  16584. });
  16585. // Included from: js/tinymce/classes/ui/Container.js
  16586. /**
  16587. * Container.js
  16588. *
  16589. * Copyright, Moxiecode Systems AB
  16590. * Released under LGPL License.
  16591. *
  16592. * License: http://www.tinymce.com/license
  16593. * Contributing: http://www.tinymce.com/contributing
  16594. */
  16595. /**
  16596. * Container control. This is extended by all controls that can have
  16597. * children such as panels etc. You can also use this class directly as an
  16598. * generic container instance. The container doesn't have any specific role or style.
  16599. *
  16600. * @-x-less Container.less
  16601. * @class tinymce.ui.Container
  16602. * @extends tinymce.ui.Control
  16603. */
  16604. define("tinymce/ui/Container", [
  16605. "tinymce/ui/Control",
  16606. "tinymce/ui/Collection",
  16607. "tinymce/ui/Selector",
  16608. "tinymce/ui/Factory",
  16609. "tinymce/ui/KeyboardNavigation",
  16610. "tinymce/util/Tools",
  16611. "tinymce/ui/DomUtils"
  16612. ], function(Control, Collection, Selector, Factory, KeyboardNavigation, Tools, DomUtils) {
  16613. "use strict";
  16614. var selectorCache = {};
  16615. return Control.extend({
  16616. layout: '',
  16617. innerClass: 'container-inner',
  16618. /**
  16619. * Constructs a new control instance with the specified settings.
  16620. *
  16621. * @constructor
  16622. * @param {Object} settings Name/value object with settings.
  16623. * @setting {Array} items Items to add to container in JSON format or control instances.
  16624. * @setting {String} layout Layout manager by name to use.
  16625. * @setting {Object} defaults Default settings to apply to all items.
  16626. */
  16627. init: function(settings) {
  16628. var self = this;
  16629. self._super(settings);
  16630. settings = self.settings;
  16631. self._fixed = settings.fixed;
  16632. self._items = new Collection();
  16633. if (self.isRtl()) {
  16634. self.addClass('rtl');
  16635. }
  16636. self.addClass('container');
  16637. self.addClass('container-body', 'body');
  16638. if (settings.containerCls) {
  16639. self.addClass(settings.containerCls);
  16640. }
  16641. self._layout = Factory.create((settings.layout || self.layout) + 'layout');
  16642. if (self.settings.items) {
  16643. self.add(self.settings.items);
  16644. }
  16645. // TODO: Fix this!
  16646. self._hasBody = true;
  16647. },
  16648. /**
  16649. * Returns a collection of child items that the container currently have.
  16650. *
  16651. * @method items
  16652. * @return {tinymce.ui.Collection} Control collection direct child controls.
  16653. */
  16654. items: function() {
  16655. return this._items;
  16656. },
  16657. /**
  16658. * Find child controls by selector.
  16659. *
  16660. * @method find
  16661. * @param {String} selector Selector CSS pattern to find children by.
  16662. * @return {tinymce.ui.Collection} Control collection with child controls.
  16663. */
  16664. find: function(selector) {
  16665. selector = selectorCache[selector] = selectorCache[selector] || new Selector(selector);
  16666. return selector.find(this);
  16667. },
  16668. /**
  16669. * Adds one or many items to the current container. This will create instances of
  16670. * the object representations if needed.
  16671. *
  16672. * @method add
  16673. * @param {Array/Object/tinymce.ui.Control} items Array or item that will be added to the container.
  16674. * @return {tinymce.ui.Collection} Current collection control.
  16675. */
  16676. add: function(items) {
  16677. var self = this;
  16678. self.items().add(self.create(items)).parent(self);
  16679. return self;
  16680. },
  16681. /**
  16682. * Focuses the current container instance. This will look
  16683. * for the first control in the container and focus that.
  16684. *
  16685. * @method focus
  16686. * @param {Boolean} keyboard Optional true/false if the focus was a keyboard focus or not.
  16687. * @return {tinymce.ui.Collection} Current instance.
  16688. */
  16689. focus: function(keyboard) {
  16690. var self = this, focusCtrl, keyboardNav, items;
  16691. if (keyboard) {
  16692. keyboardNav = self.keyboardNav || self.parents().eq(-1)[0].keyboardNav;
  16693. if (keyboardNav) {
  16694. keyboardNav.focusFirst(self);
  16695. return;
  16696. }
  16697. }
  16698. items = self.find('*');
  16699. // TODO: Figure out a better way to auto focus alert dialog buttons
  16700. if (self.statusbar) {
  16701. items.add(self.statusbar.items());
  16702. }
  16703. items.each(function(ctrl) {
  16704. if (ctrl.settings.autofocus) {
  16705. focusCtrl = null;
  16706. return false;
  16707. }
  16708. if (ctrl.canFocus) {
  16709. focusCtrl = focusCtrl || ctrl;
  16710. }
  16711. });
  16712. if (focusCtrl) {
  16713. focusCtrl.focus();
  16714. }
  16715. return self;
  16716. },
  16717. /**
  16718. * Replaces the specified child control with a new control.
  16719. *
  16720. * @method replace
  16721. * @param {tinymce.ui.Control} oldItem Old item to be replaced.
  16722. * @param {tinymce.ui.Control} newItem New item to be inserted.
  16723. */
  16724. replace: function(oldItem, newItem) {
  16725. var ctrlElm, items = this.items(), i = items.length;
  16726. // Replace the item in collection
  16727. while (i--) {
  16728. if (items[i] === oldItem) {
  16729. items[i] = newItem;
  16730. break;
  16731. }
  16732. }
  16733. if (i >= 0) {
  16734. // Remove new item from DOM
  16735. ctrlElm = newItem.getEl();
  16736. if (ctrlElm) {
  16737. ctrlElm.parentNode.removeChild(ctrlElm);
  16738. }
  16739. // Remove old item from DOM
  16740. ctrlElm = oldItem.getEl();
  16741. if (ctrlElm) {
  16742. ctrlElm.parentNode.removeChild(ctrlElm);
  16743. }
  16744. }
  16745. // Adopt the item
  16746. newItem.parent(this);
  16747. },
  16748. /**
  16749. * Creates the specified items. If any of the items is plain JSON style objects
  16750. * it will convert these into real tinymce.ui.Control instances.
  16751. *
  16752. * @method create
  16753. * @param {Array} items Array of items to convert into control instances.
  16754. * @return {Array} Array with control instances.
  16755. */
  16756. create: function(items) {
  16757. var self = this, settings, ctrlItems = [];
  16758. // Non array structure, then force it into an array
  16759. if (!Tools.isArray(items)) {
  16760. items = [items];
  16761. }
  16762. // Add default type to each child control
  16763. Tools.each(items, function(item) {
  16764. if (item) {
  16765. // Construct item if needed
  16766. if (!(item instanceof Control)) {
  16767. // Name only then convert it to an object
  16768. if (typeof(item) == "string") {
  16769. item = {type: item};
  16770. }
  16771. // Create control instance based on input settings and default settings
  16772. settings = Tools.extend({}, self.settings.defaults, item);
  16773. item.type = settings.type = settings.type || item.type || self.settings.defaultType ||
  16774. (settings.defaults ? settings.defaults.type : null);
  16775. item = Factory.create(settings);
  16776. }
  16777. ctrlItems.push(item);
  16778. }
  16779. });
  16780. return ctrlItems;
  16781. },
  16782. /**
  16783. * Renders new control instances.
  16784. *
  16785. * @private
  16786. */
  16787. renderNew: function() {
  16788. var self = this;
  16789. // Render any new items
  16790. self.items().each(function(ctrl, index) {
  16791. var containerElm, fragment;
  16792. ctrl.parent(self);
  16793. if (!ctrl._rendered) {
  16794. containerElm = self.getEl('body');
  16795. fragment = DomUtils.createFragment(ctrl.renderHtml());
  16796. // Insert or append the item
  16797. if (containerElm.hasChildNodes() && index <= containerElm.childNodes.length - 1) {
  16798. containerElm.insertBefore(fragment, containerElm.childNodes[index]);
  16799. } else {
  16800. containerElm.appendChild(fragment);
  16801. }
  16802. ctrl.postRender();
  16803. }
  16804. });
  16805. self._layout.applyClasses(self);
  16806. self._lastRect = null;
  16807. return self;
  16808. },
  16809. /**
  16810. * Appends new instances to the current container.
  16811. *
  16812. * @method append
  16813. * @param {Array/tinymce.ui.Collection} items Array if controls to append.
  16814. * @return {tinymce.ui.Container} Current container instance.
  16815. */
  16816. append: function(items) {
  16817. return this.add(items).renderNew();
  16818. },
  16819. /**
  16820. * Prepends new instances to the current container.
  16821. *
  16822. * @method prepend
  16823. * @param {Array/tinymce.ui.Collection} items Array if controls to prepend.
  16824. * @return {tinymce.ui.Container} Current container instance.
  16825. */
  16826. prepend: function(items) {
  16827. var self = this;
  16828. self.items().set(self.create(items).concat(self.items().toArray()));
  16829. return self.renderNew();
  16830. },
  16831. /**
  16832. * Inserts an control at a specific index.
  16833. *
  16834. * @method insert
  16835. * @param {Array/tinymce.ui.Collection} items Array if controls to insert.
  16836. * @param {Number} index Index to insert controls at.
  16837. * @param {Boolean} [before=false] Inserts controls before the index.
  16838. */
  16839. insert: function(items, index, before) {
  16840. var self = this, curItems, beforeItems, afterItems;
  16841. items = self.create(items);
  16842. curItems = self.items();
  16843. if (!before && index < curItems.length - 1) {
  16844. index += 1;
  16845. }
  16846. if (index >= 0 && index < curItems.length) {
  16847. beforeItems = curItems.slice(0, index).toArray();
  16848. afterItems = curItems.slice(index).toArray();
  16849. curItems.set(beforeItems.concat(items, afterItems));
  16850. }
  16851. return self.renderNew();
  16852. },
  16853. /**
  16854. * Populates the form fields from the specified JSON data object.
  16855. *
  16856. * Control items in the form that matches the data will have it's value set.
  16857. *
  16858. * @method fromJSON
  16859. * @param {Object} data JSON data object to set control values by.
  16860. * @return {tinymce.ui.Container} Current form instance.
  16861. */
  16862. fromJSON: function(data) {
  16863. var self = this;
  16864. for (var name in data) {
  16865. self.find('#' + name).value(data[name]);
  16866. }
  16867. return self;
  16868. },
  16869. /**
  16870. * Serializes the form into a JSON object by getting all items
  16871. * that has a name and a value.
  16872. *
  16873. * @method toJSON
  16874. * @return {Object} JSON object with form data.
  16875. */
  16876. toJSON: function() {
  16877. var self = this, data = {};
  16878. self.find('*').each(function(ctrl) {
  16879. var name = ctrl.name(), value = ctrl.value();
  16880. if (name && typeof(value) != "undefined") {
  16881. data[name] = value;
  16882. }
  16883. });
  16884. return data;
  16885. },
  16886. preRender: function() {
  16887. },
  16888. /**
  16889. * Renders the control as a HTML string.
  16890. *
  16891. * @method renderHtml
  16892. * @return {String} HTML representing the control.
  16893. */
  16894. renderHtml: function() {
  16895. var self = this, layout = self._layout, role = this.settings.role;
  16896. self.preRender();
  16897. layout.preRender(self);
  16898. return (
  16899. '<div id="' + self._id + '" class="' + self.classes() + '"' + (role ? ' role="' + this.settings.role + '"' : '') + '>' +
  16900. '<div id="' + self._id + '-body" class="' + self.classes('body') + '">' +
  16901. (self.settings.html || '') + layout.renderHtml(self) +
  16902. '</div>' +
  16903. '</div>'
  16904. );
  16905. },
  16906. /**
  16907. * Post render method. Called after the control has been rendered to the target.
  16908. *
  16909. * @method postRender
  16910. * @return {tinymce.ui.Container} Current combobox instance.
  16911. */
  16912. postRender: function() {
  16913. var self = this, box;
  16914. self.items().exec('postRender');
  16915. self._super();
  16916. self._layout.postRender(self);
  16917. self._rendered = true;
  16918. if (self.settings.style) {
  16919. DomUtils.css(self.getEl(), self.settings.style);
  16920. }
  16921. if (self.settings.border) {
  16922. box = self.borderBox();
  16923. DomUtils.css(self.getEl(), {
  16924. 'border-top-width': box.top,
  16925. 'border-right-width': box.right,
  16926. 'border-bottom-width': box.bottom,
  16927. 'border-left-width': box.left
  16928. });
  16929. }
  16930. if (!self.parent()) {
  16931. self.keyboardNav = new KeyboardNavigation({
  16932. root: self
  16933. });
  16934. }
  16935. return self;
  16936. },
  16937. /**
  16938. * Initializes the current controls layout rect.
  16939. * This will be executed by the layout managers to determine the
  16940. * default minWidth/minHeight etc.
  16941. *
  16942. * @method initLayoutRect
  16943. * @return {Object} Layout rect instance.
  16944. */
  16945. initLayoutRect: function() {
  16946. var self = this, layoutRect = self._super();
  16947. // Recalc container size by asking layout manager
  16948. self._layout.recalc(self);
  16949. return layoutRect;
  16950. },
  16951. /**
  16952. * Recalculates the positions of the controls in the current container.
  16953. * This is invoked by the reflow method and shouldn't be called directly.
  16954. *
  16955. * @method recalc
  16956. */
  16957. recalc: function() {
  16958. var self = this, rect = self._layoutRect, lastRect = self._lastRect;
  16959. if (!lastRect || lastRect.w != rect.w || lastRect.h != rect.h) {
  16960. self._layout.recalc(self);
  16961. rect = self.layoutRect();
  16962. self._lastRect = {x: rect.x, y: rect.y, w: rect.w, h: rect.h};
  16963. return true;
  16964. }
  16965. },
  16966. /**
  16967. * Reflows the current container and it's children and possible parents.
  16968. * This should be used after you for example append children to the current control so
  16969. * that the layout managers know that they need to reposition everything.
  16970. *
  16971. * @example
  16972. * container.append({type: 'button', text: 'My button'}).reflow();
  16973. *
  16974. * @method reflow
  16975. * @return {tinymce.ui.Container} Current container instance.
  16976. */
  16977. reflow: function() {
  16978. var i;
  16979. if (this.visible()) {
  16980. Control.repaintControls = [];
  16981. Control.repaintControls.map = {};
  16982. this.recalc();
  16983. i = Control.repaintControls.length;
  16984. while (i--) {
  16985. Control.repaintControls[i].repaint();
  16986. }
  16987. // TODO: Fix me!
  16988. if (this.settings.layout !== "flow" && this.settings.layout !== "stack") {
  16989. this.repaint();
  16990. }
  16991. Control.repaintControls = [];
  16992. }
  16993. return this;
  16994. }
  16995. });
  16996. });
  16997. // Included from: js/tinymce/classes/ui/DragHelper.js
  16998. /**
  16999. * DragHelper.js
  17000. *
  17001. * Copyright, Moxiecode Systems AB
  17002. * Released under LGPL License.
  17003. *
  17004. * License: http://www.tinymce.com/license
  17005. * Contributing: http://www.tinymce.com/contributing
  17006. */
  17007. /**
  17008. * Drag/drop helper class.
  17009. *
  17010. * @example
  17011. * var dragHelper = new tinymce.ui.DragHelper('mydiv', {
  17012. * start: function(evt) {
  17013. * },
  17014. *
  17015. * drag: function(evt) {
  17016. * },
  17017. *
  17018. * end: function(evt) {
  17019. * }
  17020. * });
  17021. *
  17022. * @class tinymce.ui.DragHelper
  17023. */
  17024. define("tinymce/ui/DragHelper", [
  17025. "tinymce/ui/DomUtils"
  17026. ], function(DomUtils) {
  17027. "use strict";
  17028. function getDocumentSize() {
  17029. var doc = document, documentElement, body, scrollWidth, clientWidth;
  17030. var offsetWidth, scrollHeight, clientHeight, offsetHeight, max = Math.max;
  17031. documentElement = doc.documentElement;
  17032. body = doc.body;
  17033. scrollWidth = max(documentElement.scrollWidth, body.scrollWidth);
  17034. clientWidth = max(documentElement.clientWidth, body.clientWidth);
  17035. offsetWidth = max(documentElement.offsetWidth, body.offsetWidth);
  17036. scrollHeight = max(documentElement.scrollHeight, body.scrollHeight);
  17037. clientHeight = max(documentElement.clientHeight, body.clientHeight);
  17038. offsetHeight = max(documentElement.offsetHeight, body.offsetHeight);
  17039. return {
  17040. width: scrollWidth < offsetWidth ? clientWidth : scrollWidth,
  17041. height: scrollHeight < offsetHeight ? clientHeight : scrollHeight
  17042. };
  17043. }
  17044. return function(id, settings) {
  17045. var eventOverlayElm, doc = document, downButton, start, stop, drag, startX, startY;
  17046. settings = settings || {};
  17047. function getHandleElm() {
  17048. return doc.getElementById(settings.handle || id);
  17049. }
  17050. start = function(e) {
  17051. var docSize = getDocumentSize(), handleElm, cursor;
  17052. e.preventDefault();
  17053. downButton = e.button;
  17054. handleElm = getHandleElm();
  17055. startX = e.screenX;
  17056. startY = e.screenY;
  17057. // Grab cursor from handle
  17058. if (window.getComputedStyle) {
  17059. cursor = window.getComputedStyle(handleElm, null).getPropertyValue("cursor");
  17060. } else {
  17061. cursor = handleElm.runtimeStyle.cursor;
  17062. }
  17063. // Create event overlay and add it to document
  17064. eventOverlayElm = doc.createElement('div');
  17065. DomUtils.css(eventOverlayElm, {
  17066. position: "absolute",
  17067. top: 0, left: 0,
  17068. width: docSize.width,
  17069. height: docSize.height,
  17070. zIndex: 0x7FFFFFFF,
  17071. opacity: 0.0001,
  17072. background: 'red',
  17073. cursor: cursor
  17074. });
  17075. doc.body.appendChild(eventOverlayElm);
  17076. // Bind mouse events
  17077. DomUtils.on(doc, 'mousemove', drag);
  17078. DomUtils.on(doc, 'mouseup', stop);
  17079. // Begin drag
  17080. settings.start(e);
  17081. };
  17082. drag = function(e) {
  17083. if (e.button !== downButton) {
  17084. return stop(e);
  17085. }
  17086. e.deltaX = e.screenX - startX;
  17087. e.deltaY = e.screenY - startY;
  17088. e.preventDefault();
  17089. settings.drag(e);
  17090. };
  17091. stop = function(e) {
  17092. DomUtils.off(doc, 'mousemove', drag);
  17093. DomUtils.off(doc, 'mouseup', stop);
  17094. eventOverlayElm.parentNode.removeChild(eventOverlayElm);
  17095. if (settings.stop) {
  17096. settings.stop(e);
  17097. }
  17098. };
  17099. /**
  17100. * Destroys the drag/drop helper instance.
  17101. *
  17102. * @method destroy
  17103. */
  17104. this.destroy = function() {
  17105. DomUtils.off(getHandleElm());
  17106. };
  17107. DomUtils.on(getHandleElm(), 'mousedown', start);
  17108. };
  17109. });
  17110. // Included from: js/tinymce/classes/ui/Scrollable.js
  17111. /**
  17112. * Scrollable.js
  17113. *
  17114. * Copyright, Moxiecode Systems AB
  17115. * Released under LGPL License.
  17116. *
  17117. * License: http://www.tinymce.com/license
  17118. * Contributing: http://www.tinymce.com/contributing
  17119. */
  17120. /**
  17121. * This mixin makes controls scrollable using custom scrollbars.
  17122. *
  17123. * @-x-less Scrollable.less
  17124. * @mixin tinymce.ui.Scrollable
  17125. */
  17126. define("tinymce/ui/Scrollable", [
  17127. "tinymce/ui/DomUtils",
  17128. "tinymce/ui/DragHelper"
  17129. ], function(DomUtils, DragHelper) {
  17130. "use strict";
  17131. return {
  17132. init: function() {
  17133. var self = this;
  17134. self.on('repaint', self.renderScroll);
  17135. },
  17136. renderScroll: function() {
  17137. var self = this, margin = 2;
  17138. function repaintScroll() {
  17139. var hasScrollH, hasScrollV, bodyElm;
  17140. function repaintAxis(axisName, posName, sizeName, contentSizeName, hasScroll, ax) {
  17141. var containerElm, scrollBarElm, scrollThumbElm;
  17142. var containerSize, scrollSize, ratio, rect;
  17143. var posNameLower, sizeNameLower;
  17144. scrollBarElm = self.getEl('scroll' + axisName);
  17145. if (scrollBarElm) {
  17146. posNameLower = posName.toLowerCase();
  17147. sizeNameLower = sizeName.toLowerCase();
  17148. if (self.getEl('absend')) {
  17149. DomUtils.css(self.getEl('absend'), posNameLower, self.layoutRect()[contentSizeName] - 1);
  17150. }
  17151. if (!hasScroll) {
  17152. DomUtils.css(scrollBarElm, 'display', 'none');
  17153. return;
  17154. }
  17155. DomUtils.css(scrollBarElm, 'display', 'block');
  17156. containerElm = self.getEl('body');
  17157. scrollThumbElm = self.getEl('scroll' + axisName + "t");
  17158. containerSize = containerElm["client" + sizeName] - (margin * 2);
  17159. containerSize -= hasScrollH && hasScrollV ? scrollBarElm["client" + ax] : 0;
  17160. scrollSize = containerElm["scroll" + sizeName];
  17161. ratio = containerSize / scrollSize;
  17162. rect = {};
  17163. rect[posNameLower] = containerElm["offset" + posName] + margin;
  17164. rect[sizeNameLower] = containerSize;
  17165. DomUtils.css(scrollBarElm, rect);
  17166. rect = {};
  17167. rect[posNameLower] = containerElm["scroll" + posName] * ratio;
  17168. rect[sizeNameLower] = containerSize * ratio;
  17169. DomUtils.css(scrollThumbElm, rect);
  17170. }
  17171. }
  17172. bodyElm = self.getEl('body');
  17173. hasScrollH = bodyElm.scrollWidth > bodyElm.clientWidth;
  17174. hasScrollV = bodyElm.scrollHeight > bodyElm.clientHeight;
  17175. repaintAxis("h", "Left", "Width", "contentW", hasScrollH, "Height");
  17176. repaintAxis("v", "Top", "Height", "contentH", hasScrollV, "Width");
  17177. }
  17178. function addScroll() {
  17179. function addScrollAxis(axisName, posName, sizeName, deltaPosName, ax) {
  17180. var scrollStart, axisId = self._id + '-scroll' + axisName, prefix = self.classPrefix;
  17181. self.getEl().appendChild(DomUtils.createFragment(
  17182. '<div id="' + axisId + '" class="' + prefix + 'scrollbar ' + prefix + 'scrollbar-' + axisName + '">' +
  17183. '<div id="' + axisId + 't" class="' + prefix + 'scrollbar-thumb"></div>' +
  17184. '</div>'
  17185. ));
  17186. self.draghelper = new DragHelper(axisId + 't', {
  17187. start: function() {
  17188. scrollStart = self.getEl('body')["scroll" + posName];
  17189. DomUtils.addClass(DomUtils.get(axisId), prefix + 'active');
  17190. },
  17191. drag: function(e) {
  17192. var ratio, hasScrollH, hasScrollV, containerSize, layoutRect = self.layoutRect();
  17193. hasScrollH = layoutRect.contentW > layoutRect.innerW;
  17194. hasScrollV = layoutRect.contentH > layoutRect.innerH;
  17195. containerSize = self.getEl('body')["client" + sizeName] - (margin * 2);
  17196. containerSize -= hasScrollH && hasScrollV ? self.getEl('scroll' + axisName)["client" + ax] : 0;
  17197. ratio = containerSize / self.getEl('body')["scroll" + sizeName];
  17198. self.getEl('body')["scroll" + posName] = scrollStart + (e["delta" + deltaPosName] / ratio);
  17199. },
  17200. stop: function() {
  17201. DomUtils.removeClass(DomUtils.get(axisId), prefix + 'active');
  17202. }
  17203. });
  17204. /*
  17205. self.on('click', function(e) {
  17206. if (e.target.id == self._id + '-scrollv') {
  17207. }
  17208. });*/
  17209. }
  17210. self.addClass('scroll');
  17211. addScrollAxis("v", "Top", "Height", "Y", "Width");
  17212. addScrollAxis("h", "Left", "Width", "X", "Height");
  17213. }
  17214. if (self.settings.autoScroll) {
  17215. if (!self._hasScroll) {
  17216. self._hasScroll = true;
  17217. addScroll();
  17218. self.on('wheel', function(e) {
  17219. var bodyEl = self.getEl('body');
  17220. bodyEl.scrollLeft += (e.deltaX || 0) * 10;
  17221. bodyEl.scrollTop += e.deltaY * 10;
  17222. repaintScroll();
  17223. });
  17224. DomUtils.on(self.getEl('body'), "scroll", repaintScroll);
  17225. }
  17226. repaintScroll();
  17227. }
  17228. }
  17229. };
  17230. });
  17231. // Included from: js/tinymce/classes/ui/Panel.js
  17232. /**
  17233. * Panel.js
  17234. *
  17235. * Copyright, Moxiecode Systems AB
  17236. * Released under LGPL License.
  17237. *
  17238. * License: http://www.tinymce.com/license
  17239. * Contributing: http://www.tinymce.com/contributing
  17240. */
  17241. /**
  17242. * Creates a new panel.
  17243. *
  17244. * @-x-less Panel.less
  17245. * @class tinymce.ui.Panel
  17246. * @extends tinymce.ui.Container
  17247. * @mixes tinymce.ui.Scrollable
  17248. */
  17249. define("tinymce/ui/Panel", [
  17250. "tinymce/ui/Container",
  17251. "tinymce/ui/Scrollable"
  17252. ], function(Container, Scrollable) {
  17253. "use strict";
  17254. return Container.extend({
  17255. Defaults: {
  17256. layout: 'fit',
  17257. containerCls: 'panel'
  17258. },
  17259. Mixins: [Scrollable],
  17260. /**
  17261. * Renders the control as a HTML string.
  17262. *
  17263. * @method renderHtml
  17264. * @return {String} HTML representing the control.
  17265. */
  17266. renderHtml: function() {
  17267. var self = this, layout = self._layout, innerHtml = self.settings.html;
  17268. self.preRender();
  17269. layout.preRender(self);
  17270. if (typeof(innerHtml) == "undefined") {
  17271. innerHtml = (
  17272. '<div id="' + self._id + '-body" class="' + self.classes('body') + '">' +
  17273. layout.renderHtml(self) +
  17274. '</div>'
  17275. );
  17276. } else {
  17277. if (typeof(innerHtml) == 'function') {
  17278. innerHtml = innerHtml.call(self);
  17279. }
  17280. self._hasBody = false;
  17281. }
  17282. return (
  17283. '<div id="' + self._id + '" class="' + self.classes() + '" hidefocus="1" tabindex="-1" role="group">' +
  17284. (self._preBodyHtml || '') +
  17285. innerHtml +
  17286. '</div>'
  17287. );
  17288. }
  17289. });
  17290. });
  17291. // Included from: js/tinymce/classes/ui/Movable.js
  17292. /**
  17293. * Movable.js
  17294. *
  17295. * Copyright, Moxiecode Systems AB
  17296. * Released under LGPL License.
  17297. *
  17298. * License: http://www.tinymce.com/license
  17299. * Contributing: http://www.tinymce.com/contributing
  17300. */
  17301. /**
  17302. * Movable mixin. Makes controls movable absolute and relative to other elements.
  17303. *
  17304. * @mixin tinymce.ui.Movable
  17305. */
  17306. define("tinymce/ui/Movable", [
  17307. "tinymce/ui/DomUtils"
  17308. ], function(DomUtils) {
  17309. "use strict";
  17310. function calculateRelativePosition(ctrl, targetElm, rel) {
  17311. var ctrlElm, pos, x, y, selfW, selfH, targetW, targetH, viewport, size;
  17312. viewport = DomUtils.getViewPort();
  17313. // Get pos of target
  17314. pos = DomUtils.getPos(targetElm);
  17315. x = pos.x;
  17316. y = pos.y;
  17317. if (ctrl._fixed) {
  17318. x -= viewport.x;
  17319. y -= viewport.y;
  17320. }
  17321. // Get size of self
  17322. ctrlElm = ctrl.getEl();
  17323. size = DomUtils.getSize(ctrlElm);
  17324. selfW = size.width;
  17325. selfH = size.height;
  17326. // Get size of target
  17327. size = DomUtils.getSize(targetElm);
  17328. targetW = size.width;
  17329. targetH = size.height;
  17330. // Parse align string
  17331. rel = (rel || '').split('');
  17332. // Target corners
  17333. if (rel[0] === 'b') {
  17334. y += targetH;
  17335. }
  17336. if (rel[1] === 'r') {
  17337. x += targetW;
  17338. }
  17339. if (rel[0] === 'c') {
  17340. y += Math.round(targetH / 2);
  17341. }
  17342. if (rel[1] === 'c') {
  17343. x += Math.round(targetW / 2);
  17344. }
  17345. // Self corners
  17346. if (rel[3] === 'b') {
  17347. y -= selfH;
  17348. }
  17349. if (rel[4] === 'r') {
  17350. x -= selfW;
  17351. }
  17352. if (rel[3] === 'c') {
  17353. y -= Math.round(selfH / 2);
  17354. }
  17355. if (rel[4] === 'c') {
  17356. x -= Math.round(selfW / 2);
  17357. }
  17358. return {
  17359. x: x,
  17360. y: y,
  17361. w: selfW,
  17362. h: selfH
  17363. };
  17364. }
  17365. return {
  17366. /**
  17367. * Tests various positions to get the most suitable one.
  17368. *
  17369. * @method testMoveRel
  17370. * @param {DOMElement} elm Element to position against.
  17371. * @param {Array} rels Array with relative positions.
  17372. * @return {String} Best suitable relative position.
  17373. */
  17374. testMoveRel: function(elm, rels) {
  17375. var viewPortRect = DomUtils.getViewPort();
  17376. for (var i = 0; i < rels.length; i++) {
  17377. var pos = calculateRelativePosition(this, elm, rels[i]);
  17378. if (this._fixed) {
  17379. if (pos.x > 0 && pos.x + pos.w < viewPortRect.w && pos.y > 0 && pos.y + pos.h < viewPortRect.h) {
  17380. return rels[i];
  17381. }
  17382. } else {
  17383. if (pos.x > viewPortRect.x && pos.x + pos.w < viewPortRect.w + viewPortRect.x &&
  17384. pos.y > viewPortRect.y && pos.y + pos.h < viewPortRect.h + viewPortRect.y) {
  17385. return rels[i];
  17386. }
  17387. }
  17388. }
  17389. return rels[0];
  17390. },
  17391. /**
  17392. * Move relative to the specified element.
  17393. *
  17394. * @method moveRel
  17395. * @param {Element} elm Element to move relative to.
  17396. * @param {String} rel Relative mode. For example: br-tl.
  17397. * @return {tinymce.ui.Control} Current control instance.
  17398. */
  17399. moveRel: function(elm, rel) {
  17400. if (typeof(rel) != 'string') {
  17401. rel = this.testMoveRel(elm, rel);
  17402. }
  17403. var pos = calculateRelativePosition(this, elm, rel);
  17404. return this.moveTo(pos.x, pos.y);
  17405. },
  17406. /**
  17407. * Move by a relative x, y values.
  17408. *
  17409. * @method moveBy
  17410. * @param {Number} dx Relative x position.
  17411. * @param {Number} dy Relative y position.
  17412. * @return {tinymce.ui.Control} Current control instance.
  17413. */
  17414. moveBy: function(dx, dy) {
  17415. var self = this, rect = self.layoutRect();
  17416. self.moveTo(rect.x + dx, rect.y + dy);
  17417. return self;
  17418. },
  17419. /**
  17420. * Move to absolute position.
  17421. *
  17422. * @method moveTo
  17423. * @param {Number} x Absolute x position.
  17424. * @param {Number} y Absolute y position.
  17425. * @return {tinymce.ui.Control} Current control instance.
  17426. */
  17427. moveTo: function(x, y) {
  17428. var self = this;
  17429. // TODO: Move this to some global class
  17430. function contrain(value, max, size) {
  17431. if (value < 0) {
  17432. return 0;
  17433. }
  17434. if (value + size > max) {
  17435. value = max - size;
  17436. return value < 0 ? 0 : value;
  17437. }
  17438. return value;
  17439. }
  17440. if (self.settings.constrainToViewport) {
  17441. var viewPortRect = DomUtils.getViewPort(window);
  17442. var layoutRect = self.layoutRect();
  17443. x = contrain(x, viewPortRect.w + viewPortRect.x, layoutRect.w);
  17444. y = contrain(y, viewPortRect.h + viewPortRect.y, layoutRect.h);
  17445. }
  17446. if (self._rendered) {
  17447. self.layoutRect({x: x, y: y}).repaint();
  17448. } else {
  17449. self.settings.x = x;
  17450. self.settings.y = y;
  17451. }
  17452. self.fire('move', {x: x, y: y});
  17453. return self;
  17454. }
  17455. };
  17456. });
  17457. // Included from: js/tinymce/classes/ui/Resizable.js
  17458. /**
  17459. * Resizable.js
  17460. *
  17461. * Copyright, Moxiecode Systems AB
  17462. * Released under LGPL License.
  17463. *
  17464. * License: http://www.tinymce.com/license
  17465. * Contributing: http://www.tinymce.com/contributing
  17466. */
  17467. /**
  17468. * Resizable mixin. Enables controls to be resized.
  17469. *
  17470. * @mixin tinymce.ui.Resizable
  17471. */
  17472. define("tinymce/ui/Resizable", [
  17473. "tinymce/ui/DomUtils"
  17474. ], function(DomUtils) {
  17475. "use strict";
  17476. return {
  17477. /**
  17478. * Resizes the control to contents.
  17479. *
  17480. * @method resizeToContent
  17481. */
  17482. resizeToContent: function() {
  17483. this._layoutRect.autoResize = true;
  17484. this._lastRect = null;
  17485. this.reflow();
  17486. },
  17487. /**
  17488. * Resizes the control to a specific width/height.
  17489. *
  17490. * @method resizeTo
  17491. * @param {Number} w Control width.
  17492. * @param {Number} h Control height.
  17493. * @return {tinymce.ui.Control} Current control instance.
  17494. */
  17495. resizeTo: function(w, h) {
  17496. // TODO: Fix hack
  17497. if (w <= 1 || h <= 1) {
  17498. var rect = DomUtils.getWindowSize();
  17499. w = w <= 1 ? w * rect.w : w;
  17500. h = h <= 1 ? h * rect.h : h;
  17501. }
  17502. this._layoutRect.autoResize = false;
  17503. return this.layoutRect({minW: w, minH: h, w: w, h: h}).reflow();
  17504. },
  17505. /**
  17506. * Resizes the control to a specific relative width/height.
  17507. *
  17508. * @method resizeBy
  17509. * @param {Number} dw Relative control width.
  17510. * @param {Number} dh Relative control height.
  17511. * @return {tinymce.ui.Control} Current control instance.
  17512. */
  17513. resizeBy: function(dw, dh) {
  17514. var self = this, rect = self.layoutRect();
  17515. return self.resizeTo(rect.w + dw, rect.h + dh);
  17516. }
  17517. };
  17518. });
  17519. // Included from: js/tinymce/classes/ui/FloatPanel.js
  17520. /**
  17521. * FloatPanel.js
  17522. *
  17523. * Copyright, Moxiecode Systems AB
  17524. * Released under LGPL License.
  17525. *
  17526. * License: http://www.tinymce.com/license
  17527. * Contributing: http://www.tinymce.com/contributing
  17528. */
  17529. /**
  17530. * This class creates a floating panel.
  17531. *
  17532. * @-x-less FloatPanel.less
  17533. * @class tinymce.ui.FloatPanel
  17534. * @extends tinymce.ui.Panel
  17535. * @mixes tinymce.ui.Movable
  17536. * @mixes tinymce.ui.Resizable
  17537. */
  17538. define("tinymce/ui/FloatPanel", [
  17539. "tinymce/ui/Panel",
  17540. "tinymce/ui/Movable",
  17541. "tinymce/ui/Resizable",
  17542. "tinymce/ui/DomUtils"
  17543. ], function(Panel, Movable, Resizable, DomUtils) {
  17544. "use strict";
  17545. var documentClickHandler, documentScrollHandler, visiblePanels = [];
  17546. var zOrder = [], hasModal;
  17547. var FloatPanel = Panel.extend({
  17548. Mixins: [Movable, Resizable],
  17549. /**
  17550. * Constructs a new control instance with the specified settings.
  17551. *
  17552. * @constructor
  17553. * @param {Object} settings Name/value object with settings.
  17554. * @setting {Boolean} autohide Automatically hide the panel.
  17555. */
  17556. init: function(settings) {
  17557. var self = this;
  17558. function reorder() {
  17559. var i, zIndex = FloatPanel.zIndex || 0xFFFF, topModal;
  17560. if (zOrder.length) {
  17561. for (i = 0; i < zOrder.length; i++) {
  17562. if (zOrder[i].modal) {
  17563. zIndex++;
  17564. topModal = zOrder[i];
  17565. }
  17566. zOrder[i].getEl().style.zIndex = zIndex;
  17567. zOrder[i].zIndex = zIndex;
  17568. zIndex++;
  17569. }
  17570. }
  17571. var modalBlockEl = document.getElementById(self.classPrefix + 'modal-block');
  17572. if (topModal) {
  17573. DomUtils.css(modalBlockEl, 'z-index', topModal.zIndex - 1);
  17574. } else if (modalBlockEl) {
  17575. modalBlockEl.parentNode.removeChild(modalBlockEl);
  17576. hasModal = false;
  17577. }
  17578. FloatPanel.currentZIndex = zIndex;
  17579. }
  17580. function isChildOf(ctrl, parent) {
  17581. while (ctrl) {
  17582. if (ctrl == parent) {
  17583. return true;
  17584. }
  17585. ctrl = ctrl.parent();
  17586. }
  17587. }
  17588. /**
  17589. * Repositions the panel to the top of page if the panel is outside of the visual viewport. It will
  17590. * also reposition all child panels of the current panel.
  17591. */
  17592. function repositionPanel(panel) {
  17593. var scrollY = DomUtils.getViewPort().y;
  17594. function toggleFixedChildPanels(fixed, deltaY) {
  17595. var parent;
  17596. for (var i = 0; i < visiblePanels.length; i++) {
  17597. if (visiblePanels[i] != panel) {
  17598. parent = visiblePanels[i].parent();
  17599. while (parent && (parent = parent.parent())) {
  17600. if (parent == panel) {
  17601. visiblePanels[i].fixed(fixed).moveBy(0, deltaY).repaint();
  17602. }
  17603. }
  17604. }
  17605. }
  17606. }
  17607. if (panel.settings.autofix) {
  17608. if (!panel._fixed) {
  17609. panel._autoFixY = panel.layoutRect().y;
  17610. if (panel._autoFixY < scrollY) {
  17611. panel.fixed(true).layoutRect({y: 0}).repaint();
  17612. toggleFixedChildPanels(true, scrollY - panel._autoFixY);
  17613. }
  17614. } else {
  17615. if (panel._autoFixY > scrollY) {
  17616. panel.fixed(false).layoutRect({y: panel._autoFixY}).repaint();
  17617. toggleFixedChildPanels(false, panel._autoFixY - scrollY);
  17618. }
  17619. }
  17620. }
  17621. }
  17622. self._super(settings);
  17623. self._eventsRoot = self;
  17624. self.addClass('floatpanel');
  17625. // Hide floatpanes on click out side the root button
  17626. if (settings.autohide) {
  17627. if (!documentClickHandler) {
  17628. documentClickHandler = function(e) {
  17629. // Hide any float panel when a click is out side that float panel and the
  17630. // float panels direct parent for example a click on a menu button
  17631. var i = visiblePanels.length;
  17632. while (i--) {
  17633. var panel = visiblePanels[i], clickCtrl = panel.getParentCtrl(e.target);
  17634. if (panel.settings.autohide) {
  17635. if (clickCtrl) {
  17636. if (isChildOf(clickCtrl, panel) || panel.parent() === clickCtrl) {
  17637. continue;
  17638. }
  17639. }
  17640. e = panel.fire('autohide', {target: e.target});
  17641. if (!e.isDefaultPrevented()) {
  17642. panel.hide();
  17643. }
  17644. }
  17645. }
  17646. };
  17647. DomUtils.on(document, 'click', documentClickHandler);
  17648. }
  17649. visiblePanels.push(self);
  17650. }
  17651. if (settings.autofix) {
  17652. if (!documentScrollHandler) {
  17653. documentScrollHandler = function() {
  17654. var i;
  17655. i = visiblePanels.length;
  17656. while (i--) {
  17657. repositionPanel(visiblePanels[i]);
  17658. }
  17659. };
  17660. DomUtils.on(window, 'scroll', documentScrollHandler);
  17661. }
  17662. self.on('move', function() {
  17663. repositionPanel(this);
  17664. });
  17665. }
  17666. self.on('postrender show', function(e) {
  17667. if (e.control == self) {
  17668. var modalBlockEl, prefix = self.classPrefix;
  17669. if (self.modal && !hasModal) {
  17670. modalBlockEl = DomUtils.createFragment('<div id="' + prefix + 'modal-block" class="' +
  17671. prefix + 'reset ' + prefix + 'fade"></div>');
  17672. modalBlockEl = modalBlockEl.firstChild;
  17673. self.getContainerElm().appendChild(modalBlockEl);
  17674. setTimeout(function() {
  17675. DomUtils.addClass(modalBlockEl, prefix + 'in');
  17676. DomUtils.addClass(self.getEl(), prefix + 'in');
  17677. }, 0);
  17678. hasModal = true;
  17679. }
  17680. zOrder.push(self);
  17681. reorder();
  17682. }
  17683. });
  17684. self.on('close hide', function(e) {
  17685. if (e.control == self) {
  17686. var i = zOrder.length;
  17687. while (i--) {
  17688. if (zOrder[i] === self) {
  17689. zOrder.splice(i, 1);
  17690. }
  17691. }
  17692. reorder();
  17693. }
  17694. });
  17695. self.on('show', function() {
  17696. self.parents().each(function(ctrl) {
  17697. if (ctrl._fixed) {
  17698. self.fixed(true);
  17699. return false;
  17700. }
  17701. });
  17702. });
  17703. if (settings.popover) {
  17704. self._preBodyHtml = '<div class="' + self.classPrefix + 'arrow"></div>';
  17705. self.addClass('popover').addClass('bottom').addClass(self.isRtl() ? 'end' : 'start');
  17706. }
  17707. },
  17708. fixed: function(state) {
  17709. var self = this;
  17710. if (self._fixed != state) {
  17711. if (self._rendered) {
  17712. var viewport = DomUtils.getViewPort();
  17713. if (state) {
  17714. self.layoutRect().y -= viewport.y;
  17715. } else {
  17716. self.layoutRect().y += viewport.y;
  17717. }
  17718. }
  17719. self.toggleClass('fixed', state);
  17720. self._fixed = state;
  17721. }
  17722. return self;
  17723. },
  17724. /**
  17725. * Shows the current float panel.
  17726. *
  17727. * @method show
  17728. * @return {tinymce.ui.FloatPanel} Current floatpanel instance.
  17729. */
  17730. show: function() {
  17731. var self = this, i, state = self._super();
  17732. i = visiblePanels.length;
  17733. while (i--) {
  17734. if (visiblePanels[i] === self) {
  17735. break;
  17736. }
  17737. }
  17738. if (i === -1) {
  17739. visiblePanels.push(self);
  17740. }
  17741. return state;
  17742. },
  17743. /**
  17744. * Hides the current float panel.
  17745. *
  17746. * @method hide
  17747. * @return {tinymce.ui.FloatPanel} Current floatpanel instance.
  17748. */
  17749. hide: function() {
  17750. removeVisiblePanel(this);
  17751. return this._super();
  17752. },
  17753. /**
  17754. * Hides all visible the float panels.
  17755. *
  17756. * @method hideAll
  17757. */
  17758. hideAll: function() {
  17759. FloatPanel.hideAll();
  17760. },
  17761. /**
  17762. * Closes the float panel. This will remove the float panel from page and fire the close event.
  17763. *
  17764. * @method close
  17765. */
  17766. close: function() {
  17767. var self = this;
  17768. self.fire('close');
  17769. return self.remove();
  17770. },
  17771. /**
  17772. * Removes the float panel from page.
  17773. *
  17774. * @method remove
  17775. */
  17776. remove: function() {
  17777. removeVisiblePanel(this);
  17778. this._super();
  17779. },
  17780. postRender: function() {
  17781. var self = this;
  17782. if (self.settings.bodyRole) {
  17783. this.getEl('body').setAttribute('role', self.settings.bodyRole);
  17784. }
  17785. return self._super();
  17786. }
  17787. });
  17788. /**
  17789. * Hides all visible the float panels.
  17790. *
  17791. * @static
  17792. * @method hideAll
  17793. */
  17794. FloatPanel.hideAll = function() {
  17795. var i = visiblePanels.length;
  17796. while (i--) {
  17797. var panel = visiblePanels[i];
  17798. if (panel && panel.settings.autohide) {
  17799. panel.hide();
  17800. visiblePanels.splice(i, 1);
  17801. }
  17802. }
  17803. };
  17804. function removeVisiblePanel(panel) {
  17805. var i;
  17806. i = visiblePanels.length;
  17807. while (i--) {
  17808. if (visiblePanels[i] === panel) {
  17809. visiblePanels.splice(i, 1);
  17810. }
  17811. }
  17812. i = zOrder.length;
  17813. while (i--) {
  17814. if (zOrder[i] === panel) {
  17815. zOrder.splice(i, 1);
  17816. }
  17817. }
  17818. }
  17819. return FloatPanel;
  17820. });
  17821. // Included from: js/tinymce/classes/ui/Window.js
  17822. /**
  17823. * Window.js
  17824. *
  17825. * Copyright, Moxiecode Systems AB
  17826. * Released under LGPL License.
  17827. *
  17828. * License: http://www.tinymce.com/license
  17829. * Contributing: http://www.tinymce.com/contributing
  17830. */
  17831. /**
  17832. * Creates a new window.
  17833. *
  17834. * @-x-less Window.less
  17835. * @class tinymce.ui.Window
  17836. * @extends tinymce.ui.FloatPanel
  17837. */
  17838. define("tinymce/ui/Window", [
  17839. "tinymce/ui/FloatPanel",
  17840. "tinymce/ui/Panel",
  17841. "tinymce/ui/DomUtils",
  17842. "tinymce/ui/DragHelper"
  17843. ], function(FloatPanel, Panel, DomUtils, DragHelper) {
  17844. "use strict";
  17845. var Window = FloatPanel.extend({
  17846. modal: true,
  17847. Defaults: {
  17848. border: 1,
  17849. layout: 'flex',
  17850. containerCls: 'panel',
  17851. role: 'dialog',
  17852. callbacks: {
  17853. submit: function() {
  17854. this.fire('submit', {data: this.toJSON()});
  17855. },
  17856. close: function() {
  17857. this.close();
  17858. }
  17859. }
  17860. },
  17861. /**
  17862. * Constructs a instance with the specified settings.
  17863. *
  17864. * @constructor
  17865. * @param {Object} settings Name/value object with settings.
  17866. */
  17867. init: function(settings) {
  17868. var self = this;
  17869. self._super(settings);
  17870. if (self.isRtl()) {
  17871. self.addClass('rtl');
  17872. }
  17873. self.addClass('window');
  17874. self._fixed = true;
  17875. // Create statusbar
  17876. if (settings.buttons) {
  17877. self.statusbar = new Panel({
  17878. layout: 'flex',
  17879. border: '1 0 0 0',
  17880. spacing: 3,
  17881. padding: 10,
  17882. align: 'center',
  17883. pack: self.isRtl() ? 'start' : 'end',
  17884. defaults: {
  17885. type: 'button'
  17886. },
  17887. items: settings.buttons
  17888. });
  17889. self.statusbar.addClass('foot');
  17890. self.statusbar.parent(self);
  17891. }
  17892. self.on('click', function(e) {
  17893. if (e.target.className.indexOf(self.classPrefix + 'close') != -1) {
  17894. self.close();
  17895. }
  17896. });
  17897. self.on('cancel', function() {
  17898. self.close();
  17899. });
  17900. self.aria('describedby', self.describedBy || self._id + '-none');
  17901. self.aria('label', settings.title);
  17902. self._fullscreen = false;
  17903. },
  17904. /**
  17905. * Recalculates the positions of the controls in the current container.
  17906. * This is invoked by the reflow method and shouldn't be called directly.
  17907. *
  17908. * @method recalc
  17909. */
  17910. recalc: function() {
  17911. var self = this, statusbar = self.statusbar, layoutRect, width, x, needsRecalc;
  17912. if (self._fullscreen) {
  17913. self.layoutRect(DomUtils.getWindowSize());
  17914. self.layoutRect().contentH = self.layoutRect().innerH;
  17915. }
  17916. self._super();
  17917. layoutRect = self.layoutRect();
  17918. // Resize window based on title width
  17919. if (self.settings.title && !self._fullscreen) {
  17920. width = layoutRect.headerW;
  17921. if (width > layoutRect.w) {
  17922. x = layoutRect.x - Math.max(0, width / 2);
  17923. self.layoutRect({w: width, x: x});
  17924. needsRecalc = true;
  17925. }
  17926. }
  17927. // Resize window based on statusbar width
  17928. if (statusbar) {
  17929. statusbar.layoutRect({w: self.layoutRect().innerW}).recalc();
  17930. width = statusbar.layoutRect().minW + layoutRect.deltaW;
  17931. if (width > layoutRect.w) {
  17932. x = layoutRect.x - Math.max(0, width - layoutRect.w);
  17933. self.layoutRect({w: width, x: x});
  17934. needsRecalc = true;
  17935. }
  17936. }
  17937. // Recalc body and disable auto resize
  17938. if (needsRecalc) {
  17939. self.recalc();
  17940. }
  17941. },
  17942. /**
  17943. * Initializes the current controls layout rect.
  17944. * This will be executed by the layout managers to determine the
  17945. * default minWidth/minHeight etc.
  17946. *
  17947. * @method initLayoutRect
  17948. * @return {Object} Layout rect instance.
  17949. */
  17950. initLayoutRect: function() {
  17951. var self = this, layoutRect = self._super(), deltaH = 0, headEl;
  17952. // Reserve vertical space for title
  17953. if (self.settings.title && !self._fullscreen) {
  17954. headEl = self.getEl('head');
  17955. var size = DomUtils.getSize(headEl);
  17956. layoutRect.headerW = size.width;
  17957. layoutRect.headerH = size.height;
  17958. deltaH += layoutRect.headerH;
  17959. }
  17960. // Reserve vertical space for statusbar
  17961. if (self.statusbar) {
  17962. deltaH += self.statusbar.layoutRect().h;
  17963. }
  17964. layoutRect.deltaH += deltaH;
  17965. layoutRect.minH += deltaH;
  17966. //layoutRect.innerH -= deltaH;
  17967. layoutRect.h += deltaH;
  17968. var rect = DomUtils.getWindowSize();
  17969. layoutRect.x = Math.max(0, rect.w / 2 - layoutRect.w / 2);
  17970. layoutRect.y = Math.max(0, rect.h / 2 - layoutRect.h / 2);
  17971. return layoutRect;
  17972. },
  17973. /**
  17974. * Renders the control as a HTML string.
  17975. *
  17976. * @method renderHtml
  17977. * @return {String} HTML representing the control.
  17978. */
  17979. renderHtml: function() {
  17980. var self = this, layout = self._layout, id = self._id, prefix = self.classPrefix;
  17981. var settings = self.settings, headerHtml = '', footerHtml = '', html = settings.html;
  17982. self.preRender();
  17983. layout.preRender(self);
  17984. if (settings.title) {
  17985. headerHtml = (
  17986. '<div id="' + id + '-head" class="' + prefix + 'window-head">' +
  17987. '<div id="' + id + '-title" class="' + prefix + 'title">' + self.encode(settings.title) + '</div>' +
  17988. '<button type="button" class="' + prefix + 'close" aria-hidden="true">\u00d7</button>' +
  17989. '<div id="' + id + '-dragh" class="' + prefix + 'dragh"></div>' +
  17990. '</div>'
  17991. );
  17992. }
  17993. if (settings.url) {
  17994. html = '<iframe src="' + settings.url + '" tabindex="-1"></iframe>';
  17995. }
  17996. if (typeof(html) == "undefined") {
  17997. html = layout.renderHtml(self);
  17998. }
  17999. if (self.statusbar) {
  18000. footerHtml = self.statusbar.renderHtml();
  18001. }
  18002. return (
  18003. '<div id="' + id + '" class="' + self.classes() + '" hidefocus="1">' +
  18004. '<div class="' + self.classPrefix + 'reset" role="application">' +
  18005. headerHtml +
  18006. '<div id="' + id + '-body" class="' + self.classes('body') + '">' +
  18007. html +
  18008. '</div>' +
  18009. footerHtml +
  18010. '</div>' +
  18011. '</div>'
  18012. );
  18013. },
  18014. /**
  18015. * Switches the window fullscreen mode.
  18016. *
  18017. * @method fullscreen
  18018. * @param {Boolean} state True/false state.
  18019. * @return {tinymce.ui.Window} Current window instance.
  18020. */
  18021. fullscreen: function(state) {
  18022. var self = this, documentElement = document.documentElement, slowRendering, prefix = self.classPrefix, layoutRect;
  18023. if (state != self._fullscreen) {
  18024. DomUtils.on(window, 'resize', function() {
  18025. var time;
  18026. if (self._fullscreen) {
  18027. // Time the layout time if it's to slow use a timeout to not hog the CPU
  18028. if (!slowRendering) {
  18029. time = new Date().getTime();
  18030. var rect = DomUtils.getWindowSize();
  18031. self.moveTo(0, 0).resizeTo(rect.w, rect.h);
  18032. if ((new Date().getTime()) - time > 50) {
  18033. slowRendering = true;
  18034. }
  18035. } else {
  18036. if (!self._timer) {
  18037. self._timer = setTimeout(function() {
  18038. var rect = DomUtils.getWindowSize();
  18039. self.moveTo(0, 0).resizeTo(rect.w, rect.h);
  18040. self._timer = 0;
  18041. }, 50);
  18042. }
  18043. }
  18044. }
  18045. });
  18046. layoutRect = self.layoutRect();
  18047. self._fullscreen = state;
  18048. if (!state) {
  18049. self._borderBox = self.parseBox(self.settings.border);
  18050. self.getEl('head').style.display = '';
  18051. layoutRect.deltaH += layoutRect.headerH;
  18052. DomUtils.removeClass(documentElement, prefix + 'fullscreen');
  18053. DomUtils.removeClass(document.body, prefix + 'fullscreen');
  18054. self.removeClass('fullscreen');
  18055. self.moveTo(self._initial.x, self._initial.y).resizeTo(self._initial.w, self._initial.h);
  18056. } else {
  18057. self._initial = {x: layoutRect.x, y: layoutRect.y, w: layoutRect.w, h: layoutRect.h};
  18058. self._borderBox = self.parseBox('0');
  18059. self.getEl('head').style.display = 'none';
  18060. layoutRect.deltaH -= layoutRect.headerH + 2;
  18061. DomUtils.addClass(documentElement, prefix + 'fullscreen');
  18062. DomUtils.addClass(document.body, prefix + 'fullscreen');
  18063. self.addClass('fullscreen');
  18064. var rect = DomUtils.getWindowSize();
  18065. self.moveTo(0, 0).resizeTo(rect.w, rect.h);
  18066. }
  18067. }
  18068. return self.reflow();
  18069. },
  18070. /**
  18071. * Called after the control has been rendered.
  18072. *
  18073. * @method postRender
  18074. */
  18075. postRender: function() {
  18076. var self = this, startPos;
  18077. setTimeout(function() {
  18078. self.addClass('in');
  18079. }, 0);
  18080. self._super();
  18081. if (self.statusbar) {
  18082. self.statusbar.postRender();
  18083. }
  18084. self.focus();
  18085. this.dragHelper = new DragHelper(self._id + '-dragh', {
  18086. start: function() {
  18087. startPos = {
  18088. x: self.layoutRect().x,
  18089. y: self.layoutRect().y
  18090. };
  18091. },
  18092. drag: function(e) {
  18093. self.moveTo(startPos.x + e.deltaX, startPos.y + e.deltaY);
  18094. }
  18095. });
  18096. self.on('submit', function(e) {
  18097. if (!e.isDefaultPrevented()) {
  18098. self.close();
  18099. }
  18100. });
  18101. },
  18102. /**
  18103. * Fires a submit event with the serialized form.
  18104. *
  18105. * @method submit
  18106. * @return {Object} Event arguments object.
  18107. */
  18108. submit: function() {
  18109. return this.fire('submit', {data: this.toJSON()});
  18110. },
  18111. /**
  18112. * Removes the current control from DOM and from UI collections.
  18113. *
  18114. * @method remove
  18115. * @return {tinymce.ui.Control} Current control instance.
  18116. */
  18117. remove: function() {
  18118. var self = this, prefix = self.classPrefix;
  18119. self.dragHelper.destroy();
  18120. self._super();
  18121. if (self.statusbar) {
  18122. this.statusbar.remove();
  18123. }
  18124. if (self._fullscreen) {
  18125. DomUtils.removeClass(document.documentElement, prefix + 'fullscreen');
  18126. DomUtils.removeClass(document.body, prefix + 'fullscreen');
  18127. }
  18128. },
  18129. /**
  18130. * Returns the contentWindow object of the iframe if it exists.
  18131. *
  18132. * @method getContentWindow
  18133. * @return {Window} window object or null.
  18134. */
  18135. getContentWindow: function() {
  18136. var ifr = this.getEl().getElementsByTagName('iframe')[0];
  18137. return ifr ? ifr.contentWindow : null;
  18138. }
  18139. });
  18140. return Window;
  18141. });
  18142. // Included from: js/tinymce/classes/ui/MessageBox.js
  18143. /**
  18144. * MessageBox.js
  18145. *
  18146. * Copyright, Moxiecode Systems AB
  18147. * Released under LGPL License.
  18148. *
  18149. * License: http://www.tinymce.com/license
  18150. * Contributing: http://www.tinymce.com/contributing
  18151. */
  18152. /**
  18153. * This class is used to create MessageBoxes like alerts/confirms etc.
  18154. *
  18155. * @class tinymce.ui.Window
  18156. * @extends tinymce.ui.FloatPanel
  18157. */
  18158. define("tinymce/ui/MessageBox", [
  18159. "tinymce/ui/Window"
  18160. ], function(Window) {
  18161. "use strict";
  18162. var MessageBox = Window.extend({
  18163. /**
  18164. * Constructs a instance with the specified settings.
  18165. *
  18166. * @constructor
  18167. * @param {Object} settings Name/value object with settings.
  18168. */
  18169. init: function(settings) {
  18170. settings = {
  18171. border: 1,
  18172. padding: 20,
  18173. layout: 'flex',
  18174. pack: "center",
  18175. align: "center",
  18176. containerCls: 'panel',
  18177. autoScroll: true,
  18178. buttons: {type: "button", text: "Ok", action: "ok"},
  18179. items: {
  18180. type: "label",
  18181. multiline: true,
  18182. maxWidth: 500,
  18183. maxHeight: 200
  18184. }
  18185. };
  18186. this._super(settings);
  18187. },
  18188. Statics: {
  18189. /**
  18190. * Ok buttons constant.
  18191. *
  18192. * @static
  18193. * @final
  18194. * @field {Number} OK
  18195. */
  18196. OK: 1,
  18197. /**
  18198. * Ok/cancel buttons constant.
  18199. *
  18200. * @static
  18201. * @final
  18202. * @field {Number} OK_CANCEL
  18203. */
  18204. OK_CANCEL: 2,
  18205. /**
  18206. * yes/no buttons constant.
  18207. *
  18208. * @static
  18209. * @final
  18210. * @field {Number} YES_NO
  18211. */
  18212. YES_NO: 3,
  18213. /**
  18214. * yes/no/cancel buttons constant.
  18215. *
  18216. * @static
  18217. * @final
  18218. * @field {Number} YES_NO_CANCEL
  18219. */
  18220. YES_NO_CANCEL: 4,
  18221. /**
  18222. * Constructs a new message box and renders it to the body element.
  18223. *
  18224. * @static
  18225. * @method msgBox
  18226. * @param {Object} settings Name/value object with settings.
  18227. */
  18228. msgBox: function(settings) {
  18229. var buttons, callback = settings.callback || function() {};
  18230. switch (settings.buttons) {
  18231. case MessageBox.OK_CANCEL:
  18232. buttons = [
  18233. {type: "button", text: "Ok", subtype: "primary", onClick: function(e) {
  18234. e.control.parents()[1].close();
  18235. callback(true);
  18236. }},
  18237. {type: "button", text: "Cancel", onClick: function(e) {
  18238. e.control.parents()[1].close();
  18239. callback(false);
  18240. }}
  18241. ];
  18242. break;
  18243. case MessageBox.YES_NO:
  18244. buttons = [
  18245. {type: "button", text: "Ok", subtype: "primary", onClick: function(e) {
  18246. e.control.parents()[1].close();
  18247. callback(true);
  18248. }}
  18249. ];
  18250. break;
  18251. case MessageBox.YES_NO_CANCEL:
  18252. buttons = [
  18253. {type: "button", text: "Ok", subtype: "primary", onClick: function(e) {
  18254. e.control.parents()[1].close();
  18255. }}
  18256. ];
  18257. break;
  18258. default:
  18259. buttons = [
  18260. {type: "button", text: "Ok", subtype: "primary", onClick: function(e) {
  18261. e.control.parents()[1].close();
  18262. callback(true);
  18263. }}
  18264. ];
  18265. break;
  18266. }
  18267. return new Window({
  18268. padding: 20,
  18269. x: settings.x,
  18270. y: settings.y,
  18271. minWidth: 300,
  18272. minHeight: 100,
  18273. layout: "flex",
  18274. pack: "center",
  18275. align: "center",
  18276. buttons: buttons,
  18277. title: settings.title,
  18278. role: 'alertdialog',
  18279. items: {
  18280. type: "label",
  18281. multiline: true,
  18282. maxWidth: 500,
  18283. maxHeight: 200,
  18284. text: settings.text
  18285. },
  18286. onPostRender: function() {
  18287. this.aria('describedby', this.items()[0]._id);
  18288. },
  18289. onClose: settings.onClose,
  18290. onCancel: function() {
  18291. callback(false);
  18292. }
  18293. }).renderTo(document.body).reflow();
  18294. },
  18295. /**
  18296. * Creates a new alert dialog.
  18297. *
  18298. * @method alert
  18299. * @param {Object} settings Settings for the alert dialog.
  18300. * @param {function} [callback] Callback to execute when the user makes a choice.
  18301. */
  18302. alert: function(settings, callback) {
  18303. if (typeof(settings) == "string") {
  18304. settings = {text: settings};
  18305. }
  18306. settings.callback = callback;
  18307. return MessageBox.msgBox(settings);
  18308. },
  18309. /**
  18310. * Creates a new confirm dialog.
  18311. *
  18312. * @method confirm
  18313. * @param {Object} settings Settings for the confirm dialog.
  18314. * @param {function} [callback] Callback to execute when the user makes a choice.
  18315. */
  18316. confirm: function(settings, callback) {
  18317. if (typeof(settings) == "string") {
  18318. settings = {text: settings};
  18319. }
  18320. settings.callback = callback;
  18321. settings.buttons = MessageBox.OK_CANCEL;
  18322. return MessageBox.msgBox(settings);
  18323. }
  18324. }
  18325. });
  18326. return MessageBox;
  18327. });
  18328. // Included from: js/tinymce/classes/WindowManager.js
  18329. /**
  18330. * WindowManager.js
  18331. *
  18332. * Copyright, Moxiecode Systems AB
  18333. * Released under LGPL License.
  18334. *
  18335. * License: http://www.tinymce.com/license
  18336. * Contributing: http://www.tinymce.com/contributing
  18337. */
  18338. /**
  18339. * This class handles the creation of native windows and dialogs. This class can be extended to provide for example inline dialogs.
  18340. *
  18341. * @class tinymce.WindowManager
  18342. * @example
  18343. * // Opens a new dialog with the file.htm file and the size 320x240
  18344. * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog.
  18345. * tinymce.activeEditor.windowManager.open({
  18346. * url: 'file.htm',
  18347. * width: 320,
  18348. * height: 240
  18349. * }, {
  18350. * custom_param: 1
  18351. * });
  18352. *
  18353. * // Displays an alert box using the active editors window manager instance
  18354. * tinymce.activeEditor.windowManager.alert('Hello world!');
  18355. *
  18356. * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm
  18357. * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) {
  18358. * if (s)
  18359. * tinymce.activeEditor.windowManager.alert("Ok");
  18360. * else
  18361. * tinymce.activeEditor.windowManager.alert("Cancel");
  18362. * });
  18363. */
  18364. define("tinymce/WindowManager", [
  18365. "tinymce/ui/Window",
  18366. "tinymce/ui/MessageBox"
  18367. ], function(Window, MessageBox) {
  18368. return function(editor) {
  18369. var self = this, windows = [];
  18370. function getTopMostWindow() {
  18371. if (windows.length) {
  18372. return windows[windows.length - 1];
  18373. }
  18374. }
  18375. self.windows = windows;
  18376. /**
  18377. * Opens a new window.
  18378. *
  18379. * @method open
  18380. * @param {Object} args Optional name/value settings collection contains things like width/height/url etc.
  18381. * @option {String} title Window title.
  18382. * @option {String} file URL of the file to open in the window.
  18383. * @option {Number} width Width in pixels.
  18384. * @option {Number} height Height in pixels.
  18385. * @option {Boolean} resizable Specifies whether the popup window is resizable or not.
  18386. * @option {Boolean} maximizable Specifies whether the popup window has a "maximize" button and can get maximized or not.
  18387. * @option {String/Boolean} scrollbars Specifies whether the popup window can have scrollbars if required (i.e. content
  18388. * larger than the popup size specified).
  18389. */
  18390. self.open = function(args, params) {
  18391. var win;
  18392. editor.editorManager.activeEditor = editor;
  18393. args.title = args.title || ' ';
  18394. // Handle URL
  18395. args.url = args.url || args.file; // Legacy
  18396. if (args.url) {
  18397. args.width = parseInt(args.width || 320, 10);
  18398. args.height = parseInt(args.height || 240, 10);
  18399. }
  18400. // Handle body
  18401. if (args.body) {
  18402. args.items = {
  18403. defaults: args.defaults,
  18404. type: args.bodyType || 'form',
  18405. items: args.body
  18406. };
  18407. }
  18408. if (!args.url && !args.buttons) {
  18409. args.buttons = [
  18410. {text: 'Ok', subtype: 'primary', onclick: function() {
  18411. win.find('form')[0].submit();
  18412. }},
  18413. {text: 'Cancel', onclick: function() {
  18414. win.close();
  18415. }}
  18416. ];
  18417. }
  18418. win = new Window(args);
  18419. windows.push(win);
  18420. win.on('close', function() {
  18421. var i = windows.length;
  18422. while (i--) {
  18423. if (windows[i] === win) {
  18424. windows.splice(i, 1);
  18425. }
  18426. }
  18427. editor.focus();
  18428. });
  18429. // Handle data
  18430. if (args.data) {
  18431. win.on('postRender', function() {
  18432. this.find('*').each(function(ctrl) {
  18433. var name = ctrl.name();
  18434. if (name in args.data) {
  18435. ctrl.value(args.data[name]);
  18436. }
  18437. });
  18438. });
  18439. }
  18440. // store args and parameters
  18441. win.features = args || {};
  18442. win.params = params || {};
  18443. // Takes a snapshot in the FocusManager of the selection before focus is lost to dialog
  18444. editor.nodeChanged();
  18445. return win.renderTo().reflow();
  18446. };
  18447. /**
  18448. * Creates a alert dialog. Please don't use the blocking behavior of this
  18449. * native version use the callback method instead then it can be extended.
  18450. *
  18451. * @method alert
  18452. * @param {String} message Text to display in the new alert dialog.
  18453. * @param {function} callback Callback function to be executed after the user has selected ok.
  18454. * @param {Object} scope Optional scope to execute the callback in.
  18455. * @example
  18456. * // Displays an alert box using the active editors window manager instance
  18457. * tinymce.activeEditor.windowManager.alert('Hello world!');
  18458. */
  18459. self.alert = function(message, callback, scope) {
  18460. MessageBox.alert(message, function() {
  18461. if (callback) {
  18462. callback.call(scope || this);
  18463. } else {
  18464. editor.focus();
  18465. }
  18466. });
  18467. };
  18468. /**
  18469. * Creates a confirm dialog. Please don't use the blocking behavior of this
  18470. * native version use the callback method instead then it can be extended.
  18471. *
  18472. * @method confirm
  18473. * @param {String} messageText to display in the new confirm dialog.
  18474. * @param {function} callback Callback function to be executed after the user has selected ok or cancel.
  18475. * @param {Object} scope Optional scope to execute the callback in.
  18476. * @example
  18477. * // Displays an confirm box and an alert message will be displayed depending on what you choose in the confirm
  18478. * tinymce.activeEditor.windowManager.confirm("Do you want to do something", function(s) {
  18479. * if (s)
  18480. * tinymce.activeEditor.windowManager.alert("Ok");
  18481. * else
  18482. * tinymce.activeEditor.windowManager.alert("Cancel");
  18483. * });
  18484. */
  18485. self.confirm = function(message, callback, scope) {
  18486. MessageBox.confirm(message, function(state) {
  18487. callback.call(scope || this, state);
  18488. });
  18489. };
  18490. /**
  18491. * Closes the top most window.
  18492. *
  18493. * @method close
  18494. */
  18495. self.close = function() {
  18496. if (getTopMostWindow()) {
  18497. getTopMostWindow().close();
  18498. }
  18499. };
  18500. /**
  18501. * Returns the params of the last window open call. This can be used in iframe based
  18502. * dialog to get params passed from the tinymce plugin.
  18503. *
  18504. * @example
  18505. * var dialogArguments = top.tinymce.activeEditor.windowManager.getParams();
  18506. *
  18507. * @method getParams
  18508. * @return {Object} Name/value object with parameters passed from windowManager.open call.
  18509. */
  18510. self.getParams = function() {
  18511. return getTopMostWindow() ? getTopMostWindow().params : null;
  18512. };
  18513. /**
  18514. * Sets the params of the last opened window.
  18515. *
  18516. * @method setParams
  18517. * @param {Object} params Params object to set for the last opened window.
  18518. */
  18519. self.setParams = function(params) {
  18520. if (getTopMostWindow()) {
  18521. getTopMostWindow().params = params;
  18522. }
  18523. };
  18524. /**
  18525. * Returns the currently opened window objects.
  18526. *
  18527. * @method getWindows
  18528. * @return {Array} Array of the currently opened windows.
  18529. */
  18530. self.getWindows = function() {
  18531. return windows;
  18532. };
  18533. };
  18534. });
  18535. // Included from: js/tinymce/classes/util/Quirks.js
  18536. /**
  18537. * Quirks.js
  18538. *
  18539. * Copyright, Moxiecode Systems AB
  18540. * Released under LGPL License.
  18541. *
  18542. * License: http://www.tinymce.com/license
  18543. * Contributing: http://www.tinymce.com/contributing
  18544. *
  18545. * @ignore-file
  18546. */
  18547. /**
  18548. * This file includes fixes for various browser quirks it's made to make it easy to add/remove browser specific fixes.
  18549. *
  18550. * @class tinymce.util.Quirks
  18551. */
  18552. define("tinymce/util/Quirks", [
  18553. "tinymce/util/VK",
  18554. "tinymce/dom/RangeUtils",
  18555. "tinymce/html/Node",
  18556. "tinymce/html/Entities",
  18557. "tinymce/Env",
  18558. "tinymce/util/Tools"
  18559. ], function(VK, RangeUtils, Node, Entities, Env, Tools) {
  18560. return function(editor) {
  18561. var each = Tools.each;
  18562. var BACKSPACE = VK.BACKSPACE, DELETE = VK.DELETE, dom = editor.dom, selection = editor.selection,
  18563. settings = editor.settings, parser = editor.parser, serializer = editor.serializer;
  18564. var isGecko = Env.gecko, isIE = Env.ie, isWebKit = Env.webkit;
  18565. /**
  18566. * Executes a command with a specific state this can be to enable/disable browser editing features.
  18567. */
  18568. function setEditorCommandState(cmd, state) {
  18569. try {
  18570. editor.getDoc().execCommand(cmd, false, state);
  18571. } catch (ex) {
  18572. // Ignore
  18573. }
  18574. }
  18575. /**
  18576. * Returns current IE document mode.
  18577. */
  18578. function getDocumentMode() {
  18579. var documentMode = editor.getDoc().documentMode;
  18580. return documentMode ? documentMode : 6;
  18581. }
  18582. /**
  18583. * Returns true/false if the event is prevented or not.
  18584. *
  18585. * @private
  18586. * @param {Event} e Event object.
  18587. * @return {Boolean} true/false if the event is prevented or not.
  18588. */
  18589. function isDefaultPrevented(e) {
  18590. return e.isDefaultPrevented();
  18591. }
  18592. /**
  18593. * Fixes a WebKit bug when deleting contents using backspace or delete key.
  18594. * WebKit will produce a span element if you delete across two block elements.
  18595. *
  18596. * Example:
  18597. * <h1>a</h1><p>|b</p>
  18598. *
  18599. * Will produce this on backspace:
  18600. * <h1>a<span style="<all runtime styles>">b</span></p>
  18601. *
  18602. * This fixes the backspace to produce:
  18603. * <h1>a|b</p>
  18604. *
  18605. * See bug: https://bugs.webkit.org/show_bug.cgi?id=45784
  18606. *
  18607. * This fixes the following delete scenarios:
  18608. * 1. Delete by pressing backspace key.
  18609. * 2. Delete by pressing delete key.
  18610. * 3. Delete by pressing backspace key with ctrl/cmd (Word delete).
  18611. * 4. Delete by pressing delete key with ctrl/cmd (Word delete).
  18612. * 5. Delete by drag/dropping contents inside the editor.
  18613. * 6. Delete by using Cut Ctrl+X/Cmd+X.
  18614. * 7. Delete by selecting contents and writing a character.'
  18615. *
  18616. * This code is a ugly hack since writing full custom delete logic for just this bug
  18617. * fix seemed like a huge task. I hope we can remove this before the year 2030.
  18618. */
  18619. function cleanupStylesWhenDeleting() {
  18620. var doc = editor.getDoc(), urlPrefix = 'data:text/mce-internal,';
  18621. var MutationObserver = window.MutationObserver, olderWebKit, dragStartRng;
  18622. // Add mini polyfill for older WebKits
  18623. // TODO: Remove this when old Safari versions gets updated
  18624. if (!MutationObserver) {
  18625. olderWebKit = true;
  18626. MutationObserver = function() {
  18627. var records = [], target;
  18628. function nodeInsert(e) {
  18629. var target = e.relatedNode || e.target;
  18630. records.push({target: target, addedNodes: [target]});
  18631. }
  18632. function attrModified(e) {
  18633. var target = e.relatedNode || e.target;
  18634. records.push({target: target, attributeName: e.attrName});
  18635. }
  18636. this.observe = function(node) {
  18637. target = node;
  18638. target.addEventListener('DOMSubtreeModified', nodeInsert, false);
  18639. target.addEventListener('DOMNodeInsertedIntoDocument', nodeInsert, false);
  18640. target.addEventListener('DOMNodeInserted', nodeInsert, false);
  18641. target.addEventListener('DOMAttrModified', attrModified, false);
  18642. };
  18643. this.disconnect = function() {
  18644. target.removeEventListener('DOMNodeInserted', nodeInsert);
  18645. target.removeEventListener('DOMAttrModified', attrModified);
  18646. target.removeEventListener('DOMSubtreeModified', nodeInsert, false);
  18647. };
  18648. this.takeRecords = function() {
  18649. return records;
  18650. };
  18651. };
  18652. }
  18653. function customDelete(isForward) {
  18654. var mutationObserver = new MutationObserver(function() {});
  18655. Tools.each(editor.getBody().getElementsByTagName('*'), function(elm) {
  18656. // Mark existing spans
  18657. if (elm.tagName == 'SPAN') {
  18658. elm.setAttribute('mce-data-marked', 1);
  18659. }
  18660. // Make sure all elements has a data-mce-style attribute
  18661. if (!elm.hasAttribute('data-mce-style') && elm.hasAttribute('style')) {
  18662. editor.dom.setAttrib(elm, 'style', elm.getAttribute('style'));
  18663. }
  18664. });
  18665. // Observe added nodes and style attribute changes
  18666. mutationObserver.observe(editor.getDoc(), {
  18667. childList: true,
  18668. attributes: true,
  18669. subtree: true,
  18670. attributeFilter: ['style']
  18671. });
  18672. editor.getDoc().execCommand(isForward ? 'ForwardDelete' : 'Delete', false, null);
  18673. var rng = editor.selection.getRng();
  18674. var caretElement = rng.startContainer.parentNode;
  18675. Tools.each(mutationObserver.takeRecords(), function(record) {
  18676. // Restore style attribute to previous value
  18677. if (record.attributeName == "style") {
  18678. var oldValue = record.target.getAttribute('data-mce-style');
  18679. if (oldValue) {
  18680. record.target.setAttribute("style", oldValue);
  18681. } else {
  18682. record.target.removeAttribute("style");
  18683. }
  18684. }
  18685. // Remove all spans that isn't maked and retain selection
  18686. Tools.each(record.addedNodes, function(node) {
  18687. if (node.nodeName == "SPAN" && !node.getAttribute('mce-data-marked')) {
  18688. var offset, container;
  18689. if (node == caretElement) {
  18690. offset = rng.startOffset;
  18691. container = node.firstChild;
  18692. }
  18693. dom.remove(node, true);
  18694. if (container) {
  18695. rng.setStart(container, offset);
  18696. rng.setEnd(container, offset);
  18697. editor.selection.setRng(rng);
  18698. }
  18699. }
  18700. });
  18701. });
  18702. mutationObserver.disconnect();
  18703. // Remove any left over marks
  18704. Tools.each(editor.dom.select('span[mce-data-marked]'), function(span) {
  18705. span.removeAttribute('mce-data-marked');
  18706. });
  18707. }
  18708. editor.on('keydown', function(e) {
  18709. var isForward = e.keyCode == DELETE, isMeta = VK.metaKeyPressed(e);
  18710. if (!isDefaultPrevented(e) && (isForward || e.keyCode == BACKSPACE)) {
  18711. var rng = editor.selection.getRng(), container = rng.startContainer, offset = rng.startOffset;
  18712. // Ignore non meta delete in the where there is text before/after the caret
  18713. if (!isMeta && rng.collapsed && container.nodeType == 3) {
  18714. if (isForward ? offset < container.data.length : offset > 0) {
  18715. return;
  18716. }
  18717. }
  18718. e.preventDefault();
  18719. if (isMeta) {
  18720. editor.selection.getSel().modify("extend", isForward ? "forward" : "backward", "word");
  18721. }
  18722. customDelete(isForward);
  18723. }
  18724. });
  18725. editor.on('keypress', function(e) {
  18726. if (!isDefaultPrevented(e) && !selection.isCollapsed() && e.charCode && !VK.metaKeyPressed(e)) {
  18727. e.preventDefault();
  18728. customDelete(true);
  18729. editor.selection.setContent(String.fromCharCode(e.charCode));
  18730. }
  18731. });
  18732. editor.addCommand('Delete', function() {
  18733. customDelete();
  18734. });
  18735. editor.addCommand('ForwardDelete', function() {
  18736. customDelete(true);
  18737. });
  18738. // Older WebKits doesn't properly handle the clipboard so we can't add the rest
  18739. if (olderWebKit) {
  18740. return;
  18741. }
  18742. editor.on('dragstart', function(e) {
  18743. var selectionHtml;
  18744. if (editor.selection.isCollapsed() && e.target.tagName == 'IMG') {
  18745. selection.select(e.target);
  18746. }
  18747. dragStartRng = selection.getRng();
  18748. selectionHtml = editor.selection.getContent();
  18749. // Safari doesn't support custom dataTransfer items so we can only use URL and Text
  18750. if (selectionHtml.length > 0) {
  18751. e.dataTransfer.setData('URL', 'data:text/mce-internal,' + escape(selectionHtml));
  18752. }
  18753. });
  18754. editor.on('drop', function(e) {
  18755. if (!isDefaultPrevented(e)) {
  18756. var internalContent = e.dataTransfer.getData('URL');
  18757. if (!internalContent || internalContent.indexOf(urlPrefix) == -1 || !doc.caretRangeFromPoint) {
  18758. return;
  18759. }
  18760. internalContent = unescape(internalContent.substr(urlPrefix.length));
  18761. if (doc.caretRangeFromPoint) {
  18762. e.preventDefault();
  18763. // Safari has a weird issue where drag/dropping images sometimes
  18764. // produces a green plus icon. When this happens the caretRangeFromPoint
  18765. // will return "null" even though the x, y coordinate is correct.
  18766. // But if we detach the insert from the drop event we will get a proper range
  18767. window.setTimeout(function() {
  18768. var pointRng = doc.caretRangeFromPoint(e.x, e.y);
  18769. if (dragStartRng) {
  18770. selection.setRng(dragStartRng);
  18771. dragStartRng = null;
  18772. }
  18773. customDelete();
  18774. selection.setRng(pointRng);
  18775. editor.insertContent(internalContent);
  18776. }, 0);
  18777. }
  18778. }
  18779. });
  18780. editor.on('cut', function(e) {
  18781. if (!isDefaultPrevented(e) && e.clipboardData) {
  18782. e.preventDefault();
  18783. e.clipboardData.clearData();
  18784. e.clipboardData.setData('text/html', editor.selection.getContent());
  18785. e.clipboardData.setData('text/plain', editor.selection.getContent({format: 'text'}));
  18786. customDelete(true);
  18787. }
  18788. });
  18789. }
  18790. /**
  18791. * Makes sure that the editor body becomes empty when backspace or delete is pressed in empty editors.
  18792. *
  18793. * For example:
  18794. * <p><b>|</b></p>
  18795. *
  18796. * Or:
  18797. * <h1>|</h1>
  18798. *
  18799. * Or:
  18800. * [<h1></h1>]
  18801. */
  18802. function emptyEditorWhenDeleting() {
  18803. function serializeRng(rng) {
  18804. var body = dom.create("body");
  18805. var contents = rng.cloneContents();
  18806. body.appendChild(contents);
  18807. return selection.serializer.serialize(body, {format: 'html'});
  18808. }
  18809. function allContentsSelected(rng) {
  18810. if (!rng.setStart) {
  18811. if (rng.item) {
  18812. return false;
  18813. }
  18814. var bodyRng = rng.duplicate();
  18815. bodyRng.moveToElementText(editor.getBody());
  18816. return RangeUtils.compareRanges(rng, bodyRng);
  18817. }
  18818. var selection = serializeRng(rng);
  18819. var allRng = dom.createRng();
  18820. allRng.selectNode(editor.getBody());
  18821. var allSelection = serializeRng(allRng);
  18822. return selection === allSelection;
  18823. }
  18824. editor.on('keydown', function(e) {
  18825. var keyCode = e.keyCode, isCollapsed, body;
  18826. // Empty the editor if it's needed for example backspace at <p><b>|</b></p>
  18827. if (!isDefaultPrevented(e) && (keyCode == DELETE || keyCode == BACKSPACE)) {
  18828. isCollapsed = editor.selection.isCollapsed();
  18829. body = editor.getBody();
  18830. // Selection is collapsed but the editor isn't empty
  18831. if (isCollapsed && !dom.isEmpty(body)) {
  18832. return;
  18833. }
  18834. // Selection isn't collapsed but not all the contents is selected
  18835. if (!isCollapsed && !allContentsSelected(editor.selection.getRng())) {
  18836. return;
  18837. }
  18838. // Manually empty the editor
  18839. e.preventDefault();
  18840. editor.setContent('');
  18841. if (body.firstChild && dom.isBlock(body.firstChild)) {
  18842. editor.selection.setCursorLocation(body.firstChild, 0);
  18843. } else {
  18844. editor.selection.setCursorLocation(body, 0);
  18845. }
  18846. editor.nodeChanged();
  18847. }
  18848. });
  18849. }
  18850. /**
  18851. * WebKit doesn't select all the nodes in the body when you press Ctrl+A.
  18852. * IE selects more than the contents <body>[<p>a</p>]</body> instead of <body><p>[a]</p]</body> see bug #6438
  18853. * This selects the whole body so that backspace/delete logic will delete everything
  18854. */
  18855. function selectAll() {
  18856. editor.on('keydown', function(e) {
  18857. if (!isDefaultPrevented(e) && e.keyCode == 65 && VK.metaKeyPressed(e)) {
  18858. e.preventDefault();
  18859. editor.execCommand('SelectAll');
  18860. }
  18861. });
  18862. }
  18863. /**
  18864. * WebKit has a weird issue where it some times fails to properly convert keypresses to input method keystrokes.
  18865. * The IME on Mac doesn't initialize when it doesn't fire a proper focus event.
  18866. *
  18867. * This seems to happen when the user manages to click the documentElement element then the window doesn't get proper focus until
  18868. * you enter a character into the editor.
  18869. *
  18870. * It also happens when the first focus in made to the body.
  18871. *
  18872. * See: https://bugs.webkit.org/show_bug.cgi?id=83566
  18873. */
  18874. function inputMethodFocus() {
  18875. if (!editor.settings.content_editable) {
  18876. // Case 1 IME doesn't initialize if you focus the document
  18877. dom.bind(editor.getDoc(), 'focusin', function() {
  18878. selection.setRng(selection.getRng());
  18879. });
  18880. // Case 2 IME doesn't initialize if you click the documentElement it also doesn't properly fire the focusin event
  18881. dom.bind(editor.getDoc(), 'mousedown', function(e) {
  18882. if (e.target == editor.getDoc().documentElement) {
  18883. editor.getBody().focus();
  18884. selection.setRng(selection.getRng());
  18885. }
  18886. });
  18887. }
  18888. }
  18889. /**
  18890. * Backspacing in FireFox/IE from a paragraph into a horizontal rule results in a floating text node because the
  18891. * browser just deletes the paragraph - the browser fails to merge the text node with a horizontal rule so it is
  18892. * left there. TinyMCE sees a floating text node and wraps it in a paragraph on the key up event (ForceBlocks.js
  18893. * addRootBlocks), meaning the action does nothing. With this code, FireFox/IE matche the behaviour of other
  18894. * browsers.
  18895. *
  18896. * It also fixes a bug on Firefox where it's impossible to delete HR elements.
  18897. */
  18898. function removeHrOnBackspace() {
  18899. editor.on('keydown', function(e) {
  18900. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  18901. if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) {
  18902. var node = selection.getNode();
  18903. var previousSibling = node.previousSibling;
  18904. if (node.nodeName == 'HR') {
  18905. dom.remove(node);
  18906. e.preventDefault();
  18907. return;
  18908. }
  18909. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "hr") {
  18910. dom.remove(previousSibling);
  18911. e.preventDefault();
  18912. }
  18913. }
  18914. }
  18915. });
  18916. }
  18917. /**
  18918. * Firefox 3.x has an issue where the body element won't get proper focus if you click out
  18919. * side it's rectangle.
  18920. */
  18921. function focusBody() {
  18922. // Fix for a focus bug in FF 3.x where the body element
  18923. // wouldn't get proper focus if the user clicked on the HTML element
  18924. if (!window.Range.prototype.getClientRects) { // Detect getClientRects got introduced in FF 4
  18925. editor.on('mousedown', function(e) {
  18926. if (!isDefaultPrevented(e) && e.target.nodeName === "HTML") {
  18927. var body = editor.getBody();
  18928. // Blur the body it's focused but not correctly focused
  18929. body.blur();
  18930. // Refocus the body after a little while
  18931. setTimeout(function() {
  18932. body.focus();
  18933. }, 0);
  18934. }
  18935. });
  18936. }
  18937. }
  18938. /**
  18939. * WebKit has a bug where it isn't possible to select image, hr or anchor elements
  18940. * by clicking on them so we need to fake that.
  18941. */
  18942. function selectControlElements() {
  18943. editor.on('click', function(e) {
  18944. e = e.target;
  18945. // Workaround for bug, http://bugs.webkit.org/show_bug.cgi?id=12250
  18946. // WebKit can't even do simple things like selecting an image
  18947. // Needs tobe the setBaseAndExtend or it will fail to select floated images
  18948. if (/^(IMG|HR)$/.test(e.nodeName)) {
  18949. selection.getSel().setBaseAndExtent(e, 0, e, 1);
  18950. }
  18951. if (e.nodeName == 'A' && dom.hasClass(e, 'mce-item-anchor')) {
  18952. selection.select(e);
  18953. }
  18954. editor.nodeChanged();
  18955. });
  18956. }
  18957. /**
  18958. * Fixes a Gecko bug where the style attribute gets added to the wrong element when deleting between two block elements.
  18959. *
  18960. * Fixes do backspace/delete on this:
  18961. * <p>bla[ck</p><p style="color:red">r]ed</p>
  18962. *
  18963. * Would become:
  18964. * <p>bla|ed</p>
  18965. *
  18966. * Instead of:
  18967. * <p style="color:red">bla|ed</p>
  18968. */
  18969. function removeStylesWhenDeletingAcrossBlockElements() {
  18970. function getAttributeApplyFunction() {
  18971. var template = dom.getAttribs(selection.getStart().cloneNode(false));
  18972. return function() {
  18973. var target = selection.getStart();
  18974. if (target !== editor.getBody()) {
  18975. dom.setAttrib(target, "style", null);
  18976. each(template, function(attr) {
  18977. target.setAttributeNode(attr.cloneNode(true));
  18978. });
  18979. }
  18980. };
  18981. }
  18982. function isSelectionAcrossElements() {
  18983. return !selection.isCollapsed() &&
  18984. dom.getParent(selection.getStart(), dom.isBlock) != dom.getParent(selection.getEnd(), dom.isBlock);
  18985. }
  18986. editor.on('keypress', function(e) {
  18987. var applyAttributes;
  18988. if (!isDefaultPrevented(e) && (e.keyCode == 8 || e.keyCode == 46) && isSelectionAcrossElements()) {
  18989. applyAttributes = getAttributeApplyFunction();
  18990. editor.getDoc().execCommand('delete', false, null);
  18991. applyAttributes();
  18992. e.preventDefault();
  18993. return false;
  18994. }
  18995. });
  18996. dom.bind(editor.getDoc(), 'cut', function(e) {
  18997. var applyAttributes;
  18998. if (!isDefaultPrevented(e) && isSelectionAcrossElements()) {
  18999. applyAttributes = getAttributeApplyFunction();
  19000. setTimeout(function() {
  19001. applyAttributes();
  19002. }, 0);
  19003. }
  19004. });
  19005. }
  19006. /**
  19007. * Fire a nodeChanged when the selection is changed on WebKit this fixes selection issues on iOS5. It only fires the nodeChange
  19008. * event every 50ms since it would other wise update the UI when you type and it hogs the CPU.
  19009. */
  19010. function selectionChangeNodeChanged() {
  19011. var lastRng, selectionTimer;
  19012. editor.on('selectionchange', function() {
  19013. if (selectionTimer) {
  19014. clearTimeout(selectionTimer);
  19015. selectionTimer = 0;
  19016. }
  19017. selectionTimer = window.setTimeout(function() {
  19018. if (editor.removed) {
  19019. return;
  19020. }
  19021. var rng = selection.getRng();
  19022. // Compare the ranges to see if it was a real change or not
  19023. if (!lastRng || !RangeUtils.compareRanges(rng, lastRng)) {
  19024. editor.nodeChanged();
  19025. lastRng = rng;
  19026. }
  19027. }, 50);
  19028. });
  19029. }
  19030. /**
  19031. * Screen readers on IE needs to have the role application set on the body.
  19032. */
  19033. function ensureBodyHasRoleApplication() {
  19034. document.body.setAttribute("role", "application");
  19035. }
  19036. /**
  19037. * Backspacing into a table behaves differently depending upon browser type.
  19038. * Therefore, disable Backspace when cursor immediately follows a table.
  19039. */
  19040. function disableBackspaceIntoATable() {
  19041. editor.on('keydown', function(e) {
  19042. if (!isDefaultPrevented(e) && e.keyCode === BACKSPACE) {
  19043. if (selection.isCollapsed() && selection.getRng(true).startOffset === 0) {
  19044. var previousSibling = selection.getNode().previousSibling;
  19045. if (previousSibling && previousSibling.nodeName && previousSibling.nodeName.toLowerCase() === "table") {
  19046. e.preventDefault();
  19047. return false;
  19048. }
  19049. }
  19050. }
  19051. });
  19052. }
  19053. /**
  19054. * Old IE versions can't properly render BR elements in PRE tags white in contentEditable mode. So this
  19055. * logic adds a \n before the BR so that it will get rendered.
  19056. */
  19057. function addNewLinesBeforeBrInPre() {
  19058. // IE8+ rendering mode does the right thing with BR in PRE
  19059. if (getDocumentMode() > 7) {
  19060. return;
  19061. }
  19062. // Enable display: none in area and add a specific class that hides all BR elements in PRE to
  19063. // avoid the caret from getting stuck at the BR elements while pressing the right arrow key
  19064. setEditorCommandState('RespectVisibilityInDesign', true);
  19065. editor.contentStyles.push('.mceHideBrInPre pre br {display: none}');
  19066. dom.addClass(editor.getBody(), 'mceHideBrInPre');
  19067. // Adds a \n before all BR elements in PRE to get them visual
  19068. parser.addNodeFilter('pre', function(nodes) {
  19069. var i = nodes.length, brNodes, j, brElm, sibling;
  19070. while (i--) {
  19071. brNodes = nodes[i].getAll('br');
  19072. j = brNodes.length;
  19073. while (j--) {
  19074. brElm = brNodes[j];
  19075. // Add \n before BR in PRE elements on older IE:s so the new lines get rendered
  19076. sibling = brElm.prev;
  19077. if (sibling && sibling.type === 3 && sibling.value.charAt(sibling.value - 1) != '\n') {
  19078. sibling.value += '\n';
  19079. } else {
  19080. brElm.parent.insert(new Node('#text', 3), brElm, true).value = '\n';
  19081. }
  19082. }
  19083. }
  19084. });
  19085. // Removes any \n before BR elements in PRE since other browsers and in contentEditable=false mode they will be visible
  19086. serializer.addNodeFilter('pre', function(nodes) {
  19087. var i = nodes.length, brNodes, j, brElm, sibling;
  19088. while (i--) {
  19089. brNodes = nodes[i].getAll('br');
  19090. j = brNodes.length;
  19091. while (j--) {
  19092. brElm = brNodes[j];
  19093. sibling = brElm.prev;
  19094. if (sibling && sibling.type == 3) {
  19095. sibling.value = sibling.value.replace(/\r?\n$/, '');
  19096. }
  19097. }
  19098. }
  19099. });
  19100. }
  19101. /**
  19102. * Moves style width/height to attribute width/height when the user resizes an image on IE.
  19103. */
  19104. function removePreSerializedStylesWhenSelectingControls() {
  19105. dom.bind(editor.getBody(), 'mouseup', function() {
  19106. var value, node = selection.getNode();
  19107. // Moved styles to attributes on IMG eements
  19108. if (node.nodeName == 'IMG') {
  19109. // Convert style width to width attribute
  19110. if ((value = dom.getStyle(node, 'width'))) {
  19111. dom.setAttrib(node, 'width', value.replace(/[^0-9%]+/g, ''));
  19112. dom.setStyle(node, 'width', '');
  19113. }
  19114. // Convert style height to height attribute
  19115. if ((value = dom.getStyle(node, 'height'))) {
  19116. dom.setAttrib(node, 'height', value.replace(/[^0-9%]+/g, ''));
  19117. dom.setStyle(node, 'height', '');
  19118. }
  19119. }
  19120. });
  19121. }
  19122. /**
  19123. * Removes a blockquote when backspace is pressed at the beginning of it.
  19124. *
  19125. * For example:
  19126. * <blockquote><p>|x</p></blockquote>
  19127. *
  19128. * Becomes:
  19129. * <p>|x</p>
  19130. */
  19131. function removeBlockQuoteOnBackSpace() {
  19132. // Add block quote deletion handler
  19133. editor.on('keydown', function(e) {
  19134. var rng, container, offset, root, parent;
  19135. if (isDefaultPrevented(e) || e.keyCode != VK.BACKSPACE) {
  19136. return;
  19137. }
  19138. rng = selection.getRng();
  19139. container = rng.startContainer;
  19140. offset = rng.startOffset;
  19141. root = dom.getRoot();
  19142. parent = container;
  19143. if (!rng.collapsed || offset !== 0) {
  19144. return;
  19145. }
  19146. while (parent && parent.parentNode && parent.parentNode.firstChild == parent && parent.parentNode != root) {
  19147. parent = parent.parentNode;
  19148. }
  19149. // Is the cursor at the beginning of a blockquote?
  19150. if (parent.tagName === 'BLOCKQUOTE') {
  19151. // Remove the blockquote
  19152. editor.formatter.toggle('blockquote', null, parent);
  19153. // Move the caret to the beginning of container
  19154. rng = dom.createRng();
  19155. rng.setStart(container, 0);
  19156. rng.setEnd(container, 0);
  19157. selection.setRng(rng);
  19158. }
  19159. });
  19160. }
  19161. /**
  19162. * Sets various Gecko editing options on mouse down and before a execCommand to disable inline table editing that is broken etc.
  19163. */
  19164. function setGeckoEditingOptions() {
  19165. function setOpts() {
  19166. editor._refreshContentEditable();
  19167. setEditorCommandState("StyleWithCSS", false);
  19168. setEditorCommandState("enableInlineTableEditing", false);
  19169. if (!settings.object_resizing) {
  19170. setEditorCommandState("enableObjectResizing", false);
  19171. }
  19172. }
  19173. if (!settings.readonly) {
  19174. editor.on('BeforeExecCommand MouseDown', setOpts);
  19175. }
  19176. }
  19177. /**
  19178. * Fixes a gecko link bug, when a link is placed at the end of block elements there is
  19179. * no way to move the caret behind the link. This fix adds a bogus br element after the link.
  19180. *
  19181. * For example this:
  19182. * <p><b><a href="#">x</a></b></p>
  19183. *
  19184. * Becomes this:
  19185. * <p><b><a href="#">x</a></b><br></p>
  19186. */
  19187. function addBrAfterLastLinks() {
  19188. function fixLinks() {
  19189. each(dom.select('a'), function(node) {
  19190. var parentNode = node.parentNode, root = dom.getRoot();
  19191. if (parentNode.lastChild === node) {
  19192. while (parentNode && !dom.isBlock(parentNode)) {
  19193. if (parentNode.parentNode.lastChild !== parentNode || parentNode === root) {
  19194. return;
  19195. }
  19196. parentNode = parentNode.parentNode;
  19197. }
  19198. dom.add(parentNode, 'br', {'data-mce-bogus': 1});
  19199. }
  19200. });
  19201. }
  19202. editor.on('SetContent ExecCommand', function(e) {
  19203. if (e.type == "setcontent" || e.command === 'mceInsertLink') {
  19204. fixLinks();
  19205. }
  19206. });
  19207. }
  19208. /**
  19209. * WebKit will produce DIV elements here and there by default. But since TinyMCE uses paragraphs by
  19210. * default we want to change that behavior.
  19211. */
  19212. function setDefaultBlockType() {
  19213. if (settings.forced_root_block) {
  19214. editor.on('init', function() {
  19215. setEditorCommandState('DefaultParagraphSeparator', settings.forced_root_block);
  19216. });
  19217. }
  19218. }
  19219. /**
  19220. * Removes ghost selections from images/tables on Gecko.
  19221. */
  19222. function removeGhostSelection() {
  19223. editor.on('Undo Redo SetContent', function(e) {
  19224. if (!e.initial) {
  19225. editor.execCommand('mceRepaint');
  19226. }
  19227. });
  19228. }
  19229. /**
  19230. * Deletes the selected image on IE instead of navigating to previous page.
  19231. */
  19232. function deleteControlItemOnBackSpace() {
  19233. editor.on('keydown', function(e) {
  19234. var rng;
  19235. if (!isDefaultPrevented(e) && e.keyCode == BACKSPACE) {
  19236. rng = editor.getDoc().selection.createRange();
  19237. if (rng && rng.item) {
  19238. e.preventDefault();
  19239. editor.undoManager.beforeChange();
  19240. dom.remove(rng.item(0));
  19241. editor.undoManager.add();
  19242. }
  19243. }
  19244. });
  19245. }
  19246. /**
  19247. * IE10 doesn't properly render block elements with the right height until you add contents to them.
  19248. * This fixes that by adding a padding-right to all empty text block elements.
  19249. * See: https://connect.microsoft.com/IE/feedback/details/743881
  19250. */
  19251. function renderEmptyBlocksFix() {
  19252. var emptyBlocksCSS;
  19253. // IE10+
  19254. if (getDocumentMode() >= 10) {
  19255. emptyBlocksCSS = '';
  19256. each('p div h1 h2 h3 h4 h5 h6'.split(' '), function(name, i) {
  19257. emptyBlocksCSS += (i > 0 ? ',' : '') + name + ':empty';
  19258. });
  19259. editor.contentStyles.push(emptyBlocksCSS + '{padding-right: 1px !important}');
  19260. }
  19261. }
  19262. /**
  19263. * Old IE versions can't retain contents within noscript elements so this logic will store the contents
  19264. * as a attribute and the insert that value as it's raw text when the DOM is serialized.
  19265. */
  19266. function keepNoScriptContents() {
  19267. if (getDocumentMode() < 9) {
  19268. parser.addNodeFilter('noscript', function(nodes) {
  19269. var i = nodes.length, node, textNode;
  19270. while (i--) {
  19271. node = nodes[i];
  19272. textNode = node.firstChild;
  19273. if (textNode) {
  19274. node.attr('data-mce-innertext', textNode.value);
  19275. }
  19276. }
  19277. });
  19278. serializer.addNodeFilter('noscript', function(nodes) {
  19279. var i = nodes.length, node, textNode, value;
  19280. while (i--) {
  19281. node = nodes[i];
  19282. textNode = nodes[i].firstChild;
  19283. if (textNode) {
  19284. textNode.value = Entities.decode(textNode.value);
  19285. } else {
  19286. // Old IE can't retain noscript value so an attribute is used to store it
  19287. value = node.attributes.map['data-mce-innertext'];
  19288. if (value) {
  19289. node.attr('data-mce-innertext', null);
  19290. textNode = new Node('#text', 3);
  19291. textNode.value = value;
  19292. textNode.raw = true;
  19293. node.append(textNode);
  19294. }
  19295. }
  19296. }
  19297. });
  19298. }
  19299. }
  19300. /**
  19301. * IE has an issue where you can't select/move the caret by clicking outside the body if the document is in standards mode.
  19302. */
  19303. function fixCaretSelectionOfDocumentElementOnIe() {
  19304. var doc = dom.doc, body = doc.body, started, startRng, htmlElm;
  19305. // Return range from point or null if it failed
  19306. function rngFromPoint(x, y) {
  19307. var rng = body.createTextRange();
  19308. try {
  19309. rng.moveToPoint(x, y);
  19310. } catch (ex) {
  19311. // IE sometimes throws and exception, so lets just ignore it
  19312. rng = null;
  19313. }
  19314. return rng;
  19315. }
  19316. // Fires while the selection is changing
  19317. function selectionChange(e) {
  19318. var pointRng;
  19319. // Check if the button is down or not
  19320. if (e.button) {
  19321. // Create range from mouse position
  19322. pointRng = rngFromPoint(e.x, e.y);
  19323. if (pointRng) {
  19324. // Check if pointRange is before/after selection then change the endPoint
  19325. if (pointRng.compareEndPoints('StartToStart', startRng) > 0) {
  19326. pointRng.setEndPoint('StartToStart', startRng);
  19327. } else {
  19328. pointRng.setEndPoint('EndToEnd', startRng);
  19329. }
  19330. pointRng.select();
  19331. }
  19332. } else {
  19333. endSelection();
  19334. }
  19335. }
  19336. // Removes listeners
  19337. function endSelection() {
  19338. var rng = doc.selection.createRange();
  19339. // If the range is collapsed then use the last start range
  19340. if (startRng && !rng.item && rng.compareEndPoints('StartToEnd', rng) === 0) {
  19341. startRng.select();
  19342. }
  19343. dom.unbind(doc, 'mouseup', endSelection);
  19344. dom.unbind(doc, 'mousemove', selectionChange);
  19345. startRng = started = 0;
  19346. }
  19347. // Make HTML element unselectable since we are going to handle selection by hand
  19348. doc.documentElement.unselectable = true;
  19349. // Detect when user selects outside BODY
  19350. dom.bind(doc, 'mousedown contextmenu', function(e) {
  19351. if (e.target.nodeName === 'HTML') {
  19352. if (started) {
  19353. endSelection();
  19354. }
  19355. // Detect vertical scrollbar, since IE will fire a mousedown on the scrollbar and have target set as HTML
  19356. htmlElm = doc.documentElement;
  19357. if (htmlElm.scrollHeight > htmlElm.clientHeight) {
  19358. return;
  19359. }
  19360. started = 1;
  19361. // Setup start position
  19362. startRng = rngFromPoint(e.x, e.y);
  19363. if (startRng) {
  19364. // Listen for selection change events
  19365. dom.bind(doc, 'mouseup', endSelection);
  19366. dom.bind(doc, 'mousemove', selectionChange);
  19367. dom.getRoot().focus();
  19368. startRng.select();
  19369. }
  19370. }
  19371. });
  19372. }
  19373. /**
  19374. * Fixes selection issues where the caret can be placed between two inline elements like <b>a</b>|<b>b</b>
  19375. * this fix will lean the caret right into the closest inline element.
  19376. */
  19377. function normalizeSelection() {
  19378. // Normalize selection for example <b>a</b><i>|a</i> becomes <b>a|</b><i>a</i> except for Ctrl+A since it selects everything
  19379. editor.on('keyup focusin mouseup', function(e) {
  19380. if (e.keyCode != 65 || !VK.metaKeyPressed(e)) {
  19381. selection.normalize();
  19382. }
  19383. }, true);
  19384. }
  19385. /**
  19386. * Forces Gecko to render a broken image icon if it fails to load an image.
  19387. */
  19388. function showBrokenImageIcon() {
  19389. editor.contentStyles.push(
  19390. 'img:-moz-broken {' +
  19391. '-moz-force-broken-image-icon:1;' +
  19392. 'min-width:24px;' +
  19393. 'min-height:24px' +
  19394. '}'
  19395. );
  19396. }
  19397. /**
  19398. * iOS has a bug where it's impossible to type if the document has a touchstart event
  19399. * bound and the user touches the document while having the on screen keyboard visible.
  19400. *
  19401. * The touch event moves the focus to the parent document while having the caret inside the iframe
  19402. * this fix moves the focus back into the iframe document.
  19403. */
  19404. function restoreFocusOnKeyDown() {
  19405. if (!editor.inline) {
  19406. editor.on('keydown', function() {
  19407. if (document.activeElement == document.body) {
  19408. editor.getWin().focus();
  19409. }
  19410. });
  19411. }
  19412. }
  19413. /**
  19414. * IE 11 has an annoying issue where you can't move focus into the editor
  19415. * by clicking on the white area HTML element. We used to be able to to fix this with
  19416. * the fixCaretSelectionOfDocumentElementOnIe fix. But since M$ removed the selection
  19417. * object it's not possible anymore. So we need to hack in a ungly CSS to force the
  19418. * body to be at least 150px. If the user clicks the HTML element out side this 150px region
  19419. * we simply move the focus into the first paragraph. Not ideal since you loose the
  19420. * positioning of the caret but goot enough for most cases.
  19421. */
  19422. function bodyHeight() {
  19423. if (!editor.inline) {
  19424. editor.contentStyles.push('body {min-height: 150px}');
  19425. editor.on('click', function(e) {
  19426. if (e.target.nodeName == 'HTML') {
  19427. editor.getBody().focus();
  19428. editor.selection.normalize();
  19429. editor.nodeChanged();
  19430. }
  19431. });
  19432. }
  19433. }
  19434. /**
  19435. * Firefox on Mac OS will move the browser back to the previous page if you press CMD+Left arrow.
  19436. * You might then loose all your work so we need to block that behavior and replace it with our own.
  19437. */
  19438. function blockCmdArrowNavigation() {
  19439. if (Env.mac) {
  19440. editor.on('keydown', function(e) {
  19441. if (VK.metaKeyPressed(e) && (e.keyCode == 37 || e.keyCode == 39)) {
  19442. e.preventDefault();
  19443. editor.selection.getSel().modify('move', e.keyCode == 37 ? 'backward' : 'forward', 'word');
  19444. }
  19445. });
  19446. }
  19447. }
  19448. /**
  19449. * Disables the autolinking in IE 9+ this is then re-enabled by the autolink plugin.
  19450. */
  19451. function disableAutoUrlDetect() {
  19452. setEditorCommandState("AutoUrlDetect", false);
  19453. }
  19454. /**
  19455. * IE 11 has a fantastic bug where it will produce two trailing BR elements to iframe bodies when
  19456. * the iframe is hidden by display: none on a parent container. The DOM is actually out of sync
  19457. * with innerHTML in this case. It's like IE adds shadow DOM BR elements that appears on innerHTML
  19458. * but not as the lastChild of the body. However is we add a BR element to the body then remove it
  19459. * it doesn't seem to add these BR elements makes sence right?!
  19460. *
  19461. * Example of what happens: <body>text</body> becomes <body>text<br><br></body>
  19462. */
  19463. function doubleTrailingBrElements() {
  19464. if (!editor.inline) {
  19465. editor.on('focus blur beforegetcontent', function() {
  19466. var br = editor.dom.create('br');
  19467. editor.getBody().appendChild(br);
  19468. br.parentNode.removeChild(br);
  19469. }, true);
  19470. }
  19471. }
  19472. /**
  19473. * iOS 7.1 introduced two new bugs:
  19474. * 1) It's possible to open links within a contentEditable area by clicking on them.
  19475. * 2) If you hold down the finger it will display the link/image touch callout menu.
  19476. */
  19477. function tapLinksAndImages() {
  19478. editor.on('click', function(e) {
  19479. var elm = e.target;
  19480. do {
  19481. if (elm.tagName === 'A') {
  19482. e.preventDefault();
  19483. return;
  19484. }
  19485. } while ((elm = elm.parentNode));
  19486. });
  19487. editor.contentStyles.push('.mce-content-body {-webkit-touch-callout: none}');
  19488. }
  19489. /**
  19490. * WebKit has a bug where it will allow forms to be submitted if they are inside a contentEditable element.
  19491. * For example this: <form><button></form>
  19492. */
  19493. function blockFormSubmitInsideEditor() {
  19494. editor.on('init', function() {
  19495. editor.dom.bind(editor.getBody(), 'submit', function(e) {
  19496. e.preventDefault();
  19497. });
  19498. });
  19499. }
  19500. // All browsers
  19501. disableBackspaceIntoATable();
  19502. removeBlockQuoteOnBackSpace();
  19503. emptyEditorWhenDeleting();
  19504. normalizeSelection();
  19505. // WebKit
  19506. if (isWebKit) {
  19507. cleanupStylesWhenDeleting();
  19508. inputMethodFocus();
  19509. selectControlElements();
  19510. setDefaultBlockType();
  19511. blockFormSubmitInsideEditor();
  19512. // iOS
  19513. if (Env.iOS) {
  19514. selectionChangeNodeChanged();
  19515. restoreFocusOnKeyDown();
  19516. bodyHeight();
  19517. tapLinksAndImages();
  19518. } else {
  19519. selectAll();
  19520. }
  19521. }
  19522. // IE
  19523. if (isIE && Env.ie < 11) {
  19524. removeHrOnBackspace();
  19525. ensureBodyHasRoleApplication();
  19526. addNewLinesBeforeBrInPre();
  19527. removePreSerializedStylesWhenSelectingControls();
  19528. deleteControlItemOnBackSpace();
  19529. renderEmptyBlocksFix();
  19530. keepNoScriptContents();
  19531. fixCaretSelectionOfDocumentElementOnIe();
  19532. }
  19533. if (Env.ie >= 11) {
  19534. bodyHeight();
  19535. doubleTrailingBrElements();
  19536. }
  19537. if (Env.ie) {
  19538. selectAll();
  19539. disableAutoUrlDetect();
  19540. }
  19541. // Gecko
  19542. if (isGecko) {
  19543. removeHrOnBackspace();
  19544. focusBody();
  19545. removeStylesWhenDeletingAcrossBlockElements();
  19546. setGeckoEditingOptions();
  19547. addBrAfterLastLinks();
  19548. removeGhostSelection();
  19549. showBrokenImageIcon();
  19550. blockCmdArrowNavigation();
  19551. }
  19552. };
  19553. });
  19554. // Included from: js/tinymce/classes/util/Observable.js
  19555. /**
  19556. * Observable.js
  19557. *
  19558. * Copyright, Moxiecode Systems AB
  19559. * Released under LGPL License.
  19560. *
  19561. * License: http://www.tinymce.com/license
  19562. * Contributing: http://www.tinymce.com/contributing
  19563. */
  19564. /**
  19565. * This mixin will add event binding logic to classes.
  19566. *
  19567. * @mixin tinymce.util.Observable
  19568. */
  19569. define("tinymce/util/Observable", [
  19570. "tinymce/util/Tools"
  19571. ], function(Tools) {
  19572. var bindingsName = "__bindings";
  19573. var nativeEvents = Tools.makeMap(
  19574. "focusin focusout click dblclick mousedown mouseup mousemove mouseover beforepaste paste cut copy selectionchange" +
  19575. " mouseout mouseenter mouseleave keydown keypress keyup contextmenu dragstart dragend dragover draggesture dragdrop drop drag", ' '
  19576. );
  19577. function returnFalse() {
  19578. return false;
  19579. }
  19580. function returnTrue() {
  19581. return true;
  19582. }
  19583. return {
  19584. /**
  19585. * Fires the specified event by name.
  19586. *
  19587. * @method fire
  19588. * @param {String} name Name of the event to fire.
  19589. * @param {tinymce.Event/Object?} args Event arguments.
  19590. * @param {Boolean?} bubble True/false if the event is to be bubbled.
  19591. * @return {tinymce.Event} Event instance passed in converted into tinymce.Event instance.
  19592. * @example
  19593. * instance.fire('event', {...});
  19594. */
  19595. fire: function(name, args, bubble) {
  19596. var self = this, handlers, i, l, callback, parent;
  19597. name = name.toLowerCase();
  19598. args = args || {};
  19599. args.type = name;
  19600. // Prevent all events except the remove event after the editor has been removed
  19601. if (self.removed && name !== "remove") {
  19602. return;
  19603. }
  19604. // Setup target is there isn't one
  19605. if (!args.target) {
  19606. args.target = self;
  19607. }
  19608. // Add event delegation methods if they are missing
  19609. if (!args.preventDefault) {
  19610. // Add preventDefault method
  19611. args.preventDefault = function() {
  19612. args.isDefaultPrevented = returnTrue;
  19613. };
  19614. // Add stopPropagation
  19615. args.stopPropagation = function() {
  19616. args.isPropagationStopped = returnTrue;
  19617. };
  19618. // Add stopImmediatePropagation
  19619. args.stopImmediatePropagation = function() {
  19620. args.isImmediatePropagationStopped = returnTrue;
  19621. };
  19622. // Add event delegation states
  19623. args.isDefaultPrevented = returnFalse;
  19624. args.isPropagationStopped = returnFalse;
  19625. args.isImmediatePropagationStopped = returnFalse;
  19626. }
  19627. //console.log(name, args);
  19628. if (self[bindingsName]) {
  19629. handlers = self[bindingsName][name];
  19630. if (handlers) {
  19631. for (i = 0, l = handlers.length; i < l; i++) {
  19632. handlers[i] = callback = handlers[i];
  19633. // Stop immediate propagation if needed
  19634. if (args.isImmediatePropagationStopped()) {
  19635. break;
  19636. }
  19637. // If callback returns false then prevent default and stop all propagation
  19638. if (callback.call(self, args) === false) {
  19639. args.preventDefault();
  19640. return args;
  19641. }
  19642. }
  19643. }
  19644. }
  19645. // Bubble event up to parents
  19646. if (bubble !== false && self.parent) {
  19647. parent = self.parent();
  19648. while (parent && !args.isPropagationStopped()) {
  19649. parent.fire(name, args, false);
  19650. parent = parent.parent();
  19651. }
  19652. }
  19653. return args;
  19654. },
  19655. /**
  19656. * Binds an event listener to a specific event by name.
  19657. *
  19658. * @method on
  19659. * @param {String} name Event name or space separated list of events to bind.
  19660. * @param {callback} callback Callback to be executed when the event occurs.
  19661. * @param {Boolean} first Optional flag if the event should be prepended. Use this with care.
  19662. * @return {Object} Current class instance.
  19663. * @example
  19664. * instance.on('event', function(e) {
  19665. * // Callback logic
  19666. * });
  19667. */
  19668. on: function(name, callback, prepend) {
  19669. var self = this, bindings, handlers, names, i;
  19670. if (callback === false) {
  19671. callback = function() {
  19672. return false;
  19673. };
  19674. }
  19675. if (callback) {
  19676. names = name.toLowerCase().split(' ');
  19677. i = names.length;
  19678. while (i--) {
  19679. name = names[i];
  19680. bindings = self[bindingsName];
  19681. if (!bindings) {
  19682. bindings = self[bindingsName] = {};
  19683. }
  19684. handlers = bindings[name];
  19685. if (!handlers) {
  19686. handlers = bindings[name] = [];
  19687. if (self.bindNative && nativeEvents[name]) {
  19688. self.bindNative(name);
  19689. }
  19690. }
  19691. if (prepend) {
  19692. handlers.unshift(callback);
  19693. } else {
  19694. handlers.push(callback);
  19695. }
  19696. }
  19697. }
  19698. return self;
  19699. },
  19700. /**
  19701. * Unbinds an event listener to a specific event by name.
  19702. *
  19703. * @method off
  19704. * @param {String?} name Name of the event to unbind.
  19705. * @param {callback?} callback Callback to unbind.
  19706. * @return {Object} Current class instance.
  19707. * @example
  19708. * // Unbind specific callback
  19709. * instance.off('event', handler);
  19710. *
  19711. * // Unbind all listeners by name
  19712. * instance.off('event');
  19713. *
  19714. * // Unbind all events
  19715. * instance.off();
  19716. */
  19717. off: function(name, callback) {
  19718. var self = this, i, bindings = self[bindingsName], handlers, bindingName, names, hi;
  19719. if (bindings) {
  19720. if (name) {
  19721. names = name.toLowerCase().split(' ');
  19722. i = names.length;
  19723. while (i--) {
  19724. name = names[i];
  19725. handlers = bindings[name];
  19726. // Unbind all handlers
  19727. if (!name) {
  19728. for (bindingName in bindings) {
  19729. bindings[name].length = 0;
  19730. }
  19731. return self;
  19732. }
  19733. if (handlers) {
  19734. // Unbind all by name
  19735. if (!callback) {
  19736. handlers.length = 0;
  19737. } else {
  19738. // Unbind specific ones
  19739. hi = handlers.length;
  19740. while (hi--) {
  19741. if (handlers[hi] === callback) {
  19742. handlers.splice(hi, 1);
  19743. }
  19744. }
  19745. }
  19746. if (!handlers.length && self.unbindNative && nativeEvents[name]) {
  19747. self.unbindNative(name);
  19748. delete bindings[name];
  19749. }
  19750. }
  19751. }
  19752. } else {
  19753. if (self.unbindNative) {
  19754. for (name in bindings) {
  19755. self.unbindNative(name);
  19756. }
  19757. }
  19758. self[bindingsName] = [];
  19759. }
  19760. }
  19761. return self;
  19762. },
  19763. hasEventListeners: function(name) {
  19764. var bindings = this[bindingsName];
  19765. name = name.toLowerCase();
  19766. return !(!bindings || !bindings[name] || bindings[name].length === 0);
  19767. }
  19768. };
  19769. });
  19770. // Included from: js/tinymce/classes/Shortcuts.js
  19771. /**
  19772. * Shortcuts.js
  19773. *
  19774. * Copyright, Moxiecode Systems AB
  19775. * Released under LGPL License.
  19776. *
  19777. * License: http://www.tinymce.com/license
  19778. * Contributing: http://www.tinymce.com/contributing
  19779. */
  19780. /**
  19781. * Contains all logic for handling of keyboard shortcuts.
  19782. */
  19783. define("tinymce/Shortcuts", [
  19784. "tinymce/util/Tools",
  19785. "tinymce/Env"
  19786. ], function(Tools, Env) {
  19787. var each = Tools.each, explode = Tools.explode;
  19788. var keyCodeLookup = {
  19789. "f9": 120,
  19790. "f10": 121,
  19791. "f11": 122
  19792. };
  19793. return function(editor) {
  19794. var self = this, shortcuts = {};
  19795. editor.on('keyup keypress keydown', function(e) {
  19796. if (e.altKey || e.ctrlKey || e.metaKey) {
  19797. each(shortcuts, function(shortcut) {
  19798. var ctrlKey = Env.mac ? e.metaKey : e.ctrlKey;
  19799. if (shortcut.ctrl != ctrlKey || shortcut.alt != e.altKey || shortcut.shift != e.shiftKey) {
  19800. return;
  19801. }
  19802. if (e.keyCode == shortcut.keyCode || (e.charCode && e.charCode == shortcut.charCode)) {
  19803. e.preventDefault();
  19804. if (e.type == "keydown") {
  19805. shortcut.func.call(shortcut.scope);
  19806. }
  19807. return true;
  19808. }
  19809. });
  19810. }
  19811. });
  19812. /**
  19813. * Adds a keyboard shortcut for some command or function.
  19814. *
  19815. * @method addShortcut
  19816. * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o.
  19817. * @param {String} desc Text description for the command.
  19818. * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed.
  19819. * @param {Object} sc Optional scope to execute the function in.
  19820. * @return {Boolean} true/false state if the shortcut was added or not.
  19821. */
  19822. self.add = function(pattern, desc, cmdFunc, scope) {
  19823. var cmd;
  19824. cmd = cmdFunc;
  19825. if (typeof(cmdFunc) === 'string') {
  19826. cmdFunc = function() {
  19827. editor.execCommand(cmd, false, null);
  19828. };
  19829. } else if (Tools.isArray(cmd)) {
  19830. cmdFunc = function() {
  19831. editor.execCommand(cmd[0], cmd[1], cmd[2]);
  19832. };
  19833. }
  19834. each(explode(pattern.toLowerCase()), function(pattern) {
  19835. var shortcut = {
  19836. func: cmdFunc,
  19837. scope: scope || editor,
  19838. desc: editor.translate(desc),
  19839. alt: false,
  19840. ctrl: false,
  19841. shift: false
  19842. };
  19843. each(explode(pattern, '+'), function(value) {
  19844. switch (value) {
  19845. case 'alt':
  19846. case 'ctrl':
  19847. case 'shift':
  19848. shortcut[value] = true;
  19849. break;
  19850. default:
  19851. shortcut.charCode = value.charCodeAt(0);
  19852. shortcut.keyCode = keyCodeLookup[value] || value.toUpperCase().charCodeAt(0);
  19853. }
  19854. });
  19855. shortcuts[
  19856. (shortcut.ctrl ? 'ctrl' : '') + ',' +
  19857. (shortcut.alt ? 'alt' : '') + ',' +
  19858. (shortcut.shift ? 'shift' : '') + ',' +
  19859. shortcut.keyCode
  19860. ] = shortcut;
  19861. });
  19862. return true;
  19863. };
  19864. };
  19865. });
  19866. // Included from: js/tinymce/classes/Editor.js
  19867. /**
  19868. * Editor.js
  19869. *
  19870. * Copyright, Moxiecode Systems AB
  19871. * Released under LGPL License.
  19872. *
  19873. * License: http://www.tinymce.com/license
  19874. * Contributing: http://www.tinymce.com/contributing
  19875. */
  19876. /*jshint scripturl:true */
  19877. /**
  19878. * Include the base event class documentation.
  19879. *
  19880. * @include ../../../tools/docs/tinymce.Event.js
  19881. */
  19882. /**
  19883. * This class contains the core logic for a TinyMCE editor.
  19884. *
  19885. * @class tinymce.Editor
  19886. * @mixes tinymce.util.Observable
  19887. * @example
  19888. * // Add a class to all paragraphs in the editor.
  19889. * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass');
  19890. *
  19891. * // Gets the current editors selection as text
  19892. * tinymce.activeEditor.selection.getContent({format: 'text'});
  19893. *
  19894. * // Creates a new editor instance
  19895. * var ed = new tinymce.Editor('textareaid', {
  19896. * some_setting: 1
  19897. * }, tinymce.EditorManager);
  19898. *
  19899. * // Select each item the user clicks on
  19900. * ed.on('click', function(e) {
  19901. * ed.selection.select(e.target);
  19902. * });
  19903. *
  19904. * ed.render();
  19905. */
  19906. define("tinymce/Editor", [
  19907. "tinymce/dom/DOMUtils",
  19908. "tinymce/AddOnManager",
  19909. "tinymce/html/Node",
  19910. "tinymce/dom/Serializer",
  19911. "tinymce/html/Serializer",
  19912. "tinymce/dom/Selection",
  19913. "tinymce/Formatter",
  19914. "tinymce/UndoManager",
  19915. "tinymce/EnterKey",
  19916. "tinymce/ForceBlocks",
  19917. "tinymce/EditorCommands",
  19918. "tinymce/util/URI",
  19919. "tinymce/dom/ScriptLoader",
  19920. "tinymce/dom/EventUtils",
  19921. "tinymce/WindowManager",
  19922. "tinymce/html/Schema",
  19923. "tinymce/html/DomParser",
  19924. "tinymce/util/Quirks",
  19925. "tinymce/Env",
  19926. "tinymce/util/Tools",
  19927. "tinymce/util/Observable",
  19928. "tinymce/Shortcuts"
  19929. ], function(
  19930. DOMUtils, AddOnManager, Node, DomSerializer, Serializer,
  19931. Selection, Formatter, UndoManager, EnterKey, ForceBlocks, EditorCommands,
  19932. URI, ScriptLoader, EventUtils, WindowManager,
  19933. Schema, DomParser, Quirks, Env, Tools, Observable, Shortcuts
  19934. ) {
  19935. // Shorten these names
  19936. var DOM = DOMUtils.DOM, ThemeManager = AddOnManager.ThemeManager, PluginManager = AddOnManager.PluginManager;
  19937. var extend = Tools.extend, each = Tools.each, explode = Tools.explode;
  19938. var inArray = Tools.inArray, trim = Tools.trim, resolve = Tools.resolve;
  19939. var Event = EventUtils.Event;
  19940. var isGecko = Env.gecko, ie = Env.ie;
  19941. function getEventTarget(editor, eventName) {
  19942. if (eventName == 'selectionchange') {
  19943. return editor.getDoc();
  19944. }
  19945. // Need to bind mousedown/mouseup etc to document not body in iframe mode
  19946. // Since the user might click on the HTML element not the BODY
  19947. if (!editor.inline && /^mouse|click|contextmenu|drop/.test(eventName)) {
  19948. return editor.getDoc();
  19949. }
  19950. return editor.getBody();
  19951. }
  19952. /**
  19953. * Include documentation for all the events.
  19954. *
  19955. * @include ../../../tools/docs/tinymce.Editor.js
  19956. */
  19957. /**
  19958. * Constructs a editor instance by id.
  19959. *
  19960. * @constructor
  19961. * @method Editor
  19962. * @param {String} id Unique id for the editor.
  19963. * @param {Object} settings Settings for the editor.
  19964. * @param {tinymce.EditorManager} editorManager EditorManager instance.
  19965. * @author Moxiecode
  19966. */
  19967. function Editor(id, settings, editorManager) {
  19968. var self = this, documentBaseUrl, baseUri;
  19969. documentBaseUrl = self.documentBaseUrl = editorManager.documentBaseURL;
  19970. baseUri = editorManager.baseURI;
  19971. /**
  19972. * Name/value collection with editor settings.
  19973. *
  19974. * @property settings
  19975. * @type Object
  19976. * @example
  19977. * // Get the value of the theme setting
  19978. * tinymce.activeEditor.windowManager.alert("You are using the " + tinymce.activeEditor.settings.theme + " theme");
  19979. */
  19980. self.settings = settings = extend({
  19981. id: id,
  19982. theme: 'modern',
  19983. delta_width: 0,
  19984. delta_height: 0,
  19985. popup_css: '',
  19986. plugins: '',
  19987. document_base_url: documentBaseUrl,
  19988. add_form_submit_trigger: true,
  19989. submit_patch: true,
  19990. add_unload_trigger: true,
  19991. convert_urls: true,
  19992. relative_urls: true,
  19993. remove_script_host: true,
  19994. object_resizing: true,
  19995. doctype: '<!DOCTYPE html>',
  19996. visual: true,
  19997. font_size_style_values: 'xx-small,x-small,small,medium,large,x-large,xx-large',
  19998. // See: http://www.w3.org/TR/CSS2/fonts.html#propdef-font-size
  19999. font_size_legacy_values: 'xx-small,small,medium,large,x-large,xx-large,300%',
  20000. forced_root_block: 'p',
  20001. hidden_input: true,
  20002. padd_empty_editor: true,
  20003. render_ui: true,
  20004. indentation: '30px',
  20005. inline_styles: true,
  20006. convert_fonts_to_spans: true,
  20007. indent: 'simple',
  20008. indent_before: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,' +
  20009. 'tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist',
  20010. indent_after: 'p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,' +
  20011. 'tfoot,tbody,tr,section,article,hgroup,aside,figure,option,optgroup,datalist',
  20012. validate: true,
  20013. entity_encoding: 'named',
  20014. url_converter: self.convertURL,
  20015. url_converter_scope: self,
  20016. ie7_compat: true
  20017. }, settings);
  20018. AddOnManager.language = settings.language || 'en';
  20019. AddOnManager.languageLoad = settings.language_load;
  20020. AddOnManager.baseURL = editorManager.baseURL;
  20021. /**
  20022. * Editor instance id, normally the same as the div/textarea that was replaced.
  20023. *
  20024. * @property id
  20025. * @type String
  20026. */
  20027. self.id = settings.id = id;
  20028. /**
  20029. * State to force the editor to return false on a isDirty call.
  20030. *
  20031. * @property isNotDirty
  20032. * @type Boolean
  20033. * @example
  20034. * function ajaxSave() {
  20035. * var ed = tinymce.get('elm1');
  20036. *
  20037. * // Save contents using some XHR call
  20038. * alert(ed.getContent());
  20039. *
  20040. * ed.isNotDirty = true; // Force not dirty state
  20041. * }
  20042. */
  20043. self.isNotDirty = true;
  20044. /**
  20045. * Name/Value object containting plugin instances.
  20046. *
  20047. * @property plugins
  20048. * @type Object
  20049. * @example
  20050. * // Execute a method inside a plugin directly
  20051. * tinymce.activeEditor.plugins.someplugin.someMethod();
  20052. */
  20053. self.plugins = {};
  20054. /**
  20055. * URI object to document configured for the TinyMCE instance.
  20056. *
  20057. * @property documentBaseURI
  20058. * @type tinymce.util.URI
  20059. * @example
  20060. * // Get relative URL from the location of document_base_url
  20061. * tinymce.activeEditor.documentBaseURI.toRelative('/somedir/somefile.htm');
  20062. *
  20063. * // Get absolute URL from the location of document_base_url
  20064. * tinymce.activeEditor.documentBaseURI.toAbsolute('somefile.htm');
  20065. */
  20066. self.documentBaseURI = new URI(settings.document_base_url || documentBaseUrl, {
  20067. base_uri: baseUri
  20068. });
  20069. /**
  20070. * URI object to current document that holds the TinyMCE editor instance.
  20071. *
  20072. * @property baseURI
  20073. * @type tinymce.util.URI
  20074. * @example
  20075. * // Get relative URL from the location of the API
  20076. * tinymce.activeEditor.baseURI.toRelative('/somedir/somefile.htm');
  20077. *
  20078. * // Get absolute URL from the location of the API
  20079. * tinymce.activeEditor.baseURI.toAbsolute('somefile.htm');
  20080. */
  20081. self.baseURI = baseUri;
  20082. /**
  20083. * Array with CSS files to load into the iframe.
  20084. *
  20085. * @property contentCSS
  20086. * @type Array
  20087. */
  20088. self.contentCSS = [];
  20089. /**
  20090. * Array of CSS styles to add to head of document when the editor loads.
  20091. *
  20092. * @property contentStyles
  20093. * @type Array
  20094. */
  20095. self.contentStyles = [];
  20096. // Creates all events like onClick, onSetContent etc see Editor.Events.js for the actual logic
  20097. self.shortcuts = new Shortcuts(self);
  20098. // Internal command handler objects
  20099. self.execCommands = {};
  20100. self.queryStateCommands = {};
  20101. self.queryValueCommands = {};
  20102. self.loadedCSS = {};
  20103. self.suffix = editorManager.suffix;
  20104. self.editorManager = editorManager;
  20105. self.inline = settings.inline;
  20106. // Call setup
  20107. editorManager.fire('SetupEditor', self);
  20108. self.execCallback('setup', self);
  20109. }
  20110. Editor.prototype = {
  20111. /**
  20112. * Renderes the editor/adds it to the page.
  20113. *
  20114. * @method render
  20115. */
  20116. render: function() {
  20117. var self = this, settings = self.settings, id = self.id, suffix = self.suffix;
  20118. function readyHandler() {
  20119. DOM.unbind(window, 'ready', readyHandler);
  20120. self.render();
  20121. }
  20122. // Page is not loaded yet, wait for it
  20123. if (!Event.domLoaded) {
  20124. DOM.bind(window, 'ready', readyHandler);
  20125. return;
  20126. }
  20127. // Element not found, then skip initialization
  20128. if (!self.getElement()) {
  20129. return;
  20130. }
  20131. // No editable support old iOS versions etc
  20132. if (!Env.contentEditable) {
  20133. return;
  20134. }
  20135. // Hide target element early to prevent content flashing
  20136. if (!settings.inline) {
  20137. self.orgVisibility = self.getElement().style.visibility;
  20138. self.getElement().style.visibility = 'hidden';
  20139. } else {
  20140. self.inline = true;
  20141. }
  20142. var form = self.getElement().form || DOM.getParent(id, 'form');
  20143. if (form) {
  20144. self.formElement = form;
  20145. // Add hidden input for non input elements inside form elements
  20146. if (settings.hidden_input && !/TEXTAREA|INPUT/i.test(self.getElement().nodeName)) {
  20147. DOM.insertAfter(DOM.create('input', {type: 'hidden', name: id}), id);
  20148. self.hasHiddenInput = true;
  20149. }
  20150. // Pass submit/reset from form to editor instance
  20151. self.formEventDelegate = function(e) {
  20152. self.fire(e.type, e);
  20153. };
  20154. DOM.bind(form, 'submit reset', self.formEventDelegate);
  20155. // Reset contents in editor when the form is reset
  20156. self.on('reset', function() {
  20157. self.setContent(self.startContent, {format: 'raw'});
  20158. });
  20159. // Check page uses id="submit" or name="submit" for it's submit button
  20160. if (settings.submit_patch && !form.submit.nodeType && !form.submit.length && !form._mceOldSubmit) {
  20161. form._mceOldSubmit = form.submit;
  20162. form.submit = function() {
  20163. self.editorManager.triggerSave();
  20164. self.isNotDirty = true;
  20165. return form._mceOldSubmit(form);
  20166. };
  20167. }
  20168. }
  20169. /**
  20170. * Window manager reference, use this to open new windows and dialogs.
  20171. *
  20172. * @property windowManager
  20173. * @type tinymce.WindowManager
  20174. * @example
  20175. * // Shows an alert message
  20176. * tinymce.activeEditor.windowManager.alert('Hello world!');
  20177. *
  20178. * // Opens a new dialog with the file.htm file and the size 320x240
  20179. * // It also adds a custom parameter this can be retrieved by using tinyMCEPopup.getWindowArg inside the dialog.
  20180. * tinymce.activeEditor.windowManager.open({
  20181. * url: 'file.htm',
  20182. * width: 320,
  20183. * height: 240
  20184. * }, {
  20185. * custom_param: 1
  20186. * });
  20187. */
  20188. self.windowManager = new WindowManager(self);
  20189. if (settings.encoding == 'xml') {
  20190. self.on('GetContent', function(e) {
  20191. if (e.save) {
  20192. e.content = DOM.encode(e.content);
  20193. }
  20194. });
  20195. }
  20196. if (settings.add_form_submit_trigger) {
  20197. self.on('submit', function() {
  20198. if (self.initialized) {
  20199. self.save();
  20200. }
  20201. });
  20202. }
  20203. if (settings.add_unload_trigger) {
  20204. self._beforeUnload = function() {
  20205. if (self.initialized && !self.destroyed && !self.isHidden()) {
  20206. self.save({format: 'raw', no_events: true, set_dirty: false});
  20207. }
  20208. };
  20209. self.editorManager.on('BeforeUnload', self._beforeUnload);
  20210. }
  20211. // Load scripts
  20212. function loadScripts() {
  20213. var scriptLoader = ScriptLoader.ScriptLoader;
  20214. if (settings.language && settings.language != 'en' && !settings.language_url) {
  20215. settings.language_url = self.editorManager.baseURL + '/langs/' + settings.language + '.js';
  20216. }
  20217. if (settings.language_url) {
  20218. scriptLoader.add(settings.language_url);
  20219. }
  20220. if (settings.theme && typeof settings.theme != "function" &&
  20221. settings.theme.charAt(0) != '-' && !ThemeManager.urls[settings.theme]) {
  20222. var themeUrl = settings.theme_url;
  20223. if (themeUrl) {
  20224. themeUrl = self.documentBaseURI.toAbsolute(themeUrl);
  20225. } else {
  20226. themeUrl = 'themes/' + settings.theme + '/theme' + suffix + '.js';
  20227. }
  20228. ThemeManager.load(settings.theme, themeUrl);
  20229. }
  20230. if (Tools.isArray(settings.plugins)) {
  20231. settings.plugins = settings.plugins.join(' ');
  20232. }
  20233. each(settings.external_plugins, function(url, name) {
  20234. PluginManager.load(name, url);
  20235. settings.plugins += ' ' + name;
  20236. });
  20237. each(settings.plugins.split(/[ ,]/), function(plugin) {
  20238. plugin = trim(plugin);
  20239. if (plugin && !PluginManager.urls[plugin]) {
  20240. if (plugin.charAt(0) == '-') {
  20241. plugin = plugin.substr(1, plugin.length);
  20242. var dependencies = PluginManager.dependencies(plugin);
  20243. each(dependencies, function(dep) {
  20244. var defaultSettings = {
  20245. prefix:'plugins/',
  20246. resource: dep,
  20247. suffix:'/plugin' + suffix + '.js'
  20248. };
  20249. dep = PluginManager.createUrl(defaultSettings, dep);
  20250. PluginManager.load(dep.resource, dep);
  20251. });
  20252. } else {
  20253. PluginManager.load(plugin, {
  20254. prefix: 'plugins/',
  20255. resource: plugin,
  20256. suffix: '/plugin' + suffix + '.js'
  20257. });
  20258. }
  20259. }
  20260. });
  20261. scriptLoader.loadQueue(function() {
  20262. if (!self.removed) {
  20263. self.init();
  20264. }
  20265. });
  20266. }
  20267. loadScripts();
  20268. },
  20269. /**
  20270. * Initializes the editor this will be called automatically when
  20271. * all plugins/themes and language packs are loaded by the rendered method.
  20272. * This method will setup the iframe and create the theme and plugin instances.
  20273. *
  20274. * @method init
  20275. */
  20276. init: function() {
  20277. var self = this, settings = self.settings, elm = self.getElement();
  20278. var w, h, minHeight, n, o, Theme, url, bodyId, bodyClass, re, i, initializedPlugins = [];
  20279. self.rtl = this.editorManager.i18n.rtl;
  20280. self.editorManager.add(self);
  20281. settings.aria_label = settings.aria_label || DOM.getAttrib(elm, 'aria-label', self.getLang('aria.rich_text_area'));
  20282. /**
  20283. * Reference to the theme instance that was used to generate the UI.
  20284. *
  20285. * @property theme
  20286. * @type tinymce.Theme
  20287. * @example
  20288. * // Executes a method on the theme directly
  20289. * tinymce.activeEditor.theme.someMethod();
  20290. */
  20291. if (settings.theme) {
  20292. if (typeof settings.theme != "function") {
  20293. settings.theme = settings.theme.replace(/-/, '');
  20294. Theme = ThemeManager.get(settings.theme);
  20295. self.theme = new Theme(self, ThemeManager.urls[settings.theme]);
  20296. if (self.theme.init) {
  20297. self.theme.init(self, ThemeManager.urls[settings.theme] || self.documentBaseUrl.replace(/\/$/, ''));
  20298. }
  20299. } else {
  20300. self.theme = settings.theme;
  20301. }
  20302. }
  20303. function initPlugin(plugin) {
  20304. var Plugin = PluginManager.get(plugin), pluginUrl, pluginInstance;
  20305. pluginUrl = PluginManager.urls[plugin] || self.documentBaseUrl.replace(/\/$/, '');
  20306. plugin = trim(plugin);
  20307. if (Plugin && inArray(initializedPlugins, plugin) === -1) {
  20308. each(PluginManager.dependencies(plugin), function(dep){
  20309. initPlugin(dep);
  20310. });
  20311. pluginInstance = new Plugin(self, pluginUrl);
  20312. self.plugins[plugin] = pluginInstance;
  20313. if (pluginInstance.init) {
  20314. pluginInstance.init(self, pluginUrl);
  20315. initializedPlugins.push(plugin);
  20316. }
  20317. }
  20318. }
  20319. // Create all plugins
  20320. each(settings.plugins.replace(/\-/g, '').split(/[ ,]/), initPlugin);
  20321. // Measure box
  20322. if (settings.render_ui && self.theme) {
  20323. self.orgDisplay = elm.style.display;
  20324. if (typeof settings.theme != "function") {
  20325. w = settings.width || elm.style.width || elm.offsetWidth;
  20326. h = settings.height || elm.style.height || elm.offsetHeight;
  20327. minHeight = settings.min_height || 100;
  20328. re = /^[0-9\.]+(|px)$/i;
  20329. if (re.test('' + w)) {
  20330. w = Math.max(parseInt(w, 10), 100);
  20331. }
  20332. if (re.test('' + h)) {
  20333. h = Math.max(parseInt(h, 10), minHeight);
  20334. }
  20335. // Render UI
  20336. o = self.theme.renderUI({
  20337. targetNode: elm,
  20338. width: w,
  20339. height: h,
  20340. deltaWidth: settings.delta_width,
  20341. deltaHeight: settings.delta_height
  20342. });
  20343. // Resize editor
  20344. if (!settings.content_editable) {
  20345. DOM.setStyles(o.sizeContainer || o.editorContainer, {
  20346. wi2dth: w,
  20347. // TODO: Fix this
  20348. h2eight: h
  20349. });
  20350. h = (o.iframeHeight || h) + (typeof(h) == 'number' ? (o.deltaHeight || 0) : '');
  20351. if (h < minHeight) {
  20352. h = minHeight;
  20353. }
  20354. }
  20355. } else {
  20356. o = settings.theme(self, elm);
  20357. // Convert element type to id:s
  20358. if (o.editorContainer.nodeType) {
  20359. o.editorContainer = o.editorContainer.id = o.editorContainer.id || self.id + "_parent";
  20360. }
  20361. // Convert element type to id:s
  20362. if (o.iframeContainer.nodeType) {
  20363. o.iframeContainer = o.iframeContainer.id = o.iframeContainer.id || self.id + "_iframecontainer";
  20364. }
  20365. // Use specified iframe height or the targets offsetHeight
  20366. h = o.iframeHeight || elm.offsetHeight;
  20367. }
  20368. self.editorContainer = o.editorContainer;
  20369. }
  20370. // Load specified content CSS last
  20371. if (settings.content_css) {
  20372. each(explode(settings.content_css), function(u) {
  20373. self.contentCSS.push(self.documentBaseURI.toAbsolute(u));
  20374. });
  20375. }
  20376. // Load specified content CSS last
  20377. if (settings.content_style) {
  20378. self.contentStyles.push(settings.content_style);
  20379. }
  20380. // Content editable mode ends here
  20381. if (settings.content_editable) {
  20382. elm = n = o = null; // Fix IE leak
  20383. return self.initContentBody();
  20384. }
  20385. self.iframeHTML = settings.doctype + '<html><head>';
  20386. // We only need to override paths if we have to
  20387. // IE has a bug where it remove site absolute urls to relative ones if this is specified
  20388. if (settings.document_base_url != self.documentBaseUrl) {
  20389. self.iframeHTML += '<base href="' + self.documentBaseURI.getURI() + '" />';
  20390. }
  20391. // IE8 doesn't support carets behind images setting ie7_compat would force IE8+ to run in IE7 compat mode.
  20392. if (!Env.caretAfter && settings.ie7_compat) {
  20393. self.iframeHTML += '<meta http-equiv="X-UA-Compatible" content="IE=7" />';
  20394. }
  20395. self.iframeHTML += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
  20396. // Load the CSS by injecting them into the HTML this will reduce "flicker"
  20397. for (i = 0; i < self.contentCSS.length; i++) {
  20398. var cssUrl = self.contentCSS[i];
  20399. self.iframeHTML += '<link type="text/css" rel="stylesheet" href="' + cssUrl + '" />';
  20400. self.loadedCSS[cssUrl] = true;
  20401. }
  20402. bodyId = settings.body_id || 'tinymce';
  20403. if (bodyId.indexOf('=') != -1) {
  20404. bodyId = self.getParam('body_id', '', 'hash');
  20405. bodyId = bodyId[self.id] || bodyId;
  20406. }
  20407. bodyClass = settings.body_class || '';
  20408. if (bodyClass.indexOf('=') != -1) {
  20409. bodyClass = self.getParam('body_class', '', 'hash');
  20410. bodyClass = bodyClass[self.id] || '';
  20411. }
  20412. self.iframeHTML += '</head><body id="' + bodyId + '" class="mce-content-body ' + bodyClass + '" ' +
  20413. 'onload="window.parent.tinymce.get(\'' + self.id + '\').fire(\'load\');"><br></body></html>';
  20414. /*eslint no-script-url:0 */
  20415. var domainRelaxUrl = 'javascript:(function(){' +
  20416. 'document.open();document.domain="' + document.domain + '";' +
  20417. 'var ed = window.parent.tinymce.get("' + self.id + '");document.write(ed.iframeHTML);' +
  20418. 'document.close();ed.initContentBody(true);})()';
  20419. // Domain relaxing is required since the user has messed around with document.domain
  20420. if (document.domain != location.hostname) {
  20421. url = domainRelaxUrl;
  20422. }
  20423. // Create iframe
  20424. // TODO: ACC add the appropriate description on this.
  20425. n = DOM.add(o.iframeContainer, 'iframe', {
  20426. id: self.id + "_ifr",
  20427. src: url || 'javascript:""', // Workaround for HTTPS warning in IE6/7
  20428. frameBorder: '0',
  20429. allowTransparency: "true",
  20430. title: self.editorManager.translate(
  20431. "Rich Text Area. Press ALT-F9 for menu. " +
  20432. "Press ALT-F10 for toolbar. Press ALT-0 for help"
  20433. ),
  20434. style: {
  20435. width: '100%',
  20436. height: h,
  20437. display: 'block' // Important for Gecko to render the iframe correctly
  20438. }
  20439. });
  20440. // Try accessing the document this will fail on IE when document.domain is set to the same as location.hostname
  20441. // Then we have to force domain relaxing using the domainRelaxUrl approach very ugly!!
  20442. if (ie) {
  20443. try {
  20444. self.getDoc();
  20445. } catch (e) {
  20446. n.src = url = domainRelaxUrl;
  20447. }
  20448. }
  20449. self.contentAreaContainer = o.iframeContainer;
  20450. if (o.editorContainer) {
  20451. DOM.get(o.editorContainer).style.display = self.orgDisplay;
  20452. }
  20453. DOM.get(self.id).style.display = 'none';
  20454. DOM.setAttrib(self.id, 'aria-hidden', true);
  20455. if (!url) {
  20456. self.initContentBody();
  20457. }
  20458. elm = n = o = null; // Cleanup
  20459. },
  20460. /**
  20461. * This method get called by the init method ones the iframe is loaded.
  20462. * It will fill the iframe with contents, setups DOM and selection objects for the iframe.
  20463. *
  20464. * @method initContentBody
  20465. * @private
  20466. */
  20467. initContentBody: function(skipWrite) {
  20468. var self = this, settings = self.settings, targetElm = DOM.get(self.id), doc = self.getDoc(), body, contentCssText;
  20469. // Restore visibility on target element
  20470. if (!settings.inline) {
  20471. self.getElement().style.visibility = self.orgVisibility;
  20472. }
  20473. // Setup iframe body
  20474. if (!skipWrite && !settings.content_editable) {
  20475. doc.open();
  20476. doc.write(self.iframeHTML);
  20477. doc.close();
  20478. }
  20479. if (settings.content_editable) {
  20480. self.on('remove', function() {
  20481. var bodyEl = this.getBody();
  20482. DOM.removeClass(bodyEl, 'mce-content-body');
  20483. DOM.removeClass(bodyEl, 'mce-edit-focus');
  20484. DOM.setAttrib(bodyEl, 'contentEditable', null);
  20485. });
  20486. DOM.addClass(targetElm, 'mce-content-body');
  20487. self.contentDocument = doc = settings.content_document || document;
  20488. self.contentWindow = settings.content_window || window;
  20489. self.bodyElement = targetElm;
  20490. // Prevent leak in IE
  20491. settings.content_document = settings.content_window = null;
  20492. // TODO: Fix this
  20493. settings.root_name = targetElm.nodeName.toLowerCase();
  20494. }
  20495. // It will not steal focus while setting contentEditable
  20496. body = self.getBody();
  20497. body.disabled = true;
  20498. if (!settings.readonly) {
  20499. if (self.inline && DOM.getStyle(body, 'position', true) == 'static') {
  20500. body.style.position = 'relative';
  20501. }
  20502. body.contentEditable = self.getParam('content_editable_state', true);
  20503. }
  20504. body.disabled = false;
  20505. /**
  20506. * Schema instance, enables you to validate elements and it's children.
  20507. *
  20508. * @property schema
  20509. * @type tinymce.html.Schema
  20510. */
  20511. self.schema = new Schema(settings);
  20512. /**
  20513. * DOM instance for the editor.
  20514. *
  20515. * @property dom
  20516. * @type tinymce.dom.DOMUtils
  20517. * @example
  20518. * // Adds a class to all paragraphs within the editor
  20519. * tinymce.activeEditor.dom.addClass(tinymce.activeEditor.dom.select('p'), 'someclass');
  20520. */
  20521. self.dom = new DOMUtils(doc, {
  20522. keep_values: true,
  20523. url_converter: self.convertURL,
  20524. url_converter_scope: self,
  20525. hex_colors: settings.force_hex_style_colors,
  20526. class_filter: settings.class_filter,
  20527. update_styles: true,
  20528. root_element: settings.content_editable ? self.id : null,
  20529. collect: settings.content_editable,
  20530. schema: self.schema,
  20531. onSetAttrib: function(e) {
  20532. self.fire('SetAttrib', e);
  20533. }
  20534. });
  20535. /**
  20536. * HTML parser will be used when contents is inserted into the editor.
  20537. *
  20538. * @property parser
  20539. * @type tinymce.html.DomParser
  20540. */
  20541. self.parser = new DomParser(settings, self.schema);
  20542. // Convert src and href into data-mce-src, data-mce-href and data-mce-style
  20543. self.parser.addAttributeFilter('src,href,style,tabindex', function(nodes, name) {
  20544. var i = nodes.length, node, dom = self.dom, value, internalName;
  20545. while (i--) {
  20546. node = nodes[i];
  20547. value = node.attr(name);
  20548. internalName = 'data-mce-' + name;
  20549. // Add internal attribute if we need to we don't on a refresh of the document
  20550. if (!node.attributes.map[internalName]) {
  20551. if (name === "style") {
  20552. node.attr(internalName, dom.serializeStyle(dom.parseStyle(value), node.name));
  20553. } else if (name === "tabindex") {
  20554. node.attr(internalName, value);
  20555. node.attr(name, null);
  20556. } else {
  20557. node.attr(internalName, self.convertURL(value, name, node.name));
  20558. }
  20559. }
  20560. }
  20561. });
  20562. // Keep scripts from executing
  20563. self.parser.addNodeFilter('script', function(nodes) {
  20564. var i = nodes.length, node;
  20565. while (i--) {
  20566. node = nodes[i];
  20567. node.attr('type', 'mce-' + (node.attr('type') || 'text/javascript'));
  20568. }
  20569. });
  20570. self.parser.addNodeFilter('#cdata', function(nodes) {
  20571. var i = nodes.length, node;
  20572. while (i--) {
  20573. node = nodes[i];
  20574. node.type = 8;
  20575. node.name = '#comment';
  20576. node.value = '[CDATA[' + node.value + ']]';
  20577. }
  20578. });
  20579. self.parser.addNodeFilter('p,h1,h2,h3,h4,h5,h6,div', function(nodes) {
  20580. var i = nodes.length, node, nonEmptyElements = self.schema.getNonEmptyElements();
  20581. while (i--) {
  20582. node = nodes[i];
  20583. if (node.isEmpty(nonEmptyElements)) {
  20584. node.empty().append(new Node('br', 1)).shortEnded = true;
  20585. }
  20586. }
  20587. });
  20588. /**
  20589. * DOM serializer for the editor. Will be used when contents is extracted from the editor.
  20590. *
  20591. * @property serializer
  20592. * @type tinymce.dom.Serializer
  20593. * @example
  20594. * // Serializes the first paragraph in the editor into a string
  20595. * tinymce.activeEditor.serializer.serialize(tinymce.activeEditor.dom.select('p')[0]);
  20596. */
  20597. self.serializer = new DomSerializer(settings, self);
  20598. /**
  20599. * Selection instance for the editor.
  20600. *
  20601. * @property selection
  20602. * @type tinymce.dom.Selection
  20603. * @example
  20604. * // Sets some contents to the current selection in the editor
  20605. * tinymce.activeEditor.selection.setContent('Some contents');
  20606. *
  20607. * // Gets the current selection
  20608. * alert(tinymce.activeEditor.selection.getContent());
  20609. *
  20610. * // Selects the first paragraph found
  20611. * tinymce.activeEditor.selection.select(tinymce.activeEditor.dom.select('p')[0]);
  20612. */
  20613. self.selection = new Selection(self.dom, self.getWin(), self.serializer, self);
  20614. /**
  20615. * Formatter instance.
  20616. *
  20617. * @property formatter
  20618. * @type tinymce.Formatter
  20619. */
  20620. self.formatter = new Formatter(self);
  20621. /**
  20622. * Undo manager instance, responsible for handling undo levels.
  20623. *
  20624. * @property undoManager
  20625. * @type tinymce.UndoManager
  20626. * @example
  20627. * // Undoes the last modification to the editor
  20628. * tinymce.activeEditor.undoManager.undo();
  20629. */
  20630. self.undoManager = new UndoManager(self);
  20631. self.forceBlocks = new ForceBlocks(self);
  20632. self.enterKey = new EnterKey(self);
  20633. self.editorCommands = new EditorCommands(self);
  20634. self.fire('PreInit');
  20635. if (!settings.browser_spellcheck && !settings.gecko_spellcheck) {
  20636. doc.body.spellcheck = false; // Gecko
  20637. DOM.setAttrib(body, "spellcheck", "false");
  20638. }
  20639. self.fire('PostRender');
  20640. self.quirks = Quirks(self);
  20641. if (settings.directionality) {
  20642. body.dir = settings.directionality;
  20643. }
  20644. if (settings.nowrap) {
  20645. body.style.whiteSpace = "nowrap";
  20646. }
  20647. if (settings.protect) {
  20648. self.on('BeforeSetContent', function(e) {
  20649. each(settings.protect, function(pattern) {
  20650. e.content = e.content.replace(pattern, function(str) {
  20651. return '<!--mce:protected ' + escape(str) + '-->';
  20652. });
  20653. });
  20654. });
  20655. }
  20656. self.on('SetContent', function() {
  20657. self.addVisual(self.getBody());
  20658. });
  20659. // Remove empty contents
  20660. if (settings.padd_empty_editor) {
  20661. self.on('PostProcess', function(e) {
  20662. e.content = e.content.replace(/^(<p[^>]*>(&nbsp;|&#160;|\s|\u00a0|)<\/p>[\r\n]*|<br \/>[\r\n]*)$/, '');
  20663. });
  20664. }
  20665. self.load({initial: true, format: 'html'});
  20666. self.startContent = self.getContent({format: 'raw'});
  20667. /**
  20668. * Is set to true after the editor instance has been initialized
  20669. *
  20670. * @property initialized
  20671. * @type Boolean
  20672. * @example
  20673. * function isEditorInitialized(editor) {
  20674. * return editor && editor.initialized;
  20675. * }
  20676. */
  20677. self.initialized = true;
  20678. each(self._pendingNativeEvents, function(name) {
  20679. self.dom.bind(getEventTarget(self, name), name, function(e) {
  20680. self.fire(e.type, e);
  20681. });
  20682. });
  20683. self.fire('init');
  20684. self.focus(true);
  20685. self.nodeChanged({initial: true});
  20686. self.execCallback('init_instance_callback', self);
  20687. // Add editor specific CSS styles
  20688. if (self.contentStyles.length > 0) {
  20689. contentCssText = '';
  20690. each(self.contentStyles, function(style) {
  20691. contentCssText += style + "\r\n";
  20692. });
  20693. self.dom.addStyle(contentCssText);
  20694. }
  20695. // Load specified content CSS last
  20696. each(self.contentCSS, function(cssUrl) {
  20697. if (!self.loadedCSS[cssUrl]) {
  20698. self.dom.loadCSS(cssUrl);
  20699. self.loadedCSS[cssUrl] = true;
  20700. }
  20701. });
  20702. // Handle auto focus
  20703. if (settings.auto_focus) {
  20704. setTimeout(function () {
  20705. var ed = self.editorManager.get(settings.auto_focus);
  20706. ed.selection.select(ed.getBody(), 1);
  20707. ed.selection.collapse(1);
  20708. ed.getBody().focus();
  20709. ed.getWin().focus();
  20710. }, 100);
  20711. }
  20712. // Clean up references for IE
  20713. targetElm = doc = body = null;
  20714. },
  20715. /**
  20716. * Focuses/activates the editor. This will set this editor as the activeEditor in the tinymce collection
  20717. * it will also place DOM focus inside the editor.
  20718. *
  20719. * @method focus
  20720. * @param {Boolean} skip_focus Skip DOM focus. Just set is as the active editor.
  20721. */
  20722. focus: function(skip_focus) {
  20723. var oed, self = this, selection = self.selection, contentEditable = self.settings.content_editable, rng;
  20724. var controlElm, doc = self.getDoc(), body;
  20725. if (!skip_focus) {
  20726. // Get selected control element
  20727. rng = selection.getRng();
  20728. if (rng.item) {
  20729. controlElm = rng.item(0);
  20730. }
  20731. self._refreshContentEditable();
  20732. // Focus the window iframe
  20733. if (!contentEditable) {
  20734. // WebKit needs this call to fire focusin event properly see #5948
  20735. // But Opera pre Blink engine will produce an empty selection so skip Opera
  20736. if (!Env.opera) {
  20737. self.getBody().focus();
  20738. }
  20739. self.getWin().focus();
  20740. }
  20741. // Focus the body as well since it's contentEditable
  20742. if (isGecko || contentEditable) {
  20743. body = self.getBody();
  20744. // Check for setActive since it doesn't scroll to the element
  20745. if (body.setActive) {
  20746. // IE 11 sometimes throws "Invalid function" then fallback to focus
  20747. try {
  20748. body.setActive();
  20749. } catch (ex) {
  20750. body.focus();
  20751. }
  20752. } else {
  20753. body.focus();
  20754. }
  20755. if (contentEditable) {
  20756. selection.normalize();
  20757. }
  20758. }
  20759. // Restore selected control element
  20760. // This is needed when for example an image is selected within a
  20761. // layer a call to focus will then remove the control selection
  20762. if (controlElm && controlElm.ownerDocument == doc) {
  20763. rng = doc.body.createControlRange();
  20764. rng.addElement(controlElm);
  20765. rng.select();
  20766. }
  20767. }
  20768. if (self.editorManager.activeEditor != self) {
  20769. if ((oed = self.editorManager.activeEditor)) {
  20770. oed.fire('deactivate', {relatedTarget: self});
  20771. }
  20772. self.fire('activate', {relatedTarget: oed});
  20773. }
  20774. self.editorManager.activeEditor = self;
  20775. },
  20776. /**
  20777. * Executes a legacy callback. This method is useful to call old 2.x option callbacks.
  20778. * There new event model is a better way to add callback so this method might be removed in the future.
  20779. *
  20780. * @method execCallback
  20781. * @param {String} name Name of the callback to execute.
  20782. * @return {Object} Return value passed from callback function.
  20783. */
  20784. execCallback: function(name) {
  20785. var self = this, callback = self.settings[name], scope;
  20786. if (!callback) {
  20787. return;
  20788. }
  20789. // Look through lookup
  20790. if (self.callbackLookup && (scope = self.callbackLookup[name])) {
  20791. callback = scope.func;
  20792. scope = scope.scope;
  20793. }
  20794. if (typeof(callback) === 'string') {
  20795. scope = callback.replace(/\.\w+$/, '');
  20796. scope = scope ? resolve(scope) : 0;
  20797. callback = resolve(callback);
  20798. self.callbackLookup = self.callbackLookup || {};
  20799. self.callbackLookup[name] = {func: callback, scope: scope};
  20800. }
  20801. return callback.apply(scope || self, Array.prototype.slice.call(arguments, 1));
  20802. },
  20803. /**
  20804. * Translates the specified string by replacing variables with language pack items it will also check if there is
  20805. * a key mathcin the input.
  20806. *
  20807. * @method translate
  20808. * @param {String} text String to translate by the language pack data.
  20809. * @return {String} Translated string.
  20810. */
  20811. translate: function(text) {
  20812. var lang = this.settings.language || 'en', i18n = this.editorManager.i18n;
  20813. if (!text) {
  20814. return '';
  20815. }
  20816. return i18n.data[lang + '.' + text] || text.replace(/\{\#([^\}]+)\}/g, function(a, b) {
  20817. return i18n.data[lang + '.' + b] || '{#' + b + '}';
  20818. });
  20819. },
  20820. /**
  20821. * Returns a language pack item by name/key.
  20822. *
  20823. * @method getLang
  20824. * @param {String} name Name/key to get from the language pack.
  20825. * @param {String} defaultVal Optional default value to retrive.
  20826. */
  20827. getLang: function(name, defaultVal) {
  20828. return (
  20829. this.editorManager.i18n.data[(this.settings.language || 'en') + '.' + name] ||
  20830. (defaultVal !== undefined ? defaultVal : '{#' + name + '}')
  20831. );
  20832. },
  20833. /**
  20834. * Returns a configuration parameter by name.
  20835. *
  20836. * @method getParam
  20837. * @param {String} name Configruation parameter to retrive.
  20838. * @param {String} defaultVal Optional default value to return.
  20839. * @param {String} type Optional type parameter.
  20840. * @return {String} Configuration parameter value or default value.
  20841. * @example
  20842. * // Returns a specific config value from the currently active editor
  20843. * var someval = tinymce.activeEditor.getParam('myvalue');
  20844. *
  20845. * // Returns a specific config value from a specific editor instance by id
  20846. * var someval2 = tinymce.get('my_editor').getParam('myvalue');
  20847. */
  20848. getParam: function(name, defaultVal, type) {
  20849. var value = name in this.settings ? this.settings[name] : defaultVal, output;
  20850. if (type === 'hash') {
  20851. output = {};
  20852. if (typeof(value) === 'string') {
  20853. each(value.indexOf('=') > 0 ? value.split(/[;,](?![^=;,]*(?:[;,]|$))/) : value.split(','), function(value) {
  20854. value = value.split('=');
  20855. if (value.length > 1) {
  20856. output[trim(value[0])] = trim(value[1]);
  20857. } else {
  20858. output[trim(value[0])] = trim(value);
  20859. }
  20860. });
  20861. } else {
  20862. output = value;
  20863. }
  20864. return output;
  20865. }
  20866. return value;
  20867. },
  20868. /**
  20869. * Distpaches out a onNodeChange event to all observers. This method should be called when you
  20870. * need to update the UI states or element path etc.
  20871. *
  20872. * @method nodeChanged
  20873. */
  20874. nodeChanged: function() {
  20875. var self = this, selection = self.selection, node, parents, root;
  20876. // Fix for bug #1896577 it seems that this can not be fired while the editor is loading
  20877. if (self.initialized && !self.settings.disable_nodechange && !self.settings.readonly) {
  20878. // Get start node
  20879. root = self.getBody();
  20880. node = selection.getStart() || root;
  20881. node = ie && node.ownerDocument != self.getDoc() ? self.getBody() : node; // Fix for IE initial state
  20882. // Edge case for <p>|<img></p>
  20883. if (node.nodeName == 'IMG' && selection.isCollapsed()) {
  20884. node = node.parentNode;
  20885. }
  20886. // Get parents and add them to object
  20887. parents = [];
  20888. self.dom.getParent(node, function(node) {
  20889. if (node === root) {
  20890. return true;
  20891. }
  20892. parents.push(node);
  20893. });
  20894. self.fire('NodeChange', {element: node, parents: parents});
  20895. }
  20896. },
  20897. /**
  20898. * Adds a button that later gets created by the theme in the editors toolbars.
  20899. *
  20900. * @method addButton
  20901. * @param {String} name Button name to add.
  20902. * @param {Object} settings Settings object with title, cmd etc.
  20903. * @example
  20904. * // Adds a custom button to the editor that inserts contents when clicked
  20905. * tinymce.init({
  20906. * ...
  20907. *
  20908. * toolbar: 'example'
  20909. *
  20910. * setup: function(ed) {
  20911. * ed.addButton('example', {
  20912. * title: 'My title',
  20913. * image: '../js/tinymce/plugins/example/img/example.gif',
  20914. * onclick: function() {
  20915. * ed.insertContent('Hello world!!');
  20916. * }
  20917. * });
  20918. * }
  20919. * });
  20920. */
  20921. addButton: function(name, settings) {
  20922. var self = this;
  20923. if (settings.cmd) {
  20924. settings.onclick = function() {
  20925. self.execCommand(settings.cmd);
  20926. };
  20927. }
  20928. if (!settings.text && !settings.icon) {
  20929. settings.icon = name;
  20930. }
  20931. self.buttons = self.buttons || {};
  20932. settings.tooltip = settings.tooltip || settings.title;
  20933. self.buttons[name] = settings;
  20934. },
  20935. /**
  20936. * Adds a menu item to be used in the menus of the theme. There might be multiple instances
  20937. * of this menu item for example it might be used in the main menus of the theme but also in
  20938. * the context menu so make sure that it's self contained and supports multiple instances.
  20939. *
  20940. * @method addMenuItem
  20941. * @param {String} name Menu item name to add.
  20942. * @param {Object} settings Settings object with title, cmd etc.
  20943. * @example
  20944. * // Adds a custom menu item to the editor that inserts contents when clicked
  20945. * // The context option allows you to add the menu item to an existing default menu
  20946. * tinymce.init({
  20947. * ...
  20948. *
  20949. * setup: function(ed) {
  20950. * ed.addMenuItem('example', {
  20951. * text: 'My menu item',
  20952. * context: 'tools',
  20953. * onclick: function() {
  20954. * ed.insertContent('Hello world!!');
  20955. * }
  20956. * });
  20957. * }
  20958. * });
  20959. */
  20960. addMenuItem: function(name, settings) {
  20961. var self = this;
  20962. if (settings.cmd) {
  20963. settings.onclick = function() {
  20964. self.execCommand(settings.cmd);
  20965. };
  20966. }
  20967. self.menuItems = self.menuItems || {};
  20968. self.menuItems[name] = settings;
  20969. },
  20970. /**
  20971. * Adds a custom command to the editor, you can also override existing commands with this method.
  20972. * The command that you add can be executed with execCommand.
  20973. *
  20974. * @method addCommand
  20975. * @param {String} name Command name to add/override.
  20976. * @param {addCommandCallback} callback Function to execute when the command occurs.
  20977. * @param {Object} scope Optional scope to execute the function in.
  20978. * @example
  20979. * // Adds a custom command that later can be executed using execCommand
  20980. * tinymce.init({
  20981. * ...
  20982. *
  20983. * setup: function(ed) {
  20984. * // Register example command
  20985. * ed.addCommand('mycommand', function(ui, v) {
  20986. * ed.windowManager.alert('Hello world!! Selection: ' + ed.selection.getContent({format: 'text'}));
  20987. * });
  20988. * }
  20989. * });
  20990. */
  20991. addCommand: function(name, callback, scope) {
  20992. /**
  20993. * Callback function that gets called when a command is executed.
  20994. *
  20995. * @callback addCommandCallback
  20996. * @param {Boolean} ui Display UI state true/false.
  20997. * @param {Object} value Optional value for command.
  20998. * @return {Boolean} True/false state if the command was handled or not.
  20999. */
  21000. this.execCommands[name] = {func: callback, scope: scope || this};
  21001. },
  21002. /**
  21003. * Adds a custom query state command to the editor, you can also override existing commands with this method.
  21004. * The command that you add can be executed with queryCommandState function.
  21005. *
  21006. * @method addQueryStateHandler
  21007. * @param {String} name Command name to add/override.
  21008. * @param {addQueryStateHandlerCallback} callback Function to execute when the command state retrival occurs.
  21009. * @param {Object} scope Optional scope to execute the function in.
  21010. */
  21011. addQueryStateHandler: function(name, callback, scope) {
  21012. /**
  21013. * Callback function that gets called when a queryCommandState is executed.
  21014. *
  21015. * @callback addQueryStateHandlerCallback
  21016. * @return {Boolean} True/false state if the command is enabled or not like is it bold.
  21017. */
  21018. this.queryStateCommands[name] = {func: callback, scope: scope || this};
  21019. },
  21020. /**
  21021. * Adds a custom query value command to the editor, you can also override existing commands with this method.
  21022. * The command that you add can be executed with queryCommandValue function.
  21023. *
  21024. * @method addQueryValueHandler
  21025. * @param {String} name Command name to add/override.
  21026. * @param {addQueryValueHandlerCallback} callback Function to execute when the command value retrival occurs.
  21027. * @param {Object} scope Optional scope to execute the function in.
  21028. */
  21029. addQueryValueHandler: function(name, callback, scope) {
  21030. /**
  21031. * Callback function that gets called when a queryCommandValue is executed.
  21032. *
  21033. * @callback addQueryValueHandlerCallback
  21034. * @return {Object} Value of the command or undefined.
  21035. */
  21036. this.queryValueCommands[name] = {func: callback, scope: scope || this};
  21037. },
  21038. /**
  21039. * Adds a keyboard shortcut for some command or function.
  21040. *
  21041. * @method addShortcut
  21042. * @param {String} pattern Shortcut pattern. Like for example: ctrl+alt+o.
  21043. * @param {String} desc Text description for the command.
  21044. * @param {String/Function} cmdFunc Command name string or function to execute when the key is pressed.
  21045. * @param {Object} sc Optional scope to execute the function in.
  21046. * @return {Boolean} true/false state if the shortcut was added or not.
  21047. */
  21048. addShortcut: function(pattern, desc, cmdFunc, scope) {
  21049. this.shortcuts.add(pattern, desc, cmdFunc, scope);
  21050. },
  21051. /**
  21052. * Executes a command on the current instance. These commands can be TinyMCE internal commands prefixed with "mce" or
  21053. * they can be build in browser commands such as "Bold". A compleate list of browser commands is available on MSDN or Mozilla.org.
  21054. * This function will dispatch the execCommand function on each plugin, theme or the execcommand_callback option if none of these
  21055. * return true it will handle the command as a internal browser command.
  21056. *
  21057. * @method execCommand
  21058. * @param {String} cmd Command name to execute, for example mceLink or Bold.
  21059. * @param {Boolean} ui True/false state if a UI (dialog) should be presented or not.
  21060. * @param {mixed} value Optional command value, this can be anything.
  21061. * @param {Object} a Optional arguments object.
  21062. */
  21063. execCommand: function(cmd, ui, value, args) {
  21064. var self = this, state = 0, cmdItem;
  21065. if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(cmd) && (!args || !args.skip_focus)) {
  21066. self.focus();
  21067. }
  21068. args = extend({}, args);
  21069. args = self.fire('BeforeExecCommand', {command: cmd, ui: ui, value: value});
  21070. if (args.isDefaultPrevented()) {
  21071. return false;
  21072. }
  21073. // Registred commands
  21074. if ((cmdItem = self.execCommands[cmd])) {
  21075. // Fall through on true
  21076. if (cmdItem.func.call(cmdItem.scope, ui, value) !== true) {
  21077. self.fire('ExecCommand', {command: cmd, ui: ui, value: value});
  21078. return true;
  21079. }
  21080. }
  21081. // Plugin commands
  21082. each(self.plugins, function(p) {
  21083. if (p.execCommand && p.execCommand(cmd, ui, value)) {
  21084. self.fire('ExecCommand', {command: cmd, ui: ui, value: value});
  21085. state = true;
  21086. return false;
  21087. }
  21088. });
  21089. if (state) {
  21090. return state;
  21091. }
  21092. // Theme commands
  21093. if (self.theme && self.theme.execCommand && self.theme.execCommand(cmd, ui, value)) {
  21094. self.fire('ExecCommand', {command: cmd, ui: ui, value: value});
  21095. return true;
  21096. }
  21097. // Editor commands
  21098. if (self.editorCommands.execCommand(cmd, ui, value)) {
  21099. self.fire('ExecCommand', {command: cmd, ui: ui, value: value});
  21100. return true;
  21101. }
  21102. // Browser commands
  21103. self.getDoc().execCommand(cmd, ui, value);
  21104. self.fire('ExecCommand', {command: cmd, ui: ui, value: value});
  21105. },
  21106. /**
  21107. * Returns a command specific state, for example if bold is enabled or not.
  21108. *
  21109. * @method queryCommandState
  21110. * @param {string} cmd Command to query state from.
  21111. * @return {Boolean} Command specific state, for example if bold is enabled or not.
  21112. */
  21113. queryCommandState: function(cmd) {
  21114. var self = this, queryItem, returnVal;
  21115. // Is hidden then return undefined
  21116. if (self._isHidden()) {
  21117. return;
  21118. }
  21119. // Registred commands
  21120. if ((queryItem = self.queryStateCommands[cmd])) {
  21121. returnVal = queryItem.func.call(queryItem.scope);
  21122. // Fall though on true
  21123. if (returnVal !== true) {
  21124. return returnVal;
  21125. }
  21126. }
  21127. // Editor commands
  21128. returnVal = self.editorCommands.queryCommandState(cmd);
  21129. if (returnVal !== -1) {
  21130. return returnVal;
  21131. }
  21132. // Browser commands
  21133. try {
  21134. return self.getDoc().queryCommandState(cmd);
  21135. } catch (ex) {
  21136. // Fails sometimes see bug: 1896577
  21137. }
  21138. },
  21139. /**
  21140. * Returns a command specific value, for example the current font size.
  21141. *
  21142. * @method queryCommandValue
  21143. * @param {string} cmd Command to query value from.
  21144. * @return {Object} Command specific value, for example the current font size.
  21145. */
  21146. queryCommandValue: function(cmd) {
  21147. var self = this, queryItem, returnVal;
  21148. // Is hidden then return undefined
  21149. if (self._isHidden()) {
  21150. return;
  21151. }
  21152. // Registred commands
  21153. if ((queryItem = self.queryValueCommands[cmd])) {
  21154. returnVal = queryItem.func.call(queryItem.scope);
  21155. // Fall though on true
  21156. if (returnVal !== true) {
  21157. return returnVal;
  21158. }
  21159. }
  21160. // Editor commands
  21161. returnVal = self.editorCommands.queryCommandValue(cmd);
  21162. if (returnVal !== undefined) {
  21163. return returnVal;
  21164. }
  21165. // Browser commands
  21166. try {
  21167. return self.getDoc().queryCommandValue(cmd);
  21168. } catch (ex) {
  21169. // Fails sometimes see bug: 1896577
  21170. }
  21171. },
  21172. /**
  21173. * Shows the editor and hides any textarea/div that the editor is supposed to replace.
  21174. *
  21175. * @method show
  21176. */
  21177. show: function() {
  21178. var self = this;
  21179. DOM.show(self.getContainer());
  21180. DOM.hide(self.id);
  21181. self.load();
  21182. self.fire('show');
  21183. },
  21184. /**
  21185. * Hides the editor and shows any textarea/div that the editor is supposed to replace.
  21186. *
  21187. * @method hide
  21188. */
  21189. hide: function() {
  21190. var self = this, doc = self.getDoc();
  21191. // Fixed bug where IE has a blinking cursor left from the editor
  21192. if (ie && doc && !self.inline) {
  21193. doc.execCommand('SelectAll');
  21194. }
  21195. // We must save before we hide so Safari doesn't crash
  21196. self.save();
  21197. // defer the call to hide to prevent an IE9 crash #4921
  21198. DOM.hide(self.getContainer());
  21199. DOM.setStyle(self.id, 'display', self.orgDisplay);
  21200. self.fire('hide');
  21201. },
  21202. /**
  21203. * Returns true/false if the editor is hidden or not.
  21204. *
  21205. * @method isHidden
  21206. * @return {Boolean} True/false if the editor is hidden or not.
  21207. */
  21208. isHidden: function() {
  21209. return !DOM.isHidden(this.id);
  21210. },
  21211. /**
  21212. * Sets the progress state, this will display a throbber/progess for the editor.
  21213. * This is ideal for asycronous operations like an AJAX save call.
  21214. *
  21215. * @method setProgressState
  21216. * @param {Boolean} state Boolean state if the progress should be shown or hidden.
  21217. * @param {Number} time Optional time to wait before the progress gets shown.
  21218. * @return {Boolean} Same as the input state.
  21219. * @example
  21220. * // Show progress for the active editor
  21221. * tinymce.activeEditor.setProgressState(true);
  21222. *
  21223. * // Hide progress for the active editor
  21224. * tinymce.activeEditor.setProgressState(false);
  21225. *
  21226. * // Show progress after 3 seconds
  21227. * tinymce.activeEditor.setProgressState(true, 3000);
  21228. */
  21229. setProgressState: function(state, time) {
  21230. this.fire('ProgressState', {state: state, time: time});
  21231. },
  21232. /**
  21233. * Loads contents from the textarea or div element that got converted into an editor instance.
  21234. * This method will move the contents from that textarea or div into the editor by using setContent
  21235. * so all events etc that method has will get dispatched as well.
  21236. *
  21237. * @method load
  21238. * @param {Object} args Optional content object, this gets passed around through the whole load process.
  21239. * @return {String} HTML string that got set into the editor.
  21240. */
  21241. load: function(args) {
  21242. var self = this, elm = self.getElement(), html;
  21243. if (elm) {
  21244. args = args || {};
  21245. args.load = true;
  21246. html = self.setContent(elm.value !== undefined ? elm.value : elm.innerHTML, args);
  21247. args.element = elm;
  21248. if (!args.no_events) {
  21249. self.fire('LoadContent', args);
  21250. }
  21251. args.element = elm = null;
  21252. return html;
  21253. }
  21254. },
  21255. /**
  21256. * Saves the contents from a editor out to the textarea or div element that got converted into an editor instance.
  21257. * This method will move the HTML contents from the editor into that textarea or div by getContent
  21258. * so all events etc that method has will get dispatched as well.
  21259. *
  21260. * @method save
  21261. * @param {Object} args Optional content object, this gets passed around through the whole save process.
  21262. * @return {String} HTML string that got set into the textarea/div.
  21263. */
  21264. save: function(args) {
  21265. var self = this, elm = self.getElement(), html, form;
  21266. if (!elm || !self.initialized) {
  21267. return;
  21268. }
  21269. args = args || {};
  21270. args.save = true;
  21271. args.element = elm;
  21272. html = args.content = self.getContent(args);
  21273. if (!args.no_events) {
  21274. self.fire('SaveContent', args);
  21275. }
  21276. html = args.content;
  21277. if (!/TEXTAREA|INPUT/i.test(elm.nodeName)) {
  21278. // Update DIV element when not in inline mode
  21279. if (!self.inline) {
  21280. elm.innerHTML = html;
  21281. }
  21282. // Update hidden form element
  21283. if ((form = DOM.getParent(self.id, 'form'))) {
  21284. each(form.elements, function(elm) {
  21285. if (elm.name == self.id) {
  21286. elm.value = html;
  21287. return false;
  21288. }
  21289. });
  21290. }
  21291. } else {
  21292. elm.value = html;
  21293. }
  21294. args.element = elm = null;
  21295. if (args.set_dirty !== false) {
  21296. self.isNotDirty = true;
  21297. }
  21298. return html;
  21299. },
  21300. /**
  21301. * Sets the specified content to the editor instance, this will cleanup the content before it gets set using
  21302. * the different cleanup rules options.
  21303. *
  21304. * @method setContent
  21305. * @param {String} content Content to set to editor, normally HTML contents but can be other formats as well.
  21306. * @param {Object} args Optional content object, this gets passed around through the whole set process.
  21307. * @return {String} HTML string that got set into the editor.
  21308. * @example
  21309. * // Sets the HTML contents of the activeEditor editor
  21310. * tinymce.activeEditor.setContent('<span>some</span> html');
  21311. *
  21312. * // Sets the raw contents of the activeEditor editor
  21313. * tinymce.activeEditor.setContent('<span>some</span> html', {format: 'raw'});
  21314. *
  21315. * // Sets the content of a specific editor (my_editor in this example)
  21316. * tinymce.get('my_editor').setContent(data);
  21317. *
  21318. * // Sets the bbcode contents of the activeEditor editor if the bbcode plugin was added
  21319. * tinymce.activeEditor.setContent('[b]some[/b] html', {format: 'bbcode'});
  21320. */
  21321. setContent: function(content, args) {
  21322. var self = this, body = self.getBody(), forcedRootBlockName;
  21323. // Setup args object
  21324. args = args || {};
  21325. args.format = args.format || 'html';
  21326. args.set = true;
  21327. args.content = content;
  21328. // Do preprocessing
  21329. if (!args.no_events) {
  21330. self.fire('BeforeSetContent', args);
  21331. }
  21332. content = args.content;
  21333. // Padd empty content in Gecko and Safari. Commands will otherwise fail on the content
  21334. // It will also be impossible to place the caret in the editor unless there is a BR element present
  21335. if (content.length === 0 || /^\s+$/.test(content)) {
  21336. forcedRootBlockName = self.settings.forced_root_block;
  21337. // Check if forcedRootBlock is configured and that the block is a valid child of the body
  21338. if (forcedRootBlockName && self.schema.isValidChild(body.nodeName.toLowerCase(), forcedRootBlockName.toLowerCase())) {
  21339. // Padd with bogus BR elements on modern browsers and IE 7 and 8 since they don't render empty P tags properly
  21340. content = ie && ie < 11 ? '' : '<br data-mce-bogus="1">';
  21341. content = self.dom.createHTML(forcedRootBlockName, self.settings.forced_root_block_attrs, content);
  21342. } else if (!ie) {
  21343. // We need to add a BR when forced_root_block is disabled on non IE browsers to place the caret
  21344. content = '<br data-mce-bogus="1">';
  21345. }
  21346. body.innerHTML = content;
  21347. self.fire('SetContent', args);
  21348. } else {
  21349. // Parse and serialize the html
  21350. if (args.format !== 'raw') {
  21351. content = new Serializer({}, self.schema).serialize(
  21352. self.parser.parse(content, {isRootContent: true})
  21353. );
  21354. }
  21355. // Set the new cleaned contents to the editor
  21356. args.content = trim(content);
  21357. self.dom.setHTML(body, args.content);
  21358. // Do post processing
  21359. if (!args.no_events) {
  21360. self.fire('SetContent', args);
  21361. }
  21362. // Don't normalize selection if the focused element isn't the body in
  21363. // content editable mode since it will steal focus otherwise
  21364. /*if (!self.settings.content_editable || document.activeElement === self.getBody()) {
  21365. self.selection.normalize();
  21366. }*/
  21367. }
  21368. return args.content;
  21369. },
  21370. /**
  21371. * Gets the content from the editor instance, this will cleanup the content before it gets returned using
  21372. * the different cleanup rules options.
  21373. *
  21374. * @method getContent
  21375. * @param {Object} args Optional content object, this gets passed around through the whole get process.
  21376. * @return {String} Cleaned content string, normally HTML contents.
  21377. * @example
  21378. * // Get the HTML contents of the currently active editor
  21379. * console.debug(tinymce.activeEditor.getContent());
  21380. *
  21381. * // Get the raw contents of the currently active editor
  21382. * tinymce.activeEditor.getContent({format: 'raw'});
  21383. *
  21384. * // Get content of a specific editor:
  21385. * tinymce.get('content id').getContent()
  21386. */
  21387. getContent: function(args) {
  21388. var self = this, content, body = self.getBody();
  21389. // Setup args object
  21390. args = args || {};
  21391. args.format = args.format || 'html';
  21392. args.get = true;
  21393. args.getInner = true;
  21394. // Do preprocessing
  21395. if (!args.no_events) {
  21396. self.fire('BeforeGetContent', args);
  21397. }
  21398. // Get raw contents or by default the cleaned contents
  21399. if (args.format == 'raw') {
  21400. content = body.innerHTML;
  21401. } else if (args.format == 'text') {
  21402. content = body.innerText || body.textContent;
  21403. } else {
  21404. content = self.serializer.serialize(body, args);
  21405. }
  21406. // Trim whitespace in beginning/end of HTML
  21407. if (args.format != 'text') {
  21408. args.content = trim(content);
  21409. } else {
  21410. args.content = content;
  21411. }
  21412. // Do post processing
  21413. if (!args.no_events) {
  21414. self.fire('GetContent', args);
  21415. }
  21416. return args.content;
  21417. },
  21418. /**
  21419. * Inserts content at caret position.
  21420. *
  21421. * @method insertContent
  21422. * @param {String} content Content to insert.
  21423. */
  21424. insertContent: function(content) {
  21425. this.execCommand('mceInsertContent', false, content);
  21426. },
  21427. /**
  21428. * Returns true/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents.
  21429. *
  21430. * @method isDirty
  21431. * @return {Boolean} True/false if the editor is dirty or not. It will get dirty if the user has made modifications to the contents.
  21432. * @example
  21433. * if (tinymce.activeEditor.isDirty())
  21434. * alert("You must save your contents.");
  21435. */
  21436. isDirty: function() {
  21437. return !this.isNotDirty;
  21438. },
  21439. /**
  21440. * Returns the editors container element. The container element wrappes in
  21441. * all the elements added to the page for the editor. Such as UI, iframe etc.
  21442. *
  21443. * @method getContainer
  21444. * @return {Element} HTML DOM element for the editor container.
  21445. */
  21446. getContainer: function() {
  21447. var self = this;
  21448. if (!self.container) {
  21449. self.container = DOM.get(self.editorContainer || self.id + '_parent');
  21450. }
  21451. return self.container;
  21452. },
  21453. /**
  21454. * Returns the editors content area container element. The this element is the one who
  21455. * holds the iframe or the editable element.
  21456. *
  21457. * @method getContentAreaContainer
  21458. * @return {Element} HTML DOM element for the editor area container.
  21459. */
  21460. getContentAreaContainer: function() {
  21461. return this.contentAreaContainer;
  21462. },
  21463. /**
  21464. * Returns the target element/textarea that got replaced with a TinyMCE editor instance.
  21465. *
  21466. * @method getElement
  21467. * @return {Element} HTML DOM element for the replaced element.
  21468. */
  21469. getElement: function() {
  21470. return DOM.get(this.settings.content_element || this.id);
  21471. },
  21472. /**
  21473. * Returns the iframes window object.
  21474. *
  21475. * @method getWin
  21476. * @return {Window} Iframe DOM window object.
  21477. */
  21478. getWin: function() {
  21479. var self = this, elm;
  21480. if (!self.contentWindow) {
  21481. elm = DOM.get(self.id + "_ifr");
  21482. if (elm) {
  21483. self.contentWindow = elm.contentWindow;
  21484. }
  21485. }
  21486. return self.contentWindow;
  21487. },
  21488. /**
  21489. * Returns the iframes document object.
  21490. *
  21491. * @method getDoc
  21492. * @return {Document} Iframe DOM document object.
  21493. */
  21494. getDoc: function() {
  21495. var self = this, win;
  21496. if (!self.contentDocument) {
  21497. win = self.getWin();
  21498. if (win) {
  21499. self.contentDocument = win.document;
  21500. }
  21501. }
  21502. return self.contentDocument;
  21503. },
  21504. /**
  21505. * Returns the iframes body element.
  21506. *
  21507. * @method getBody
  21508. * @return {Element} Iframe body element.
  21509. */
  21510. getBody: function() {
  21511. return this.bodyElement || this.getDoc().body;
  21512. },
  21513. /**
  21514. * URL converter function this gets executed each time a user adds an img, a or
  21515. * any other element that has a URL in it. This will be called both by the DOM and HTML
  21516. * manipulation functions.
  21517. *
  21518. * @method convertURL
  21519. * @param {string} url URL to convert.
  21520. * @param {string} name Attribute name src, href etc.
  21521. * @param {string/HTMLElement} elm Tag name or HTML DOM element depending on HTML or DOM insert.
  21522. * @return {string} Converted URL string.
  21523. */
  21524. convertURL: function(url, name, elm) {
  21525. var self = this, settings = self.settings;
  21526. // Use callback instead
  21527. if (settings.urlconverter_callback) {
  21528. return self.execCallback('urlconverter_callback', url, elm, true, name);
  21529. }
  21530. // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs
  21531. if (!settings.convert_urls || (elm && elm.nodeName == 'LINK') || url.indexOf('file:') === 0 || url.length === 0) {
  21532. return url;
  21533. }
  21534. // Convert to relative
  21535. if (settings.relative_urls) {
  21536. return self.documentBaseURI.toRelative(url);
  21537. }
  21538. // Convert to absolute
  21539. url = self.documentBaseURI.toAbsolute(url, settings.remove_script_host);
  21540. return url;
  21541. },
  21542. /**
  21543. * Adds visual aid for tables, anchors etc so they can be more easily edited inside the editor.
  21544. *
  21545. * @method addVisual
  21546. * @param {Element} elm Optional root element to loop though to find tables etc that needs the visual aid.
  21547. */
  21548. addVisual: function(elm) {
  21549. var self = this, settings = self.settings, dom = self.dom, cls;
  21550. elm = elm || self.getBody();
  21551. if (self.hasVisual === undefined) {
  21552. self.hasVisual = settings.visual;
  21553. }
  21554. each(dom.select('table,a', elm), function(elm) {
  21555. var value;
  21556. switch (elm.nodeName) {
  21557. case 'TABLE':
  21558. cls = settings.visual_table_class || 'mce-item-table';
  21559. value = dom.getAttrib(elm, 'border');
  21560. if (!value || value == '0') {
  21561. if (self.hasVisual) {
  21562. dom.addClass(elm, cls);
  21563. } else {
  21564. dom.removeClass(elm, cls);
  21565. }
  21566. }
  21567. return;
  21568. case 'A':
  21569. if (!dom.getAttrib(elm, 'href', false)) {
  21570. value = dom.getAttrib(elm, 'name') || elm.id;
  21571. cls = settings.visual_anchor_class || 'mce-item-anchor';
  21572. if (value) {
  21573. if (self.hasVisual) {
  21574. dom.addClass(elm, cls);
  21575. } else {
  21576. dom.removeClass(elm, cls);
  21577. }
  21578. }
  21579. }
  21580. return;
  21581. }
  21582. });
  21583. self.fire('VisualAid', {element: elm, hasVisual: self.hasVisual});
  21584. },
  21585. /**
  21586. * Removes the editor from the dom and tinymce collection.
  21587. *
  21588. * @method remove
  21589. */
  21590. remove: function() {
  21591. var self = this;
  21592. if (!self.removed) {
  21593. self.removed = 1;
  21594. self.save();
  21595. // Remove any hidden input
  21596. if (self.hasHiddenInput) {
  21597. DOM.remove(self.getElement().nextSibling);
  21598. }
  21599. if (!self.inline) {
  21600. // IE 9 has a bug where the selection stops working if you place the
  21601. // caret inside the editor then remove the iframe
  21602. if (ie && ie < 10) {
  21603. self.getDoc().execCommand('SelectAll', false, null);
  21604. }
  21605. DOM.setStyle(self.id, 'display', self.orgDisplay);
  21606. self.getBody().onload = null; // Prevent #6816
  21607. // Don't clear the window or document if content editable
  21608. // is enabled since other instances might still be present
  21609. Event.unbind(self.getWin());
  21610. Event.unbind(self.getDoc());
  21611. }
  21612. var elm = self.getContainer();
  21613. Event.unbind(self.getBody());
  21614. Event.unbind(elm);
  21615. self.fire('remove');
  21616. self.editorManager.remove(self);
  21617. DOM.remove(elm);
  21618. self.destroy();
  21619. }
  21620. },
  21621. bindNative: function(name) {
  21622. var self = this;
  21623. if (self.settings.readonly) {
  21624. return;
  21625. }
  21626. if (self.initialized) {
  21627. self.dom.bind(getEventTarget(self, name), name, function(e) {
  21628. self.fire(name, e);
  21629. });
  21630. } else {
  21631. if (!self._pendingNativeEvents) {
  21632. self._pendingNativeEvents = [name];
  21633. } else {
  21634. self._pendingNativeEvents.push(name);
  21635. }
  21636. }
  21637. },
  21638. unbindNative: function(name) {
  21639. var self = this;
  21640. if (self.initialized) {
  21641. self.dom.unbind(name);
  21642. }
  21643. },
  21644. /**
  21645. * Destroys the editor instance by removing all events, element references or other resources
  21646. * that could leak memory. This method will be called automatically when the page is unloaded
  21647. * but you can also call it directly if you know what you are doing.
  21648. *
  21649. * @method destroy
  21650. * @param {Boolean} automatic Optional state if the destroy is an automatic destroy or user called one.
  21651. */
  21652. destroy: function(automatic) {
  21653. var self = this, form;
  21654. // One time is enough
  21655. if (self.destroyed) {
  21656. return;
  21657. }
  21658. // If user manually calls destroy and not remove
  21659. // Users seems to have logic that calls destroy instead of remove
  21660. if (!automatic && !self.removed) {
  21661. self.remove();
  21662. return;
  21663. }
  21664. // We must unbind on Gecko since it would otherwise produce the pesky "attempt
  21665. // to run compile-and-go script on a cleared scope" message
  21666. if (automatic && isGecko) {
  21667. Event.unbind(self.getDoc());
  21668. Event.unbind(self.getWin());
  21669. Event.unbind(self.getBody());
  21670. }
  21671. if (!automatic) {
  21672. self.editorManager.off('beforeunload', self._beforeUnload);
  21673. // Manual destroy
  21674. if (self.theme && self.theme.destroy) {
  21675. self.theme.destroy();
  21676. }
  21677. // Destroy controls, selection and dom
  21678. self.selection.destroy();
  21679. self.dom.destroy();
  21680. }
  21681. form = self.formElement;
  21682. if (form) {
  21683. if (form._mceOldSubmit) {
  21684. form.submit = form._mceOldSubmit;
  21685. form._mceOldSubmit = null;
  21686. }
  21687. DOM.unbind(form, 'submit reset', self.formEventDelegate);
  21688. }
  21689. self.contentAreaContainer = self.formElement = self.container = self.editorContainer = null;
  21690. self.settings.content_element = self.bodyElement = self.contentDocument = self.contentWindow = null;
  21691. if (self.selection) {
  21692. self.selection = self.selection.win = self.selection.dom = self.selection.dom.doc = null;
  21693. }
  21694. self.destroyed = 1;
  21695. },
  21696. // Internal functions
  21697. _refreshContentEditable: function() {
  21698. var self = this, body, parent;
  21699. // Check if the editor was hidden and the re-initalize contentEditable mode by removing and adding the body again
  21700. if (self._isHidden()) {
  21701. body = self.getBody();
  21702. parent = body.parentNode;
  21703. parent.removeChild(body);
  21704. parent.appendChild(body);
  21705. body.focus();
  21706. }
  21707. },
  21708. _isHidden: function() {
  21709. var sel;
  21710. if (!isGecko) {
  21711. return 0;
  21712. }
  21713. // Weird, wheres that cursor selection?
  21714. sel = this.selection.getSel();
  21715. return (!sel || !sel.rangeCount || sel.rangeCount === 0);
  21716. }
  21717. };
  21718. extend(Editor.prototype, Observable);
  21719. return Editor;
  21720. });
  21721. // Included from: js/tinymce/classes/util/I18n.js
  21722. /**
  21723. * I18n.js
  21724. *
  21725. * Copyright, Moxiecode Systems AB
  21726. * Released under LGPL License.
  21727. *
  21728. * License: http://www.tinymce.com/license
  21729. * Contributing: http://www.tinymce.com/contributing
  21730. */
  21731. /**
  21732. * I18n class that handles translation of TinyMCE UI.
  21733. * Uses po style with csharp style parameters.
  21734. *
  21735. * @class tinymce.util.I18n
  21736. */
  21737. define("tinymce/util/I18n", [], function() {
  21738. "use strict";
  21739. var data = {};
  21740. return {
  21741. /**
  21742. * Property gets set to true if a RTL language pack was loaded.
  21743. *
  21744. * @property rtl
  21745. * @type Boolean
  21746. */
  21747. rtl: false,
  21748. /**
  21749. * Adds translations for a specific language code.
  21750. *
  21751. * @method add
  21752. * @param {String} code Language code like sv_SE.
  21753. * @param {Array} items Name/value array with English en_US to sv_SE.
  21754. */
  21755. add: function(code, items) {
  21756. for (var name in items) {
  21757. data[name] = items[name];
  21758. }
  21759. this.rtl = this.rtl || data._dir === 'rtl';
  21760. },
  21761. /**
  21762. * Translates the specified text.
  21763. *
  21764. * It has a few formats:
  21765. * I18n.translate("Text");
  21766. * I18n.translate(["Text {0}/{1}", 0, 1]);
  21767. * I18n.translate({raw: "Raw string"});
  21768. *
  21769. * @method translate
  21770. * @param {String/Object/Array} text Text to translate.
  21771. * @return {String} String that got translated.
  21772. */
  21773. translate: function(text) {
  21774. if (typeof(text) == "undefined") {
  21775. return text;
  21776. }
  21777. if (typeof(text) != "string" && text.raw) {
  21778. return text.raw;
  21779. }
  21780. if (text.push) {
  21781. var values = text.slice(1);
  21782. text = (data[text[0]] || text[0]).replace(/\{([^\}]+)\}/g, function(match1, match2) {
  21783. return values[match2];
  21784. });
  21785. }
  21786. return data[text] || text;
  21787. },
  21788. data: data
  21789. };
  21790. });
  21791. // Included from: js/tinymce/classes/FocusManager.js
  21792. /**
  21793. * FocusManager.js
  21794. *
  21795. * Copyright, Moxiecode Systems AB
  21796. * Released under LGPL License.
  21797. *
  21798. * License: http://www.tinymce.com/license
  21799. * Contributing: http://www.tinymce.com/contributing
  21800. */
  21801. /**
  21802. * This class manages the focus/blur state of the editor. This class is needed since some
  21803. * browsers fire false focus/blur states when the selection is moved to a UI dialog or similar.
  21804. *
  21805. * This class will fire two events focus and blur on the editor instances that got affected.
  21806. * It will also handle the restore of selection when the focus is lost and returned.
  21807. *
  21808. * @class tinymce.FocusManager
  21809. */
  21810. define("tinymce/FocusManager", [
  21811. "tinymce/dom/DOMUtils",
  21812. "tinymce/Env"
  21813. ], function(DOMUtils, Env) {
  21814. var selectionChangeHandler, documentFocusInHandler, documentMouseUpHandler, DOM = DOMUtils.DOM;
  21815. /**
  21816. * Constructs a new focus manager instance.
  21817. *
  21818. * @constructor FocusManager
  21819. * @param {tinymce.EditorManager} editorManager Editor manager instance to handle focus for.
  21820. */
  21821. function FocusManager(editorManager) {
  21822. function getActiveElement() {
  21823. try {
  21824. return document.activeElement;
  21825. } catch (ex) {
  21826. // IE sometimes fails to get the activeElement when resizing table
  21827. // TODO: Investigate this
  21828. return document.body;
  21829. }
  21830. }
  21831. // We can't store a real range on IE 11 since it gets mutated so we need to use a bookmark object
  21832. // TODO: Move this to a separate range utils class since it's it's logic is present in Selection as well.
  21833. function createBookmark(dom, rng) {
  21834. if (rng && rng.startContainer) {
  21835. // Verify that the range is within the root of the editor
  21836. if (!dom.isChildOf(rng.startContainer, dom.getRoot()) || !dom.isChildOf(rng.endContainer, dom.getRoot())) {
  21837. return;
  21838. }
  21839. return {
  21840. startContainer: rng.startContainer,
  21841. startOffset: rng.startOffset,
  21842. endContainer: rng.endContainer,
  21843. endOffset: rng.endOffset
  21844. };
  21845. }
  21846. return rng;
  21847. }
  21848. function bookmarkToRng(editor, bookmark) {
  21849. var rng;
  21850. if (bookmark.startContainer) {
  21851. rng = editor.getDoc().createRange();
  21852. rng.setStart(bookmark.startContainer, bookmark.startOffset);
  21853. rng.setEnd(bookmark.endContainer, bookmark.endOffset);
  21854. } else {
  21855. rng = bookmark;
  21856. }
  21857. return rng;
  21858. }
  21859. function isUIElement(elm) {
  21860. return !!DOM.getParent(elm, FocusManager.isEditorUIElement);
  21861. }
  21862. function registerEvents(e) {
  21863. var editor = e.editor;
  21864. editor.on('init', function() {
  21865. // Gecko/WebKit has ghost selections in iframes and IE only has one selection per browser tab
  21866. if (editor.inline || Env.ie) {
  21867. // On other browsers take snapshot on nodechange in inline mode since they have Ghost selections for iframes
  21868. editor.on('nodechange keyup', function() {
  21869. var node = document.activeElement;
  21870. // IE 11 reports active element as iframe not body of iframe
  21871. if (node && node.id == editor.id + '_ifr') {
  21872. node = editor.getBody();
  21873. }
  21874. if (editor.dom.isChildOf(node, editor.getBody())) {
  21875. editor.lastRng = editor.selection.getRng();
  21876. }
  21877. });
  21878. // Handles the issue with WebKit not retaining selection within inline document
  21879. // If the user releases the mouse out side the body since a mouse up event wont occur on the body
  21880. if (Env.webkit && !selectionChangeHandler) {
  21881. selectionChangeHandler = function() {
  21882. var activeEditor = editorManager.activeEditor;
  21883. if (activeEditor && activeEditor.selection) {
  21884. var rng = activeEditor.selection.getRng();
  21885. // Store when it's non collapsed
  21886. if (rng && !rng.collapsed) {
  21887. editor.lastRng = rng;
  21888. }
  21889. }
  21890. };
  21891. DOM.bind(document, 'selectionchange', selectionChangeHandler);
  21892. }
  21893. }
  21894. });
  21895. editor.on('setcontent', function() {
  21896. editor.lastRng = null;
  21897. });
  21898. // Remove last selection bookmark on mousedown see #6305
  21899. editor.on('mousedown', function() {
  21900. editor.selection.lastFocusBookmark = null;
  21901. });
  21902. editor.on('focusin', function() {
  21903. var focusedEditor = editorManager.focusedEditor;
  21904. if (editor.selection.lastFocusBookmark) {
  21905. editor.selection.setRng(bookmarkToRng(editor, editor.selection.lastFocusBookmark));
  21906. editor.selection.lastFocusBookmark = null;
  21907. }
  21908. if (focusedEditor != editor) {
  21909. if (focusedEditor) {
  21910. focusedEditor.fire('blur', {focusedEditor: editor});
  21911. }
  21912. editorManager.activeEditor = editor;
  21913. editorManager.focusedEditor = editor;
  21914. editor.fire('focus', {blurredEditor: focusedEditor});
  21915. editor.focus(true);
  21916. }
  21917. editor.lastRng = null;
  21918. });
  21919. editor.on('focusout', function() {
  21920. window.setTimeout(function() {
  21921. var focusedEditor = editorManager.focusedEditor;
  21922. // Still the same editor the the blur was outside any editor UI
  21923. if (!isUIElement(getActiveElement()) && focusedEditor == editor) {
  21924. editor.fire('blur', {focusedEditor: null});
  21925. editorManager.focusedEditor = null;
  21926. // Make sure selection is valid could be invalid if the editor is blured and removed before the timeout occurs
  21927. if (editor.selection) {
  21928. editor.selection.lastFocusBookmark = null;
  21929. }
  21930. }
  21931. }, 0);
  21932. });
  21933. // Check if focus is moved to an element outside the active editor by checking if the target node
  21934. // isn't within the body of the activeEditor nor a UI element such as a dialog child control
  21935. if (!documentFocusInHandler) {
  21936. documentFocusInHandler = function(e) {
  21937. var activeEditor = editorManager.activeEditor;
  21938. if (activeEditor && e.target.ownerDocument == document) {
  21939. // Check to make sure we have a valid selection
  21940. if (activeEditor.selection) {
  21941. activeEditor.selection.lastFocusBookmark = createBookmark(activeEditor.dom, activeEditor.lastRng);
  21942. }
  21943. // Fire a blur event if the element isn't a UI element
  21944. if (!isUIElement(e.target) && editorManager.focusedEditor == activeEditor) {
  21945. activeEditor.fire('blur', {focusedEditor: null});
  21946. editorManager.focusedEditor = null;
  21947. }
  21948. }
  21949. };
  21950. DOM.bind(document, 'focusin', documentFocusInHandler);
  21951. }
  21952. // Handle edge case when user starts the selection inside the editor and releases
  21953. // the mouse outside the editor producing a new selection. This weird workaround is needed since
  21954. // Gecko doesn't have the "selectionchange" event we need to do this. Fixes: #6843
  21955. if (editor.inline && !documentMouseUpHandler) {
  21956. documentMouseUpHandler = function(e) {
  21957. var activeEditor = editorManager.activeEditor;
  21958. if (activeEditor.inline && !activeEditor.dom.isChildOf(e.target, activeEditor.getBody())) {
  21959. var rng = activeEditor.selection.getRng();
  21960. if (!rng.collapsed) {
  21961. activeEditor.lastRng = rng;
  21962. }
  21963. }
  21964. };
  21965. DOM.bind(document, 'mouseup', documentMouseUpHandler);
  21966. }
  21967. }
  21968. function unregisterDocumentEvents(e) {
  21969. if (editorManager.focusedEditor == e.editor) {
  21970. editorManager.focusedEditor = null;
  21971. }
  21972. if (!editorManager.activeEditor) {
  21973. DOM.unbind(document, 'selectionchange', selectionChangeHandler);
  21974. DOM.unbind(document, 'focusin', documentFocusInHandler);
  21975. DOM.unbind(document, 'mouseup', documentMouseUpHandler);
  21976. selectionChangeHandler = documentFocusInHandler = documentMouseUpHandler = null;
  21977. }
  21978. }
  21979. editorManager.on('AddEditor', registerEvents);
  21980. editorManager.on('RemoveEditor', unregisterDocumentEvents);
  21981. }
  21982. /**
  21983. * Returns true if the specified element is part of the UI for example an button or text input.
  21984. *
  21985. * @method isEditorUIElement
  21986. * @param {Element} elm Element to check if it's part of the UI or not.
  21987. * @return {Boolean} True/false state if the element is part of the UI or not.
  21988. */
  21989. FocusManager.isEditorUIElement = function(elm) {
  21990. // Needs to be converted to string since svg can have focus: #6776
  21991. return elm.className.toString().indexOf('mce-') !== -1;
  21992. };
  21993. return FocusManager;
  21994. });
  21995. // Included from: js/tinymce/classes/EditorManager.js
  21996. /**
  21997. * EditorManager.js
  21998. *
  21999. * Copyright, Moxiecode Systems AB
  22000. * Released under LGPL License.
  22001. *
  22002. * License: http://www.tinymce.com/license
  22003. * Contributing: http://www.tinymce.com/contributing
  22004. */
  22005. /**
  22006. * This class used as a factory for manager for tinymce.Editor instances.
  22007. *
  22008. * @example
  22009. * tinymce.EditorManager.init({});
  22010. *
  22011. * @class tinymce.EditorManager
  22012. * @mixes tinymce.util.Observable
  22013. * @static
  22014. */
  22015. define("tinymce/EditorManager", [
  22016. "tinymce/Editor",
  22017. "tinymce/dom/DOMUtils",
  22018. "tinymce/util/URI",
  22019. "tinymce/Env",
  22020. "tinymce/util/Tools",
  22021. "tinymce/util/Observable",
  22022. "tinymce/util/I18n",
  22023. "tinymce/FocusManager"
  22024. ], function(Editor, DOMUtils, URI, Env, Tools, Observable, I18n, FocusManager) {
  22025. var DOM = DOMUtils.DOM;
  22026. var explode = Tools.explode, each = Tools.each, extend = Tools.extend;
  22027. var instanceCounter = 0, beforeUnloadDelegate, EditorManager;
  22028. function removeEditorFromList(editor) {
  22029. var editors = EditorManager.editors, removedFromList;
  22030. delete editors[editor.id];
  22031. for (var i = 0; i < editors.length; i++) {
  22032. if (editors[i] == editor) {
  22033. editors.splice(i, 1);
  22034. removedFromList = true;
  22035. break;
  22036. }
  22037. }
  22038. // Select another editor since the active one was removed
  22039. if (EditorManager.activeEditor == editor) {
  22040. EditorManager.activeEditor = editors[0];
  22041. }
  22042. // Clear focusedEditor if necessary, so that we don't try to blur the destroyed editor
  22043. if (EditorManager.focusedEditor == editor) {
  22044. EditorManager.focusedEditor = null;
  22045. }
  22046. return removedFromList;
  22047. }
  22048. function purgeDestroyedEditor(editor) {
  22049. // User has manually destroyed the editor lets clean up the mess
  22050. if (editor && !(editor.getContainer() || editor.getBody()).parentNode) {
  22051. removeEditorFromList(editor);
  22052. editor.destroy(true);
  22053. editor = null;
  22054. }
  22055. return editor;
  22056. }
  22057. EditorManager = {
  22058. /**
  22059. * Major version of TinyMCE build.
  22060. *
  22061. * @property majorVersion
  22062. * @type String
  22063. */
  22064. majorVersion : '4',
  22065. /**
  22066. * Minor version of TinyMCE build.
  22067. *
  22068. * @property minorVersion
  22069. * @type String
  22070. */
  22071. minorVersion : '0.23',
  22072. /**
  22073. * Release date of TinyMCE build.
  22074. *
  22075. * @property releaseDate
  22076. * @type String
  22077. */
  22078. releaseDate: '2014-04-24',
  22079. /**
  22080. * Collection of editor instances.
  22081. *
  22082. * @property editors
  22083. * @type Object
  22084. * @example
  22085. * for (edId in tinymce.editors)
  22086. * tinymce.editors[edId].save();
  22087. */
  22088. editors: [],
  22089. /**
  22090. * Collection of language pack data.
  22091. *
  22092. * @property i18n
  22093. * @type Object
  22094. */
  22095. i18n: I18n,
  22096. /**
  22097. * Currently active editor instance.
  22098. *
  22099. * @property activeEditor
  22100. * @type tinymce.Editor
  22101. * @example
  22102. * tinyMCE.activeEditor.selection.getContent();
  22103. * tinymce.EditorManager.activeEditor.selection.getContent();
  22104. */
  22105. activeEditor: null,
  22106. setup: function() {
  22107. var self = this, baseURL, documentBaseURL, suffix = "", preInit, src;
  22108. // Get base URL for the current document
  22109. documentBaseURL = document.location.href.replace(/[\?#].*$/, '').replace(/[\/\\][^\/]+$/, '');
  22110. if (!/[\/\\]$/.test(documentBaseURL)) {
  22111. documentBaseURL += '/';
  22112. }
  22113. // If tinymce is defined and has a base use that or use the old tinyMCEPreInit
  22114. preInit = window.tinymce || window.tinyMCEPreInit;
  22115. if (preInit) {
  22116. baseURL = preInit.base || preInit.baseURL;
  22117. suffix = preInit.suffix;
  22118. } else {
  22119. // Get base where the tinymce script is located
  22120. var scripts = document.getElementsByTagName('script');
  22121. for (var i = 0; i < scripts.length; i++) {
  22122. src = scripts[i].src;
  22123. // Script types supported:
  22124. // tinymce.js tinymce.min.js tinymce.dev.js
  22125. // tinymce.jquery.js tinymce.jquery.min.js tinymce.jquery.dev.js
  22126. // tinymce.full.js tinymce.full.min.js tinymce.full.dev.js
  22127. if (/tinymce(\.full|\.jquery|)(\.min|\.dev|)\.js/.test(src)) {
  22128. if (src.indexOf('.min') != -1) {
  22129. suffix = '.min';
  22130. }
  22131. baseURL = src.substring(0, src.lastIndexOf('/'));
  22132. break;
  22133. }
  22134. }
  22135. // We didn't find any baseURL by looking at the script elements
  22136. // Try to use the document.currentScript as a fallback
  22137. if (!baseURL && document.currentScript) {
  22138. src = document.currentScript.src;
  22139. if (src.indexOf('.min') != -1) {
  22140. suffix = '.min';
  22141. }
  22142. baseURL = src.substring(0, src.lastIndexOf('/'));
  22143. }
  22144. }
  22145. /**
  22146. * Base URL where the root directory if TinyMCE is located.
  22147. *
  22148. * @property baseURL
  22149. * @type String
  22150. */
  22151. self.baseURL = new URI(documentBaseURL).toAbsolute(baseURL);
  22152. /**
  22153. * Document base URL where the current document is located.
  22154. *
  22155. * @property documentBaseURL
  22156. * @type String
  22157. */
  22158. self.documentBaseURL = documentBaseURL;
  22159. /**
  22160. * Absolute baseURI for the installation path of TinyMCE.
  22161. *
  22162. * @property baseURI
  22163. * @type tinymce.util.URI
  22164. */
  22165. self.baseURI = new URI(self.baseURL);
  22166. /**
  22167. * Current suffix to add to each plugin/theme that gets loaded for example ".min".
  22168. *
  22169. * @property suffix
  22170. * @type String
  22171. */
  22172. self.suffix = suffix;
  22173. self.focusManager = new FocusManager(self);
  22174. },
  22175. /**
  22176. * Initializes a set of editors. This method will create editors based on various settings.
  22177. *
  22178. * @method init
  22179. * @param {Object} settings Settings object to be passed to each editor instance.
  22180. * @example
  22181. * // Initializes a editor using the longer method
  22182. * tinymce.EditorManager.init({
  22183. * some_settings : 'some value'
  22184. * });
  22185. *
  22186. * // Initializes a editor instance using the shorter version
  22187. * tinyMCE.init({
  22188. * some_settings : 'some value'
  22189. * });
  22190. */
  22191. init: function(settings) {
  22192. var self = this, editors = [], editor;
  22193. function createId(elm) {
  22194. var id = elm.id;
  22195. // Use element id, or unique name or generate a unique id
  22196. if (!id) {
  22197. id = elm.name;
  22198. if (id && !DOM.get(id)) {
  22199. id = elm.name;
  22200. } else {
  22201. // Generate unique name
  22202. id = DOM.uniqueId();
  22203. }
  22204. elm.setAttribute('id', id);
  22205. }
  22206. return id;
  22207. }
  22208. function createEditor(id, settings) {
  22209. if (!purgeDestroyedEditor(self.get(id))) {
  22210. var editor = new Editor(id, settings, self);
  22211. editors.push(editor);
  22212. editor.render();
  22213. }
  22214. }
  22215. function execCallback(se, n, s) {
  22216. var f = se[n];
  22217. if (!f) {
  22218. return;
  22219. }
  22220. return f.apply(s || this, Array.prototype.slice.call(arguments, 2));
  22221. }
  22222. function hasClass(n, c) {
  22223. return c.constructor === RegExp ? c.test(n.className) : DOM.hasClass(n, c);
  22224. }
  22225. function readyHandler() {
  22226. var l, co;
  22227. DOM.unbind(window, 'ready', readyHandler);
  22228. execCallback(settings, 'onpageload');
  22229. if (settings.types) {
  22230. // Process type specific selector
  22231. each(settings.types, function(type) {
  22232. each(DOM.select(type.selector), function(elm) {
  22233. createEditor(createId(elm), extend({}, settings, type));
  22234. });
  22235. });
  22236. return;
  22237. } else if (settings.selector) {
  22238. // Process global selector
  22239. each(DOM.select(settings.selector), function(elm) {
  22240. createEditor(createId(elm), settings);
  22241. });
  22242. return;
  22243. }
  22244. // Fallback to old setting
  22245. switch (settings.mode) {
  22246. case "exact":
  22247. l = settings.elements || '';
  22248. if (l.length > 0) {
  22249. each(explode(l), function(v) {
  22250. if (DOM.get(v)) {
  22251. editor = new Editor(v, settings, self);
  22252. editors.push(editor);
  22253. editor.render();
  22254. } else {
  22255. each(document.forms, function(f) {
  22256. each(f.elements, function(e) {
  22257. if (e.name === v) {
  22258. v = 'mce_editor_' + instanceCounter++;
  22259. DOM.setAttrib(e, 'id', v);
  22260. createEditor(v, settings);
  22261. }
  22262. });
  22263. });
  22264. }
  22265. });
  22266. }
  22267. break;
  22268. case "textareas":
  22269. case "specific_textareas":
  22270. each(DOM.select('textarea'), function(elm) {
  22271. if (settings.editor_deselector && hasClass(elm, settings.editor_deselector)) {
  22272. return;
  22273. }
  22274. if (!settings.editor_selector || hasClass(elm, settings.editor_selector)) {
  22275. createEditor(createId(elm), settings);
  22276. }
  22277. });
  22278. break;
  22279. }
  22280. // Call onInit when all editors are initialized
  22281. if (settings.oninit) {
  22282. l = co = 0;
  22283. each(editors, function(ed) {
  22284. co++;
  22285. if (!ed.initialized) {
  22286. // Wait for it
  22287. ed.on('init', function() {
  22288. l++;
  22289. // All done
  22290. if (l == co) {
  22291. execCallback(settings, 'oninit');
  22292. }
  22293. });
  22294. } else {
  22295. l++;
  22296. }
  22297. // All done
  22298. if (l == co) {
  22299. execCallback(settings, 'oninit');
  22300. }
  22301. });
  22302. }
  22303. }
  22304. self.settings = settings;
  22305. DOM.bind(window, 'ready', readyHandler);
  22306. },
  22307. /**
  22308. * Returns a editor instance by id.
  22309. *
  22310. * @method get
  22311. * @param {String/Number} id Editor instance id or index to return.
  22312. * @return {tinymce.Editor} Editor instance to return.
  22313. * @example
  22314. * // Adds an onclick event to an editor by id (shorter version)
  22315. * tinymce.get('mytextbox').on('click', function(e) {
  22316. * ed.windowManager.alert('Hello world!');
  22317. * });
  22318. *
  22319. * // Adds an onclick event to an editor by id (longer version)
  22320. * tinymce.EditorManager.get('mytextbox').on('click', function(e) {
  22321. * ed.windowManager.alert('Hello world!');
  22322. * });
  22323. */
  22324. get: function(id) {
  22325. if (!arguments.length) {
  22326. return this.editors;
  22327. }
  22328. return id in this.editors ? this.editors[id] : null;
  22329. },
  22330. /**
  22331. * Adds an editor instance to the editor collection. This will also set it as the active editor.
  22332. *
  22333. * @method add
  22334. * @param {tinymce.Editor} editor Editor instance to add to the collection.
  22335. * @return {tinymce.Editor} The same instance that got passed in.
  22336. */
  22337. add: function(editor) {
  22338. var self = this, editors = self.editors;
  22339. // Add named and index editor instance
  22340. editors[editor.id] = editor;
  22341. editors.push(editor);
  22342. self.activeEditor = editor;
  22343. /**
  22344. * Fires when an editor is added to the EditorManager collection.
  22345. *
  22346. * @event AddEditor
  22347. * @param {Object} e Event arguments.
  22348. */
  22349. self.fire('AddEditor', {editor: editor});
  22350. if (!beforeUnloadDelegate) {
  22351. beforeUnloadDelegate = function() {
  22352. self.fire('BeforeUnload');
  22353. };
  22354. DOM.bind(window, 'beforeunload', beforeUnloadDelegate);
  22355. }
  22356. return editor;
  22357. },
  22358. /**
  22359. * Creates an editor instance and adds it to the EditorManager collection.
  22360. *
  22361. * @method createEditor
  22362. * @param {String} id Instance id to use for editor.
  22363. * @param {Object} settings Editor instance settings.
  22364. * @return {tinymce.Editor} Editor instance that got created.
  22365. */
  22366. createEditor: function(id, settings) {
  22367. return this.add(new Editor(id, settings, this));
  22368. },
  22369. /**
  22370. * Removes a editor or editors form page.
  22371. *
  22372. * @example
  22373. * // Remove all editors bound to divs
  22374. * tinymce.remove('div');
  22375. *
  22376. * // Remove all editors bound to textareas
  22377. * tinymce.remove('textarea');
  22378. *
  22379. * // Remove all editors
  22380. * tinymce.remove();
  22381. *
  22382. * // Remove specific instance by id
  22383. * tinymce.remove('#id');
  22384. *
  22385. * @method remove
  22386. * @param {tinymce.Editor/String/Object} [selector] CSS selector or editor instance to remove.
  22387. * @return {tinymce.Editor} The editor that got passed in will be return if it was found otherwise null.
  22388. */
  22389. remove: function(selector) {
  22390. var self = this, i, editors = self.editors, editor;
  22391. // Remove all editors
  22392. if (!selector) {
  22393. for (i = editors.length - 1; i >= 0; i--) {
  22394. self.remove(editors[i]);
  22395. }
  22396. return;
  22397. }
  22398. // Remove editors by selector
  22399. if (typeof(selector) == "string") {
  22400. selector = selector.selector || selector;
  22401. each(DOM.select(selector), function(elm) {
  22402. self.remove(editors[elm.id]);
  22403. });
  22404. return;
  22405. }
  22406. // Remove specific editor
  22407. editor = selector;
  22408. // Not in the collection
  22409. if (!editors[editor.id]) {
  22410. return null;
  22411. }
  22412. /**
  22413. * Fires when an editor is removed from EditorManager collection.
  22414. *
  22415. * @event RemoveEditor
  22416. * @param {Object} e Event arguments.
  22417. */
  22418. if (removeEditorFromList(editor)) {
  22419. self.fire('RemoveEditor', {editor: editor});
  22420. }
  22421. if (!editors.length) {
  22422. DOM.unbind(window, 'beforeunload', beforeUnloadDelegate);
  22423. }
  22424. editor.remove();
  22425. return editor;
  22426. },
  22427. /**
  22428. * Executes a specific command on the currently active editor.
  22429. *
  22430. * @method execCommand
  22431. * @param {String} c Command to perform for example Bold.
  22432. * @param {Boolean} u Optional boolean state if a UI should be presented for the command or not.
  22433. * @param {String} v Optional value parameter like for example an URL to a link.
  22434. * @return {Boolean} true/false if the command was executed or not.
  22435. */
  22436. execCommand: function(cmd, ui, value) {
  22437. var self = this, editor = self.get(value);
  22438. // Manager commands
  22439. switch (cmd) {
  22440. case "mceAddEditor":
  22441. if (!self.get(value)) {
  22442. new Editor(value, self.settings, self).render();
  22443. }
  22444. return true;
  22445. case "mceRemoveEditor":
  22446. if (editor) {
  22447. editor.remove();
  22448. }
  22449. return true;
  22450. case 'mceToggleEditor':
  22451. if (!editor) {
  22452. self.execCommand('mceAddEditor', 0, value);
  22453. return true;
  22454. }
  22455. if (editor.isHidden()) {
  22456. editor.show();
  22457. } else {
  22458. editor.hide();
  22459. }
  22460. return true;
  22461. }
  22462. // Run command on active editor
  22463. if (self.activeEditor) {
  22464. return self.activeEditor.execCommand(cmd, ui, value);
  22465. }
  22466. return false;
  22467. },
  22468. /**
  22469. * Calls the save method on all editor instances in the collection. This can be useful when a form is to be submitted.
  22470. *
  22471. * @method triggerSave
  22472. * @example
  22473. * // Saves all contents
  22474. * tinyMCE.triggerSave();
  22475. */
  22476. triggerSave: function() {
  22477. each(this.editors, function(editor) {
  22478. editor.save();
  22479. });
  22480. },
  22481. /**
  22482. * Adds a language pack, this gets called by the loaded language files like en.js.
  22483. *
  22484. * @method addI18n
  22485. * @param {String} code Optional language code.
  22486. * @param {Object} items Name/value object with translations.
  22487. */
  22488. addI18n: function(code, items) {
  22489. I18n.add(code, items);
  22490. },
  22491. /**
  22492. * Translates the specified string using the language pack items.
  22493. *
  22494. * @method translate
  22495. * @param {String/Array/Object} text String to translate
  22496. * @return {String} Translated string.
  22497. */
  22498. translate: function(text) {
  22499. return I18n.translate(text);
  22500. }
  22501. };
  22502. extend(EditorManager, Observable);
  22503. EditorManager.setup();
  22504. // Export EditorManager as tinymce/tinymce in global namespace
  22505. window.tinymce = window.tinyMCE = EditorManager;
  22506. return EditorManager;
  22507. });
  22508. // Included from: js/tinymce/classes/LegacyInput.js
  22509. /**
  22510. * LegacyInput.js
  22511. *
  22512. * Copyright, Moxiecode Systems AB
  22513. * Released under LGPL License.
  22514. *
  22515. * License: http://www.tinymce.com/license
  22516. * Contributing: http://www.tinymce.com/contributing
  22517. */
  22518. define("tinymce/LegacyInput", [
  22519. "tinymce/EditorManager",
  22520. "tinymce/util/Tools"
  22521. ], function(EditorManager, Tools) {
  22522. var each = Tools.each, explode = Tools.explode;
  22523. EditorManager.on('AddEditor', function(e) {
  22524. var editor = e.editor;
  22525. editor.on('preInit', function() {
  22526. var filters, fontSizes, dom, settings = editor.settings;
  22527. function replaceWithSpan(node, styles) {
  22528. each(styles, function(value, name) {
  22529. if (value) {
  22530. dom.setStyle(node, name, value);
  22531. }
  22532. });
  22533. dom.rename(node, 'span');
  22534. }
  22535. function convert(e) {
  22536. dom = editor.dom;
  22537. if (settings.convert_fonts_to_spans) {
  22538. each(dom.select('font,u,strike', e.node), function(node) {
  22539. filters[node.nodeName.toLowerCase()](dom, node);
  22540. });
  22541. }
  22542. }
  22543. if (settings.inline_styles) {
  22544. fontSizes = explode(settings.font_size_legacy_values);
  22545. filters = {
  22546. font: function(dom, node) {
  22547. replaceWithSpan(node, {
  22548. backgroundColor: node.style.backgroundColor,
  22549. color: node.color,
  22550. fontFamily: node.face,
  22551. fontSize: fontSizes[parseInt(node.size, 10) - 1]
  22552. });
  22553. },
  22554. u: function(dom, node) {
  22555. replaceWithSpan(node, {
  22556. textDecoration: 'underline'
  22557. });
  22558. },
  22559. strike: function(dom, node) {
  22560. replaceWithSpan(node, {
  22561. textDecoration: 'line-through'
  22562. });
  22563. }
  22564. };
  22565. editor.on('PreProcess SetContent', convert);
  22566. }
  22567. });
  22568. });
  22569. });
  22570. // Included from: js/tinymce/classes/util/XHR.js
  22571. /**
  22572. * XHR.js
  22573. *
  22574. * Copyright, Moxiecode Systems AB
  22575. * Released under LGPL License.
  22576. *
  22577. * License: http://www.tinymce.com/license
  22578. * Contributing: http://www.tinymce.com/contributing
  22579. */
  22580. /**
  22581. * This class enables you to send XMLHTTPRequests cross browser.
  22582. * @class tinymce.util.XHR
  22583. * @static
  22584. * @example
  22585. * // Sends a low level Ajax request
  22586. * tinymce.util.XHR.send({
  22587. * url: 'someurl',
  22588. * success: function(text) {
  22589. * console.debug(text);
  22590. * }
  22591. * });
  22592. */
  22593. define("tinymce/util/XHR", [], function() {
  22594. return {
  22595. /**
  22596. * Sends a XMLHTTPRequest.
  22597. * Consult the Wiki for details on what settings this method takes.
  22598. *
  22599. * @method send
  22600. * @param {Object} settings Object will target URL, callbacks and other info needed to make the request.
  22601. */
  22602. send: function(settings) {
  22603. var xhr, count = 0;
  22604. function ready() {
  22605. if (!settings.async || xhr.readyState == 4 || count++ > 10000) {
  22606. if (settings.success && count < 10000 && xhr.status == 200) {
  22607. settings.success.call(settings.success_scope, '' + xhr.responseText, xhr, settings);
  22608. } else if (settings.error) {
  22609. settings.error.call(settings.error_scope, count > 10000 ? 'TIMED_OUT' : 'GENERAL', xhr, settings);
  22610. }
  22611. xhr = null;
  22612. } else {
  22613. setTimeout(ready, 10);
  22614. }
  22615. }
  22616. // Default settings
  22617. settings.scope = settings.scope || this;
  22618. settings.success_scope = settings.success_scope || settings.scope;
  22619. settings.error_scope = settings.error_scope || settings.scope;
  22620. settings.async = settings.async === false ? false : true;
  22621. settings.data = settings.data || '';
  22622. xhr = new XMLHttpRequest();
  22623. if (xhr) {
  22624. if (xhr.overrideMimeType) {
  22625. xhr.overrideMimeType(settings.content_type);
  22626. }
  22627. xhr.open(settings.type || (settings.data ? 'POST' : 'GET'), settings.url, settings.async);
  22628. if (settings.content_type) {
  22629. xhr.setRequestHeader('Content-Type', settings.content_type);
  22630. }
  22631. xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
  22632. xhr.send(settings.data);
  22633. // Syncronous request
  22634. if (!settings.async) {
  22635. return ready();
  22636. }
  22637. // Wait for response, onReadyStateChange can not be used since it leaks memory in IE
  22638. setTimeout(ready, 10);
  22639. }
  22640. }
  22641. };
  22642. });
  22643. // Included from: js/tinymce/classes/util/JSON.js
  22644. /**
  22645. * JSON.js
  22646. *
  22647. * Copyright, Moxiecode Systems AB
  22648. * Released under LGPL License.
  22649. *
  22650. * License: http://www.tinymce.com/license
  22651. * Contributing: http://www.tinymce.com/contributing
  22652. */
  22653. /**
  22654. * JSON parser and serializer class.
  22655. *
  22656. * @class tinymce.util.JSON
  22657. * @static
  22658. * @example
  22659. * // JSON parse a string into an object
  22660. * var obj = tinymce.util.JSON.parse(somestring);
  22661. *
  22662. * // JSON serialize a object into an string
  22663. * var str = tinymce.util.JSON.serialize(obj);
  22664. */
  22665. define("tinymce/util/JSON", [], function() {
  22666. function serialize(o, quote) {
  22667. var i, v, t, name;
  22668. quote = quote || '"';
  22669. if (o === null) {
  22670. return 'null';
  22671. }
  22672. t = typeof o;
  22673. if (t == 'string') {
  22674. v = '\bb\tt\nn\ff\rr\""\'\'\\\\';
  22675. return quote + o.replace(/([\u0080-\uFFFF\x00-\x1f\"\'\\])/g, function(a, b) {
  22676. // Make sure single quotes never get encoded inside double quotes for JSON compatibility
  22677. if (quote === '"' && a === "'") {
  22678. return a;
  22679. }
  22680. i = v.indexOf(b);
  22681. if (i + 1) {
  22682. return '\\' + v.charAt(i + 1);
  22683. }
  22684. a = b.charCodeAt().toString(16);
  22685. return '\\u' + '0000'.substring(a.length) + a;
  22686. }) + quote;
  22687. }
  22688. if (t == 'object') {
  22689. if (o.hasOwnProperty && Object.prototype.toString.call(o) === '[object Array]') {
  22690. for (i = 0, v = '['; i < o.length; i++) {
  22691. v += (i > 0 ? ',' : '') + serialize(o[i], quote);
  22692. }
  22693. return v + ']';
  22694. }
  22695. v = '{';
  22696. for (name in o) {
  22697. if (o.hasOwnProperty(name)) {
  22698. v += typeof o[name] != 'function' ? (v.length > 1 ? ',' + quote : quote) + name +
  22699. quote + ':' + serialize(o[name], quote) : '';
  22700. }
  22701. }
  22702. return v + '}';
  22703. }
  22704. return '' + o;
  22705. }
  22706. return {
  22707. /**
  22708. * Serializes the specified object as a JSON string.
  22709. *
  22710. * @method serialize
  22711. * @param {Object} obj Object to serialize as a JSON string.
  22712. * @param {String} quote Optional quote string defaults to ".
  22713. * @return {string} JSON string serialized from input.
  22714. */
  22715. serialize: serialize,
  22716. /**
  22717. * Unserializes/parses the specified JSON string into a object.
  22718. *
  22719. * @method parse
  22720. * @param {string} s JSON String to parse into a JavaScript object.
  22721. * @return {Object} Object from input JSON string or undefined if it failed.
  22722. */
  22723. parse: function(text) {
  22724. try {
  22725. // Trick uglify JS
  22726. return window[String.fromCharCode(101) + 'val']('(' + text + ')');
  22727. } catch (ex) {
  22728. // Ignore
  22729. }
  22730. }
  22731. /**#@-*/
  22732. };
  22733. });
  22734. // Included from: js/tinymce/classes/util/JSONRequest.js
  22735. /**
  22736. * JSONRequest.js
  22737. *
  22738. * Copyright, Moxiecode Systems AB
  22739. * Released under LGPL License.
  22740. *
  22741. * License: http://www.tinymce.com/license
  22742. * Contributing: http://www.tinymce.com/contributing
  22743. */
  22744. /**
  22745. * This class enables you to use JSON-RPC to call backend methods.
  22746. *
  22747. * @class tinymce.util.JSONRequest
  22748. * @example
  22749. * var json = new tinymce.util.JSONRequest({
  22750. * url: 'somebackend.php'
  22751. * });
  22752. *
  22753. * // Send RPC call 1
  22754. * json.send({
  22755. * method: 'someMethod1',
  22756. * params: ['a', 'b'],
  22757. * success: function(result) {
  22758. * console.dir(result);
  22759. * }
  22760. * });
  22761. *
  22762. * // Send RPC call 2
  22763. * json.send({
  22764. * method: 'someMethod2',
  22765. * params: ['a', 'b'],
  22766. * success: function(result) {
  22767. * console.dir(result);
  22768. * }
  22769. * });
  22770. */
  22771. define("tinymce/util/JSONRequest", [
  22772. "tinymce/util/JSON",
  22773. "tinymce/util/XHR",
  22774. "tinymce/util/Tools"
  22775. ], function(JSON, XHR, Tools) {
  22776. var extend = Tools.extend;
  22777. function JSONRequest(settings) {
  22778. this.settings = extend({}, settings);
  22779. this.count = 0;
  22780. }
  22781. /**
  22782. * Simple helper function to send a JSON-RPC request without the need to initialize an object.
  22783. * Consult the Wiki API documentation for more details on what you can pass to this function.
  22784. *
  22785. * @method sendRPC
  22786. * @static
  22787. * @param {Object} o Call object where there are three field id, method and params this object should also contain callbacks etc.
  22788. */
  22789. JSONRequest.sendRPC = function(o) {
  22790. return new JSONRequest().send(o);
  22791. };
  22792. JSONRequest.prototype = {
  22793. /**
  22794. * Sends a JSON-RPC call. Consult the Wiki API documentation for more details on what you can pass to this function.
  22795. *
  22796. * @method send
  22797. * @param {Object} args Call object where there are three field id, method and params this object should also contain callbacks etc.
  22798. */
  22799. send: function(args) {
  22800. var ecb = args.error, scb = args.success;
  22801. args = extend(this.settings, args);
  22802. args.success = function(c, x) {
  22803. c = JSON.parse(c);
  22804. if (typeof(c) == 'undefined') {
  22805. c = {
  22806. error : 'JSON Parse error.'
  22807. };
  22808. }
  22809. if (c.error) {
  22810. ecb.call(args.error_scope || args.scope, c.error, x);
  22811. } else {
  22812. scb.call(args.success_scope || args.scope, c.result);
  22813. }
  22814. };
  22815. args.error = function(ty, x) {
  22816. if (ecb) {
  22817. ecb.call(args.error_scope || args.scope, ty, x);
  22818. }
  22819. };
  22820. args.data = JSON.serialize({
  22821. id: args.id || 'c' + (this.count++),
  22822. method: args.method,
  22823. params: args.params
  22824. });
  22825. // JSON content type for Ruby on rails. Bug: #1883287
  22826. args.content_type = 'application/json';
  22827. XHR.send(args);
  22828. }
  22829. };
  22830. return JSONRequest;
  22831. });
  22832. // Included from: js/tinymce/classes/util/JSONP.js
  22833. /**
  22834. * JSONP.js
  22835. *
  22836. * Copyright, Moxiecode Systems AB
  22837. * Released under LGPL License.
  22838. *
  22839. * License: http://www.tinymce.com/license
  22840. * Contributing: http://www.tinymce.com/contributing
  22841. */
  22842. define("tinymce/util/JSONP", [
  22843. "tinymce/dom/DOMUtils"
  22844. ], function(DOMUtils) {
  22845. return {
  22846. callbacks: {},
  22847. count: 0,
  22848. send: function(settings) {
  22849. var self = this, dom = DOMUtils.DOM, count = settings.count !== undefined ? settings.count : self.count;
  22850. var id = 'tinymce_jsonp_' + count;
  22851. self.callbacks[count] = function(json) {
  22852. dom.remove(id);
  22853. delete self.callbacks[count];
  22854. settings.callback(json);
  22855. };
  22856. dom.add(dom.doc.body, 'script', {
  22857. id: id,
  22858. src: settings.url,
  22859. type: 'text/javascript'
  22860. });
  22861. self.count++;
  22862. }
  22863. };
  22864. });
  22865. // Included from: js/tinymce/classes/util/LocalStorage.js
  22866. /**
  22867. * LocalStorage.js
  22868. *
  22869. * Copyright, Moxiecode Systems AB
  22870. * Released under LGPL License.
  22871. *
  22872. * License: http://www.tinymce.com/license
  22873. * Contributing: http://www.tinymce.com/contributing
  22874. */
  22875. /**
  22876. * This class will simulate LocalStorage on IE 7 and return the native version on modern browsers.
  22877. * Storage is done using userData on IE 7 and a special serialization format. The format is designed
  22878. * to be as small as possible by making sure that the keys and values doesn't need to be encoded. This
  22879. * makes it possible to store for example HTML data.
  22880. *
  22881. * Storage format for userData:
  22882. * <base 32 key length>,<key string>,<base 32 value length>,<value>,...
  22883. *
  22884. * For example this data key1=value1,key2=value2 would be:
  22885. * 4,key1,6,value1,4,key2,6,value2
  22886. *
  22887. * @class tinymce.util.LocalStorage
  22888. * @static
  22889. * @version 4.0
  22890. * @example
  22891. * tinymce.util.LocalStorage.setItem('key', 'value');
  22892. * var value = tinymce.util.LocalStorage.getItem('key');
  22893. */
  22894. define("tinymce/util/LocalStorage", [], function() {
  22895. var LocalStorage, storageElm, items, keys, userDataKey, hasOldIEDataSupport;
  22896. // Check for native support
  22897. try {
  22898. if (window.localStorage) {
  22899. return localStorage;
  22900. }
  22901. } catch (ex) {
  22902. // Ignore
  22903. }
  22904. userDataKey = "tinymce";
  22905. storageElm = document.documentElement;
  22906. hasOldIEDataSupport = !!storageElm.addBehavior;
  22907. if (hasOldIEDataSupport) {
  22908. storageElm.addBehavior('#default#userData');
  22909. }
  22910. /**
  22911. * Gets the keys names and updates LocalStorage.length property. Since IE7 doesn't have any getters/setters.
  22912. */
  22913. function updateKeys() {
  22914. keys = [];
  22915. for (var key in items) {
  22916. keys.push(key);
  22917. }
  22918. LocalStorage.length = keys.length;
  22919. }
  22920. /**
  22921. * Loads the userData string and parses it into the items structure.
  22922. */
  22923. function load() {
  22924. var key, data, value, pos = 0;
  22925. items = {};
  22926. // localStorage can be disabled on WebKit/Gecko so make a dummy storage
  22927. if (!hasOldIEDataSupport) {
  22928. return;
  22929. }
  22930. function next(end) {
  22931. var value, nextPos;
  22932. nextPos = end !== undefined ? pos + end : data.indexOf(',', pos);
  22933. if (nextPos === -1 || nextPos > data.length) {
  22934. return null;
  22935. }
  22936. value = data.substring(pos, nextPos);
  22937. pos = nextPos + 1;
  22938. return value;
  22939. }
  22940. storageElm.load(userDataKey);
  22941. data = storageElm.getAttribute(userDataKey) || '';
  22942. do {
  22943. var offset = next();
  22944. if (offset === null) {
  22945. break;
  22946. }
  22947. key = next(parseInt(offset, 32) || 0);
  22948. if (key !== null) {
  22949. offset = next();
  22950. if (offset === null) {
  22951. break;
  22952. }
  22953. value = next(parseInt(offset, 32) || 0);
  22954. if (key) {
  22955. items[key] = value;
  22956. }
  22957. }
  22958. } while (key !== null);
  22959. updateKeys();
  22960. }
  22961. /**
  22962. * Saves the items structure into a the userData format.
  22963. */
  22964. function save() {
  22965. var value, data = '';
  22966. // localStorage can be disabled on WebKit/Gecko so make a dummy storage
  22967. if (!hasOldIEDataSupport) {
  22968. return;
  22969. }
  22970. for (var key in items) {
  22971. value = items[key];
  22972. data += (data ? ',' : '') + key.length.toString(32) + ',' + key + ',' + value.length.toString(32) + ',' + value;
  22973. }
  22974. storageElm.setAttribute(userDataKey, data);
  22975. try {
  22976. storageElm.save(userDataKey);
  22977. } catch (ex) {
  22978. // Ignore disk full
  22979. }
  22980. updateKeys();
  22981. }
  22982. LocalStorage = {
  22983. /**
  22984. * Length of the number of items in storage.
  22985. *
  22986. * @property length
  22987. * @type Number
  22988. * @return {Number} Number of items in storage.
  22989. */
  22990. //length:0,
  22991. /**
  22992. * Returns the key name by index.
  22993. *
  22994. * @method key
  22995. * @param {Number} index Index of key to return.
  22996. * @return {String} Key value or null if it wasn't found.
  22997. */
  22998. key: function(index) {
  22999. return keys[index];
  23000. },
  23001. /**
  23002. * Returns the value if the specified key or null if it wasn't found.
  23003. *
  23004. * @method getItem
  23005. * @param {String} key Key of item to retrive.
  23006. * @return {String} Value of the specified item or null if it wasn't found.
  23007. */
  23008. getItem: function(key) {
  23009. return key in items ? items[key] : null;
  23010. },
  23011. /**
  23012. * Sets the value of the specified item by it's key.
  23013. *
  23014. * @method setItem
  23015. * @param {String} key Key of the item to set.
  23016. * @param {String} value Value of the item to set.
  23017. */
  23018. setItem: function(key, value) {
  23019. items[key] = "" + value;
  23020. save();
  23021. },
  23022. /**
  23023. * Removes the specified item by key.
  23024. *
  23025. * @method removeItem
  23026. * @param {String} key Key of item to remove.
  23027. */
  23028. removeItem: function(key) {
  23029. delete items[key];
  23030. save();
  23031. },
  23032. /**
  23033. * Removes all items.
  23034. *
  23035. * @method clear
  23036. */
  23037. clear: function() {
  23038. items = {};
  23039. save();
  23040. }
  23041. };
  23042. load();
  23043. return LocalStorage;
  23044. });
  23045. // Included from: js/tinymce/classes/Compat.js
  23046. /**
  23047. * Compat.js
  23048. *
  23049. * Copyright, Moxiecode Systems AB
  23050. * Released under LGPL License.
  23051. *
  23052. * License: http://www.tinymce.com/license
  23053. * Contributing: http://www.tinymce.com/contributing
  23054. */
  23055. /**
  23056. * TinyMCE core class.
  23057. *
  23058. * @static
  23059. * @class tinymce
  23060. * @borrow-members tinymce.EditorManager
  23061. * @borrow-members tinymce.util.Tools
  23062. */
  23063. define("tinymce/Compat", [
  23064. "tinymce/dom/DOMUtils",
  23065. "tinymce/dom/EventUtils",
  23066. "tinymce/dom/ScriptLoader",
  23067. "tinymce/AddOnManager",
  23068. "tinymce/util/Tools",
  23069. "tinymce/Env"
  23070. ], function(DOMUtils, EventUtils, ScriptLoader, AddOnManager, Tools, Env) {
  23071. var tinymce = window.tinymce;
  23072. /**
  23073. * @property {tinymce.dom.DOMUtils} DOM Global DOM instance.
  23074. * @property {tinymce.dom.ScriptLoader} ScriptLoader Global ScriptLoader instance.
  23075. * @property {tinymce.AddOnManager} PluginManager Global PluginManager instance.
  23076. * @property {tinymce.AddOnManager} ThemeManager Global ThemeManager instance.
  23077. */
  23078. tinymce.DOM = DOMUtils.DOM;
  23079. tinymce.ScriptLoader = ScriptLoader.ScriptLoader;
  23080. tinymce.PluginManager = AddOnManager.PluginManager;
  23081. tinymce.ThemeManager = AddOnManager.ThemeManager;
  23082. tinymce.dom = tinymce.dom || {};
  23083. tinymce.dom.Event = EventUtils.Event;
  23084. Tools.each(Tools, function(func, key) {
  23085. tinymce[key] = func;
  23086. });
  23087. Tools.each('isOpera isWebKit isIE isGecko isMac'.split(' '), function(name) {
  23088. tinymce[name] = Env[name.substr(2).toLowerCase()];
  23089. });
  23090. return {};
  23091. });
  23092. // Describe the different namespaces
  23093. /**
  23094. * Root level namespace this contains classes directly releated to the TinyMCE editor.
  23095. *
  23096. * @namespace tinymce
  23097. */
  23098. /**
  23099. * Contains classes for handling the browsers DOM.
  23100. *
  23101. * @namespace tinymce.dom
  23102. */
  23103. /**
  23104. * Contains html parser and serializer logic.
  23105. *
  23106. * @namespace tinymce.html
  23107. */
  23108. /**
  23109. * Contains the different UI types such as buttons, listboxes etc.
  23110. *
  23111. * @namespace tinymce.ui
  23112. */
  23113. /**
  23114. * Contains various utility classes such as json parser, cookies etc.
  23115. *
  23116. * @namespace tinymce.util
  23117. */
  23118. // Included from: js/tinymce/classes/ui/Layout.js
  23119. /**
  23120. * Layout.js
  23121. *
  23122. * Copyright, Moxiecode Systems AB
  23123. * Released under LGPL License.
  23124. *
  23125. * License: http://www.tinymce.com/license
  23126. * Contributing: http://www.tinymce.com/contributing
  23127. */
  23128. /**
  23129. * Base layout manager class.
  23130. *
  23131. * @class tinymce.ui.Layout
  23132. */
  23133. define("tinymce/ui/Layout", [
  23134. "tinymce/util/Class",
  23135. "tinymce/util/Tools"
  23136. ], function(Class, Tools) {
  23137. "use strict";
  23138. return Class.extend({
  23139. Defaults: {
  23140. firstControlClass: 'first',
  23141. lastControlClass: 'last'
  23142. },
  23143. /**
  23144. * Constructs a layout instance with the specified settings.
  23145. *
  23146. * @constructor
  23147. * @param {Object} settings Name/value object with settings.
  23148. */
  23149. init: function(settings) {
  23150. this.settings = Tools.extend({}, this.Defaults, settings);
  23151. },
  23152. /**
  23153. * This method gets invoked before the layout renders the controls.
  23154. *
  23155. * @method preRender
  23156. * @param {tinymce.ui.Container} container Container instance to preRender.
  23157. */
  23158. preRender: function(container) {
  23159. container.addClass(this.settings.containerClass, 'body');
  23160. },
  23161. /**
  23162. * Applies layout classes to the container.
  23163. *
  23164. * @private
  23165. */
  23166. applyClasses: function(container) {
  23167. var self = this, settings = self.settings, items, firstClass, lastClass;
  23168. items = container.items().filter(':visible');
  23169. firstClass = settings.firstControlClass;
  23170. lastClass = settings.lastControlClass;
  23171. items.each(function(item) {
  23172. item.removeClass(firstClass).removeClass(lastClass);
  23173. if (settings.controlClass) {
  23174. item.addClass(settings.controlClass);
  23175. }
  23176. });
  23177. items.eq(0).addClass(firstClass);
  23178. items.eq(-1).addClass(lastClass);
  23179. },
  23180. /**
  23181. * Renders the specified container and any layout specific HTML.
  23182. *
  23183. * @method renderHtml
  23184. * @param {tinymce.ui.Container} container Container to render HTML for.
  23185. */
  23186. renderHtml: function(container) {
  23187. var self = this, settings = self.settings, items, html = '';
  23188. items = container.items();
  23189. items.eq(0).addClass(settings.firstControlClass);
  23190. items.eq(-1).addClass(settings.lastControlClass);
  23191. items.each(function(item) {
  23192. if (settings.controlClass) {
  23193. item.addClass(settings.controlClass);
  23194. }
  23195. html += item.renderHtml();
  23196. });
  23197. return html;
  23198. },
  23199. /**
  23200. * Recalculates the positions of the controls in the specified container.
  23201. *
  23202. * @method recalc
  23203. * @param {tinymce.ui.Container} container Container instance to recalc.
  23204. */
  23205. recalc: function() {
  23206. },
  23207. /**
  23208. * This method gets invoked after the layout renders the controls.
  23209. *
  23210. * @method postRender
  23211. * @param {tinymce.ui.Container} container Container instance to postRender.
  23212. */
  23213. postRender: function() {
  23214. }
  23215. });
  23216. });
  23217. // Included from: js/tinymce/classes/ui/AbsoluteLayout.js
  23218. /**
  23219. * AbsoluteLayout.js
  23220. *
  23221. * Copyright, Moxiecode Systems AB
  23222. * Released under LGPL License.
  23223. *
  23224. * License: http://www.tinymce.com/license
  23225. * Contributing: http://www.tinymce.com/contributing
  23226. */
  23227. /**
  23228. * LayoutManager for absolute positioning. This layout manager is more of
  23229. * a base class for other layouts but can be created and used directly.
  23230. *
  23231. * @-x-less AbsoluteLayout.less
  23232. * @class tinymce.ui.AbsoluteLayout
  23233. * @extends tinymce.ui.Layout
  23234. */
  23235. define("tinymce/ui/AbsoluteLayout", [
  23236. "tinymce/ui/Layout"
  23237. ], function(Layout) {
  23238. "use strict";
  23239. return Layout.extend({
  23240. Defaults: {
  23241. containerClass: 'abs-layout',
  23242. controlClass: 'abs-layout-item'
  23243. },
  23244. /**
  23245. * Recalculates the positions of the controls in the specified container.
  23246. *
  23247. * @method recalc
  23248. * @param {tinymce.ui.Container} container Container instance to recalc.
  23249. */
  23250. recalc: function(container) {
  23251. container.items().filter(':visible').each(function(ctrl) {
  23252. var settings = ctrl.settings;
  23253. ctrl.layoutRect({
  23254. x: settings.x,
  23255. y: settings.y,
  23256. w: settings.w,
  23257. h: settings.h
  23258. });
  23259. if (ctrl.recalc) {
  23260. ctrl.recalc();
  23261. }
  23262. });
  23263. },
  23264. /**
  23265. * Renders the specified container and any layout specific HTML.
  23266. *
  23267. * @method renderHtml
  23268. * @param {tinymce.ui.Container} container Container to render HTML for.
  23269. */
  23270. renderHtml: function(container) {
  23271. return '<div id="' + container._id + '-absend" class="' + container.classPrefix + 'abs-end"></div>' + this._super(container);
  23272. }
  23273. });
  23274. });
  23275. // Included from: js/tinymce/classes/ui/Tooltip.js
  23276. /**
  23277. * Tooltip.js
  23278. *
  23279. * Copyright, Moxiecode Systems AB
  23280. * Released under LGPL License.
  23281. *
  23282. * License: http://www.tinymce.com/license
  23283. * Contributing: http://www.tinymce.com/contributing
  23284. */
  23285. /**
  23286. * Creates a tooltip instance.
  23287. *
  23288. * @-x-less ToolTip.less
  23289. * @class tinymce.ui.ToolTip
  23290. * @extends tinymce.ui.Control
  23291. * @mixes tinymce.ui.Movable
  23292. */
  23293. define("tinymce/ui/Tooltip", [
  23294. "tinymce/ui/Control",
  23295. "tinymce/ui/Movable"
  23296. ], function(Control, Movable) {
  23297. return Control.extend({
  23298. Mixins: [Movable],
  23299. Defaults: {
  23300. classes: 'widget tooltip tooltip-n'
  23301. },
  23302. /**
  23303. * Sets/gets the current label text.
  23304. *
  23305. * @method text
  23306. * @param {String} [text] New label text.
  23307. * @return {String|tinymce.ui.Tooltip} Current text or current label instance.
  23308. */
  23309. text: function(value) {
  23310. var self = this;
  23311. if (typeof(value) != "undefined") {
  23312. self._value = value;
  23313. if (self._rendered) {
  23314. self.getEl().lastChild.innerHTML = self.encode(value);
  23315. }
  23316. return self;
  23317. }
  23318. return self._value;
  23319. },
  23320. /**
  23321. * Renders the control as a HTML string.
  23322. *
  23323. * @method renderHtml
  23324. * @return {String} HTML representing the control.
  23325. */
  23326. renderHtml: function() {
  23327. var self = this, prefix = self.classPrefix;
  23328. return (
  23329. '<div id="' + self._id + '" class="' + self.classes() + '" role="presentation">' +
  23330. '<div class="' + prefix + 'tooltip-arrow"></div>' +
  23331. '<div class="' + prefix + 'tooltip-inner">' + self.encode(self._text) + '</div>' +
  23332. '</div>'
  23333. );
  23334. },
  23335. /**
  23336. * Repaints the control after a layout operation.
  23337. *
  23338. * @method repaint
  23339. */
  23340. repaint: function() {
  23341. var self = this, style, rect;
  23342. style = self.getEl().style;
  23343. rect = self._layoutRect;
  23344. style.left = rect.x + 'px';
  23345. style.top = rect.y + 'px';
  23346. style.zIndex = 0xFFFF + 0xFFFF;
  23347. }
  23348. });
  23349. });
  23350. // Included from: js/tinymce/classes/ui/Widget.js
  23351. /**
  23352. * Widget.js
  23353. *
  23354. * Copyright, Moxiecode Systems AB
  23355. * Released under LGPL License.
  23356. *
  23357. * License: http://www.tinymce.com/license
  23358. * Contributing: http://www.tinymce.com/contributing
  23359. */
  23360. /**
  23361. * Widget base class a widget is a control that has a tooltip and some basic states.
  23362. *
  23363. * @class tinymce.ui.Widget
  23364. * @extends tinymce.ui.Control
  23365. */
  23366. define("tinymce/ui/Widget", [
  23367. "tinymce/ui/Control",
  23368. "tinymce/ui/Tooltip"
  23369. ], function(Control, Tooltip) {
  23370. "use strict";
  23371. var tooltip;
  23372. var Widget = Control.extend({
  23373. /**
  23374. * Constructs a instance with the specified settings.
  23375. *
  23376. * @constructor
  23377. * @param {Object} settings Name/value object with settings.
  23378. * @setting {String} tooltip Tooltip text to display when hovering.
  23379. * @setting {Boolean} autofocus True if the control should be focused when rendered.
  23380. * @setting {String} text Text to display inside widget.
  23381. */
  23382. init: function(settings) {
  23383. var self = this;
  23384. self._super(settings);
  23385. settings = self.settings;
  23386. self.canFocus = true;
  23387. if (settings.tooltip && Widget.tooltips !== false) {
  23388. self.on('mouseenter', function(e) {
  23389. var tooltip = self.tooltip().moveTo(-0xFFFF);
  23390. if (e.control == self) {
  23391. var rel = tooltip.text(settings.tooltip).show().testMoveRel(self.getEl(), ['bc-tc', 'bc-tl', 'bc-tr']);
  23392. tooltip.toggleClass('tooltip-n', rel == 'bc-tc');
  23393. tooltip.toggleClass('tooltip-nw', rel == 'bc-tl');
  23394. tooltip.toggleClass('tooltip-ne', rel == 'bc-tr');
  23395. tooltip.moveRel(self.getEl(), rel);
  23396. } else {
  23397. tooltip.hide();
  23398. }
  23399. });
  23400. self.on('mouseleave mousedown click', function() {
  23401. self.tooltip().hide();
  23402. });
  23403. }
  23404. self.aria('label', settings.ariaLabel || settings.tooltip);
  23405. },
  23406. /**
  23407. * Returns the current tooltip instance.
  23408. *
  23409. * @method tooltip
  23410. * @return {tinymce.ui.Tooltip} Tooltip instance.
  23411. */
  23412. tooltip: function() {
  23413. if (!tooltip) {
  23414. tooltip = new Tooltip({type: 'tooltip'});
  23415. tooltip.renderTo();
  23416. }
  23417. return tooltip;
  23418. },
  23419. /**
  23420. * Sets/gets the active state of the widget.
  23421. *
  23422. * @method active
  23423. * @param {Boolean} [state] State if the control is active.
  23424. * @return {Boolean|tinymce.ui.Widget} True/false or current widget instance.
  23425. */
  23426. active: function(state) {
  23427. var self = this, undef;
  23428. if (state !== undef) {
  23429. self.aria('pressed', state);
  23430. self.toggleClass('active', state);
  23431. }
  23432. return self._super(state);
  23433. },
  23434. /**
  23435. * Sets/gets the disabled state of the widget.
  23436. *
  23437. * @method disabled
  23438. * @param {Boolean} [state] State if the control is disabled.
  23439. * @return {Boolean|tinymce.ui.Widget} True/false or current widget instance.
  23440. */
  23441. disabled: function(state) {
  23442. var self = this, undef;
  23443. if (state !== undef) {
  23444. self.aria('disabled', state);
  23445. self.toggleClass('disabled', state);
  23446. }
  23447. return self._super(state);
  23448. },
  23449. /**
  23450. * Called after the control has been rendered.
  23451. *
  23452. * @method postRender
  23453. */
  23454. postRender: function() {
  23455. var self = this, settings = self.settings;
  23456. self._rendered = true;
  23457. self._super();
  23458. if (!self.parent() && (settings.width || settings.height)) {
  23459. self.initLayoutRect();
  23460. self.repaint();
  23461. }
  23462. if (settings.autofocus) {
  23463. self.focus();
  23464. }
  23465. },
  23466. /**
  23467. * Removes the current control from DOM and from UI collections.
  23468. *
  23469. * @method remove
  23470. * @return {tinymce.ui.Control} Current control instance.
  23471. */
  23472. remove: function() {
  23473. this._super();
  23474. if (tooltip) {
  23475. tooltip.remove();
  23476. tooltip = null;
  23477. }
  23478. }
  23479. });
  23480. return Widget;
  23481. });
  23482. // Included from: js/tinymce/classes/ui/Button.js
  23483. /**
  23484. * Button.js
  23485. *
  23486. * Copyright, Moxiecode Systems AB
  23487. * Released under LGPL License.
  23488. *
  23489. * License: http://www.tinymce.com/license
  23490. * Contributing: http://www.tinymce.com/contributing
  23491. */
  23492. /**
  23493. * This class is used to create buttons. You can create them directly or through the Factory.
  23494. *
  23495. * @example
  23496. * // Create and render a button to the body element
  23497. * tinymce.ui.Factory.create({
  23498. * type: 'button',
  23499. * text: 'My button'
  23500. * }).renderTo(document.body);
  23501. *
  23502. * @-x-less Button.less
  23503. * @class tinymce.ui.Button
  23504. * @extends tinymce.ui.Widget
  23505. */
  23506. define("tinymce/ui/Button", [
  23507. "tinymce/ui/Widget"
  23508. ], function(Widget) {
  23509. "use strict";
  23510. return Widget.extend({
  23511. Defaults: {
  23512. classes: "widget btn",
  23513. role: "button"
  23514. },
  23515. /**
  23516. * Constructs a new button instance with the specified settings.
  23517. *
  23518. * @constructor
  23519. * @param {Object} settings Name/value object with settings.
  23520. * @setting {String} size Size of the button small|medium|large.
  23521. * @setting {String} image Image to use for icon.
  23522. * @setting {String} icon Icon to use for button.
  23523. */
  23524. init: function(settings) {
  23525. var self = this, size;
  23526. self.on('click mousedown', function(e) {
  23527. e.preventDefault();
  23528. });
  23529. self._super(settings);
  23530. size = settings.size;
  23531. if (settings.subtype) {
  23532. self.addClass(settings.subtype);
  23533. }
  23534. if (size) {
  23535. self.addClass('btn-' + size);
  23536. }
  23537. },
  23538. /**
  23539. * Sets/gets the current button icon.
  23540. *
  23541. * @method icon
  23542. * @param {String} [icon] New icon identifier.
  23543. * @return {String|tinymce.ui.MenuButton} Current icon or current MenuButton instance.
  23544. */
  23545. icon: function(icon) {
  23546. var self = this, prefix = self.classPrefix;
  23547. if (typeof(icon) == 'undefined') {
  23548. return self.settings.icon;
  23549. }
  23550. self.settings.icon = icon;
  23551. icon = icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : '';
  23552. if (self._rendered) {
  23553. var btnElm = self.getEl().firstChild, iconElm = btnElm.getElementsByTagName('i')[0];
  23554. if (icon) {
  23555. if (!iconElm || iconElm != btnElm.firstChild) {
  23556. iconElm = document.createElement('i');
  23557. btnElm.insertBefore(iconElm, btnElm.firstChild);
  23558. }
  23559. iconElm.className = icon;
  23560. } else if (iconElm) {
  23561. btnElm.removeChild(iconElm);
  23562. }
  23563. self.text(self._text); // Set text again to fix whitespace between icon + text
  23564. }
  23565. return self;
  23566. },
  23567. /**
  23568. * Repaints the button for example after it's been resizes by a layout engine.
  23569. *
  23570. * @method repaint
  23571. */
  23572. repaint: function() {
  23573. var btnStyle = this.getEl().firstChild.style;
  23574. btnStyle.width = btnStyle.height = "100%";
  23575. this._super();
  23576. },
  23577. /**
  23578. * Sets/gets the current button text.
  23579. *
  23580. * @method text
  23581. * @param {String} [text] New button text.
  23582. * @return {String|tinymce.ui.Button} Current text or current Button instance.
  23583. */
  23584. text: function(text) {
  23585. var self = this;
  23586. if (self._rendered) {
  23587. var textNode = self.getEl().lastChild.lastChild;
  23588. if (textNode) {
  23589. textNode.data = self.translate(text);
  23590. }
  23591. }
  23592. return self._super(text);
  23593. },
  23594. /**
  23595. * Renders the control as a HTML string.
  23596. *
  23597. * @method renderHtml
  23598. * @return {String} HTML representing the control.
  23599. */
  23600. renderHtml: function() {
  23601. var self = this, id = self._id, prefix = self.classPrefix;
  23602. var icon = self.settings.icon, image;
  23603. image = self.settings.image;
  23604. if (image) {
  23605. icon = 'none';
  23606. // Support for [high dpi, low dpi] image sources
  23607. if (typeof image != "string") {
  23608. image = window.getSelection ? image[0] : image[1];
  23609. }
  23610. image = ' style="background-image: url(\'' + image + '\')"';
  23611. } else {
  23612. image = '';
  23613. }
  23614. icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + icon : '';
  23615. return (
  23616. '<div id="' + id + '" class="' + self.classes() + '" tabindex="-1" aria-labelledby="' + id + '">' +
  23617. '<button role="presentation" type="button" tabindex="-1">' +
  23618. (icon ? '<i class="' + icon + '"' + image + '></i>' : '') +
  23619. (self._text ? (icon ? '\u00a0' : '') + self.encode(self._text) : '') +
  23620. '</button>' +
  23621. '</div>'
  23622. );
  23623. }
  23624. });
  23625. });
  23626. // Included from: js/tinymce/classes/ui/ButtonGroup.js
  23627. /**
  23628. * ButtonGroup.js
  23629. *
  23630. * Copyright, Moxiecode Systems AB
  23631. * Released under LGPL License.
  23632. *
  23633. * License: http://www.tinymce.com/license
  23634. * Contributing: http://www.tinymce.com/contributing
  23635. */
  23636. /**
  23637. * This control enables you to put multiple buttons into a group. This is
  23638. * useful when you want to combine similar toolbar buttons into a group.
  23639. *
  23640. * @example
  23641. * // Create and render a buttongroup with two buttons to the body element
  23642. * tinymce.ui.Factory.create({
  23643. * type: 'buttongroup',
  23644. * items: [
  23645. * {text: 'Button A'},
  23646. * {text: 'Button B'}
  23647. * ]
  23648. * }).renderTo(document.body);
  23649. *
  23650. * @-x-less ButtonGroup.less
  23651. * @class tinymce.ui.ButtonGroup
  23652. * @extends tinymce.ui.Container
  23653. */
  23654. define("tinymce/ui/ButtonGroup", [
  23655. "tinymce/ui/Container"
  23656. ], function(Container) {
  23657. "use strict";
  23658. return Container.extend({
  23659. Defaults: {
  23660. defaultType: 'button',
  23661. role: 'group'
  23662. },
  23663. /**
  23664. * Renders the control as a HTML string.
  23665. *
  23666. * @method renderHtml
  23667. * @return {String} HTML representing the control.
  23668. */
  23669. renderHtml: function() {
  23670. var self = this, layout = self._layout;
  23671. self.addClass('btn-group');
  23672. self.preRender();
  23673. layout.preRender(self);
  23674. return (
  23675. '<div id="' + self._id + '" class="' + self.classes() + '">' +
  23676. '<div id="' + self._id + '-body">' +
  23677. (self.settings.html || '') + layout.renderHtml(self) +
  23678. '</div>' +
  23679. '</div>'
  23680. );
  23681. }
  23682. });
  23683. });
  23684. // Included from: js/tinymce/classes/ui/Checkbox.js
  23685. /**
  23686. * Checkbox.js
  23687. *
  23688. * Copyright, Moxiecode Systems AB
  23689. * Released under LGPL License.
  23690. *
  23691. * License: http://www.tinymce.com/license
  23692. * Contributing: http://www.tinymce.com/contributing
  23693. */
  23694. /**
  23695. * This control creates a custom checkbox.
  23696. *
  23697. * @example
  23698. * // Create and render a checkbox to the body element
  23699. * tinymce.ui.Factory.create({
  23700. * type: 'checkbox',
  23701. * checked: true,
  23702. * text: 'My checkbox'
  23703. * }).renderTo(document.body);
  23704. *
  23705. * @-x-less Checkbox.less
  23706. * @class tinymce.ui.Checkbox
  23707. * @extends tinymce.ui.Widget
  23708. */
  23709. define("tinymce/ui/Checkbox", [
  23710. "tinymce/ui/Widget"
  23711. ], function(Widget) {
  23712. "use strict";
  23713. return Widget.extend({
  23714. Defaults: {
  23715. classes: "checkbox",
  23716. role: "checkbox",
  23717. checked: false
  23718. },
  23719. /**
  23720. * Constructs a new Checkbox instance with the specified settings.
  23721. *
  23722. * @constructor
  23723. * @param {Object} settings Name/value object with settings.
  23724. * @setting {Boolean} checked True if the checkbox should be checked by default.
  23725. */
  23726. init: function(settings) {
  23727. var self = this;
  23728. self._super(settings);
  23729. self.on('click mousedown', function(e) {
  23730. e.preventDefault();
  23731. });
  23732. self.on('click', function(e) {
  23733. e.preventDefault();
  23734. if (!self.disabled()) {
  23735. self.checked(!self.checked());
  23736. }
  23737. });
  23738. self.checked(self.settings.checked);
  23739. },
  23740. /**
  23741. * Getter/setter function for the checked state.
  23742. *
  23743. * @method checked
  23744. * @param {Boolean} [state] State to be set.
  23745. * @return {Boolean|tinymce.ui.Checkbox} True/false or checkbox if it's a set operation.
  23746. */
  23747. checked: function(state) {
  23748. var self = this;
  23749. if (typeof state != "undefined") {
  23750. if (state) {
  23751. self.addClass('checked');
  23752. } else {
  23753. self.removeClass('checked');
  23754. }
  23755. self._checked = state;
  23756. self.aria('checked', state);
  23757. return self;
  23758. }
  23759. return self._checked;
  23760. },
  23761. /**
  23762. * Getter/setter function for the value state.
  23763. *
  23764. * @method value
  23765. * @param {Boolean} [state] State to be set.
  23766. * @return {Boolean|tinymce.ui.Checkbox} True/false or checkbox if it's a set operation.
  23767. */
  23768. value: function(state) {
  23769. return this.checked(state);
  23770. },
  23771. /**
  23772. * Renders the control as a HTML string.
  23773. *
  23774. * @method renderHtml
  23775. * @return {String} HTML representing the control.
  23776. */
  23777. renderHtml: function() {
  23778. var self = this, id = self._id, prefix = self.classPrefix;
  23779. return (
  23780. '<div id="' + id + '" class="' + self.classes() + '" unselectable="on" aria-labelledby="' + id + '-al" tabindex="-1">' +
  23781. '<i class="' + prefix + 'ico ' + prefix + 'i-checkbox"></i>' +
  23782. '<span id="' + id + '-al" class="' + prefix + 'label">' + self.encode(self._text) + '</span>' +
  23783. '</div>'
  23784. );
  23785. }
  23786. });
  23787. });
  23788. // Included from: js/tinymce/classes/ui/PanelButton.js
  23789. /**
  23790. * PanelButton.js
  23791. *
  23792. * Copyright, Moxiecode Systems AB
  23793. * Released under LGPL License.
  23794. *
  23795. * License: http://www.tinymce.com/license
  23796. * Contributing: http://www.tinymce.com/contributing
  23797. */
  23798. /**
  23799. * Creates a new panel button.
  23800. *
  23801. * @class tinymce.ui.PanelButton
  23802. * @extends tinymce.ui.Button
  23803. */
  23804. define("tinymce/ui/PanelButton", [
  23805. "tinymce/ui/Button",
  23806. "tinymce/ui/FloatPanel"
  23807. ], function(Button, FloatPanel) {
  23808. "use strict";
  23809. return Button.extend({
  23810. /**
  23811. * Shows the panel for the button.
  23812. *
  23813. * @method showPanel
  23814. */
  23815. showPanel: function() {
  23816. var self = this, settings = self.settings;
  23817. self.active(true);
  23818. if (!self.panel) {
  23819. var panelSettings = settings.panel;
  23820. // Wrap panel in grid layout if type if specified
  23821. // This makes it possible to add forms or other containers directly in the panel option
  23822. if (panelSettings.type) {
  23823. panelSettings = {
  23824. layout: 'grid',
  23825. items: panelSettings
  23826. };
  23827. }
  23828. panelSettings.role = panelSettings.role || 'dialog';
  23829. panelSettings.popover = true;
  23830. panelSettings.autohide = true;
  23831. panelSettings.ariaRoot = true;
  23832. self.panel = new FloatPanel(panelSettings).on('hide', function() {
  23833. self.active(false);
  23834. }).on('cancel', function(e) {
  23835. e.stopPropagation();
  23836. self.focus();
  23837. self.hidePanel();
  23838. }).parent(self).renderTo(self.getContainerElm());
  23839. self.panel.fire('show');
  23840. self.panel.reflow();
  23841. } else {
  23842. self.panel.show();
  23843. }
  23844. self.panel.moveRel(self.getEl(), settings.popoverAlign || (self.isRtl() ? ['bc-tr', 'bc-tc'] : ['bc-tl', 'bc-tc']));
  23845. },
  23846. /**
  23847. * Hides the panel for the button.
  23848. *
  23849. * @method hidePanel
  23850. */
  23851. hidePanel: function() {
  23852. var self = this;
  23853. if (self.panel) {
  23854. self.panel.hide();
  23855. }
  23856. },
  23857. /**
  23858. * Called after the control has been rendered.
  23859. *
  23860. * @method postRender
  23861. */
  23862. postRender: function() {
  23863. var self = this;
  23864. self.aria('haspopup', true);
  23865. self.on('click', function(e) {
  23866. if (e.control === self) {
  23867. if (self.panel && self.panel.visible()) {
  23868. self.hidePanel();
  23869. } else {
  23870. self.showPanel();
  23871. self.panel.focus(!!e.aria);
  23872. }
  23873. }
  23874. });
  23875. return self._super();
  23876. }
  23877. });
  23878. });
  23879. // Included from: js/tinymce/classes/ui/ColorButton.js
  23880. /**
  23881. * ColorButton.js
  23882. *
  23883. * Copyright, Moxiecode Systems AB
  23884. * Released under LGPL License.
  23885. *
  23886. * License: http://www.tinymce.com/license
  23887. * Contributing: http://www.tinymce.com/contributing
  23888. */
  23889. /**
  23890. * This class creates a color button control. This is a split button in which the main
  23891. * button has a visual representation of the currently selected color. When clicked
  23892. * the caret button displays a color picker, allowing the user to select a new color.
  23893. *
  23894. * @-x-less ColorButton.less
  23895. * @class tinymce.ui.ColorButton
  23896. * @extends tinymce.ui.PanelButton
  23897. */
  23898. define("tinymce/ui/ColorButton", [
  23899. "tinymce/ui/PanelButton",
  23900. "tinymce/dom/DOMUtils"
  23901. ], function(PanelButton, DomUtils) {
  23902. "use strict";
  23903. var DOM = DomUtils.DOM;
  23904. return PanelButton.extend({
  23905. /**
  23906. * Constructs a new ColorButton instance with the specified settings.
  23907. *
  23908. * @constructor
  23909. * @param {Object} settings Name/value object with settings.
  23910. */
  23911. init: function(settings) {
  23912. this._super(settings);
  23913. this.addClass('colorbutton');
  23914. },
  23915. /**
  23916. * Getter/setter for the current color.
  23917. *
  23918. * @method color
  23919. * @param {String} [color] Color to set.
  23920. * @return {String|tinymce.ui.ColorButton} Current color or current instance.
  23921. */
  23922. color: function(color) {
  23923. if (color) {
  23924. this._color = color;
  23925. this.getEl('preview').style.backgroundColor = color;
  23926. return this;
  23927. }
  23928. return this._color;
  23929. },
  23930. /**
  23931. * Renders the control as a HTML string.
  23932. *
  23933. * @method renderHtml
  23934. * @return {String} HTML representing the control.
  23935. */
  23936. renderHtml: function() {
  23937. var self = this, id = self._id, prefix = self.classPrefix;
  23938. var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : '';
  23939. var image = self.settings.image ? ' style="background-image: url(\'' + self.settings.image + '\')"' : '';
  23940. return (
  23941. '<div id="' + id + '" class="' + self.classes() + '" role="button" tabindex="-1" aria-haspopup="true">' +
  23942. '<button role="presentation" hidefocus="1" type="button" tabindex="-1">' +
  23943. (icon ? '<i class="' + icon + '"' + image + '></i>' : '') +
  23944. '<span id="' + id + '-preview" class="' + prefix + 'preview"></span>' +
  23945. (self._text ? (icon ? ' ' : '') + (self._text) : '') +
  23946. '</button>' +
  23947. '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' +
  23948. ' <i class="' + prefix + 'caret"></i>' +
  23949. '</button>' +
  23950. '</div>'
  23951. );
  23952. },
  23953. /**
  23954. * Called after the control has been rendered.
  23955. *
  23956. * @method postRender
  23957. */
  23958. postRender: function() {
  23959. var self = this, onClickHandler = self.settings.onclick;
  23960. self.on('click', function(e) {
  23961. if (e.aria && e.aria.key == 'down') {
  23962. return;
  23963. }
  23964. if (e.control == self && !DOM.getParent(e.target, '.' + self.classPrefix + 'open')) {
  23965. e.stopImmediatePropagation();
  23966. onClickHandler.call(self, e);
  23967. }
  23968. });
  23969. delete self.settings.onclick;
  23970. return self._super();
  23971. }
  23972. });
  23973. });
  23974. // Included from: js/tinymce/classes/ui/ComboBox.js
  23975. /**
  23976. * ComboBox.js
  23977. *
  23978. * Copyright, Moxiecode Systems AB
  23979. * Released under LGPL License.
  23980. *
  23981. * License: http://www.tinymce.com/license
  23982. * Contributing: http://www.tinymce.com/contributing
  23983. */
  23984. /**
  23985. * This class creates a combobox control. Select box that you select a value from or
  23986. * type a value into.
  23987. *
  23988. * @-x-less ComboBox.less
  23989. * @class tinymce.ui.ComboBox
  23990. * @extends tinymce.ui.Widget
  23991. */
  23992. define("tinymce/ui/ComboBox", [
  23993. "tinymce/ui/Widget",
  23994. "tinymce/ui/Factory",
  23995. "tinymce/ui/DomUtils"
  23996. ], function(Widget, Factory, DomUtils) {
  23997. "use strict";
  23998. return Widget.extend({
  23999. /**
  24000. * Constructs a new control instance with the specified settings.
  24001. *
  24002. * @constructor
  24003. * @param {Object} settings Name/value object with settings.
  24004. * @setting {String} placeholder Placeholder text to display.
  24005. */
  24006. init: function(settings) {
  24007. var self = this;
  24008. self._super(settings);
  24009. self.addClass('combobox');
  24010. self.subinput = true;
  24011. self.ariaTarget = 'inp'; // TODO: Figure out a better way
  24012. settings = self.settings;
  24013. settings.menu = settings.menu || settings.values;
  24014. if (settings.menu) {
  24015. settings.icon = 'caret';
  24016. }
  24017. self.on('click', function(e) {
  24018. var elm = e.target, root = self.getEl();
  24019. while (elm && elm != root) {
  24020. if (elm.id && elm.id.indexOf('-open') != -1) {
  24021. self.fire('action');
  24022. if (settings.menu) {
  24023. self.showMenu();
  24024. if (e.aria) {
  24025. self.menu.items()[0].focus();
  24026. }
  24027. }
  24028. }
  24029. elm = elm.parentNode;
  24030. }
  24031. });
  24032. // TODO: Rework this
  24033. self.on('keydown', function(e) {
  24034. if (e.target.nodeName == "INPUT" && e.keyCode == 13) {
  24035. self.parents().reverse().each(function(ctrl) {
  24036. e.preventDefault();
  24037. self.fire('change');
  24038. if (ctrl.hasEventListeners('submit') && ctrl.toJSON) {
  24039. ctrl.fire('submit', {data: ctrl.toJSON()});
  24040. return false;
  24041. }
  24042. });
  24043. }
  24044. });
  24045. if (settings.placeholder) {
  24046. self.addClass('placeholder');
  24047. self.on('focusin', function() {
  24048. if (!self._hasOnChange) {
  24049. DomUtils.on(self.getEl('inp'), 'change', function() {
  24050. self.fire('change');
  24051. });
  24052. self._hasOnChange = true;
  24053. }
  24054. if (self.hasClass('placeholder')) {
  24055. self.getEl('inp').value = '';
  24056. self.removeClass('placeholder');
  24057. }
  24058. });
  24059. self.on('focusout', function() {
  24060. if (self.value().length === 0) {
  24061. self.getEl('inp').value = settings.placeholder;
  24062. self.addClass('placeholder');
  24063. }
  24064. });
  24065. }
  24066. },
  24067. showMenu: function() {
  24068. var self = this, settings = self.settings, menu;
  24069. if (!self.menu) {
  24070. menu = settings.menu || [];
  24071. // Is menu array then auto constuct menu control
  24072. if (menu.length) {
  24073. menu = {
  24074. type: 'menu',
  24075. items: menu
  24076. };
  24077. } else {
  24078. menu.type = menu.type || 'menu';
  24079. }
  24080. self.menu = Factory.create(menu).parent(self).renderTo(self.getContainerElm());
  24081. self.fire('createmenu');
  24082. self.menu.reflow();
  24083. self.menu.on('cancel', function(e) {
  24084. if (e.control === self.menu) {
  24085. self.focus();
  24086. }
  24087. });
  24088. self.menu.on('show hide', function(e) {
  24089. e.control.items().each(function(ctrl) {
  24090. ctrl.active(ctrl.value() == self.value());
  24091. });
  24092. }).fire('show');
  24093. self.menu.on('select', function(e) {
  24094. self.value(e.control.value());
  24095. });
  24096. self.on('focusin', function(e) {
  24097. if (e.target.tagName.toUpperCase() == 'INPUT') {
  24098. self.menu.hide();
  24099. }
  24100. });
  24101. self.aria('expanded', true);
  24102. }
  24103. self.menu.show();
  24104. self.menu.layoutRect({w: self.layoutRect().w});
  24105. self.menu.moveRel(self.getEl(), self.isRtl() ? ['br-tr', 'tr-br'] : ['bl-tl', 'tl-bl']);
  24106. },
  24107. /**
  24108. * Getter/setter function for the control value.
  24109. *
  24110. * @method value
  24111. * @param {String} [value] Value to be set.
  24112. * @return {String|tinymce.ui.ComboBox} Value or self if it's a set operation.
  24113. */
  24114. value: function(value) {
  24115. var self = this;
  24116. if (typeof(value) != "undefined") {
  24117. self._value = value;
  24118. self.removeClass('placeholder');
  24119. if (self._rendered) {
  24120. self.getEl('inp').value = value;
  24121. }
  24122. return self;
  24123. }
  24124. if (self._rendered) {
  24125. value = self.getEl('inp').value;
  24126. if (value != self.settings.placeholder) {
  24127. return value;
  24128. }
  24129. return '';
  24130. }
  24131. return self._value;
  24132. },
  24133. /**
  24134. * Getter/setter function for the disabled state.
  24135. *
  24136. * @method value
  24137. * @param {Boolean} [state] State to be set.
  24138. * @return {Boolean|tinymce.ui.ComboBox} True/false or self if it's a set operation.
  24139. */
  24140. disabled: function(state) {
  24141. var self = this;
  24142. if (self._rendered && typeof(state) != 'undefined') {
  24143. self.getEl('inp').disabled = state;
  24144. }
  24145. return self._super(state);
  24146. },
  24147. /**
  24148. * Focuses the input area of the control.
  24149. *
  24150. * @method focus
  24151. */
  24152. focus: function() {
  24153. this.getEl('inp').focus();
  24154. },
  24155. /**
  24156. * Repaints the control after a layout operation.
  24157. *
  24158. * @method repaint
  24159. */
  24160. repaint: function() {
  24161. var self = this, elm = self.getEl(), openElm = self.getEl('open'), rect = self.layoutRect();
  24162. var width, lineHeight;
  24163. if (openElm) {
  24164. width = rect.w - DomUtils.getSize(openElm).width - 10;
  24165. } else {
  24166. width = rect.w - 10;
  24167. }
  24168. // Detect old IE 7+8 add lineHeight to align caret vertically in the middle
  24169. var doc = document;
  24170. if (doc.all && (!doc.documentMode || doc.documentMode <= 8)) {
  24171. lineHeight = (self.layoutRect().h - 2) + 'px';
  24172. }
  24173. DomUtils.css(elm.firstChild, {
  24174. width: width,
  24175. lineHeight: lineHeight
  24176. });
  24177. self._super();
  24178. return self;
  24179. },
  24180. /**
  24181. * Post render method. Called after the control has been rendered to the target.
  24182. *
  24183. * @method postRender
  24184. * @return {tinymce.ui.ComboBox} Current combobox instance.
  24185. */
  24186. postRender: function() {
  24187. var self = this;
  24188. DomUtils.on(this.getEl('inp'), 'change', function() {
  24189. self.fire('change');
  24190. });
  24191. return self._super();
  24192. },
  24193. remove: function() {
  24194. DomUtils.off(this.getEl('inp'));
  24195. this._super();
  24196. },
  24197. /**
  24198. * Renders the control as a HTML string.
  24199. *
  24200. * @method renderHtml
  24201. * @return {String} HTML representing the control.
  24202. */
  24203. renderHtml: function() {
  24204. var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix;
  24205. var value = settings.value || settings.placeholder || '';
  24206. var icon, text, openBtnHtml = '', extraAttrs = '';
  24207. if ("spellcheck" in settings) {
  24208. extraAttrs += ' spellcheck="' + settings.spellcheck + '"';
  24209. }
  24210. if (settings.maxLength) {
  24211. extraAttrs += ' maxlength="' + settings.maxLength + '"';
  24212. }
  24213. if (settings.size) {
  24214. extraAttrs += ' size="' + settings.size + '"';
  24215. }
  24216. if (settings.subtype) {
  24217. extraAttrs += ' type="' + settings.subtype + '"';
  24218. }
  24219. if (self.disabled()) {
  24220. extraAttrs += ' disabled="disabled"';
  24221. }
  24222. icon = settings.icon;
  24223. if (icon && icon != 'caret') {
  24224. icon = prefix + 'ico ' + prefix + 'i-' + settings.icon;
  24225. }
  24226. text = self._text;
  24227. if (icon || text) {
  24228. openBtnHtml = (
  24229. '<div id="' + id + '-open" class="' + prefix + 'btn ' + prefix + 'open" tabIndex="-1" role="button">' +
  24230. '<button id="' + id + '-action" type="button" hidefocus="1" tabindex="-1">' +
  24231. (icon != 'caret' ? '<i class="' + icon + '"></i>' : '<i class="' + prefix + 'caret"></i>') +
  24232. (text ? (icon ? ' ' : '') + text : '') +
  24233. '</button>' +
  24234. '</div>'
  24235. );
  24236. self.addClass('has-open');
  24237. }
  24238. return (
  24239. '<div id="' + id + '" class="' + self.classes() + '">' +
  24240. '<input id="' + id + '-inp" class="' + prefix + 'textbox ' + prefix + 'placeholder" value="' +
  24241. value + '" hidefocus="1"' + extraAttrs + ' />' +
  24242. openBtnHtml +
  24243. '</div>'
  24244. );
  24245. }
  24246. });
  24247. });
  24248. // Included from: js/tinymce/classes/ui/Path.js
  24249. /**
  24250. * Path.js
  24251. *
  24252. * Copyright, Moxiecode Systems AB
  24253. * Released under LGPL License.
  24254. *
  24255. * License: http://www.tinymce.com/license
  24256. * Contributing: http://www.tinymce.com/contributing
  24257. */
  24258. /**
  24259. * Creates a new path control.
  24260. *
  24261. * @-x-less Path.less
  24262. * @class tinymce.ui.Path
  24263. * @extends tinymce.ui.Widget
  24264. */
  24265. define("tinymce/ui/Path", [
  24266. "tinymce/ui/Widget"
  24267. ], function(Widget) {
  24268. "use strict";
  24269. return Widget.extend({
  24270. /**
  24271. * Constructs a instance with the specified settings.
  24272. *
  24273. * @constructor
  24274. * @param {Object} settings Name/value object with settings.
  24275. * @setting {String} delimiter Delimiter to display between items in path.
  24276. */
  24277. init: function(settings) {
  24278. var self = this;
  24279. if (!settings.delimiter) {
  24280. settings.delimiter = '\u00BB';
  24281. }
  24282. self._super(settings);
  24283. self.addClass('path');
  24284. self.canFocus = true;
  24285. self.on('click', function(e) {
  24286. var index, target = e.target;
  24287. if ((index = target.getAttribute('data-index'))) {
  24288. self.fire('select', {value: self.data()[index], index: index});
  24289. }
  24290. });
  24291. },
  24292. /**
  24293. * Focuses the current control.
  24294. *
  24295. * @method focus
  24296. * @return {tinymce.ui.Control} Current control instance.
  24297. */
  24298. focus: function() {
  24299. var self = this;
  24300. self.getEl().firstChild.focus();
  24301. return self;
  24302. },
  24303. /**
  24304. * Sets/gets the data to be used for the path.
  24305. *
  24306. * @method data
  24307. * @param {Array} data Array with items name is rendered to path.
  24308. */
  24309. data: function(data) {
  24310. var self = this;
  24311. if (typeof(data) !== "undefined") {
  24312. self._data = data;
  24313. self.update();
  24314. return self;
  24315. }
  24316. return self._data;
  24317. },
  24318. /**
  24319. * Updated the path.
  24320. *
  24321. * @private
  24322. */
  24323. update: function() {
  24324. this.innerHtml(this._getPathHtml());
  24325. },
  24326. /**
  24327. * Called after the control has been rendered.
  24328. *
  24329. * @method postRender
  24330. */
  24331. postRender: function() {
  24332. var self = this;
  24333. self._super();
  24334. self.data(self.settings.data);
  24335. },
  24336. /**
  24337. * Renders the control as a HTML string.
  24338. *
  24339. * @method renderHtml
  24340. * @return {String} HTML representing the control.
  24341. */
  24342. renderHtml: function() {
  24343. var self = this;
  24344. return (
  24345. '<div id="' + self._id + '" class="' + self.classes() + '">' +
  24346. self._getPathHtml() +
  24347. '</div>'
  24348. );
  24349. },
  24350. _getPathHtml: function() {
  24351. var self = this, parts = self._data || [], i, l, html = '', prefix = self.classPrefix;
  24352. for (i = 0, l = parts.length; i < l; i++) {
  24353. html += (
  24354. (i > 0 ? '<div class="' + prefix + 'divider" aria-hidden="true"> ' + self.settings.delimiter + ' </div>' : '') +
  24355. '<div role="button" class="' + prefix + 'path-item' + (i == l - 1 ? ' ' + prefix + 'last' : '') + '" data-index="' +
  24356. i + '" tabindex="-1" id="' + self._id + '-' + i + '" aria-level="' + i + '">' + parts[i].name + '</div>'
  24357. );
  24358. }
  24359. if (!html) {
  24360. html = '<div class="' + prefix + 'path-item">\u00a0</div>';
  24361. }
  24362. return html;
  24363. }
  24364. });
  24365. });
  24366. // Included from: js/tinymce/classes/ui/ElementPath.js
  24367. /**
  24368. * ElementPath.js
  24369. *
  24370. * Copyright, Moxiecode Systems AB
  24371. * Released under LGPL License.
  24372. *
  24373. * License: http://www.tinymce.com/license
  24374. * Contributing: http://www.tinymce.com/contributing
  24375. */
  24376. /**
  24377. * This control creates an path for the current selections parent elements in TinyMCE.
  24378. *
  24379. * @class tinymce.ui.ElementPath
  24380. * @extends tinymce.ui.Path
  24381. */
  24382. define("tinymce/ui/ElementPath", [
  24383. "tinymce/ui/Path",
  24384. "tinymce/EditorManager"
  24385. ], function(Path, EditorManager) {
  24386. return Path.extend({
  24387. /**
  24388. * Post render method. Called after the control has been rendered to the target.
  24389. *
  24390. * @method postRender
  24391. * @return {tinymce.ui.ElementPath} Current combobox instance.
  24392. */
  24393. postRender: function() {
  24394. var self = this, editor = EditorManager.activeEditor;
  24395. function isHidden(elm) {
  24396. if (elm.nodeType === 1) {
  24397. if (elm.nodeName == "BR" || !!elm.getAttribute('data-mce-bogus')) {
  24398. return true;
  24399. }
  24400. if (elm.getAttribute('data-mce-type') === 'bookmark') {
  24401. return true;
  24402. }
  24403. }
  24404. return false;
  24405. }
  24406. self.on('select', function(e) {
  24407. var parents = [], node, body = editor.getBody();
  24408. editor.focus();
  24409. node = editor.selection.getStart();
  24410. while (node && node != body) {
  24411. if (!isHidden(node)) {
  24412. parents.push(node);
  24413. }
  24414. node = node.parentNode;
  24415. }
  24416. editor.selection.select(parents[parents.length - 1 - e.index]);
  24417. editor.nodeChanged();
  24418. });
  24419. editor.on('nodeChange', function(e) {
  24420. var parents = [], selectionParents = e.parents, i = selectionParents.length;
  24421. while (i--) {
  24422. if (selectionParents[i].nodeType == 1 && !isHidden(selectionParents[i])) {
  24423. var args = editor.fire('ResolveName', {
  24424. name: selectionParents[i].nodeName.toLowerCase(),
  24425. target: selectionParents[i]
  24426. });
  24427. parents.push({name: args.name});
  24428. }
  24429. }
  24430. self.data(parents);
  24431. });
  24432. return self._super();
  24433. }
  24434. });
  24435. });
  24436. // Included from: js/tinymce/classes/ui/FormItem.js
  24437. /**
  24438. * FormItem.js
  24439. *
  24440. * Copyright, Moxiecode Systems AB
  24441. * Released under LGPL License.
  24442. *
  24443. * License: http://www.tinymce.com/license
  24444. * Contributing: http://www.tinymce.com/contributing
  24445. */
  24446. /**
  24447. * This class is a container created by the form element with
  24448. * a label and control item.
  24449. *
  24450. * @class tinymce.ui.FormItem
  24451. * @extends tinymce.ui.Container
  24452. * @setting {String} label Label to display for the form item.
  24453. */
  24454. define("tinymce/ui/FormItem", [
  24455. "tinymce/ui/Container"
  24456. ], function(Container) {
  24457. "use strict";
  24458. return Container.extend({
  24459. Defaults: {
  24460. layout: 'flex',
  24461. align: 'center',
  24462. defaults: {
  24463. flex: 1
  24464. }
  24465. },
  24466. /**
  24467. * Renders the control as a HTML string.
  24468. *
  24469. * @method renderHtml
  24470. * @return {String} HTML representing the control.
  24471. */
  24472. renderHtml: function() {
  24473. var self = this, layout = self._layout, prefix = self.classPrefix;
  24474. self.addClass('formitem');
  24475. layout.preRender(self);
  24476. return (
  24477. '<div id="' + self._id + '" class="' + self.classes() + '" hidefocus="1" tabindex="-1">' +
  24478. (self.settings.title ? ('<div id="' + self._id + '-title" class="' + prefix + 'title">' +
  24479. self.settings.title + '</div>') : '') +
  24480. '<div id="' + self._id + '-body" class="' + self.classes('body') + '">' +
  24481. (self.settings.html || '') + layout.renderHtml(self) +
  24482. '</div>' +
  24483. '</div>'
  24484. );
  24485. }
  24486. });
  24487. });
  24488. // Included from: js/tinymce/classes/ui/Form.js
  24489. /**
  24490. * Form.js
  24491. *
  24492. * Copyright, Moxiecode Systems AB
  24493. * Released under LGPL License.
  24494. *
  24495. * License: http://www.tinymce.com/license
  24496. * Contributing: http://www.tinymce.com/contributing
  24497. */
  24498. /**
  24499. * This class creates a form container. A form container has the ability
  24500. * to automatically wrap items in tinymce.ui.FormItem instances.
  24501. *
  24502. * Each FormItem instance is a container for the label and the item.
  24503. *
  24504. * @example
  24505. * tinymce.ui.Factory.create({
  24506. * type: 'form',
  24507. * items: [
  24508. * {type: 'textbox', label: 'My text box'}
  24509. * ]
  24510. * }).renderTo(document.body);
  24511. *
  24512. * @class tinymce.ui.Form
  24513. * @extends tinymce.ui.Container
  24514. */
  24515. define("tinymce/ui/Form", [
  24516. "tinymce/ui/Container",
  24517. "tinymce/ui/FormItem"
  24518. ], function(Container, FormItem) {
  24519. "use strict";
  24520. return Container.extend({
  24521. Defaults: {
  24522. containerCls: 'form',
  24523. layout: 'flex',
  24524. direction: 'column',
  24525. align: 'stretch',
  24526. flex: 1,
  24527. padding: 20,
  24528. labelGap: 30,
  24529. spacing: 10,
  24530. callbacks: {
  24531. submit: function() {
  24532. this.submit();
  24533. }
  24534. }
  24535. },
  24536. /**
  24537. * This method gets invoked before the control is rendered.
  24538. *
  24539. * @method preRender
  24540. */
  24541. preRender: function() {
  24542. var self = this, items = self.items();
  24543. // Wrap any labeled items in FormItems
  24544. items.each(function(ctrl) {
  24545. var formItem, label = ctrl.settings.label;
  24546. if (label) {
  24547. formItem = new FormItem({
  24548. layout: 'flex',
  24549. autoResize: "overflow",
  24550. defaults: {flex: 1},
  24551. items: [
  24552. {type: 'label', id: ctrl._id + '-l', text: label, flex: 0, forId: ctrl._id, disabled: ctrl.disabled()}
  24553. ]
  24554. });
  24555. formItem.type = 'formitem';
  24556. ctrl.aria('labelledby', ctrl._id + '-l');
  24557. if (typeof(ctrl.settings.flex) == "undefined") {
  24558. ctrl.settings.flex = 1;
  24559. }
  24560. self.replace(ctrl, formItem);
  24561. formItem.add(ctrl);
  24562. }
  24563. });
  24564. },
  24565. /**
  24566. * Recalcs label widths.
  24567. *
  24568. * @private
  24569. */
  24570. recalcLabels: function() {
  24571. var self = this, maxLabelWidth = 0, labels = [], i, labelGap;
  24572. if (self.settings.labelGapCalc === false) {
  24573. return;
  24574. }
  24575. self.items().filter('formitem').each(function(item) {
  24576. var labelCtrl = item.items()[0], labelWidth = labelCtrl.getEl().clientWidth;
  24577. maxLabelWidth = labelWidth > maxLabelWidth ? labelWidth : maxLabelWidth;
  24578. labels.push(labelCtrl);
  24579. });
  24580. labelGap = self.settings.labelGap || 0;
  24581. i = labels.length;
  24582. while (i--) {
  24583. labels[i].settings.minWidth = maxLabelWidth + labelGap;
  24584. }
  24585. },
  24586. /**
  24587. * Getter/setter for the visibility state.
  24588. *
  24589. * @method visible
  24590. * @param {Boolean} [state] True/false state to show/hide.
  24591. * @return {tinymce.ui.Form|Boolean} True/false state or current control.
  24592. */
  24593. visible: function(state) {
  24594. var val = this._super(state);
  24595. if (state === true && this._rendered) {
  24596. this.recalcLabels();
  24597. }
  24598. return val;
  24599. },
  24600. /**
  24601. * Fires a submit event with the serialized form.
  24602. *
  24603. * @method submit
  24604. * @return {Object} Event arguments object.
  24605. */
  24606. submit: function() {
  24607. return this.fire('submit', {data: this.toJSON()});
  24608. },
  24609. /**
  24610. * Post render method. Called after the control has been rendered to the target.
  24611. *
  24612. * @method postRender
  24613. * @return {tinymce.ui.ComboBox} Current combobox instance.
  24614. */
  24615. postRender: function() {
  24616. var self = this;
  24617. self._super();
  24618. self.recalcLabels();
  24619. self.fromJSON(self.settings.data);
  24620. }
  24621. });
  24622. });
  24623. // Included from: js/tinymce/classes/ui/FieldSet.js
  24624. /**
  24625. * FieldSet.js
  24626. *
  24627. * Copyright, Moxiecode Systems AB
  24628. * Released under LGPL License.
  24629. *
  24630. * License: http://www.tinymce.com/license
  24631. * Contributing: http://www.tinymce.com/contributing
  24632. */
  24633. /**
  24634. * This class creates fieldset containers.
  24635. *
  24636. * @-x-less FieldSet.less
  24637. * @class tinymce.ui.FieldSet
  24638. * @extends tinymce.ui.Form
  24639. */
  24640. define("tinymce/ui/FieldSet", [
  24641. "tinymce/ui/Form"
  24642. ], function(Form) {
  24643. "use strict";
  24644. return Form.extend({
  24645. Defaults: {
  24646. containerCls: 'fieldset',
  24647. layout: 'flex',
  24648. direction: 'column',
  24649. align: 'stretch',
  24650. flex: 1,
  24651. padding: "25 15 5 15",
  24652. labelGap: 30,
  24653. spacing: 10,
  24654. border: 1
  24655. },
  24656. /**
  24657. * Renders the control as a HTML string.
  24658. *
  24659. * @method renderHtml
  24660. * @return {String} HTML representing the control.
  24661. */
  24662. renderHtml: function() {
  24663. var self = this, layout = self._layout, prefix = self.classPrefix;
  24664. self.preRender();
  24665. layout.preRender(self);
  24666. return (
  24667. '<fieldset id="' + self._id + '" class="' + self.classes() + '" hidefocus="1" tabindex="-1">' +
  24668. (self.settings.title ? ('<legend id="' + self._id + '-title" class="' + prefix + 'fieldset-title">' +
  24669. self.settings.title + '</legend>') : '') +
  24670. '<div id="' + self._id + '-body" class="' + self.classes('body') + '">' +
  24671. (self.settings.html || '') + layout.renderHtml(self) +
  24672. '</div>' +
  24673. '</fieldset>'
  24674. );
  24675. }
  24676. });
  24677. });
  24678. // Included from: js/tinymce/classes/ui/FilePicker.js
  24679. /**
  24680. * FilePicker.js
  24681. *
  24682. * Copyright, Moxiecode Systems AB
  24683. * Released under LGPL License.
  24684. *
  24685. * License: http://www.tinymce.com/license
  24686. * Contributing: http://www.tinymce.com/contributing
  24687. */
  24688. /*global tinymce:true */
  24689. /**
  24690. * This class creates a file picker control.
  24691. *
  24692. * @class tinymce.ui.FilePicker
  24693. * @extends tinymce.ui.ComboBox
  24694. */
  24695. define("tinymce/ui/FilePicker", [
  24696. "tinymce/ui/ComboBox"
  24697. ], function(ComboBox) {
  24698. "use strict";
  24699. return ComboBox.extend({
  24700. /**
  24701. * Constructs a new control instance with the specified settings.
  24702. *
  24703. * @constructor
  24704. * @param {Object} settings Name/value object with settings.
  24705. */
  24706. init: function(settings) {
  24707. var self = this, editor = tinymce.activeEditor, fileBrowserCallback;
  24708. settings.spellcheck = false;
  24709. fileBrowserCallback = editor.settings.file_browser_callback;
  24710. if (fileBrowserCallback) {
  24711. settings.icon = 'browse';
  24712. settings.onaction = function() {
  24713. fileBrowserCallback(
  24714. self.getEl('inp').id,
  24715. self.getEl('inp').value,
  24716. settings.filetype,
  24717. window
  24718. );
  24719. };
  24720. }
  24721. self._super(settings);
  24722. }
  24723. });
  24724. });
  24725. // Included from: js/tinymce/classes/ui/FitLayout.js
  24726. /**
  24727. * FitLayout.js
  24728. *
  24729. * Copyright, Moxiecode Systems AB
  24730. * Released under LGPL License.
  24731. *
  24732. * License: http://www.tinymce.com/license
  24733. * Contributing: http://www.tinymce.com/contributing
  24734. */
  24735. /**
  24736. * This layout manager will resize the control to be the size of it's parent container.
  24737. * In other words width: 100% and height: 100%.
  24738. *
  24739. * @-x-less FitLayout.less
  24740. * @class tinymce.ui.FitLayout
  24741. * @extends tinymce.ui.AbsoluteLayout
  24742. */
  24743. define("tinymce/ui/FitLayout", [
  24744. "tinymce/ui/AbsoluteLayout"
  24745. ], function(AbsoluteLayout) {
  24746. "use strict";
  24747. return AbsoluteLayout.extend({
  24748. /**
  24749. * Recalculates the positions of the controls in the specified container.
  24750. *
  24751. * @method recalc
  24752. * @param {tinymce.ui.Container} container Container instance to recalc.
  24753. */
  24754. recalc: function(container) {
  24755. var contLayoutRect = container.layoutRect(), paddingBox = container.paddingBox();
  24756. container.items().filter(':visible').each(function(ctrl) {
  24757. ctrl.layoutRect({
  24758. x: paddingBox.left,
  24759. y: paddingBox.top,
  24760. w: contLayoutRect.innerW - paddingBox.right - paddingBox.left,
  24761. h: contLayoutRect.innerH - paddingBox.top - paddingBox.bottom
  24762. });
  24763. if (ctrl.recalc) {
  24764. ctrl.recalc();
  24765. }
  24766. });
  24767. }
  24768. });
  24769. });
  24770. // Included from: js/tinymce/classes/ui/FlexLayout.js
  24771. /**
  24772. * FlexLayout.js
  24773. *
  24774. * Copyright, Moxiecode Systems AB
  24775. * Released under LGPL License.
  24776. *
  24777. * License: http://www.tinymce.com/license
  24778. * Contributing: http://www.tinymce.com/contributing
  24779. */
  24780. /**
  24781. * This layout manager works similar to the CSS flex box.
  24782. *
  24783. * @setting {String} direction row|row-reverse|column|column-reverse
  24784. * @setting {Number} flex A positive-number to flex by.
  24785. * @setting {String} align start|end|center|stretch
  24786. * @setting {String} pack start|end|justify
  24787. *
  24788. * @class tinymce.ui.FlexLayout
  24789. * @extends tinymce.ui.AbsoluteLayout
  24790. */
  24791. define("tinymce/ui/FlexLayout", [
  24792. "tinymce/ui/AbsoluteLayout"
  24793. ], function(AbsoluteLayout) {
  24794. "use strict";
  24795. return AbsoluteLayout.extend({
  24796. /**
  24797. * Recalculates the positions of the controls in the specified container.
  24798. *
  24799. * @method recalc
  24800. * @param {tinymce.ui.Container} container Container instance to recalc.
  24801. */
  24802. recalc: function(container) {
  24803. // A ton of variables, needs to be in the same scope for performance
  24804. var i, l, items, contLayoutRect, contPaddingBox, contSettings, align, pack, spacing, totalFlex, availableSpace, direction;
  24805. var ctrl, ctrlLayoutRect, ctrlSettings, flex, maxSizeItems = [], size, maxSize, ratio, rect, pos, maxAlignEndPos;
  24806. var sizeName, minSizeName, posName, maxSizeName, beforeName, innerSizeName, deltaSizeName, contentSizeName;
  24807. var alignAxisName, alignInnerSizeName, alignSizeName, alignMinSizeName, alignBeforeName, alignAfterName;
  24808. var alignDeltaSizeName, alignContentSizeName;
  24809. var max = Math.max, min = Math.min;
  24810. // Get container items, properties and settings
  24811. items = container.items().filter(':visible');
  24812. contLayoutRect = container.layoutRect();
  24813. contPaddingBox = container._paddingBox;
  24814. contSettings = container.settings;
  24815. direction = container.isRtl() ? (contSettings.direction || 'row-reversed') : contSettings.direction;
  24816. align = contSettings.align;
  24817. pack = container.isRtl() ? (contSettings.pack || 'end') : contSettings.pack;
  24818. spacing = contSettings.spacing || 0;
  24819. if (direction == "row-reversed" || direction == "column-reverse") {
  24820. items = items.set(items.toArray().reverse());
  24821. direction = direction.split('-')[0];
  24822. }
  24823. // Setup axis variable name for row/column direction since the calculations is the same
  24824. if (direction == "column") {
  24825. posName = "y";
  24826. sizeName = "h";
  24827. minSizeName = "minH";
  24828. maxSizeName = "maxH";
  24829. innerSizeName = "innerH";
  24830. beforeName = 'top';
  24831. deltaSizeName = "deltaH";
  24832. contentSizeName = "contentH";
  24833. alignBeforeName = "left";
  24834. alignSizeName = "w";
  24835. alignAxisName = "x";
  24836. alignInnerSizeName = "innerW";
  24837. alignMinSizeName = "minW";
  24838. alignAfterName = "right";
  24839. alignDeltaSizeName = "deltaW";
  24840. alignContentSizeName = "contentW";
  24841. } else {
  24842. posName = "x";
  24843. sizeName = "w";
  24844. minSizeName = "minW";
  24845. maxSizeName = "maxW";
  24846. innerSizeName = "innerW";
  24847. beforeName = 'left';
  24848. deltaSizeName = "deltaW";
  24849. contentSizeName = "contentW";
  24850. alignBeforeName = "top";
  24851. alignSizeName = "h";
  24852. alignAxisName = "y";
  24853. alignInnerSizeName = "innerH";
  24854. alignMinSizeName = "minH";
  24855. alignAfterName = "bottom";
  24856. alignDeltaSizeName = "deltaH";
  24857. alignContentSizeName = "contentH";
  24858. }
  24859. // Figure out total flex, availableSpace and collect any max size elements
  24860. availableSpace = contLayoutRect[innerSizeName] - contPaddingBox[beforeName] - contPaddingBox[beforeName];
  24861. maxAlignEndPos = totalFlex = 0;
  24862. for (i = 0, l = items.length; i < l; i++) {
  24863. ctrl = items[i];
  24864. ctrlLayoutRect = ctrl.layoutRect();
  24865. ctrlSettings = ctrl.settings;
  24866. flex = ctrlSettings.flex;
  24867. availableSpace -= (i < l - 1 ? spacing : 0);
  24868. if (flex > 0) {
  24869. totalFlex += flex;
  24870. // Flexed item has a max size then we need to check if we will hit that size
  24871. if (ctrlLayoutRect[maxSizeName]) {
  24872. maxSizeItems.push(ctrl);
  24873. }
  24874. ctrlLayoutRect.flex = flex;
  24875. }
  24876. availableSpace -= ctrlLayoutRect[minSizeName];
  24877. // Calculate the align end position to be used to check for overflow/underflow
  24878. size = contPaddingBox[alignBeforeName] + ctrlLayoutRect[alignMinSizeName] + contPaddingBox[alignAfterName];
  24879. if (size > maxAlignEndPos) {
  24880. maxAlignEndPos = size;
  24881. }
  24882. }
  24883. // Calculate minW/minH
  24884. rect = {};
  24885. if (availableSpace < 0) {
  24886. rect[minSizeName] = contLayoutRect[minSizeName] - availableSpace + contLayoutRect[deltaSizeName];
  24887. } else {
  24888. rect[minSizeName] = contLayoutRect[innerSizeName] - availableSpace + contLayoutRect[deltaSizeName];
  24889. }
  24890. rect[alignMinSizeName] = maxAlignEndPos + contLayoutRect[alignDeltaSizeName];
  24891. rect[contentSizeName] = contLayoutRect[innerSizeName] - availableSpace;
  24892. rect[alignContentSizeName] = maxAlignEndPos;
  24893. rect.minW = min(rect.minW, contLayoutRect.maxW);
  24894. rect.minH = min(rect.minH, contLayoutRect.maxH);
  24895. rect.minW = max(rect.minW, contLayoutRect.startMinWidth);
  24896. rect.minH = max(rect.minH, contLayoutRect.startMinHeight);
  24897. // Resize container container if minSize was changed
  24898. if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) {
  24899. rect.w = rect.minW;
  24900. rect.h = rect.minH;
  24901. container.layoutRect(rect);
  24902. this.recalc(container);
  24903. // Forced recalc for example if items are hidden/shown
  24904. if (container._lastRect === null) {
  24905. var parentCtrl = container.parent();
  24906. if (parentCtrl) {
  24907. parentCtrl._lastRect = null;
  24908. parentCtrl.recalc();
  24909. }
  24910. }
  24911. return;
  24912. }
  24913. // Handle max size elements, check if they will become to wide with current options
  24914. ratio = availableSpace / totalFlex;
  24915. for (i = 0, l = maxSizeItems.length; i < l; i++) {
  24916. ctrl = maxSizeItems[i];
  24917. ctrlLayoutRect = ctrl.layoutRect();
  24918. maxSize = ctrlLayoutRect[maxSizeName];
  24919. size = ctrlLayoutRect[minSizeName] + ctrlLayoutRect.flex * ratio;
  24920. if (size > maxSize) {
  24921. availableSpace -= (ctrlLayoutRect[maxSizeName] - ctrlLayoutRect[minSizeName]);
  24922. totalFlex -= ctrlLayoutRect.flex;
  24923. ctrlLayoutRect.flex = 0;
  24924. ctrlLayoutRect.maxFlexSize = maxSize;
  24925. } else {
  24926. ctrlLayoutRect.maxFlexSize = 0;
  24927. }
  24928. }
  24929. // Setup new ratio, target layout rect, start position
  24930. ratio = availableSpace / totalFlex;
  24931. pos = contPaddingBox[beforeName];
  24932. rect = {};
  24933. // Handle pack setting moves the start position to end, center
  24934. if (totalFlex === 0) {
  24935. if (pack == "end") {
  24936. pos = availableSpace + contPaddingBox[beforeName];
  24937. } else if (pack == "center") {
  24938. pos = Math.round(
  24939. (contLayoutRect[innerSizeName] / 2) - ((contLayoutRect[innerSizeName] - availableSpace) / 2)
  24940. ) + contPaddingBox[beforeName];
  24941. if (pos < 0) {
  24942. pos = contPaddingBox[beforeName];
  24943. }
  24944. } else if (pack == "justify") {
  24945. pos = contPaddingBox[beforeName];
  24946. spacing = Math.floor(availableSpace / (items.length - 1));
  24947. }
  24948. }
  24949. // Default aligning (start) the other ones needs to be calculated while doing the layout
  24950. rect[alignAxisName] = contPaddingBox[alignBeforeName];
  24951. // Start laying out controls
  24952. for (i = 0, l = items.length; i < l; i++) {
  24953. ctrl = items[i];
  24954. ctrlLayoutRect = ctrl.layoutRect();
  24955. size = ctrlLayoutRect.maxFlexSize || ctrlLayoutRect[minSizeName];
  24956. // Align the control on the other axis
  24957. if (align === "center") {
  24958. rect[alignAxisName] = Math.round((contLayoutRect[alignInnerSizeName] / 2) - (ctrlLayoutRect[alignSizeName] / 2));
  24959. } else if (align === "stretch") {
  24960. rect[alignSizeName] = max(
  24961. ctrlLayoutRect[alignMinSizeName] || 0,
  24962. contLayoutRect[alignInnerSizeName] - contPaddingBox[alignBeforeName] - contPaddingBox[alignAfterName]
  24963. );
  24964. rect[alignAxisName] = contPaddingBox[alignBeforeName];
  24965. } else if (align === "end") {
  24966. rect[alignAxisName] = contLayoutRect[alignInnerSizeName] - ctrlLayoutRect[alignSizeName] - contPaddingBox.top;
  24967. }
  24968. // Calculate new size based on flex
  24969. if (ctrlLayoutRect.flex > 0) {
  24970. size += ctrlLayoutRect.flex * ratio;
  24971. }
  24972. rect[sizeName] = size;
  24973. rect[posName] = pos;
  24974. ctrl.layoutRect(rect);
  24975. // Recalculate containers
  24976. if (ctrl.recalc) {
  24977. ctrl.recalc();
  24978. }
  24979. // Move x/y position
  24980. pos += size + spacing;
  24981. }
  24982. }
  24983. });
  24984. });
  24985. // Included from: js/tinymce/classes/ui/FlowLayout.js
  24986. /**
  24987. * FlowLayout.js
  24988. *
  24989. * Copyright, Moxiecode Systems AB
  24990. * Released under LGPL License.
  24991. *
  24992. * License: http://www.tinymce.com/license
  24993. * Contributing: http://www.tinymce.com/contributing
  24994. */
  24995. /**
  24996. * This layout manager will place the controls by using the browsers native layout.
  24997. *
  24998. * @-x-less FlowLayout.less
  24999. * @class tinymce.ui.FlowLayout
  25000. * @extends tinymce.ui.Layout
  25001. */
  25002. define("tinymce/ui/FlowLayout", [
  25003. "tinymce/ui/Layout"
  25004. ], function(Layout) {
  25005. return Layout.extend({
  25006. Defaults: {
  25007. containerClass: 'flow-layout',
  25008. controlClass: 'flow-layout-item',
  25009. endClass : 'break'
  25010. },
  25011. /**
  25012. * Recalculates the positions of the controls in the specified container.
  25013. *
  25014. * @method recalc
  25015. * @param {tinymce.ui.Container} container Container instance to recalc.
  25016. */
  25017. recalc: function(container) {
  25018. container.items().filter(':visible').each(function(ctrl) {
  25019. if (ctrl.recalc) {
  25020. ctrl.recalc();
  25021. }
  25022. });
  25023. }
  25024. });
  25025. });
  25026. // Included from: js/tinymce/classes/ui/FormatControls.js
  25027. /**
  25028. * FormatControls.js
  25029. *
  25030. * Copyright, Moxiecode Systems AB
  25031. * Released under LGPL License.
  25032. *
  25033. * License: http://www.tinymce.com/license
  25034. * Contributing: http://www.tinymce.com/contributing
  25035. */
  25036. /**
  25037. * Internal class containing all TinyMCE specific control types such as
  25038. * format listboxes, fontlist boxes, toolbar buttons etc.
  25039. *
  25040. * @class tinymce.ui.FormatControls
  25041. */
  25042. define("tinymce/ui/FormatControls", [
  25043. "tinymce/ui/Control",
  25044. "tinymce/ui/Widget",
  25045. "tinymce/ui/FloatPanel",
  25046. "tinymce/util/Tools",
  25047. "tinymce/EditorManager",
  25048. "tinymce/Env"
  25049. ], function(Control, Widget, FloatPanel, Tools, EditorManager, Env) {
  25050. var each = Tools.each;
  25051. EditorManager.on('AddEditor', function(e) {
  25052. if (e.editor.rtl) {
  25053. Control.rtl = true;
  25054. }
  25055. registerControls(e.editor);
  25056. });
  25057. Control.translate = function(text) {
  25058. return EditorManager.translate(text);
  25059. };
  25060. Widget.tooltips = !Env.iOS;
  25061. function registerControls(editor) {
  25062. var formatMenu;
  25063. function createListBoxChangeHandler(items, formatName) {
  25064. return function() {
  25065. var self = this;
  25066. editor.on('nodeChange', function(e) {
  25067. var formatter = editor.formatter;
  25068. var value = null;
  25069. each(e.parents, function(node) {
  25070. each(items, function(item) {
  25071. if (formatName) {
  25072. if (formatter.matchNode(node, formatName, {value: item.value})) {
  25073. value = item.value;
  25074. }
  25075. } else {
  25076. if (formatter.matchNode(node, item.value)) {
  25077. value = item.value;
  25078. }
  25079. }
  25080. if (value) {
  25081. return false;
  25082. }
  25083. });
  25084. if (value) {
  25085. return false;
  25086. }
  25087. });
  25088. self.value(value);
  25089. });
  25090. };
  25091. }
  25092. function createFormats(formats) {
  25093. formats = formats.replace(/;$/, '').split(';');
  25094. var i = formats.length;
  25095. while (i--) {
  25096. formats[i] = formats[i].split('=');
  25097. }
  25098. return formats;
  25099. }
  25100. function createFormatMenu() {
  25101. var count = 0, newFormats = [];
  25102. var defaultStyleFormats = [
  25103. {title: 'Headings', items: [
  25104. {title: 'Heading 1', format: 'h1'},
  25105. {title: 'Heading 2', format: 'h2'},
  25106. {title: 'Heading 3', format: 'h3'},
  25107. {title: 'Heading 4', format: 'h4'},
  25108. {title: 'Heading 5', format: 'h5'},
  25109. {title: 'Heading 6', format: 'h6'}
  25110. ]},
  25111. {title: 'Inline', items: [
  25112. {title: 'Bold', icon: 'bold', format: 'bold'},
  25113. {title: 'Italic', icon: 'italic', format: 'italic'},
  25114. {title: 'Underline', icon: 'underline', format: 'underline'},
  25115. {title: 'Strikethrough', icon: 'strikethrough', format: 'strikethrough'},
  25116. {title: 'Superscript', icon: 'superscript', format: 'superscript'},
  25117. {title: 'Subscript', icon: 'subscript', format: 'subscript'},
  25118. {title: 'Code', icon: 'code', format: 'code'}
  25119. ]},
  25120. {title: 'Blocks', items: [
  25121. {title: 'Paragraph', format: 'p'},
  25122. {title: 'Blockquote', format: 'blockquote'},
  25123. {title: 'Div', format: 'div'},
  25124. {title: 'Pre', format: 'pre'}
  25125. ]},
  25126. {title: 'Alignment', items: [
  25127. {title: 'Left', icon: 'alignleft', format: 'alignleft'},
  25128. {title: 'Center', icon: 'aligncenter', format: 'aligncenter'},
  25129. {title: 'Right', icon: 'alignright', format: 'alignright'},
  25130. {title: 'Justify', icon: 'alignjustify', format: 'alignjustify'}
  25131. ]}
  25132. ];
  25133. function createMenu(formats) {
  25134. var menu = [];
  25135. if (!formats) {
  25136. return;
  25137. }
  25138. each(formats, function(format) {
  25139. var menuItem = {
  25140. text: format.title,
  25141. icon: format.icon
  25142. };
  25143. if (format.items) {
  25144. menuItem.menu = createMenu(format.items);
  25145. } else {
  25146. var formatName = format.format || "custom" + count++;
  25147. if (!format.format) {
  25148. format.name = formatName;
  25149. newFormats.push(format);
  25150. }
  25151. menuItem.format = formatName;
  25152. }
  25153. menu.push(menuItem);
  25154. });
  25155. return menu;
  25156. }
  25157. function createStylesMenu() {
  25158. var menu;
  25159. if (editor.settings.style_formats_merge) {
  25160. if (editor.settings.style_formats) {
  25161. menu = createMenu(defaultStyleFormats.concat(editor.settings.style_formats));
  25162. } else {
  25163. menu = createMenu(defaultStyleFormats);
  25164. }
  25165. } else {
  25166. menu = createMenu(editor.settings.style_formats || defaultStyleFormats);
  25167. }
  25168. return menu;
  25169. }
  25170. editor.on('init', function() {
  25171. each(newFormats, function(format) {
  25172. editor.formatter.register(format.name, format);
  25173. });
  25174. });
  25175. return {
  25176. type: 'menu',
  25177. items: createStylesMenu(),
  25178. onPostRender: function(e) {
  25179. editor.fire('renderFormatsMenu', {control: e.control});
  25180. },
  25181. itemDefaults: {
  25182. preview: true,
  25183. textStyle: function() {
  25184. if (this.settings.format) {
  25185. return editor.formatter.getCssText(this.settings.format);
  25186. }
  25187. },
  25188. onPostRender: function() {
  25189. var self = this, formatName = this.settings.format;
  25190. if (formatName) {
  25191. self.parent().on('show', function() {
  25192. self.disabled(!editor.formatter.canApply(formatName));
  25193. self.active(editor.formatter.match(formatName));
  25194. });
  25195. }
  25196. },
  25197. onclick: function() {
  25198. if (this.settings.format) {
  25199. toggleFormat(this.settings.format);
  25200. }
  25201. }
  25202. }
  25203. };
  25204. }
  25205. formatMenu = createFormatMenu();
  25206. // Simple format controls <control/format>:<UI text>
  25207. each({
  25208. bold: 'Bold',
  25209. italic: 'Italic',
  25210. underline: 'Underline',
  25211. strikethrough: 'Strikethrough',
  25212. subscript: 'Subscript',
  25213. superscript: 'Superscript'
  25214. }, function(text, name) {
  25215. editor.addButton(name, {
  25216. tooltip: text,
  25217. onPostRender: function() {
  25218. var self = this;
  25219. // TODO: Fix this
  25220. if (editor.formatter) {
  25221. editor.formatter.formatChanged(name, function(state) {
  25222. self.active(state);
  25223. });
  25224. } else {
  25225. editor.on('init', function() {
  25226. editor.formatter.formatChanged(name, function(state) {
  25227. self.active(state);
  25228. });
  25229. });
  25230. }
  25231. },
  25232. onclick: function() {
  25233. toggleFormat(name);
  25234. }
  25235. });
  25236. });
  25237. // Simple command controls <control>:[<UI text>,<Command>]
  25238. each({
  25239. outdent: ['Decrease indent', 'Outdent'],
  25240. indent: ['Increase indent', 'Indent'],
  25241. cut: ['Cut', 'Cut'],
  25242. copy: ['Copy', 'Copy'],
  25243. paste: ['Paste', 'Paste'],
  25244. help: ['Help', 'mceHelp'],
  25245. selectall: ['Select all', 'SelectAll'],
  25246. hr: ['Insert horizontal rule', 'InsertHorizontalRule'],
  25247. removeformat: ['Clear formatting', 'RemoveFormat'],
  25248. visualaid: ['Visual aids', 'mceToggleVisualAid'],
  25249. newdocument: ['New document', 'mceNewDocument']
  25250. }, function(item, name) {
  25251. editor.addButton(name, {
  25252. tooltip: item[0],
  25253. cmd: item[1]
  25254. });
  25255. });
  25256. // Simple command controls with format state
  25257. each({
  25258. blockquote: ['Blockquote', 'mceBlockQuote'],
  25259. numlist: ['Numbered list', 'InsertOrderedList'],
  25260. bullist: ['Bullet list', 'InsertUnorderedList'],
  25261. subscript: ['Subscript', 'Subscript'],
  25262. superscript: ['Superscript', 'Superscript'],
  25263. alignleft: ['Align left', 'JustifyLeft'],
  25264. aligncenter: ['Align center', 'JustifyCenter'],
  25265. alignright: ['Align right', 'JustifyRight'],
  25266. alignjustify: ['Justify', 'JustifyFull']
  25267. }, function(item, name) {
  25268. editor.addButton(name, {
  25269. tooltip: item[0],
  25270. cmd: item[1],
  25271. onPostRender: function() {
  25272. var self = this;
  25273. // TODO: Fix this
  25274. if (editor.formatter) {
  25275. editor.formatter.formatChanged(name, function(state) {
  25276. self.active(state);
  25277. });
  25278. } else {
  25279. editor.on('init', function() {
  25280. editor.formatter.formatChanged(name, function(state) {
  25281. self.active(state);
  25282. });
  25283. });
  25284. }
  25285. }
  25286. });
  25287. });
  25288. function hasUndo() {
  25289. return editor.undoManager ? editor.undoManager.hasUndo() : false;
  25290. }
  25291. function hasRedo() {
  25292. return editor.undoManager ? editor.undoManager.hasRedo() : false;
  25293. }
  25294. function toggleUndoState() {
  25295. var self = this;
  25296. self.disabled(!hasUndo());
  25297. editor.on('Undo Redo AddUndo TypingUndo', function() {
  25298. self.disabled(!hasUndo());
  25299. });
  25300. }
  25301. function toggleRedoState() {
  25302. var self = this;
  25303. self.disabled(!hasRedo());
  25304. editor.on('Undo Redo AddUndo TypingUndo', function() {
  25305. self.disabled(!hasRedo());
  25306. });
  25307. }
  25308. function toggleVisualAidState() {
  25309. var self = this;
  25310. editor.on('VisualAid', function(e) {
  25311. self.active(e.hasVisual);
  25312. });
  25313. self.active(editor.hasVisual);
  25314. }
  25315. editor.addButton('undo', {
  25316. tooltip: 'Undo',
  25317. onPostRender: toggleUndoState,
  25318. cmd: 'undo'
  25319. });
  25320. editor.addButton('redo', {
  25321. tooltip: 'Redo',
  25322. onPostRender: toggleRedoState,
  25323. cmd: 'redo'
  25324. });
  25325. editor.addMenuItem('newdocument', {
  25326. text: 'New document',
  25327. shortcut: 'Ctrl+N',
  25328. icon: 'newdocument',
  25329. cmd: 'mceNewDocument'
  25330. });
  25331. editor.addMenuItem('undo', {
  25332. text: 'Undo',
  25333. icon: 'undo',
  25334. shortcut: 'Ctrl+Z',
  25335. onPostRender: toggleUndoState,
  25336. cmd: 'undo'
  25337. });
  25338. editor.addMenuItem('redo', {
  25339. text: 'Redo',
  25340. icon: 'redo',
  25341. shortcut: 'Ctrl+Y',
  25342. onPostRender: toggleRedoState,
  25343. cmd: 'redo'
  25344. });
  25345. editor.addMenuItem('visualaid', {
  25346. text: 'Visual aids',
  25347. selectable: true,
  25348. onPostRender: toggleVisualAidState,
  25349. cmd: 'mceToggleVisualAid'
  25350. });
  25351. each({
  25352. cut: ['Cut', 'Cut', 'Ctrl+X'],
  25353. copy: ['Copy', 'Copy', 'Ctrl+C'],
  25354. paste: ['Paste', 'Paste', 'Ctrl+V'],
  25355. selectall: ['Select all', 'SelectAll', 'Ctrl+A'],
  25356. bold: ['Bold', 'Bold', 'Ctrl+B'],
  25357. italic: ['Italic', 'Italic', 'Ctrl+I'],
  25358. underline: ['Underline', 'Underline'],
  25359. strikethrough: ['Strikethrough', 'Strikethrough'],
  25360. subscript: ['Subscript', 'Subscript'],
  25361. superscript: ['Superscript', 'Superscript'],
  25362. removeformat: ['Clear formatting', 'RemoveFormat']
  25363. }, function(item, name) {
  25364. editor.addMenuItem(name, {
  25365. text: item[0],
  25366. icon: name,
  25367. shortcut: item[2],
  25368. cmd: item[1]
  25369. });
  25370. });
  25371. editor.on('mousedown', function() {
  25372. FloatPanel.hideAll();
  25373. });
  25374. function toggleFormat(fmt) {
  25375. if (fmt.control) {
  25376. fmt = fmt.control.value();
  25377. }
  25378. if (fmt) {
  25379. editor.execCommand('mceToggleFormat', false, fmt);
  25380. }
  25381. }
  25382. editor.addButton('styleselect', {
  25383. type: 'menubutton',
  25384. text: 'Formats',
  25385. menu: formatMenu
  25386. });
  25387. editor.addButton('formatselect', function() {
  25388. var items = [], blocks = createFormats(editor.settings.block_formats ||
  25389. 'Paragraph=p;' +
  25390. 'Address=address;' +
  25391. 'Pre=pre;' +
  25392. 'Heading 1=h1;' +
  25393. 'Heading 2=h2;' +
  25394. 'Heading 3=h3;' +
  25395. 'Heading 4=h4;' +
  25396. 'Heading 5=h5;' +
  25397. 'Heading 6=h6'
  25398. );
  25399. each(blocks, function(block) {
  25400. items.push({
  25401. text: block[0],
  25402. value: block[1],
  25403. textStyle: function() {
  25404. return editor.formatter.getCssText(block[1]);
  25405. }
  25406. });
  25407. });
  25408. return {
  25409. type: 'listbox',
  25410. text: blocks[0][0],
  25411. values: items,
  25412. fixedWidth: true,
  25413. onselect: toggleFormat,
  25414. onPostRender: createListBoxChangeHandler(items)
  25415. };
  25416. });
  25417. editor.addButton('fontselect', function() {
  25418. var defaultFontsFormats =
  25419. 'Andale Mono=andale mono,times;' +
  25420. 'Arial=arial,helvetica,sans-serif;' +
  25421. 'Arial Black=arial black,avant garde;' +
  25422. 'Book Antiqua=book antiqua,palatino;' +
  25423. 'Comic Sans MS=comic sans ms,sans-serif;' +
  25424. 'Courier New=courier new,courier;' +
  25425. 'Georgia=georgia,palatino;' +
  25426. 'Helvetica=helvetica;' +
  25427. 'Impact=impact,chicago;' +
  25428. 'Symbol=symbol;' +
  25429. 'Tahoma=tahoma,arial,helvetica,sans-serif;' +
  25430. 'Terminal=terminal,monaco;' +
  25431. 'Times New Roman=times new roman,times;' +
  25432. 'Trebuchet MS=trebuchet ms,geneva;' +
  25433. 'Verdana=verdana,geneva;' +
  25434. 'Webdings=webdings;' +
  25435. 'Wingdings=wingdings,zapf dingbats';
  25436. var items = [], fonts = createFormats(editor.settings.font_formats || defaultFontsFormats);
  25437. each(fonts, function(font) {
  25438. items.push({
  25439. text: {raw: font[0]},
  25440. value: font[1],
  25441. textStyle: font[1].indexOf('dings') == -1 ? 'font-family:' + font[1] : ''
  25442. });
  25443. });
  25444. return {
  25445. type: 'listbox',
  25446. text: 'Font Family',
  25447. tooltip: 'Font Family',
  25448. values: items,
  25449. fixedWidth: true,
  25450. onPostRender: createListBoxChangeHandler(items, 'fontname'),
  25451. onselect: function(e) {
  25452. if (e.control.settings.value) {
  25453. editor.execCommand('FontName', false, e.control.settings.value);
  25454. }
  25455. }
  25456. };
  25457. });
  25458. editor.addButton('fontsizeselect', function() {
  25459. var items = [], defaultFontsizeFormats = '8pt 10pt 12pt 14pt 18pt 24pt 36pt';
  25460. var fontsize_formats = editor.settings.fontsize_formats || defaultFontsizeFormats;
  25461. each(fontsize_formats.split(' '), function(item) {
  25462. items.push({text: item, value: item});
  25463. });
  25464. return {
  25465. type: 'listbox',
  25466. text: 'Font Sizes',
  25467. tooltip: 'Font Sizes',
  25468. values: items,
  25469. fixedWidth: true,
  25470. onPostRender: createListBoxChangeHandler(items, 'fontsize'),
  25471. onclick: function(e) {
  25472. if (e.control.settings.value) {
  25473. editor.execCommand('FontSize', false, e.control.settings.value);
  25474. }
  25475. }
  25476. };
  25477. });
  25478. editor.addMenuItem('formats', {
  25479. text: 'Formats',
  25480. menu: formatMenu
  25481. });
  25482. }
  25483. });
  25484. // Included from: js/tinymce/classes/ui/GridLayout.js
  25485. /**
  25486. * GridLayout.js
  25487. *
  25488. * Copyright, Moxiecode Systems AB
  25489. * Released under LGPL License.
  25490. *
  25491. * License: http://www.tinymce.com/license
  25492. * Contributing: http://www.tinymce.com/contributing
  25493. */
  25494. /**
  25495. * This layout manager places controls in a grid.
  25496. *
  25497. * @setting {Number} spacing Spacing between controls.
  25498. * @setting {Number} spacingH Horizontal spacing between controls.
  25499. * @setting {Number} spacingV Vertical spacing between controls.
  25500. * @setting {Number} columns Number of columns to use.
  25501. * @setting {String/Array} alignH start|end|center|stretch or array of values for each column.
  25502. * @setting {String/Array} alignV start|end|center|stretch or array of values for each column.
  25503. * @setting {String} pack start|end
  25504. *
  25505. * @class tinymce.ui.GridLayout
  25506. * @extends tinymce.ui.AbsoluteLayout
  25507. */
  25508. define("tinymce/ui/GridLayout", [
  25509. "tinymce/ui/AbsoluteLayout"
  25510. ], function(AbsoluteLayout) {
  25511. "use strict";
  25512. return AbsoluteLayout.extend({
  25513. /**
  25514. * Recalculates the positions of the controls in the specified container.
  25515. *
  25516. * @method recalc
  25517. * @param {tinymce.ui.Container} container Container instance to recalc.
  25518. */
  25519. recalc: function(container) {
  25520. var settings = container.settings, rows, cols, items, contLayoutRect, width, height, rect,
  25521. ctrlLayoutRect, ctrl, x, y, posX, posY, ctrlSettings, contPaddingBox, align, spacingH, spacingV, alignH, alignV, maxX, maxY,
  25522. colWidths = [], rowHeights = [], ctrlMinWidth, ctrlMinHeight, availableWidth, availableHeight;
  25523. // Get layout settings
  25524. settings = container.settings;
  25525. items = container.items().filter(':visible');
  25526. contLayoutRect = container.layoutRect();
  25527. cols = settings.columns || Math.ceil(Math.sqrt(items.length));
  25528. rows = Math.ceil(items.length / cols);
  25529. spacingH = settings.spacingH || settings.spacing || 0;
  25530. spacingV = settings.spacingV || settings.spacing || 0;
  25531. alignH = settings.alignH || settings.align;
  25532. alignV = settings.alignV || settings.align;
  25533. contPaddingBox = container._paddingBox;
  25534. if (alignH && typeof(alignH) == "string") {
  25535. alignH = [alignH];
  25536. }
  25537. if (alignV && typeof(alignV) == "string") {
  25538. alignV = [alignV];
  25539. }
  25540. // Zero padd columnWidths
  25541. for (x = 0; x < cols; x++) {
  25542. colWidths.push(0);
  25543. }
  25544. // Zero padd rowHeights
  25545. for (y = 0; y < rows; y++) {
  25546. rowHeights.push(0);
  25547. }
  25548. // Calculate columnWidths and rowHeights
  25549. for (y = 0; y < rows; y++) {
  25550. for (x = 0; x < cols; x++) {
  25551. ctrl = items[y * cols + x];
  25552. // Out of bounds
  25553. if (!ctrl) {
  25554. break;
  25555. }
  25556. ctrlLayoutRect = ctrl.layoutRect();
  25557. ctrlMinWidth = ctrlLayoutRect.minW;
  25558. ctrlMinHeight = ctrlLayoutRect.minH;
  25559. colWidths[x] = ctrlMinWidth > colWidths[x] ? ctrlMinWidth : colWidths[x];
  25560. rowHeights[y] = ctrlMinHeight > rowHeights[y] ? ctrlMinHeight : rowHeights[y];
  25561. }
  25562. }
  25563. // Calculate maxX
  25564. availableWidth = contLayoutRect.innerW - contPaddingBox.left - contPaddingBox.right;
  25565. for (maxX = 0, x = 0; x < cols; x++) {
  25566. maxX += colWidths[x] + (x > 0 ? spacingH : 0);
  25567. availableWidth -= (x > 0 ? spacingH : 0) + colWidths[x];
  25568. }
  25569. // Calculate maxY
  25570. availableHeight = contLayoutRect.innerH - contPaddingBox.top - contPaddingBox.bottom;
  25571. for (maxY = 0, y = 0; y < rows; y++) {
  25572. maxY += rowHeights[y] + (y > 0 ? spacingV : 0);
  25573. availableHeight -= (y > 0 ? spacingV : 0) + rowHeights[y];
  25574. }
  25575. maxX += contPaddingBox.left + contPaddingBox.right;
  25576. maxY += contPaddingBox.top + contPaddingBox.bottom;
  25577. // Calculate minW/minH
  25578. rect = {};
  25579. rect.minW = maxX + (contLayoutRect.w - contLayoutRect.innerW);
  25580. rect.minH = maxY + (contLayoutRect.h - contLayoutRect.innerH);
  25581. rect.contentW = rect.minW - contLayoutRect.deltaW;
  25582. rect.contentH = rect.minH - contLayoutRect.deltaH;
  25583. rect.minW = Math.min(rect.minW, contLayoutRect.maxW);
  25584. rect.minH = Math.min(rect.minH, contLayoutRect.maxH);
  25585. rect.minW = Math.max(rect.minW, contLayoutRect.startMinWidth);
  25586. rect.minH = Math.max(rect.minH, contLayoutRect.startMinHeight);
  25587. // Resize container container if minSize was changed
  25588. if (contLayoutRect.autoResize && (rect.minW != contLayoutRect.minW || rect.minH != contLayoutRect.minH)) {
  25589. rect.w = rect.minW;
  25590. rect.h = rect.minH;
  25591. container.layoutRect(rect);
  25592. this.recalc(container);
  25593. // Forced recalc for example if items are hidden/shown
  25594. if (container._lastRect === null) {
  25595. var parentCtrl = container.parent();
  25596. if (parentCtrl) {
  25597. parentCtrl._lastRect = null;
  25598. parentCtrl.recalc();
  25599. }
  25600. }
  25601. return;
  25602. }
  25603. // Update contentW/contentH so absEnd moves correctly
  25604. if (contLayoutRect.autoResize) {
  25605. rect = container.layoutRect(rect);
  25606. rect.contentW = rect.minW - contLayoutRect.deltaW;
  25607. rect.contentH = rect.minH - contLayoutRect.deltaH;
  25608. }
  25609. var flexV;
  25610. if (settings.packV == 'start') {
  25611. flexV = 0;
  25612. } else {
  25613. flexV = availableHeight > 0 ? Math.floor(availableHeight / rows) : 0;
  25614. }
  25615. // Calculate totalFlex
  25616. var totalFlex = 0;
  25617. var flexWidths = settings.flexWidths;
  25618. if (flexWidths) {
  25619. for (x = 0; x < flexWidths.length; x++) {
  25620. totalFlex += flexWidths[x];
  25621. }
  25622. } else {
  25623. totalFlex = cols;
  25624. }
  25625. // Calculate new column widths based on flex values
  25626. var ratio = availableWidth / totalFlex;
  25627. for (x = 0; x < cols; x++) {
  25628. colWidths[x] += flexWidths ? flexWidths[x] * ratio : ratio;
  25629. }
  25630. // Move/resize controls
  25631. posY = contPaddingBox.top;
  25632. for (y = 0; y < rows; y++) {
  25633. posX = contPaddingBox.left;
  25634. height = rowHeights[y] + flexV;
  25635. for (x = 0; x < cols; x++) {
  25636. ctrl = items[y * cols + x];
  25637. // No more controls to render then break
  25638. if (!ctrl) {
  25639. break;
  25640. }
  25641. // Get control settings and calculate x, y
  25642. ctrlSettings = ctrl.settings;
  25643. ctrlLayoutRect = ctrl.layoutRect();
  25644. width = Math.max(colWidths[x], ctrlLayoutRect.startMinWidth);
  25645. ctrlLayoutRect.x = posX;
  25646. ctrlLayoutRect.y = posY;
  25647. // Align control horizontal
  25648. align = ctrlSettings.alignH || (alignH ? (alignH[x] || alignH[0]) : null);
  25649. if (align == "center") {
  25650. ctrlLayoutRect.x = posX + (width / 2) - (ctrlLayoutRect.w / 2);
  25651. } else if (align == "right") {
  25652. ctrlLayoutRect.x = posX + width - ctrlLayoutRect.w;
  25653. } else if (align == "stretch") {
  25654. ctrlLayoutRect.w = width;
  25655. }
  25656. // Align control vertical
  25657. align = ctrlSettings.alignV || (alignV ? (alignV[x] || alignV[0]) : null);
  25658. if (align == "center") {
  25659. ctrlLayoutRect.y = posY + (height / 2) - (ctrlLayoutRect.h / 2);
  25660. } else if (align == "bottom") {
  25661. ctrlLayoutRect.y = posY + height - ctrlLayoutRect.h;
  25662. } else if (align == "stretch") {
  25663. ctrlLayoutRect.h = height;
  25664. }
  25665. ctrl.layoutRect(ctrlLayoutRect);
  25666. posX += width + spacingH;
  25667. if (ctrl.recalc) {
  25668. ctrl.recalc();
  25669. }
  25670. }
  25671. posY += height + spacingV;
  25672. }
  25673. }
  25674. });
  25675. });
  25676. // Included from: js/tinymce/classes/ui/Iframe.js
  25677. /**
  25678. * Iframe.js
  25679. *
  25680. * Copyright, Moxiecode Systems AB
  25681. * Released under LGPL License.
  25682. *
  25683. * License: http://www.tinymce.com/license
  25684. * Contributing: http://www.tinymce.com/contributing
  25685. */
  25686. /*jshint scripturl:true */
  25687. /**
  25688. * This class creates an iframe.
  25689. *
  25690. * @setting {String} url Url to open in the iframe.
  25691. *
  25692. * @-x-less Iframe.less
  25693. * @class tinymce.ui.Iframe
  25694. * @extends tinymce.ui.Widget
  25695. */
  25696. define("tinymce/ui/Iframe", [
  25697. "tinymce/ui/Widget"
  25698. ], function(Widget) {
  25699. "use strict";
  25700. return Widget.extend({
  25701. /**
  25702. * Renders the control as a HTML string.
  25703. *
  25704. * @method renderHtml
  25705. * @return {String} HTML representing the control.
  25706. */
  25707. renderHtml: function() {
  25708. var self = this;
  25709. self.addClass('iframe');
  25710. self.canFocus = false;
  25711. /*eslint no-script-url:0 */
  25712. return (
  25713. '<iframe id="' + self._id + '" class="' + self.classes() + '" tabindex="-1" src="' +
  25714. (self.settings.url || "javascript:\'\'") + '" frameborder="0"></iframe>'
  25715. );
  25716. },
  25717. /**
  25718. * Setter for the iframe source.
  25719. *
  25720. * @method src
  25721. * @param {String} src Source URL for iframe.
  25722. */
  25723. src: function(src) {
  25724. this.getEl().src = src;
  25725. },
  25726. /**
  25727. * Inner HTML for the iframe.
  25728. *
  25729. * @method html
  25730. * @param {String} html HTML string to set as HTML inside the iframe.
  25731. * @param {function} callback Optional callback to execute when the iframe body is filled with contents.
  25732. * @return {tinymce.ui.Iframe} Current iframe control.
  25733. */
  25734. html: function(html, callback) {
  25735. var self = this, body = this.getEl().contentWindow.document.body;
  25736. // Wait for iframe to initialize IE 10 takes time
  25737. if (!body) {
  25738. setTimeout(function() {
  25739. self.html(html);
  25740. }, 0);
  25741. } else {
  25742. body.innerHTML = html;
  25743. if (callback) {
  25744. callback();
  25745. }
  25746. }
  25747. return this;
  25748. }
  25749. });
  25750. });
  25751. // Included from: js/tinymce/classes/ui/Label.js
  25752. /**
  25753. * Label.js
  25754. *
  25755. * Copyright, Moxiecode Systems AB
  25756. * Released under LGPL License.
  25757. *
  25758. * License: http://www.tinymce.com/license
  25759. * Contributing: http://www.tinymce.com/contributing
  25760. */
  25761. /**
  25762. * This class creates a label element. A label is a simple text control
  25763. * that can be bound to other controls.
  25764. *
  25765. * @-x-less Label.less
  25766. * @class tinymce.ui.Label
  25767. * @extends tinymce.ui.Widget
  25768. */
  25769. define("tinymce/ui/Label", [
  25770. "tinymce/ui/Widget",
  25771. "tinymce/ui/DomUtils"
  25772. ], function(Widget, DomUtils) {
  25773. "use strict";
  25774. return Widget.extend({
  25775. /**
  25776. * Constructs a instance with the specified settings.
  25777. *
  25778. * @constructor
  25779. * @param {Object} settings Name/value object with settings.
  25780. * @param {Boolean} multiline Multiline label.
  25781. */
  25782. init: function(settings) {
  25783. var self = this;
  25784. self._super(settings);
  25785. self.addClass('widget');
  25786. self.addClass('label');
  25787. self.canFocus = false;
  25788. if (settings.multiline) {
  25789. self.addClass('autoscroll');
  25790. }
  25791. if (settings.strong) {
  25792. self.addClass('strong');
  25793. }
  25794. },
  25795. /**
  25796. * Initializes the current controls layout rect.
  25797. * This will be executed by the layout managers to determine the
  25798. * default minWidth/minHeight etc.
  25799. *
  25800. * @method initLayoutRect
  25801. * @return {Object} Layout rect instance.
  25802. */
  25803. initLayoutRect: function() {
  25804. var self = this, layoutRect = self._super();
  25805. if (self.settings.multiline) {
  25806. var size = DomUtils.getSize(self.getEl());
  25807. // Check if the text fits within maxW if not then try word wrapping it
  25808. if (size.width > layoutRect.maxW) {
  25809. layoutRect.minW = layoutRect.maxW;
  25810. self.addClass('multiline');
  25811. }
  25812. self.getEl().style.width = layoutRect.minW + 'px';
  25813. layoutRect.startMinH = layoutRect.h = layoutRect.minH = Math.min(layoutRect.maxH, DomUtils.getSize(self.getEl()).height);
  25814. }
  25815. return layoutRect;
  25816. },
  25817. /**
  25818. * Repaints the control after a layout operation.
  25819. *
  25820. * @method repaint
  25821. */
  25822. repaint: function() {
  25823. var self = this;
  25824. if (!self.settings.multiline) {
  25825. self.getEl().style.lineHeight = self.layoutRect().h + 'px';
  25826. }
  25827. return self._super();
  25828. },
  25829. /**
  25830. * Sets/gets the current label text.
  25831. *
  25832. * @method text
  25833. * @param {String} [text] New label text.
  25834. * @return {String|tinymce.ui.Label} Current text or current label instance.
  25835. */
  25836. text: function(text) {
  25837. var self = this;
  25838. if (self._rendered && text) {
  25839. this.innerHtml(self.encode(text));
  25840. }
  25841. return self._super(text);
  25842. },
  25843. /**
  25844. * Renders the control as a HTML string.
  25845. *
  25846. * @method renderHtml
  25847. * @return {String} HTML representing the control.
  25848. */
  25849. renderHtml: function() {
  25850. var self = this, forId = self.settings.forId;
  25851. return (
  25852. '<label id="' + self._id + '" class="' + self.classes() + '"' + (forId ? ' for="' + forId + '"' : '') + '>' +
  25853. self.encode(self._text) +
  25854. '</label>'
  25855. );
  25856. }
  25857. });
  25858. });
  25859. // Included from: js/tinymce/classes/ui/Toolbar.js
  25860. /**
  25861. * Toolbar.js
  25862. *
  25863. * Copyright, Moxiecode Systems AB
  25864. * Released under LGPL License.
  25865. *
  25866. * License: http://www.tinymce.com/license
  25867. * Contributing: http://www.tinymce.com/contributing
  25868. */
  25869. /**
  25870. * Creates a new toolbar.
  25871. *
  25872. * @class tinymce.ui.Toolbar
  25873. * @extends tinymce.ui.Container
  25874. */
  25875. define("tinymce/ui/Toolbar", [
  25876. "tinymce/ui/Container"
  25877. ], function(Container) {
  25878. "use strict";
  25879. return Container.extend({
  25880. Defaults: {
  25881. role: 'toolbar',
  25882. layout: 'flow'
  25883. },
  25884. /**
  25885. * Constructs a instance with the specified settings.
  25886. *
  25887. * @constructor
  25888. * @param {Object} settings Name/value object with settings.
  25889. */
  25890. init: function(settings) {
  25891. var self = this;
  25892. self._super(settings);
  25893. self.addClass('toolbar');
  25894. },
  25895. /**
  25896. * Called after the control has been rendered.
  25897. *
  25898. * @method postRender
  25899. */
  25900. postRender: function() {
  25901. var self = this;
  25902. self.items().addClass('toolbar-item');
  25903. return self._super();
  25904. }
  25905. });
  25906. });
  25907. // Included from: js/tinymce/classes/ui/MenuBar.js
  25908. /**
  25909. * MenuBar.js
  25910. *
  25911. * Copyright, Moxiecode Systems AB
  25912. * Released under LGPL License.
  25913. *
  25914. * License: http://www.tinymce.com/license
  25915. * Contributing: http://www.tinymce.com/contributing
  25916. */
  25917. /**
  25918. * Creates a new menubar.
  25919. *
  25920. * @-x-less MenuBar.less
  25921. * @class tinymce.ui.MenuBar
  25922. * @extends tinymce.ui.Container
  25923. */
  25924. define("tinymce/ui/MenuBar", [
  25925. "tinymce/ui/Toolbar"
  25926. ], function(Toolbar) {
  25927. "use strict";
  25928. return Toolbar.extend({
  25929. Defaults: {
  25930. role: 'menubar',
  25931. containerCls: 'menubar',
  25932. ariaRoot: true,
  25933. defaults: {
  25934. type: 'menubutton'
  25935. }
  25936. }
  25937. });
  25938. });
  25939. // Included from: js/tinymce/classes/ui/MenuButton.js
  25940. /**
  25941. * MenuButton.js
  25942. *
  25943. * Copyright, Moxiecode Systems AB
  25944. * Released under LGPL License.
  25945. *
  25946. * License: http://www.tinymce.com/license
  25947. * Contributing: http://www.tinymce.com/contributing
  25948. */
  25949. /**
  25950. * Creates a new menu button.
  25951. *
  25952. * @-x-less MenuButton.less
  25953. * @class tinymce.ui.MenuButton
  25954. * @extends tinymce.ui.Button
  25955. */
  25956. define("tinymce/ui/MenuButton", [
  25957. "tinymce/ui/Button",
  25958. "tinymce/ui/Factory",
  25959. "tinymce/ui/MenuBar"
  25960. ], function(Button, Factory, MenuBar) {
  25961. "use strict";
  25962. // TODO: Maybe add as some global function
  25963. function isChildOf(node, parent) {
  25964. while (node) {
  25965. if (parent === node) {
  25966. return true;
  25967. }
  25968. node = node.parentNode;
  25969. }
  25970. return false;
  25971. }
  25972. var MenuButton = Button.extend({
  25973. /**
  25974. * Constructs a instance with the specified settings.
  25975. *
  25976. * @constructor
  25977. * @param {Object} settings Name/value object with settings.
  25978. */
  25979. init: function(settings) {
  25980. var self = this;
  25981. self._renderOpen = true;
  25982. self._super(settings);
  25983. self.addClass('menubtn');
  25984. if (settings.fixedWidth) {
  25985. self.addClass('fixed-width');
  25986. }
  25987. self.aria('haspopup', true);
  25988. self.hasPopup = true;
  25989. },
  25990. /**
  25991. * Shows the menu for the button.
  25992. *
  25993. * @method showMenu
  25994. */
  25995. showMenu: function() {
  25996. var self = this, settings = self.settings, menu;
  25997. if (self.menu && self.menu.visible()) {
  25998. return self.hideMenu();
  25999. }
  26000. if (!self.menu) {
  26001. menu = settings.menu || [];
  26002. // Is menu array then auto constuct menu control
  26003. if (menu.length) {
  26004. menu = {
  26005. type: 'menu',
  26006. items: menu
  26007. };
  26008. } else {
  26009. menu.type = menu.type || 'menu';
  26010. }
  26011. self.menu = Factory.create(menu).parent(self).renderTo();
  26012. self.fire('createmenu');
  26013. self.menu.reflow();
  26014. self.menu.on('cancel', function(e) {
  26015. if (e.control.parent() === self.menu) {
  26016. e.stopPropagation();
  26017. self.focus();
  26018. self.hideMenu();
  26019. }
  26020. });
  26021. // Move focus to button when a menu item is selected/clicked
  26022. self.menu.on('select', function() {
  26023. self.focus();
  26024. });
  26025. self.menu.on('show hide', function(e) {
  26026. if (e.control == self.menu) {
  26027. self.activeMenu(e.type == 'show');
  26028. }
  26029. self.aria('expanded', e.type == 'show');
  26030. }).fire('show');
  26031. }
  26032. self.menu.show();
  26033. self.menu.layoutRect({w: self.layoutRect().w});
  26034. self.menu.moveRel(self.getEl(), self.isRtl() ? ['br-tr', 'tr-br'] : ['bl-tl', 'tl-bl']);
  26035. },
  26036. /**
  26037. * Hides the menu for the button.
  26038. *
  26039. * @method hideMenu
  26040. */
  26041. hideMenu: function() {
  26042. var self = this;
  26043. if (self.menu) {
  26044. self.menu.items().each(function(item) {
  26045. if (item.hideMenu) {
  26046. item.hideMenu();
  26047. }
  26048. });
  26049. self.menu.hide();
  26050. }
  26051. },
  26052. /**
  26053. * Sets the active menu state.
  26054. *
  26055. * @private
  26056. */
  26057. activeMenu: function(state) {
  26058. this.toggleClass('active', state);
  26059. },
  26060. /**
  26061. * Renders the control as a HTML string.
  26062. *
  26063. * @method renderHtml
  26064. * @return {String} HTML representing the control.
  26065. */
  26066. renderHtml: function() {
  26067. var self = this, id = self._id, prefix = self.classPrefix;
  26068. var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : '';
  26069. self.aria('role', self.parent() instanceof MenuBar ? 'menuitem' : 'button');
  26070. return (
  26071. '<div id="' + id + '" class="' + self.classes() + '" tabindex="-1" aria-labelledby="' + id + '">' +
  26072. '<button id="' + id + '-open" role="presentation" type="button" tabindex="-1">' +
  26073. (icon ? '<i class="' + icon + '"></i>' : '') +
  26074. '<span>' + (self._text ? (icon ? '\u00a0' : '') + self.encode(self._text) : '') + '</span>' +
  26075. ' <i class="' + prefix + 'caret"></i>' +
  26076. '</button>' +
  26077. '</div>'
  26078. );
  26079. },
  26080. /**
  26081. * Gets invoked after the control has been rendered.
  26082. *
  26083. * @method postRender
  26084. */
  26085. postRender: function() {
  26086. var self = this;
  26087. self.on('click', function(e) {
  26088. if (e.control === self && isChildOf(e.target, self.getEl())) {
  26089. self.showMenu();
  26090. if (e.aria) {
  26091. self.menu.items()[0].focus();
  26092. }
  26093. }
  26094. });
  26095. self.on('mouseenter', function(e) {
  26096. var overCtrl = e.control, parent = self.parent(), hasVisibleSiblingMenu;
  26097. if (overCtrl && parent && overCtrl instanceof MenuButton && overCtrl.parent() == parent) {
  26098. parent.items().filter('MenuButton').each(function(ctrl) {
  26099. if (ctrl.hideMenu && ctrl != overCtrl) {
  26100. if (ctrl.menu && ctrl.menu.visible()) {
  26101. hasVisibleSiblingMenu = true;
  26102. }
  26103. ctrl.hideMenu();
  26104. }
  26105. });
  26106. if (hasVisibleSiblingMenu) {
  26107. overCtrl.focus(); // Fix for: #5887
  26108. overCtrl.showMenu();
  26109. }
  26110. }
  26111. });
  26112. return self._super();
  26113. },
  26114. /**
  26115. * Sets/gets the current button text.
  26116. *
  26117. * @method text
  26118. * @param {String} [text] New button text.
  26119. * @return {String|tinymce.ui.MenuButton} Current text or current MenuButton instance.
  26120. */
  26121. text: function(text) {
  26122. var self = this, i, children;
  26123. if (self._rendered) {
  26124. children = self.getEl('open').getElementsByTagName('span');
  26125. for (i = 0; i < children.length; i++) {
  26126. children[i].innerHTML = (self.settings.icon && text ? '\u00a0' : '') + self.encode(text);
  26127. }
  26128. }
  26129. return this._super(text);
  26130. },
  26131. /**
  26132. * Removes the control and it's menus.
  26133. *
  26134. * @method remove
  26135. */
  26136. remove: function() {
  26137. this._super();
  26138. if (this.menu) {
  26139. this.menu.remove();
  26140. }
  26141. }
  26142. });
  26143. return MenuButton;
  26144. });
  26145. // Included from: js/tinymce/classes/ui/ListBox.js
  26146. /**
  26147. * ListBox.js
  26148. *
  26149. * Copyright, Moxiecode Systems AB
  26150. * Released under LGPL License.
  26151. *
  26152. * License: http://www.tinymce.com/license
  26153. * Contributing: http://www.tinymce.com/contributing
  26154. */
  26155. /**
  26156. * Creates a new list box control.
  26157. *
  26158. * @-x-less ListBox.less
  26159. * @class tinymce.ui.ListBox
  26160. * @extends tinymce.ui.MenuButton
  26161. */
  26162. define("tinymce/ui/ListBox", [
  26163. "tinymce/ui/MenuButton"
  26164. ], function(MenuButton) {
  26165. "use strict";
  26166. return MenuButton.extend({
  26167. /**
  26168. * Constructs a instance with the specified settings.
  26169. *
  26170. * @constructor
  26171. * @param {Object} settings Name/value object with settings.
  26172. * @setting {Array} values Array with values to add to list box.
  26173. */
  26174. init: function(settings) {
  26175. var self = this, values, i, selected, selectedText, lastItemCtrl;
  26176. self._values = values = settings.values;
  26177. if (values) {
  26178. for (i = 0; i < values.length; i++) {
  26179. selected = values[i].selected || settings.value === values[i].value;
  26180. if (selected) {
  26181. selectedText = selectedText || values[i].text;
  26182. self._value = values[i].value;
  26183. break;
  26184. }
  26185. }
  26186. // Default with first item
  26187. if (!selected && values.length > 0) {
  26188. selectedText = values[0].text;
  26189. self._value = values[0].value;
  26190. }
  26191. settings.menu = values;
  26192. }
  26193. settings.text = settings.text || selectedText || values[0].text;
  26194. self._super(settings);
  26195. self.addClass('listbox');
  26196. self.on('select', function(e) {
  26197. var ctrl = e.control;
  26198. if (lastItemCtrl) {
  26199. e.lastControl = lastItemCtrl;
  26200. }
  26201. if (settings.multiple) {
  26202. ctrl.active(!ctrl.active());
  26203. } else {
  26204. self.value(e.control.settings.value);
  26205. }
  26206. lastItemCtrl = ctrl;
  26207. });
  26208. },
  26209. /**
  26210. * Getter/setter function for the control value.
  26211. *
  26212. * @method value
  26213. * @param {String} [value] Value to be set.
  26214. * @return {Boolean/tinymce.ui.ListBox} Value or self if it's a set operation.
  26215. */
  26216. value: function(value) {
  26217. var self = this, active, selectedText, menu, i;
  26218. function activateByValue(menu, value) {
  26219. menu.items().each(function(ctrl) {
  26220. active = ctrl.value() === value;
  26221. if (active) {
  26222. selectedText = selectedText || ctrl.text();
  26223. }
  26224. ctrl.active(active);
  26225. if (ctrl.menu) {
  26226. activateByValue(ctrl.menu, value);
  26227. }
  26228. });
  26229. }
  26230. if (typeof(value) != "undefined") {
  26231. if (self.menu) {
  26232. activateByValue(self.menu, value);
  26233. } else {
  26234. menu = self.settings.menu;
  26235. for (i = 0; i < menu.length; i++) {
  26236. active = menu[i].value == value;
  26237. if (active) {
  26238. selectedText = selectedText || menu[i].text;
  26239. }
  26240. menu[i].active = active;
  26241. }
  26242. }
  26243. self.text(selectedText || this.settings.text);
  26244. }
  26245. return self._super(value);
  26246. }
  26247. });
  26248. });
  26249. // Included from: js/tinymce/classes/ui/MenuItem.js
  26250. /**
  26251. * MenuItem.js
  26252. *
  26253. * Copyright, Moxiecode Systems AB
  26254. * Released under LGPL License.
  26255. *
  26256. * License: http://www.tinymce.com/license
  26257. * Contributing: http://www.tinymce.com/contributing
  26258. */
  26259. /**
  26260. * Creates a new menu item.
  26261. *
  26262. * @-x-less MenuItem.less
  26263. * @class tinymce.ui.MenuItem
  26264. * @extends tinymce.ui.Control
  26265. */
  26266. define("tinymce/ui/MenuItem", [
  26267. "tinymce/ui/Widget",
  26268. "tinymce/ui/Factory",
  26269. "tinymce/Env"
  26270. ], function(Widget, Factory, Env) {
  26271. "use strict";
  26272. return Widget.extend({
  26273. Defaults: {
  26274. border: 0,
  26275. role: 'menuitem'
  26276. },
  26277. /**
  26278. * Constructs a instance with the specified settings.
  26279. *
  26280. * @constructor
  26281. * @param {Object} settings Name/value object with settings.
  26282. * @setting {Boolean} selectable Selectable menu.
  26283. * @setting {Array} menu Submenu array with items.
  26284. * @setting {String} shortcut Shortcut to display for menu item. Example: Ctrl+X
  26285. */
  26286. init: function(settings) {
  26287. var self = this;
  26288. self.hasPopup = true;
  26289. self._super(settings);
  26290. settings = self.settings;
  26291. self.addClass('menu-item');
  26292. if (settings.menu) {
  26293. self.addClass('menu-item-expand');
  26294. }
  26295. if (settings.preview) {
  26296. self.addClass('menu-item-preview');
  26297. }
  26298. if (self._text === '-' || self._text === '|') {
  26299. self.addClass('menu-item-sep');
  26300. self.aria('role', 'separator');
  26301. self._text = '-';
  26302. }
  26303. if (settings.selectable) {
  26304. self.aria('role', 'menuitemcheckbox');
  26305. self.addClass('menu-item-checkbox');
  26306. settings.icon = 'selected';
  26307. }
  26308. if (!settings.preview && !settings.selectable) {
  26309. self.addClass('menu-item-normal');
  26310. }
  26311. self.on('mousedown', function(e) {
  26312. e.preventDefault();
  26313. });
  26314. if (settings.menu && !settings.ariaHideMenu) {
  26315. self.aria('haspopup', true);
  26316. }
  26317. },
  26318. /**
  26319. * Returns true/false if the menuitem has sub menu.
  26320. *
  26321. * @method hasMenus
  26322. * @return {Boolean} True/false state if it has submenu.
  26323. */
  26324. hasMenus: function() {
  26325. return !!this.settings.menu;
  26326. },
  26327. /**
  26328. * Shows the menu for the menu item.
  26329. *
  26330. * @method showMenu
  26331. */
  26332. showMenu: function() {
  26333. var self = this, settings = self.settings, menu, parent = self.parent();
  26334. parent.items().each(function(ctrl) {
  26335. if (ctrl !== self) {
  26336. ctrl.hideMenu();
  26337. }
  26338. });
  26339. if (settings.menu) {
  26340. menu = self.menu;
  26341. if (!menu) {
  26342. menu = settings.menu;
  26343. // Is menu array then auto constuct menu control
  26344. if (menu.length) {
  26345. menu = {
  26346. type: 'menu',
  26347. items: menu
  26348. };
  26349. } else {
  26350. menu.type = menu.type || 'menu';
  26351. }
  26352. if (parent.settings.itemDefaults) {
  26353. menu.itemDefaults = parent.settings.itemDefaults;
  26354. }
  26355. menu = self.menu = Factory.create(menu).parent(self).renderTo();
  26356. menu.reflow();
  26357. menu.fire('show');
  26358. menu.on('cancel', function(e) {
  26359. e.stopPropagation();
  26360. self.focus();
  26361. menu.hide();
  26362. });
  26363. menu.on('hide', function(e) {
  26364. if (e.control === menu) {
  26365. self.removeClass('selected');
  26366. }
  26367. });
  26368. menu.submenu = true;
  26369. } else {
  26370. menu.show();
  26371. }
  26372. menu._parentMenu = parent;
  26373. menu.addClass('menu-sub');
  26374. var rel = menu.testMoveRel(
  26375. self.getEl(),
  26376. self.isRtl() ? ['tl-tr', 'bl-br', 'tr-tl', 'br-bl'] : ['tr-tl', 'br-bl', 'tl-tr', 'bl-br']
  26377. );
  26378. menu.moveRel(self.getEl(), rel);
  26379. menu.rel = rel;
  26380. rel = 'menu-sub-' + rel;
  26381. menu.removeClass(menu._lastRel);
  26382. menu.addClass(rel);
  26383. menu._lastRel = rel;
  26384. self.addClass('selected');
  26385. self.aria('expanded', true);
  26386. }
  26387. },
  26388. /**
  26389. * Hides the menu for the menu item.
  26390. *
  26391. * @method hideMenu
  26392. */
  26393. hideMenu: function() {
  26394. var self = this;
  26395. if (self.menu) {
  26396. self.menu.items().each(function(item) {
  26397. if (item.hideMenu) {
  26398. item.hideMenu();
  26399. }
  26400. });
  26401. self.menu.hide();
  26402. self.aria('expanded', false);
  26403. }
  26404. return self;
  26405. },
  26406. /**
  26407. * Renders the control as a HTML string.
  26408. *
  26409. * @method renderHtml
  26410. * @return {String} HTML representing the control.
  26411. */
  26412. renderHtml: function() {
  26413. var self = this, id = self._id, settings = self.settings, prefix = self.classPrefix, text = self.encode(self._text);
  26414. var icon = self.settings.icon, image = '', shortcut = settings.shortcut;
  26415. if (icon) {
  26416. self.parent().addClass('menu-has-icons');
  26417. }
  26418. if (settings.image) {
  26419. icon = 'none';
  26420. image = ' style="background-image: url(\'' + settings.image + '\')"';
  26421. }
  26422. if (shortcut && Env.mac) {
  26423. // format shortcut for Mac
  26424. shortcut = shortcut.replace(/ctrl\+alt\+/i, '&#x2325;&#x2318;'); // ctrl+cmd
  26425. shortcut = shortcut.replace(/ctrl\+/i, '&#x2318;'); // ctrl symbol
  26426. shortcut = shortcut.replace(/alt\+/i, '&#x2325;'); // cmd symbol
  26427. shortcut = shortcut.replace(/shift\+/i, '&#x21E7;'); // shift symbol
  26428. }
  26429. icon = prefix + 'ico ' + prefix + 'i-' + (self.settings.icon || 'none');
  26430. return (
  26431. '<div id="' + id + '" class="' + self.classes() + '" tabindex="-1">' +
  26432. (text !== '-' ? '<i class="' + icon + '"' + image + '></i>\u00a0' : '') +
  26433. (text !== '-' ? '<span id="' + id + '-text" class="' + prefix + 'text">' + text + '</span>' : '') +
  26434. (shortcut ? '<div id="' + id + '-shortcut" class="' + prefix + 'menu-shortcut">' + shortcut + '</div>' : '') +
  26435. (settings.menu ? '<div class="' + prefix + 'caret"></div>' : '') +
  26436. '</div>'
  26437. );
  26438. },
  26439. /**
  26440. * Gets invoked after the control has been rendered.
  26441. *
  26442. * @method postRender
  26443. */
  26444. postRender: function() {
  26445. var self = this, settings = self.settings;
  26446. var textStyle = settings.textStyle;
  26447. if (typeof(textStyle) == "function") {
  26448. textStyle = textStyle.call(this);
  26449. }
  26450. if (textStyle) {
  26451. var textElm = self.getEl('text');
  26452. if (textElm) {
  26453. textElm.setAttribute('style', textStyle);
  26454. }
  26455. }
  26456. self.on('mouseenter click', function(e) {
  26457. if (e.control === self) {
  26458. if (!settings.menu && e.type === 'click') {
  26459. self.fire('select');
  26460. self.parent().hideAll();
  26461. } else {
  26462. self.showMenu();
  26463. if (e.aria) {
  26464. self.menu.focus(true);
  26465. }
  26466. }
  26467. }
  26468. });
  26469. self._super();
  26470. return self;
  26471. },
  26472. active: function(state) {
  26473. if (typeof(state) != "undefined") {
  26474. this.aria('checked', state);
  26475. }
  26476. return this._super(state);
  26477. },
  26478. /**
  26479. * Removes the control and it's menus.
  26480. *
  26481. * @method remove
  26482. */
  26483. remove: function() {
  26484. this._super();
  26485. if (this.menu) {
  26486. this.menu.remove();
  26487. }
  26488. }
  26489. });
  26490. });
  26491. // Included from: js/tinymce/classes/ui/Menu.js
  26492. /**
  26493. * Menu.js
  26494. *
  26495. * Copyright, Moxiecode Systems AB
  26496. * Released under LGPL License.
  26497. *
  26498. * License: http://www.tinymce.com/license
  26499. * Contributing: http://www.tinymce.com/contributing
  26500. */
  26501. /**
  26502. * Creates a new menu.
  26503. *
  26504. * @-x-less Menu.less
  26505. * @class tinymce.ui.Menu
  26506. * @extends tinymce.ui.FloatPanel
  26507. */
  26508. define("tinymce/ui/Menu", [
  26509. "tinymce/ui/FloatPanel",
  26510. "tinymce/ui/MenuItem",
  26511. "tinymce/util/Tools"
  26512. ], function(FloatPanel, MenuItem, Tools) {
  26513. "use strict";
  26514. var Menu = FloatPanel.extend({
  26515. Defaults: {
  26516. defaultType: 'menuitem',
  26517. border: 1,
  26518. layout: 'stack',
  26519. role: 'application',
  26520. bodyRole: 'menu',
  26521. ariaRoot: true
  26522. },
  26523. /**
  26524. * Constructs a instance with the specified settings.
  26525. *
  26526. * @constructor
  26527. * @param {Object} settings Name/value object with settings.
  26528. */
  26529. init: function(settings) {
  26530. var self = this;
  26531. settings.autohide = true;
  26532. settings.constrainToViewport = true;
  26533. if (settings.itemDefaults) {
  26534. var items = settings.items, i = items.length;
  26535. while (i--) {
  26536. items[i] = Tools.extend({}, settings.itemDefaults, items[i]);
  26537. }
  26538. }
  26539. self._super(settings);
  26540. self.addClass('menu');
  26541. },
  26542. /**
  26543. * Repaints the control after a layout operation.
  26544. *
  26545. * @method repaint
  26546. */
  26547. repaint: function() {
  26548. this.toggleClass('menu-align', true);
  26549. this._super();
  26550. this.getEl().style.height = '';
  26551. this.getEl('body').style.height = '';
  26552. return this;
  26553. },
  26554. /**
  26555. * Hides/closes the menu.
  26556. *
  26557. * @method cancel
  26558. */
  26559. cancel: function() {
  26560. var self = this;
  26561. self.hideAll();
  26562. self.fire('select');
  26563. },
  26564. /**
  26565. * Hide menu and all sub menus.
  26566. *
  26567. * @method hideAll
  26568. */
  26569. hideAll: function() {
  26570. var self = this;
  26571. this.find('menuitem').exec('hideMenu');
  26572. return self._super();
  26573. },
  26574. /*
  26575. getContainerElm: function() {
  26576. var doc = document, id = this.classPrefix + 'menucontainer';
  26577. var elm = doc.getElementById(id);
  26578. if (!elm) {
  26579. elm = doc.createElement('div');
  26580. elm.id = id;
  26581. elm.setAttribute('role', 'application');
  26582. elm.className = this.classPrefix + '-reset';
  26583. elm.style.position = 'absolute';
  26584. elm.style.top = elm.style.left = '0';
  26585. elm.style.overflow = 'visible';
  26586. doc.body.appendChild(elm);
  26587. }
  26588. return elm;
  26589. },
  26590. */
  26591. /**
  26592. * Invoked before the menu is rendered.
  26593. *
  26594. * @method preRender
  26595. */
  26596. preRender: function() {
  26597. var self = this;
  26598. self.items().each(function(ctrl) {
  26599. var settings = ctrl.settings;
  26600. if (settings.icon || settings.selectable) {
  26601. self._hasIcons = true;
  26602. return false;
  26603. }
  26604. });
  26605. return self._super();
  26606. }
  26607. });
  26608. return Menu;
  26609. });
  26610. // Included from: js/tinymce/classes/ui/Radio.js
  26611. /**
  26612. * Radio.js
  26613. *
  26614. * Copyright, Moxiecode Systems AB
  26615. * Released under LGPL License.
  26616. *
  26617. * License: http://www.tinymce.com/license
  26618. * Contributing: http://www.tinymce.com/contributing
  26619. */
  26620. /**
  26621. * Creates a new radio button.
  26622. *
  26623. * @-x-less Radio.less
  26624. * @class tinymce.ui.Radio
  26625. * @extends tinymce.ui.Checkbox
  26626. */
  26627. define("tinymce/ui/Radio", [
  26628. "tinymce/ui/Checkbox"
  26629. ], function(Checkbox) {
  26630. "use strict";
  26631. return Checkbox.extend({
  26632. Defaults: {
  26633. classes: "radio",
  26634. role: "radio"
  26635. }
  26636. });
  26637. });
  26638. // Included from: js/tinymce/classes/ui/ResizeHandle.js
  26639. /**
  26640. * ResizeHandle.js
  26641. *
  26642. * Copyright, Moxiecode Systems AB
  26643. * Released under LGPL License.
  26644. *
  26645. * License: http://www.tinymce.com/license
  26646. * Contributing: http://www.tinymce.com/contributing
  26647. */
  26648. /**
  26649. * Renders a resize handle that fires ResizeStart, Resize and ResizeEnd events.
  26650. *
  26651. * @-x-less ResizeHandle.less
  26652. * @class tinymce.ui.ResizeHandle
  26653. * @extends tinymce.ui.Widget
  26654. */
  26655. define("tinymce/ui/ResizeHandle", [
  26656. "tinymce/ui/Widget",
  26657. "tinymce/ui/DragHelper"
  26658. ], function(Widget, DragHelper) {
  26659. "use strict";
  26660. return Widget.extend({
  26661. /**
  26662. * Renders the control as a HTML string.
  26663. *
  26664. * @method renderHtml
  26665. * @return {String} HTML representing the control.
  26666. */
  26667. renderHtml: function() {
  26668. var self = this, prefix = self.classPrefix;
  26669. self.addClass('resizehandle');
  26670. if (self.settings.direction == "both") {
  26671. self.addClass('resizehandle-both');
  26672. }
  26673. self.canFocus = false;
  26674. return (
  26675. '<div id="' + self._id + '" class="' + self.classes() + '">' +
  26676. '<i class="' + prefix + 'ico ' + prefix + 'i-resize"></i>' +
  26677. '</div>'
  26678. );
  26679. },
  26680. /**
  26681. * Called after the control has been rendered.
  26682. *
  26683. * @method postRender
  26684. */
  26685. postRender: function() {
  26686. var self = this;
  26687. self._super();
  26688. self.resizeDragHelper = new DragHelper(this._id, {
  26689. start: function() {
  26690. self.fire('ResizeStart');
  26691. },
  26692. drag: function(e) {
  26693. if (self.settings.direction != "both") {
  26694. e.deltaX = 0;
  26695. }
  26696. self.fire('Resize', e);
  26697. },
  26698. stop: function() {
  26699. self.fire('ResizeEnd');
  26700. }
  26701. });
  26702. },
  26703. remove: function() {
  26704. if (this.resizeDragHelper) {
  26705. this.resizeDragHelper.destroy();
  26706. }
  26707. return this._super();
  26708. }
  26709. });
  26710. });
  26711. // Included from: js/tinymce/classes/ui/Spacer.js
  26712. /**
  26713. * Spacer.js
  26714. *
  26715. * Copyright, Moxiecode Systems AB
  26716. * Released under LGPL License.
  26717. *
  26718. * License: http://www.tinymce.com/license
  26719. * Contributing: http://www.tinymce.com/contributing
  26720. */
  26721. /**
  26722. * Creates a spacer. This control is used in flex layouts for example.
  26723. *
  26724. * @-x-less Spacer.less
  26725. * @class tinymce.ui.Spacer
  26726. * @extends tinymce.ui.Widget
  26727. */
  26728. define("tinymce/ui/Spacer", [
  26729. "tinymce/ui/Widget"
  26730. ], function(Widget) {
  26731. "use strict";
  26732. return Widget.extend({
  26733. /**
  26734. * Renders the control as a HTML string.
  26735. *
  26736. * @method renderHtml
  26737. * @return {String} HTML representing the control.
  26738. */
  26739. renderHtml: function() {
  26740. var self = this;
  26741. self.addClass('spacer');
  26742. self.canFocus = false;
  26743. return '<div id="' + self._id + '" class="' + self.classes() + '"></div>';
  26744. }
  26745. });
  26746. });
  26747. // Included from: js/tinymce/classes/ui/SplitButton.js
  26748. /**
  26749. * SplitButton.js
  26750. *
  26751. * Copyright, Moxiecode Systems AB
  26752. * Released under LGPL License.
  26753. *
  26754. * License: http://www.tinymce.com/license
  26755. * Contributing: http://www.tinymce.com/contributing
  26756. */
  26757. /**
  26758. * Creates a split button.
  26759. *
  26760. * @-x-less SplitButton.less
  26761. * @class tinymce.ui.SplitButton
  26762. * @extends tinymce.ui.Button
  26763. */
  26764. define("tinymce/ui/SplitButton", [
  26765. "tinymce/ui/MenuButton",
  26766. "tinymce/ui/DomUtils"
  26767. ], function(MenuButton, DomUtils) {
  26768. return MenuButton.extend({
  26769. Defaults: {
  26770. classes: "widget btn splitbtn",
  26771. role: "button"
  26772. },
  26773. /**
  26774. * Repaints the control after a layout operation.
  26775. *
  26776. * @method repaint
  26777. */
  26778. repaint: function() {
  26779. var self = this, elm = self.getEl(), rect = self.layoutRect(), mainButtonElm, menuButtonElm;
  26780. self._super();
  26781. mainButtonElm = elm.firstChild;
  26782. menuButtonElm = elm.lastChild;
  26783. DomUtils.css(mainButtonElm, {
  26784. width: rect.w - DomUtils.getSize(menuButtonElm).width,
  26785. height: rect.h - 2
  26786. });
  26787. DomUtils.css(menuButtonElm, {
  26788. height: rect.h - 2
  26789. });
  26790. return self;
  26791. },
  26792. /**
  26793. * Sets the active menu state.
  26794. *
  26795. * @private
  26796. */
  26797. activeMenu: function(state) {
  26798. var self = this;
  26799. DomUtils.toggleClass(self.getEl().lastChild, self.classPrefix + 'active', state);
  26800. },
  26801. /**
  26802. * Renders the control as a HTML string.
  26803. *
  26804. * @method renderHtml
  26805. * @return {String} HTML representing the control.
  26806. */
  26807. renderHtml: function() {
  26808. var self = this, id = self._id, prefix = self.classPrefix;
  26809. var icon = self.settings.icon ? prefix + 'ico ' + prefix + 'i-' + self.settings.icon : '';
  26810. return (
  26811. '<div id="' + id + '" class="' + self.classes() + '" role="button" tabindex="-1">' +
  26812. '<button type="button" hidefocus="1" tabindex="-1">' +
  26813. (icon ? '<i class="' + icon + '"></i>' : '') +
  26814. (self._text ? (icon ? ' ' : '') + self._text : '') +
  26815. '</button>' +
  26816. '<button type="button" class="' + prefix + 'open" hidefocus="1" tabindex="-1">' +
  26817. //(icon ? '<i class="' + icon + '"></i>' : '') +
  26818. (self._menuBtnText ? (icon ? '\u00a0' : '') + self._menuBtnText : '') +
  26819. ' <i class="' + prefix + 'caret"></i>' +
  26820. '</button>' +
  26821. '</div>'
  26822. );
  26823. },
  26824. /**
  26825. * Called after the control has been rendered.
  26826. *
  26827. * @method postRender
  26828. */
  26829. postRender: function() {
  26830. var self = this, onClickHandler = self.settings.onclick;
  26831. self.on('click', function(e) {
  26832. var node = e.target;
  26833. if (e.control == this) {
  26834. // Find clicks that is on the main button
  26835. while (node) {
  26836. if ((e.aria && e.aria.key != 'down') || (node.nodeName == 'BUTTON' && node.className.indexOf('open') == -1)) {
  26837. e.stopImmediatePropagation();
  26838. onClickHandler.call(this, e);
  26839. return;
  26840. }
  26841. node = node.parentNode;
  26842. }
  26843. }
  26844. });
  26845. delete self.settings.onclick;
  26846. return self._super();
  26847. }
  26848. });
  26849. });
  26850. // Included from: js/tinymce/classes/ui/StackLayout.js
  26851. /**
  26852. * StackLayout.js
  26853. *
  26854. * Copyright, Moxiecode Systems AB
  26855. * Released under LGPL License.
  26856. *
  26857. * License: http://www.tinymce.com/license
  26858. * Contributing: http://www.tinymce.com/contributing
  26859. */
  26860. /**
  26861. * This layout uses the browsers layout when the items are blocks.
  26862. *
  26863. * @-x-less StackLayout.less
  26864. * @class tinymce.ui.StackLayout
  26865. * @extends tinymce.ui.FlowLayout
  26866. */
  26867. define("tinymce/ui/StackLayout", [
  26868. "tinymce/ui/FlowLayout"
  26869. ], function(FlowLayout) {
  26870. "use strict";
  26871. return FlowLayout.extend({
  26872. Defaults: {
  26873. containerClass: 'stack-layout',
  26874. controlClass: 'stack-layout-item',
  26875. endClass : 'break'
  26876. }
  26877. });
  26878. });
  26879. // Included from: js/tinymce/classes/ui/TabPanel.js
  26880. /**
  26881. * TabPanel.js
  26882. *
  26883. * Copyright, Moxiecode Systems AB
  26884. * Released under LGPL License.
  26885. *
  26886. * License: http://www.tinymce.com/license
  26887. * Contributing: http://www.tinymce.com/contributing
  26888. */
  26889. /**
  26890. * Creates a tab panel control.
  26891. *
  26892. * @-x-less TabPanel.less
  26893. * @class tinymce.ui.TabPanel
  26894. * @extends tinymce.ui.Panel
  26895. *
  26896. * @setting {Number} activeTab Active tab index.
  26897. */
  26898. define("tinymce/ui/TabPanel", [
  26899. "tinymce/ui/Panel",
  26900. "tinymce/ui/DomUtils"
  26901. ], function(Panel, DomUtils) {
  26902. "use strict";
  26903. return Panel.extend({
  26904. lastIdx: 0,
  26905. Defaults: {
  26906. layout: 'absolute',
  26907. defaults: {
  26908. type: 'panel'
  26909. }
  26910. },
  26911. /**
  26912. * Activates the specified tab by index.
  26913. *
  26914. * @method activateTab
  26915. * @param {Number} idx Index of the tab to activate.
  26916. */
  26917. activateTab: function(idx) {
  26918. var activeTabElm;
  26919. if (this.activeTabId) {
  26920. activeTabElm = this.getEl(this.activeTabId);
  26921. DomUtils.removeClass(activeTabElm, this.classPrefix + 'active');
  26922. activeTabElm.setAttribute('aria-selected', "false");
  26923. }
  26924. this.activeTabId = 't' + idx;
  26925. activeTabElm = this.getEl('t' + idx);
  26926. activeTabElm.setAttribute('aria-selected', "true");
  26927. DomUtils.addClass(activeTabElm, this.classPrefix + 'active');
  26928. if (idx != this.lastIdx) {
  26929. this.items()[this.lastIdx].hide();
  26930. this.lastIdx = idx;
  26931. }
  26932. this.items()[idx].show().fire('showtab');
  26933. this.reflow();
  26934. },
  26935. /**
  26936. * Renders the control as a HTML string.
  26937. *
  26938. * @method renderHtml
  26939. * @return {String} HTML representing the control.
  26940. */
  26941. renderHtml: function() {
  26942. var self = this, layout = self._layout, tabsHtml = '', prefix = self.classPrefix;
  26943. self.preRender();
  26944. layout.preRender(self);
  26945. self.items().each(function(ctrl, i) {
  26946. var id = self._id + '-t' + i;
  26947. ctrl.aria('role', 'tabpanel');
  26948. ctrl.aria('labelledby', id);
  26949. tabsHtml += (
  26950. '<div id="' + id + '" class="' + prefix + 'tab" ' +
  26951. 'unselectable="on" role="tab" aria-controls="' + ctrl._id + '" aria-selected="false" tabIndex="-1">' +
  26952. self.encode(ctrl.settings.title) +
  26953. '</div>'
  26954. );
  26955. });
  26956. return (
  26957. '<div id="' + self._id + '" class="' + self.classes() + '" hidefocus="1" tabindex="-1">' +
  26958. '<div id="' + self._id + '-head" class="' + prefix + 'tabs" role="tablist">' +
  26959. tabsHtml +
  26960. '</div>' +
  26961. '<div id="' + self._id + '-body" class="' + self.classes('body') + '">' +
  26962. layout.renderHtml(self) +
  26963. '</div>' +
  26964. '</div>'
  26965. );
  26966. },
  26967. /**
  26968. * Called after the control has been rendered.
  26969. *
  26970. * @method postRender
  26971. */
  26972. postRender: function() {
  26973. var self = this;
  26974. self._super();
  26975. self.settings.activeTab = self.settings.activeTab || 0;
  26976. self.activateTab(self.settings.activeTab);
  26977. this.on('click', function(e) {
  26978. var targetParent = e.target.parentNode;
  26979. if (e.target.parentNode.id == self._id + '-head') {
  26980. var i = targetParent.childNodes.length;
  26981. while (i--) {
  26982. if (targetParent.childNodes[i] == e.target) {
  26983. self.activateTab(i);
  26984. }
  26985. }
  26986. }
  26987. });
  26988. },
  26989. /**
  26990. * Initializes the current controls layout rect.
  26991. * This will be executed by the layout managers to determine the
  26992. * default minWidth/minHeight etc.
  26993. *
  26994. * @method initLayoutRect
  26995. * @return {Object} Layout rect instance.
  26996. */
  26997. initLayoutRect: function() {
  26998. var self = this, rect, minW, minH;
  26999. minW = DomUtils.getSize(self.getEl('head')).width;
  27000. minW = minW < 0 ? 0 : minW;
  27001. minH = 0;
  27002. self.items().each(function(item, i) {
  27003. minW = Math.max(minW, item.layoutRect().minW);
  27004. minH = Math.max(minH, item.layoutRect().minH);
  27005. if (self.settings.activeTab != i) {
  27006. item.hide();
  27007. }
  27008. });
  27009. self.items().each(function(ctrl) {
  27010. ctrl.settings.x = 0;
  27011. ctrl.settings.y = 0;
  27012. ctrl.settings.w = minW;
  27013. ctrl.settings.h = minH;
  27014. ctrl.layoutRect({
  27015. x: 0,
  27016. y: 0,
  27017. w: minW,
  27018. h: minH
  27019. });
  27020. });
  27021. var headH = DomUtils.getSize(self.getEl('head')).height;
  27022. self.settings.minWidth = minW;
  27023. self.settings.minHeight = minH + headH;
  27024. rect = self._super();
  27025. rect.deltaH += headH;
  27026. rect.innerH = rect.h - rect.deltaH;
  27027. return rect;
  27028. }
  27029. });
  27030. });
  27031. // Included from: js/tinymce/classes/ui/TextBox.js
  27032. /**
  27033. * TextBox.js
  27034. *
  27035. * Copyright, Moxiecode Systems AB
  27036. * Released under LGPL License.
  27037. *
  27038. * License: http://www.tinymce.com/license
  27039. * Contributing: http://www.tinymce.com/contributing
  27040. */
  27041. /**
  27042. * Creates a new textbox.
  27043. *
  27044. * @-x-less TextBox.less
  27045. * @class tinymce.ui.TextBox
  27046. * @extends tinymce.ui.Widget
  27047. */
  27048. define("tinymce/ui/TextBox", [
  27049. "tinymce/ui/Widget",
  27050. "tinymce/ui/DomUtils"
  27051. ], function(Widget, DomUtils) {
  27052. "use strict";
  27053. return Widget.extend({
  27054. /**
  27055. * Constructs a instance with the specified settings.
  27056. *
  27057. * @constructor
  27058. * @param {Object} settings Name/value object with settings.
  27059. * @setting {Boolean} multiline True if the textbox is a multiline control.
  27060. * @setting {Number} maxLength Max length for the textbox.
  27061. * @setting {Number} size Size of the textbox in characters.
  27062. */
  27063. init: function(settings) {
  27064. var self = this;
  27065. self._super(settings);
  27066. self._value = settings.value || '';
  27067. self.addClass('textbox');
  27068. if (settings.multiline) {
  27069. self.addClass('multiline');
  27070. } else {
  27071. // TODO: Rework this
  27072. self.on('keydown', function(e) {
  27073. if (e.keyCode == 13) {
  27074. self.parents().reverse().each(function(ctrl) {
  27075. e.preventDefault();
  27076. if (ctrl.hasEventListeners('submit') && ctrl.toJSON) {
  27077. ctrl.fire('submit', {data: ctrl.toJSON()});
  27078. return false;
  27079. }
  27080. });
  27081. }
  27082. });
  27083. }
  27084. },
  27085. /**
  27086. * Getter/setter function for the disabled state.
  27087. *
  27088. * @method value
  27089. * @param {Boolean} [state] State to be set.
  27090. * @return {Boolean|tinymce.ui.ComboBox} True/false or self if it's a set operation.
  27091. */
  27092. disabled: function(state) {
  27093. var self = this;
  27094. if (self._rendered && typeof(state) != 'undefined') {
  27095. self.getEl().disabled = state;
  27096. }
  27097. return self._super(state);
  27098. },
  27099. /**
  27100. * Getter/setter function for the control value.
  27101. *
  27102. * @method value
  27103. * @param {String} [value] Value to be set.
  27104. * @return {String|tinymce.ui.ComboBox} Value or self if it's a set operation.
  27105. */
  27106. value: function(value) {
  27107. var self = this;
  27108. if (typeof(value) != "undefined") {
  27109. self._value = value;
  27110. if (self._rendered) {
  27111. self.getEl().value = value;
  27112. }
  27113. return self;
  27114. }
  27115. if (self._rendered) {
  27116. return self.getEl().value;
  27117. }
  27118. return self._value;
  27119. },
  27120. /**
  27121. * Repaints the control after a layout operation.
  27122. *
  27123. * @method repaint
  27124. */
  27125. repaint: function() {
  27126. var self = this, style, rect, borderBox, borderW = 0, borderH = 0, lastRepaintRect;
  27127. style = self.getEl().style;
  27128. rect = self._layoutRect;
  27129. lastRepaintRect = self._lastRepaintRect || {};
  27130. // Detect old IE 7+8 add lineHeight to align caret vertically in the middle
  27131. var doc = document;
  27132. if (!self.settings.multiline && doc.all && (!doc.documentMode || doc.documentMode <= 8)) {
  27133. style.lineHeight = (rect.h - borderH) + 'px';
  27134. }
  27135. borderBox = self._borderBox;
  27136. borderW = borderBox.left + borderBox.right + 8;
  27137. borderH = borderBox.top + borderBox.bottom + (self.settings.multiline ? 8 : 0);
  27138. if (rect.x !== lastRepaintRect.x) {
  27139. style.left = rect.x + 'px';
  27140. lastRepaintRect.x = rect.x;
  27141. }
  27142. if (rect.y !== lastRepaintRect.y) {
  27143. style.top = rect.y + 'px';
  27144. lastRepaintRect.y = rect.y;
  27145. }
  27146. if (rect.w !== lastRepaintRect.w) {
  27147. style.width = (rect.w - borderW) + 'px';
  27148. lastRepaintRect.w = rect.w;
  27149. }
  27150. if (rect.h !== lastRepaintRect.h) {
  27151. style.height = (rect.h - borderH) + 'px';
  27152. lastRepaintRect.h = rect.h;
  27153. }
  27154. self._lastRepaintRect = lastRepaintRect;
  27155. self.fire('repaint', {}, false);
  27156. return self;
  27157. },
  27158. /**
  27159. * Renders the control as a HTML string.
  27160. *
  27161. * @method renderHtml
  27162. * @return {String} HTML representing the control.
  27163. */
  27164. renderHtml: function() {
  27165. var self = this, id = self._id, settings = self.settings, value = self.encode(self._value, false), extraAttrs = '';
  27166. if ("spellcheck" in settings) {
  27167. extraAttrs += ' spellcheck="' + settings.spellcheck + '"';
  27168. }
  27169. if (settings.maxLength) {
  27170. extraAttrs += ' maxlength="' + settings.maxLength + '"';
  27171. }
  27172. if (settings.size) {
  27173. extraAttrs += ' size="' + settings.size + '"';
  27174. }
  27175. if (settings.subtype) {
  27176. extraAttrs += ' type="' + settings.subtype + '"';
  27177. }
  27178. if (self.disabled()) {
  27179. extraAttrs += ' disabled="disabled"';
  27180. }
  27181. if (settings.multiline) {
  27182. return (
  27183. '<textarea id="' + id + '" class="' + self.classes() + '" ' +
  27184. (settings.rows ? ' rows="' + settings.rows + '"' : '') +
  27185. ' hidefocus="1"' + extraAttrs + '>' + value +
  27186. '</textarea>'
  27187. );
  27188. }
  27189. return '<input id="' + id + '" class="' + self.classes() + '" value="' + value + '" hidefocus="1"' + extraAttrs + ' />';
  27190. },
  27191. /**
  27192. * Called after the control has been rendered.
  27193. *
  27194. * @method postRender
  27195. */
  27196. postRender: function() {
  27197. var self = this;
  27198. DomUtils.on(self.getEl(), 'change', function(e) {
  27199. self.fire('change', e);
  27200. });
  27201. return self._super();
  27202. },
  27203. remove: function() {
  27204. DomUtils.off(this.getEl());
  27205. this._super();
  27206. }
  27207. });
  27208. });
  27209. // Included from: js/tinymce/classes/ui/Throbber.js
  27210. /**
  27211. * Throbber.js
  27212. *
  27213. * Copyright, Moxiecode Systems AB
  27214. * Released under LGPL License.
  27215. *
  27216. * License: http://www.tinymce.com/license
  27217. * Contributing: http://www.tinymce.com/contributing
  27218. */
  27219. /**
  27220. * This class enables you to display a Throbber for any element.
  27221. *
  27222. * @-x-less Throbber.less
  27223. * @class tinymce.ui.Throbber
  27224. */
  27225. define("tinymce/ui/Throbber", [
  27226. "tinymce/ui/DomUtils",
  27227. "tinymce/ui/Control"
  27228. ], function(DomUtils, Control) {
  27229. "use strict";
  27230. /**
  27231. * Constructs a new throbber.
  27232. *
  27233. * @constructor
  27234. * @param {Element} elm DOM Html element to display throbber in.
  27235. * @param {Boolean} inline Optional true/false state if the throbber should be appended to end of element for infinite scroll.
  27236. */
  27237. return function(elm, inline) {
  27238. var self = this, state, classPrefix = Control.classPrefix;
  27239. /**
  27240. * Shows the throbber.
  27241. *
  27242. * @method show
  27243. * @param {Number} [time] Time to wait before showing.
  27244. * @return {tinymce.ui.Throbber} Current throbber instance.
  27245. */
  27246. self.show = function(time) {
  27247. self.hide();
  27248. state = true;
  27249. window.setTimeout(function() {
  27250. if (state) {
  27251. elm.appendChild(DomUtils.createFragment(
  27252. '<div class="' + classPrefix + 'throbber' + (inline ? ' ' + classPrefix + 'throbber-inline' : '') + '"></div>'
  27253. ));
  27254. }
  27255. }, time || 0);
  27256. return self;
  27257. };
  27258. /**
  27259. * Hides the throbber.
  27260. *
  27261. * @method hide
  27262. * @return {tinymce.ui.Throbber} Current throbber instance.
  27263. */
  27264. self.hide = function() {
  27265. var child = elm.lastChild;
  27266. if (child && child.className.indexOf('throbber') != -1) {
  27267. child.parentNode.removeChild(child);
  27268. }
  27269. state = false;
  27270. return self;
  27271. };
  27272. };
  27273. });
  27274. expose(["tinymce/dom/Sizzle","tinymce/html/Styles","tinymce/dom/EventUtils","tinymce/dom/TreeWalker","tinymce/util/Tools","tinymce/dom/Range","tinymce/html/Entities","tinymce/Env","tinymce/dom/StyleSheetLoader","tinymce/dom/DOMUtils","tinymce/dom/ScriptLoader","tinymce/AddOnManager","tinymce/html/Node","tinymce/html/Schema","tinymce/html/SaxParser","tinymce/html/DomParser","tinymce/html/Writer","tinymce/html/Serializer","tinymce/dom/Serializer","tinymce/dom/TridentSelection","tinymce/util/VK","tinymce/dom/ControlSelection","tinymce/dom/RangeUtils","tinymce/dom/Selection","tinymce/fmt/Preview","tinymce/Formatter","tinymce/UndoManager","tinymce/EnterKey","tinymce/ForceBlocks","tinymce/EditorCommands","tinymce/util/URI","tinymce/util/Class","tinymce/ui/Selector","tinymce/ui/Collection","tinymce/ui/DomUtils","tinymce/ui/Control","tinymce/ui/Factory","tinymce/ui/KeyboardNavigation","tinymce/ui/Container","tinymce/ui/DragHelper","tinymce/ui/Scrollable","tinymce/ui/Panel","tinymce/ui/Movable","tinymce/ui/Resizable","tinymce/ui/FloatPanel","tinymce/ui/Window","tinymce/ui/MessageBox","tinymce/WindowManager","tinymce/util/Quirks","tinymce/util/Observable","tinymce/Shortcuts","tinymce/Editor","tinymce/util/I18n","tinymce/FocusManager","tinymce/EditorManager","tinymce/LegacyInput","tinymce/util/XHR","tinymce/util/JSON","tinymce/util/JSONRequest","tinymce/util/JSONP","tinymce/util/LocalStorage","tinymce/Compat","tinymce/ui/Layout","tinymce/ui/AbsoluteLayout","tinymce/ui/Tooltip","tinymce/ui/Widget","tinymce/ui/Button","tinymce/ui/ButtonGroup","tinymce/ui/Checkbox","tinymce/ui/PanelButton","tinymce/ui/ColorButton","tinymce/ui/ComboBox","tinymce/ui/Path","tinymce/ui/ElementPath","tinymce/ui/FormItem","tinymce/ui/Form","tinymce/ui/FieldSet","tinymce/ui/FilePicker","tinymce/ui/FitLayout","tinymce/ui/FlexLayout","tinymce/ui/FlowLayout","tinymce/ui/FormatControls","tinymce/ui/GridLayout","tinymce/ui/Iframe","tinymce/ui/Label","tinymce/ui/Toolbar","tinymce/ui/MenuBar","tinymce/ui/MenuButton","tinymce/ui/ListBox","tinymce/ui/MenuItem","tinymce/ui/Menu","tinymce/ui/Radio","tinymce/ui/ResizeHandle","tinymce/ui/Spacer","tinymce/ui/SplitButton","tinymce/ui/StackLayout","tinymce/ui/TabPanel","tinymce/ui/TextBox","tinymce/ui/Throbber"]);
  27275. })(this);